view: added `sv_copy_to()`: copy a `view_t` to a nul-terminated buffer. (`snprintf()` for `view_t`)

Fortune for sink's current commit: Future small blessing − 末小吉
args
Avril 3 years ago
parent ac7ec87484
commit f12c1fffdd
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -2,6 +2,7 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <stdbool.h> #include <stdbool.h>
#include <limits.h>
#include "view.h" #include "view.h"
@ -74,16 +75,39 @@ static struct string_data* _s_data(char* str, bool check) {
} }
__attribute__((pure)) __attribute__((pure))
str_info_t s_get_info(sv_t str) str_info_t s_get_info(view_t str)
{ {
return _s_data($nullchk(str.ptr, return NULL), true); return _s_data($nullchk(str.ptr, return NULL), true);
} }
__attribute__((pure)) __attribute__((pure))
sv_t s_get_str(str_info_t data) view_t s_get_str(str_info_t data)
{ {
return (sv_t) { return (view_t) {
.len = data->len, .len = data->len,
.ptr = (unsigned char*)data->ptr, .ptr = data->ptr,
}; };
} }
__attribute__((cold))
static size_t _sv_copy_manual(size_t sz, char buffer[restrict static sz], view_t view)
{
size_t i=0;
for(;i< (sz-1) && i<view.len;i++)
{
buffer[i] = view.ptr[i];
}
buffer[i] = 0;
return view.len+1;
}
size_t sv_copy_to(size_t sz, char buffer[restrict static sz], view_t view)
{
if(__builtin_expect(view.len <= INT_MAX, true))
return (size_t)snprintf(buffer, sz, "%.*s", (int)view.len, view.ptr);
else {
// Manual implementation, for views longer than INT_MAX
//XXX: TODO: Ensure return value follows the same construct.
return _sv_copy_manual(sz, buffer, view);
}
}

@ -6,8 +6,8 @@
typedef struct string_view { typedef struct string_view {
size_t len; size_t len;
unsigned char* ptr; char* ptr;
} sv_t; } view_t;
struct string_data; struct string_data;
typedef struct string_data* str_info_t; typedef struct string_data* str_info_t;
@ -16,7 +16,10 @@ struct string;
// Functions // // Functions //
sv_t s_get_str(str_info_t data) __attribute__((pure)); view_t s_get_str(str_info_t data) __attribute__((pure));
str_info_t s_get_info(sv_t str) __attribute__((pure)); str_info_t s_get_info(view_t str) __attribute__((pure));
/// Copy `view` into nul-terminated `buffer`, up to `size` bytes. Return the number of bytes that would've been copied regardless of `sz` (incl. nul-terminator)
size_t sv_copy_to(size_t sz, char buffer[restrict static sz], view_t view);
#endif /* _VIEW_H */ #endif /* _VIEW_H */

Loading…
Cancel
Save