feat(lsm): add str copy_n functions

lsm
Jef Roosens 2023-11-02 13:08:36 +01:00
parent afd18d3a37
commit 7a21bed2b2
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
2 changed files with 41 additions and 2 deletions

View File

@ -36,6 +36,17 @@ lsm_error lsm_str_init_zero(lsm_str **ptr);
*/
lsm_error lsm_str_init_copy(lsm_str **ptr, char *s);
/**
* Same as `lsm_str_init_copy`, except that it takes an additional argument
* specifying the length of the string to copy over. This can be used to more
* easily "cut" parts of a C-style string out into an LSM string.
*
* @param ptr pointer to store newly allocated pointer
* @param s string to copy into lsm string
* @param len length of string to copy
*/
lsm_error lsm_str_init_copy_n(lsm_str **ptr, char *s, uint64_t len);
/**
* Overwrite an existing lsm_str so it now represents the new provided string.
* The string pointer of the original object is free'd if needed. Ownership of
@ -52,10 +63,20 @@ void lsm_str_overwrite(lsm_str *str, char *s);
* string is copied, leaving the original untouched.
*
* @param str lsm_str object to modify
* @param s string to convert into lsm string; ownership is taken over
* @param s string to copy into lsm string
*/
lsm_error lsm_str_overwrite_copy(lsm_str *str, char *s);
/**
* Same as `lsm_str_overwrite_copy`, except the length is explicitely specified,
* allowing you to easily "cut" parts of a C string out into an LSM string.
*
* @param str lsm_str object to modify
* @param s string to copy into lsm string
* @param len length of the string to copy
*/
lsm_error lsm_str_overwrite_copy_n(lsm_str *str, char *s, uint64_t len);
/**
* Deallocate the existing internal string if needed and replace the lsm_str
* with a string of length 0, wiping its contents. This function can be used as

View File

@ -47,6 +47,20 @@ lsm_error lsm_str_init_copy(lsm_str **ptr, char *s) {
return lsm_error_ok;
}
lsm_error lsm_str_init_copy_n(lsm_str **ptr, char *s, uint64_t len) {
lsm_str *str = calloc(1, sizeof(lsm_str));
if (str == NULL) {
return lsm_error_failed_alloc;
}
lsm_str_overwrite_copy_n(str, s, len);
*ptr = str;
return lsm_error_ok;
}
void lsm_str_overwrite(lsm_str *str, char *s) {
str->len = strlen(s);
@ -59,8 +73,10 @@ void lsm_str_overwrite(lsm_str *str, char *s) {
}
lsm_error lsm_str_overwrite_copy(lsm_str *str, char *s) {
str->len = strlen(s);
return lsm_str_overwrite_copy_n(str, s, strlen(s));
}
lsm_error lsm_str_overwrite_copy_n(lsm_str *str, char *s, uint64_t len) {
if (str->len <= 8) {
memcpy(str->data.val, s, str->len);
} else {
@ -74,6 +90,8 @@ lsm_error lsm_str_overwrite_copy(lsm_str *str, char *s) {
str->data.ptr = buf;
}
str->len = len;
return lsm_error_ok;
}