jwerle / b64.c

Base64 encode/decode
MIT License
269 stars 103 forks source link

should b64_buf_realloc be thread safe? #28

Closed yuridiniz closed 1 year ago

yuridiniz commented 3 years ago

buffer.c solved a problem that I was having with reallocs when doing a stress test, I'm not sure what the problem was, but it doesn't happen anymore 👍. So, I was looking at the implementation, and I believe that we may have problems when dealing with multhread application.

The buffer control variable is in a global context, which can cause problems between threads generating base64 at the same time and need different buffer sizes.

I thought if it would be interesting if the variable bufc stayed in the scope of the method, or, the buffer was a struct that would contain the information from the buffer.

I believe the simplest implementation would be something like:

int b64_buf_malloc(char * buf);
char* b64_buf_realloc(unsigned char* ptr, size_t size, int * buf_size);

Or

typedef struct buffer {
     char * ptr;
     int bufc;
} buffer_t;

buffer_t * b64_buf_malloc();
void b64_buf_realloc(buffer_t * buffer , size_t size);

I can act on it if it is an acceptable solution.

jwerle commented 3 years ago

@yuridiniz yeah go for it! I think I'd like to come back to this sometime in the near future and make this API enforce the caller to allocate memory. This should help those who want to manage their own memory (arenas, pools, etc), reuse contiguous memory available to them, or manage boundaries and locks for memory pointers this library may read from or write to