Hello folks,
I normally wouldn't bother you guys with silly things but I figured if y'all are
wasting time answering Ryanc's questions, maybe you're having a slow weekend
and won't mind the distraction.
I Need to shave two lines off this function, to bring it down to the required 25
line limit I have to follow. Normally I would just cut some statements and create
a helper function but I happen to be at the function limit for this translation
unit -five, in case you're wondering- and I rather not create another source file
just for this function. Besides, I need the function to be "inlineable"
and I can't include another definition in a header, so it *must* be
in this source file.
It's been a long day and I can't see any other way to shorten the code. Do you see
something obvious I'm missing?
Thanks!
PS: Can't initialize variables during declaration and can't change the coding
style. Can't use multiline macros either, and the max line limit is 80 columns.
Also, I rather not compress everything into one loop as that slows down
the encoding significantly. The compiler can't unroll the loop since it doesn't
know the value of size.
Code:
#define SHIFT_BYTES 3
#define READ_BUFFER SHIFT_BYTES
#define FIRST_SEXTET 26
#define SECOND_SEXTET 20
#define THIRD_SEXTET 14
#define FOURTH_SEXTET 8
#define SEXTET_MASK 0x3f
#define SEXTET 6
static inline void encode64
(char *encoded, const char *stream, unsigned int size, unsigned int padding)
{
unsigned int shift_count;
uint32_t word;
while (size >= sizeof(word))
{
word = *(uint32_t*)(void*)stream;
word = reverse_byte_order(word);
*encoded++ = b64_alphabet[(word >> FIRST_SEXTET)];
*encoded++ = b64_alphabet[(word >> SECOND_SEXTET) & SEXTET_MASK];
*encoded++ = b64_alphabet[(word >> THIRD_SEXTET) & SEXTET_MASK];
*encoded++ = b64_alphabet[(word >> FOURTH_SEXTET) & SEXTET_MASK];
stream += READ_BUFFER;
size -= READ_BUFFER;
}
word = 0;
shift_count = SHIFT_BYTES;
while (size--)
word |= *stream++ << (shift_count-- << 3);
size = (shift_count != SHIFT_BYTES ? 1 + (SHIFT_BYTES - shift_count) : 0);
shift_count = FIRST_SEXTET;
while (size--)
{
*encoded++ = b64_alphabet[(word >> shift_count) & SEXTET_MASK];
shift_count -= SEXTET;
}
while (padding--)
*encoded++ = '=';
}