ts.cpp 2.03 KB
Newer Older
Jake Read's avatar
Jake Read committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/*
osap/ts.cpp

typeset / keys / writing / reading

Jake Read at the Center for Bits and Atoms
(c) Massachusetts Institute of Technology 2019

This work may be reproduced, modified, distributed, performed, and
displayed for any purpose, but must acknowledge the squidworks and ponyo projects.
Copyright is retained and must be preserved. The work is provided as is;
no warranty is provided, and users accept all liability.
*/

#include "ts.h"

void ts_writeBoolean(boolean val, unsigned char *buf, uint16_t *ptr){
  if(val){
    buf[(*ptr) ++] = 1;
  } else {
    buf[(*ptr) ++] = 0;
  }
}

void ts_readUint16(uint16_t *val, unsigned char *buf, uint16_t *ptr){
  *val = buf[(*ptr) + 1] << 8 | buf[(*ptr)];
  *ptr += 2;
}

void ts_writeUint16(uint16_t val, unsigned char *buf, uint16_t *ptr){
  buf[(*ptr) ++] = val & 255;
  buf[(*ptr) ++] = (val >> 8) & 255;
}

void ts_writeUint32(uint32_t val, unsigned char *buf, uint16_t *ptr){
  buf[(*ptr) ++] = val & 255;
  buf[(*ptr) ++] = (val >> 8) & 255;
  buf[(*ptr) ++] = (val >> 16) & 255;
  buf[(*ptr) ++] = (val >> 24) & 255;
}

Jake Read's avatar
Jake Read committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
// pls recall the union, 
union chunk_float32 {
  uint8_t bytes[4];
  float f;
};

/*
chunk_float32 dur_chunk = { .bytes = { bPck[ptr ++], bPck[ptr ++], bPck[ptr ++], bPck[ptr ++] } } ;
float duration = dur_chunk.f;
*/

union chunk_int32 {
  uint8_t bytes[4];
  int32_t num;
};

void ts_readInt32(int32_t *val, unsigned char *buf, uint16_t *ptr){
  chunk_int32 wc = { .bytes = { buf[(*ptr) ++], buf[(*ptr) ++], buf[(*ptr) ++], buf[(*ptr) ++] }};
  *val = wc.num;
}

void ts_writeInt32(int32_t val, unsigned char *buf, uint16_t *ptr){
  chunk_int32 wc = { .num = val };
  buf[(*ptr) ++] = wc.bytes[0];
  buf[(*ptr) ++] = wc.bytes[1];
  buf[(*ptr) ++] = wc.bytes[2];
  buf[(*ptr) ++] = wc.bytes[3];
}

Jake Read's avatar
Jake Read committed
71 72 73 74 75 76 77 78 79
void ts_writeString(String val, unsigned char *buf, uint16_t *ptr){
  uint32_t len = val.length();
  buf[(*ptr) ++] = len & 255;
  buf[(*ptr) ++] = (len >> 8) & 255;
  buf[(*ptr) ++] = (len >> 16) & 255;
  buf[(*ptr) ++] = (len >> 24) & 255;
  val.getBytes(&buf[*ptr], len + 1);
  *ptr += len;
}