Skip to content

Commit

Permalink
lib: Add buffer truncate
Browse files Browse the repository at this point in the history
  • Loading branch information
cmouse authored and GitLab committed Nov 2, 2016
1 parent fb9b991 commit e07b8f0
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/lib/buffer.c
Expand Up @@ -358,3 +358,28 @@ void buffer_verify_pool(buffer_t *_buf)
i_assert(ret == buf->w_buffer);
}
}

void buffer_truncate_rshift_bits(buffer_t *buf, size_t bits)
{
/* no-op if it's shorten than bits in any case.. */
if (buf->used * 8 < bits) return;

if (bits > 0) {
/* truncate it to closest byte boundary */
size_t bytes = ((bits + 7) & -8U)/8;
/* remainding bits */
bits = bits % 8;
buffer_set_used_size(buf, I_MIN(bytes, buf->used));
unsigned char *ptr = buffer_get_modifiable_data(buf, &bytes);
/* right shift over byte array */
if (bits > 0) {
for(size_t i=bytes-1;i>0;i--)
ptr[i] = (ptr[i]>>(8-bits)) +
((ptr[i-1]&(0xff>>(bits)))<<bits);
ptr[0] = ptr[0]>>(8-bits);
}
} else {
buffer_set_used_size(buf, 0);
}
}

25 changes: 25 additions & 0 deletions src/lib/buffer.h
Expand Up @@ -121,4 +121,29 @@ buffer_get_used_size(const buffer_t *buf)
buffer needs to be increased. */
void buffer_verify_pool(buffer_t *buf);

/* This will truncate your byte buffer to contain at most
given number of bits.
1 bits: 01 00000001
2 bits: 03 00000011
3 bits: 07 00000111
4 bits: 0f 00001111
5 bits: 1f 00011111
6 bits: 3f 00111111
7 bits: 7f 01111111
8 bits: ff 11111111
9 bits: 01ff 0000000111111111
10 bits: 03ff 0000001111111111
11 bits: 07ff 0000011111111111
12 bits: 0fff 0000111111111111
13 bits: 1fff 0001111111111111
14 bits: 3fff 0011111111111111
15 bits: 7fff 0111111111111111
16 bits: ffff 1111111111111111
and so forth
*/
void buffer_truncate_rshift_bits(buffer_t *buf, size_t bits);

#endif

0 comments on commit e07b8f0

Please sign in to comment.