Chrinkus / libcgs

A C library of data structures and algorithms
MIT License
1 stars 0 forks source link

Vector and String need Splice functions #17

Open Chrinkus opened 1 year ago

Chrinkus commented 1 year ago

My initial thought is that you provide a read-only source, a start index, an end index, and a writable destination. The indexes will be [start, end) as per most uses of indexes. The user can use -1 for "to the end". Here's the signature:

void*
cgs_vector_slice(const struct cgs_vector* src, size_t beg, size_t end, struct cgs_vector* dst);

This will return 'dst' on success and NULL on any kind of failure. And a typical use:

struct cgs_vector v1 = cgs_vector_new(sizeof(int));
// fill vector with 10 goodies
struct cgs_vector v2 = cgs_vector_new(sizeof(int));
assert(cgs_vector_slice(&v1, 5, -1, &v2);

Usability concerns:

Chrinkus commented 1 year ago

Slice vs Splice vs Sub

I have struct cgs_strsub for "slices" of a string, perhaps the equivalent for vectors should be a struct vecsub? A non-owning view into a vector. Maybe.

As for my initial need, that being AoC 2022 day 5, it seems a splice function is more appropriate. This would allow me to remove and replace multiple elements if I wanted.

void*
cgs_vector_splice(struct cgs_vector* v, size_t beg, size_t end, struct cgs_vector* reps);

The replacements parameter could be NULL to just cut out the range and be done.