Fixing C Strings with String Views
I have always been frustrated about C not having a proper String type that most modern
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
I have always been frustrated about C not having a proper String type that most modern languages have nowadays. I love the simplicity of C, but there are some features that I would really like to have in it, and this is one of them.
Since I made a small library (just one .c file) that you can use to make the experience of working with strings in C just a little better, I would like to show it to you here.
For the impatient, this is the general idea:
struct str_view { const u8 *data; usize len; };
struct str_owned { u8 *data; usize len; };
But before getting into the library itself, I will go over how “strings” work in C and why I find them annoying, what the issues are with this model, and then it will be easier to explain why I decided to take the route that I took.
If you only care about the actual implementation details, you can click here.
As many might already know, strings in C are NUL-terminated. NUL is an ASCII character which, in the context of ASCII encoding, literally corresponds to the value 0. In C, this character is represented by '\0'. Inside a text, it generally does not carry any semantic meaning, so it will never be used inside the text for the sake of carrying information (as opposed to letters like 'a' or 'y').
C does not really have “strings” per se. It only has arrays. These arrays are simply chunks of data where you can put things. To understand where the array ends, one has two options:
Since “strings” (which are not really strings) in C are simply arrays of characters, each string has a NUL-terminator at the end of it.
C is a very old language and back then - when it was first created - this seemed like a good idea.
Storing the length of the data separately required more memory than a NUL-character at the end. A NUL-character in ASCII encoding is 8 bits (or 1 byte). If you tried to store the length of the data in only 8 bits, you could only have strings that are up to 255 characters in length, which is obviously too short. Bigger numbers require more data to store, so we’re talking about around 4 to 8 bytes instead of 1.
But this is not even the main reason - the main reason is because of simplicity. Back when C was created, there existed some languages that already had strings with a separately stored length. C just wanted to be as simple as possible, and having NUL-terminated character arrays seemed like a sane decision.
First of all, if you want to find out the length of a string, with a NUL-terminated string you have to start at index 0 and start counting until you reach the end of the data. This process has a time complexity of O(n)O(n)O(n), as opposed to O(1)O(1)O(1) for just reading the separately stored length.
This is fine for short character arrays, but imagine you had to figure out the length of a 1,000,0001,000,0001,000,000 character text. That would take a considerable amount of CPU cycles that could have been used for something else.
This bothers me especially in a language like C, since it is supposed to give you some of the best performance that programming languages have to offer (without counting assembly and certain exceptions in some specific scenarios). C is often the baseline when comparing languages to gauge their relative performance. Why, if C focuses so much on performance, would you settle for this?
Let us assume that we have some C-string some_str:
char *some_str = "Hello World";
This is great, but now I would like to work with the second word specifically (World). I do not care about changing the data, just about reading. Maybe I want to pass it to a function or something. Well, I could do something like this:
char *only_world = some_str + 6;
By doing this, we are reusing the NUL-terminator that some_str was using to terminate itself.
Fine, what if I want to access the first word only, though? Now we have a problem. We somehow have to end the string at the fifth index. To do that, we would have to insert a NUL-character at index 6. By doing so, we are changing the data that some_str is pointing to, and we can therefore not use that variable anymore.
So, what do we do? We have to copy the string. That’s slow, since it involves memory lookups. We have to allocate to memory, and then copy it. We can also use the stack if we know the size of the data at compile time, but that is often not the case. That would look like this:
char *only_hello = malloc(6); memcpy(only_hello, some_str, 5); only_hello[5] = 0;
In this simple example, the stack would have been fine, but in most realistic scenarios, we have to use heap allocations.
This problem is solved by so-called “string views”, which are basically immutable data and a length. You can just give the string view the same pointer as some_str and decrease the length to whatever you need, 5 in this case.
God forbid you forget to NUL-terminate a string. If you pass a pointer to a non-NUL-terminated string to a function in string.h, like strlen, the computer will just keep counting characters until it either randomly finds a NUL-character or - alternatively - until it tries to access a region of memory that it should not touch and the operating system kills the process.
This generally does not happen with actual strings (or string views), since you will use functions to interact with them, and they always keep the length of the string in sync with the data. In that case you always know when the string stops, you do not have to rely on remembering to NUL-terminate all your strings.
There are probably more issues, but these are hopefully enough to convince you. In general, I find strings with a separately stored length more intuitive and easier to work with.
Luckily, strings are not particularly hard to implement in C. Here is how I did it.
Just so you are aware when reading the code, I typedef some basic types in C before I start coding. In this case we will only need a few of them, but this is what I paste at the start of every project of mine.
#include <stdint.h> #include <stdbool.h> #include <stddef.h>
typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64;
typedef int8_t i8; typedef int16_t i16; typedef int32_t i32; typedef int64_t i64;
typedef float f32; typedef double f64;
typedef size_t usize;
This makes it more convenient to use the integer types with a fixed size instead of the older int, long, long long, etc.
I generally prefer this since int is not the same size on all platforms. int32_t on the other hand is guaranteed to be exactly 32 bits.
For your information, I have adapted this library to be compatible with my arena implementation. It can be found in the same repository as this string library. I have an article about it here if you would like to read up on that.
What you need to know is that each function that needs to allocate some memory receives a struct arena * as its first argument. Instead of malloc and realloc I use arena_alloc and arena_realloc respectively.
First, let’s define our string types. I don’t prefer not to typedef structs, but if you want to you can do so. If you do decide to typedef these structs, I would advise you to use PascalCase as a naming convention (to better differentiate them from built-in types).
struct str_view { const u8 *data; usize len; };
struct str_owned { u8 *data; usize len; };
As you can see, we have two string types: struct str_view and struct str_owned. The difference is that struct str_owned owns the data, and the data can also be changed. Ideally, you should try to only have one str_owned pointing at any given region in memory.
On the other hand, struct str_view should be used as read-only views of a given region of data. It should not be used to modify the data.
Separating these two concerns is nice for multiple reasons. Who owns the data becomes clear immediately. This is especially useful when returning string structs from functions. By using this model, it is easier to understand whether we need to concern ourselves with freeing data or something similar.
As a general rule of thumb, struct str_owned are heap-allocated. If you have a struct str_view viewing some region in memory owned by a struct str_owned, that string view is only valid as long as the underlying owned string is still valid. That means that you have to be careful about not freeing the struct str_owned and after that still using string views that view that data.
Also, you might have noticed that I am using u8s (a.k.a. uint8_ts) instead of chars. That is because, technically - even though in almost all cases it does not matter - chars are not guaranteed to have a size of exactly 8 bits. On certain embedded systems, a char is sometimes 16 or 32 bits large. On very old systems, they used to be 9 bits. This has historical reasons. A char is simply guaranteed to have a size of one byte, but the exact size of a byte is not clearly defined as a definitive size in bits. Knowing all that, using u8 is more consistent across platforms.
As a side note, this is also the reason why the CHAR_BIT macro exists. It tells you how many bits are in a char on the system that the code is run. That is because the size of a char depends on the system that you are currently on.
Also, I do not really like using a redundant type. A u8 holds all the semantic information I need, so u8 it is.
Next, we create some macros. I try to minimize the use of macros, but in certain cases they are just perfect for the job. I believe that this is one of them.
Mainly I care about the STR macro, that I use to easily create a struct str_view out of a char * literal.
#define LENGTHOF(s) (sizeof(s) / sizeof(*s)) #define STR(s) (struct str_view){(const u8 *)s, LENGTHOF(s) - 1} #define STR_PRINT(s) (i32) s.len, s.data
STR_PRINT is used to print a struct str_view. You can use the %.*s format specifier to manually give it the length of the string to be printed (since string views are not guaranteed to be NUL-terminated, since they can view a region of memory in the middle of a struct str_owned). This can be done as follows:
printf("Here is my string: %.*s\n", STR_PRINT(STR("some_string")));
Here you can also see the STR macro in action, which creates a struct str_view on the fly from a char * literal.
Since my implementation uses memory arenas, there is no need to free an owned string specifically, but if you would like to move away from arenas you can always create a simple wrapper function that calls free on the data field of an owned string.
We need some way to convert between struct str_view and struct str_owned and back. Converting an owned string to a string view is trivial; you simply use the same pointer and length of the owned string in a struct str_view:
[[nodiscard]] struct str_view str_owned_to_str_view(struct str_owned s) { struct str_view str_out = {0}; str_out.data = s.data; str_out.len = s.len; return str_out; }
Also, as you might have noticed, I like using [[nodiscard]]. This is a compiler directive which makes the compiler issue a warning if the return value of the function flagged with this directive is disregarded. In scenarios like this one I find it to be very useful, since it is completely useless to call this function if you are not going to do anything with the result.
We also need to convert string views to owned strings. This is a bit more tricky and should not be done unless strictly necessary, since it requires memory allocation. An owned string can be mutated, which means that we have to give it its own region in memory to avoid damaging other owned strings that might be using the same memory (recall when I said that we should try to avoid having multiple owned strings on the same chunk of memory).
struct str_view_to_str_owned_out { struct str_owned str; bool success; }; [[nodiscard]] struct str_view_to_str_owned_out str_view_to_str_owned( struct arena *arena, struct str_view s ) { struct str_view_to_str_owned_out out = {0}; struct arena_alloc_out alloc_
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。
