5 ms·
How 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?
by orf 5y ago
How 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