struct byte_array *byte_array_add_byte(struct byte_array *a, uint8_t b) { a->length++; byte_array_resize(a, a->length); a->current = a->data + a->length; a->data[a->length-1] = b; return a; }
// adds formatted string to end of byte_array, so sprintf + strcat void byte_array_format(struct byte_array *ba, bool append, const char *format, ...) { bool resize; do { size_t capacity = ba->size; uint8_t *at = ba->data; if (append) { capacity -= ba->length; at = ba->current; } va_list args; va_start(args, format); int written = vsnprintf((char*)at, capacity, format, args) + 1; if ((resize = (written > capacity) && (ba->size < VV_SIZE))) byte_array_resize(ba, (uint32_t)(ba->size + written - capacity)); else { ba->length = (uint32_t)(ba->length + MIN(written-1, capacity)); ba->current = ba->data + ba->length; } va_end(args); } while (resize); }
struct byte_array *byte_array_part(struct byte_array *within, uint32_t start, uint32_t length) { struct byte_array *p = byte_array_copy(within); byte_array_remove(p, start+length, within->length-start-length); byte_array_remove(p, 0, start); byte_array_resize(p, p->length); return p; }
void byte_array_append(struct byte_array *a, const struct byte_array* b) { null_check(a); null_check(b); uint32_t offset = a->length; uint32_t newlen = a->length + b->length; byte_array_resize(a, newlen); memcpy(&a->data[offset], b->data, b->length); a->length = newlen; a->current = a->data + newlen; }
struct byte_array* serial_encode_string(struct byte_array* buf, const struct byte_array* bytes) { if (!bytes) return buf; if (!buf) buf = byte_array_new(); encode_int(buf, bytes->length); byte_array_resize(buf, buf->length + bytes->length); memcpy(buf->current, bytes->data, bytes->length); buf->current = buf->data + buf->length; return buf; }
void byte_array_append(struct byte_array *b, const char *data, size_t size) { size_t new_size; if (size <= 0) return; new_size = b->size + size; if (new_size > b->capacity) byte_array_resize(b, max(new_size + 1, b->capacity << 1)); memcpy(b->end, data, size); b->end += size; b->size += size; }
struct byte_array *encode_int(struct byte_array *buf, int32_t value) { if (!buf) buf = byte_array_new(); uint8_t growth = encode_int_size(value); byte_array_resize(buf, buf->length + growth); bool neg = value < 0; value = abs(value); uint8_t byte = (value & 0x3F) | ((value >= 0x40) ? 0x80 : 0) | (neg ? 0x40 : 0); *buf->current++ = byte; value >>= 6; while (value) { byte = (value & 0x7F) | ((value >= 0x80) ? 0x80 : 0); *buf->current++ = byte; value >>= 7; } return buf; }
void byte_array_remove(struct byte_array *self, uint32_t start, int32_t length) { list_remove(self->data, &self->length, start, length, sizeof(uint8_t)); byte_array_resize(self, self->length); //DEBUGPRINT("byte_array_remove %p->%p\n", self, self->data); }
static void ensure_size(struct byte_array *ba, size_t sz) { if (ba->len + sz >= ba->cap) byte_array_resize(ba, ba->len + sz); }