UTF-8 strings: the view that borrows and the string that owns.
UTF-8 strings: the view that borrows and the string that owns.Banjo carries text in two types. The view, bj_str, is a borrowed pointer and a byte count: it measures nothing, owns nothing, and is the type every reading API of the text stack takes. The owning string, bj_string, validates its bytes once, replaces every ill-formed sequence with U+FFFD, and lets everything downstream trust what it holds. This example walks the two of them in order.
int main(
int argc,
char* argv[]) {
(void)argc; (void)argv;
bj_info(
"The slice at 7..12 spans %zu bytes", word.
len);
bj_info(
"The two spellings of cafe: %zu and %zu bytes, equal: %s",
precomposed.
len, decomposed.
len,
bj_str_eq(precomposed, decomposed) ?
"yes" :
"no");
static const char bytes[] = "\xC3\xA9\xE0\x80\x41";
const bj_str damaged = { bytes, 5 };
if (text == NULL) {
bj_err(
"Out of memory building the string");
return 1;
}
bj_info(
"The string holds %zu bytes, and cstr reads \"%s\"",
return 0;
}
#define bj_info(...)
Log a message using the BJ_LOG_INFO level.
#define bj_err(...)
Log a message using the BJ_LOG_ERROR level.
size_t len
Number of bytes in the view.
#define BJ_STR(literal)
Create a view of a string literal.
const char * bj_string_cstr(const struct bj_string *string)
Get a NUL-terminated pointer to an owning string.
bj_bool bj_str_eq(struct bj_str left, struct bj_str right)
Compare two views byte by byte.
struct bj_string * bj_create_string(struct bj_str initial)
Create an owning string from a byte view.
struct bj_str bj_string_view(const struct bj_string *string)
Get a borrowed view of an owning string.
struct bj_str bj_str_slice(struct bj_str view, size_t from, size_t to)
Create a view of a byte range within another view.
struct bj_str bj_str_from_cstr(const char *c_string)
Create a view from a NUL-terminated C string.
void bj_destroy_string(struct bj_string *string)
Destroy an owning string and release its memory.
void bj_append_string(struct bj_string *string, struct bj_str tail)
Append bytes to an owning string.
A borrowed view of a sequence of bytes.
An owning string containing valid UTF-8.
Logging utility functions.
Portable main() replacement with platform-aware entry shim.
UTF-8 string views and owning strings.