josephg / librope

UTF-8 rope library for C
Other
274 stars 26 forks source link

Allow extracting substrings #6

Open braddabug opened 6 years ago

braddabug commented 6 years ago

I see the rope_write_cstr() function, which extracts the entire string, but it'd be nice to be able to extract substrings. Something like this:

size_t rope_write_subcstr(rope *r, size_t pos, uint8_t *dest, size_t destByteLen);

josephg commented 6 years ago

That'd be good... sizes are interesting there - do you want a specific number of bytes? Of characters (with a byte limit)?

Anyway, its a good idea. Feel free to make a PR.

braddabug commented 6 years ago

To me, the "pos" parameter should be a character position, like the rest of the API (right?). I'm not sure about the return value, though. I could see different situations where I'd want the number of characters written, and other times the number of bytes written. And I left out the parameter that defines how many characters to copy. Let's try this:

size_t rope_write_subcstr(rope *r, size_t pos, size_t numChars, uint8_t *dest, size_t* destByteLen);

This returns the number of characters written, and also writes the number of bytes written into destByteLen. It would avoid writing partial characters to the buffer if they won't fit, and make sure it always writes an ending 0 byte (assuming the length of the buffer isn't 0).

An alternative, to avoid in/out parameters:

struct rope_substr_result
{
   size_t totalChars;
   size_t totalBytes;
};
rope_substr_result rope_write_subcstr(rope *r, size_t pos, size_t numChars, uint8_t *dest, size_t destByteLen);

I can't think of a super clean way of getting both bytes written and chars written.