Search code examples
clibevent

Changing a byte in an evbuffer


I have a libevent struct evbuffer that at one point in the program I write to it, and later on I might need to get back to what I wrote and change a single byte from '1' to '0'.

In order to do that I'd ideally like to have a pointer to that byte.

What would be the best way to get to that byte (either by getting its address right after writing it, or by knowing the offset), and how can I update it so that I can be sure that's the actual byte and not a copy of it libevent made when it fetched it for me?

Code example per Fiddling Bits' request:

struct evbuffer* buf = evbuffer_new();
evbuffer_add(buf, "abc1def", 7);

// What I'd like to achieve:
char *byte = evbuffer_get_by_offset(buf, 3, 1); // Get one character, offset of 3
*byte = '0'; // buf now holds "abc0def"

Solution

  • Setting aside the question of whether this should be done or not, here's a way to achieve this using evbuffer_iovec and evbuffer_peek:

    size_t offset = 3;
    
    struct evbuffer_ptr pointer;
    evbuffer_ptr_set(buf, &pointer, offset, EVBUFFER_PTR_SET);
    
    struct evbuffer_iovec vec;
    int num_of_vecs = evbuffer_peek(buf, 1, &pointer, &vec, 1);
    assert(num_of_vecs == 1);
    
    *(char *)(vec.iov_base) = '0';