3 ms·
> The only advantage of this representation is space efficency. Ignorant nonsense. There are other advantages. Advantage: If s is a non-empty string, then s +
by kazinator 8y ago
> The only advantage of this representation is space efficency.
Ignorant nonsense. There are other advantages.
Advantage: If s is a non-empty string, then s + 1 is the rest of that string. s + 1 is an extremely cheap operation: incrementing a pointer.
This allows recursion on strings. For instance, strchr can be coded like this:
char *strchr(const char *s, int ch)
{
if (*s == ch) /* including ch == 0 case */
return s;
if (*s)
return strchr(s + 1, ch); /* tail call */
return NULL;
}
A variety of useful algorithms can be implemented in this simultaneously elegant and efficient manner.
Advantage: null terminated strings can use exactly the same external representation as internal. They can be sent over the network as-is or written to files. There is no question of what format is this header, how wide is this length field and so on. Strings of wide characters just have a simple issue: how wide (16 or 32), and what endian.
- saagarjha 8y agoOf course, most actual strchr implementations tend to be heavily vectorized hand-tuned assembly with macros to select the correct streaming extension supported by the hardware. Or, for less powerful systems, something like char *strchr(const char *s, int ch) { char *p = s; while (*p && *p != chr); return p; }
- kazinator 8y agos/less powerful systems/systems with lesser compilers/ With TCO, I'd expect the same code from the recursive version. The recursive version has the benefit of being pure; it doesn't mutate anything. Speaking of which, HN ate your ++.
- viraptor 8y ago> There is no question of what format is this header, how wide is this length field and so on. It's not that simple. You either have forbidden characters then, or escaping - and with the latter you don't know how wide the content is. Null-termination in fields is a common security issue.
- kazinator 8y agoForbidden characters can occur in other string representations, like length + data. Escape sequences are higher level syntax being represented by the string; they don't belong in the string representation. A transfer encoding like UTF-8 isn't a string representation either. Manipulation of syntaxes and encodings stored in character strings can be buggy. The representation does contribute to the risk. E.g. if a UTF-8 decoder doesn't reject overlong forms, then a null character can be encoded in the middle of the data so that to the buggy function or program, it looks like a different string from one that was validated earlier.
- dagenix 8y ago> Ignorant nonsense. I could do without that - it's hardly constructive.