3 ms·
What's wrong with null termination? No, seriously. It's much cleaner than wasting an argument, hence CPU register, for a second pointer. Or heavens forbid, two
by Bancakes 5y ago
What's wrong with null termination? No, seriously. It's much cleaner than wasting an argument, hence CPU register, for a second pointer. Or heavens forbid, two size_t length and capacity counters.
- humanrebar 5y agoOther than the usual arguments [1], I just said that it causes contamination of other APIs. That's a big problem because string is a "vocabulary type". It is passed around across various libraries within a given process constantly. There should be a lot of convergence on vocabulary types to avoid copying string data around incessantly. Null terminated strings are a poor choice to converge on for high level application code in particular. It's just an inefficient (expensive substrings, redundant length calculation, unclear ownership) and unsafe default for too many use cases. I don't mind certain performance sensitive applications using C strings to avoid extra registers, though even that is a premature optimization in certain situations. [1] See Limitations: https://en.m.wikipedia.org/wiki/Null-terminated_string https://en.m.wikipedia.org/wiki/Null-terminated_string
- orf 5y agoHow do I pass a sub-slice of a source string to a function that expects a null terminated string without copying or modifying the source string?
- Bancakes 5y agoI don't understand the question. Sub-slices are not sub-strings. They are partially constructed objects. But I do get the problem.
- orf 5y agoThe question is the problem: how do you do zero-copy sharing of data contained within a string. You can’t unless you couple it with the length. In rust parlance a slice is a well defined type. There are also other reasons why having the length embedded in a string (or a string slice) is a good thing. You might want your “str_contains” function to do something different with different sized inputs: doing some vectorised lookup might only be worth it at a certain point, or if the length of the needle is greater than the haystack itself then there isn’t much point doing anything. NULL terminated strings are a huge mistake that brings in security issues, needless copying and inefficient code that might contain several redundant strlen calls at different levels.
- astrange 5y agoCopying is almost always the right answer here. - you can't assume inline storage of the substring, which is more efficient, because that'd mean overwriting the parent string with a size field - you might free the parent string early unless you keep around a reference to it, which is more expensive - usually strings (esp. substrings) aren't that long, and for very long ones you can use a different data structure