Skip to content

Commit e2d8e24

Browse files
authored
Merge pull request #476 from s-hadinger/bytes_add3
bytes() add 3-byte values
2 parents 52b61f3 + dbde2a0 commit e2d8e24

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/be_byteslib.c

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,26 @@ static size_t buf_add2_be(buf_impl* attr, const uint16_t data) // append 16 bits
258258
return attr->len;
259259
}
260260

261+
static size_t buf_add3_le(buf_impl* attr, const uint32_t data) // append 32 bits value
262+
{
263+
if (attr->len < attr->size - 2) { // do we have room for 4 bytes
264+
attr->bufptr[attr->len++] = data;
265+
attr->bufptr[attr->len++] = data >> 8;
266+
attr->bufptr[attr->len++] = data >> 16;
267+
}
268+
return attr->len;
269+
}
270+
271+
size_t buf_add3_be(buf_impl* attr, const uint32_t data) // append 32 bits value
272+
{
273+
if (attr->len < attr->size - 2) { // do we have room for 4 bytes
274+
attr->bufptr[attr->len++] = data >> 16;
275+
attr->bufptr[attr->len++] = data >> 8;
276+
attr->bufptr[attr->len++] = data;
277+
}
278+
return attr->len;
279+
}
280+
261281
static size_t buf_add4_le(buf_impl* attr, const uint32_t data) // append 32 bits value
262282
{
263283
if (attr->len < attr->size - 3) { // do we have room for 4 bytes
@@ -786,7 +806,8 @@ static int m_asstring(bvm *vm)
786806
{
787807
buf_impl attr = bytes_check_data(vm, 0);
788808
check_ptr(vm, &attr);
789-
be_pushnstring(vm, (const char*) attr.bufptr, attr.len);
809+
size_t safe_len = strnlen((const char*) attr.bufptr, attr.len);
810+
be_pushnstring(vm, (const char*) attr.bufptr, safe_len);
790811
be_return(vm);
791812
}
792813

@@ -838,10 +859,12 @@ static int m_add(bvm *vm)
838859
case -1: /* fallback below */
839860
case 1: buf_add1(&attr, v); break;
840861
case 2: buf_add2_le(&attr, v); break;
862+
case 3: buf_add3_le(&attr, v); break;
841863
case 4: buf_add4_le(&attr, v); break;
842864
case -2: buf_add2_be(&attr, v); break;
865+
case -3: buf_add3_be(&attr, v); break;
843866
case -4: buf_add4_be(&attr, v); break;
844-
default: be_raise(vm, "type_error", "size must be -4, -2, -1, 0, 1, 2 or 4.");
867+
default: be_raise(vm, "type_error", "size must be between -4 and 4.");
845868
}
846869
be_pop(vm, argc - 1);
847870
m_write_attributes(vm, 1, &attr); /* update attributes */

tests/bytes.be

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,3 +349,8 @@ assert(b.appendb64(c, 2) == bytes("AABBCC49673D3D"))
349349
b = bytes("AABBCC")
350350
assert(bytes().fromstring(bytes("11").tob64()) == bytes('45513D3D'))
351351
assert(b.appendb64(c, 1, 1) == bytes("AABBCC45513D3D"))
352+
353+
# bytes assign 3-byte values
354+
b = bytes("1122")
355+
assert(b.add(0x334455, 3) == bytes('1122554433'))
356+
assert(b.add(0x334455, -3) == bytes('1122554433334455'))

0 commit comments

Comments
 (0)