patterncMinor
Byte Stream implementation in C
Viewed 0 times
byteimplementationstream
Problem
This is a byte stream implementation in C. Its usage and purpose should be evident from main.
Implementation is not finished; this is just start. Comments are still welcome.
.h:
.c:
main
Implementation is not finished; this is just start. Comments are still welcome.
.h:
#include
typedef struct
{
uint8_t * data;
uint32_t length;
uint32_t offset;
} ByteStream;
int32_t BSInitWithSize(ByteStream *bs, uint32_t len);
uint32_t BSNrOfRemainingBytes(ByteStream *bs);
int32_t BSFreeUnderlyingArray(ByteStream *bs);
void BSPrintContents(ByteStream *bs);
void BSRewind(ByteStream *bs);
int32_t BSPutU8(ByteStream *bs, uint8_t v);
int32_t BSGetU8(ByteStream *bs, uint8_t *out);
int32_t BSPutU16LE(ByteStream *bs, uint16_t v);.c:
#include "ByteStream.h"
#include
#include
#include
int32_t BSInitWithSize(ByteStream *bs, uint32_t len)
{
if (NULL == bs)
return -1;
// Allocate data array of sufficient length
bs->data = (uint8_t*)malloc(len); // Note: Probably should check return value here
memset(bs->data,0,len); // set values to nil
bs->length = len;
bs->offset = 0;
return 0;
}
uint32_t BSNrOfRemainingBytes(ByteStream *bs)
{
return bs->length - bs->offset;
}
void BSRewind(ByteStream *bs)
{
bs->offset=0;
}
int32_t BSPutU8(ByteStream *bs, uint8_t v)
{
if(BSNrOfRemainingBytes(bs)data[bs->offset]=v;
bs->offset++;
return 0;
}
int32_t BSGetU8(ByteStream *bs, uint8_t *out)
{
if(BSNrOfRemainingBytes(bs)offset++;
*out= bs->data[bs->offset-1];
return 0;
}
int32_t BSPutU16LE(ByteStream *bs, uint16_t v)
{
if(BSNrOfRemainingBytes(bs)data[bs->offset],&v,2);
bs->offset+=2;
return 0;
}
void BSPrintContents(ByteStream *bs)
{
int i = 0;
for(i=0; ioffset; i++)
{
printf("%02X ",bs->data[i]);
}
}
int32_t BSFreeUnderlyingArray(ByteStream *bs)
{
// Free underlying data array of BS object if it is not NULL
if(NULL != bs->data)
{
free(bs->data);
bs->data=NULL; // Set to NULL
return 0;
}
return -1;
}main
Solution
A few things:
- You are casting the result of your calls to
malloc. That is something you shouldn't do actually.
- If possible, try not to used fixed-size integer types (
uint32_t,int32_t, etc...) for they are only conditionally supported by the compiler. For example, I doubt that you need a fixed-size type for your error codes. At least, useint_least32_tinstead.
- When you are not using any format string, you should consider using
putstoprintf(e.g.puts("---")instead ofprintf("---\n"). That's both shorther and safer.
- Also, you initialize
ito0twice inBSPrintContents. That seems pretty useless.
Context
StackExchange Code Review Q#45302, answer score: 6
Revisions (0)
No revisions yet.