171 points · by dredmorbius · 5y ago · 240 comments
1. Length in the context of storage or transmission is the number of bytes of its UTF-8 representation - and not just that, one of its decomposed forms too.
2. Length in terms of number of visible characters is the number of grapheme clusters.
3. Length in terms of visible space on screen is the number of pixels wide and tall when rendered in a given font.
4. Length when parsing is based on the number of code points.
If you look at it that way it makes perfect sense that the “length” of a string could change when any operation is performed on it - because there’s no such thing as a canonical length.
tl;dr bug or not, the concept of a canonical string length is an anachronism from the pre-Unicode days when all those were the same thing. There’s no such thing as a string length anymore.
If you must expose the underlying byte array do so via a sane access function that returns a typed array.
As for “string length in pixels”, that has absolutely nothing to do with the string itself as that’s determined in the UI layer that ingests the string.
> Except almost everyone always means #2.
Until the string has to be stored in a database. Or transmitted over HTTP. Or copy-pasted in Windows running Autohotkey. Or stored in a logfile. Or used to authenticate. Or used to authorize. Or used by a human to self-identify. Or encoded. Or encrypted. Or used in an element on a web page. Or sent in an email to 12,000,000 users, some of whom might read it on a Windows 2000 box running Nutscrape. Or sent to a vendor in China. Or sent to a client in Israel. Or sent in an SMS message to 12,000,000 users, some of whom might read it on a Nokia 3310. Or sent to my exwife.String length when defined #2 is also fairly complex when it comes to some languages such as Hindi. There are some symbols in Hindi which are not characters and can never exist as their own character but when placed next to a character they create a new character. So when you type them out on a keyboard you have to bit two keys but only one character will appear on screen. Unicode too represents this as two separate characters but for human eye it is one.
त + या = त्या
Following code will print 4
console.log("त्या".length);
And half the things on your list are just places that Unicode itself might fail, regardless of what the length is? That has nothing to do with how you count, because the number you get won't matter.
Except for the, what, 80% of the world's population who use languages that can't be written with ASCII.
The real statement is that no one asked a few self-chosen individual who have never travelled beyond their own valley to ruin text handling in computers like the American Standard Code for Information Interchange has.
[0] ttps://www.reference.com/world-view/percentage-world-speaks-english-859e211be5634567
In database or more subtly various filesystems code the notion of bytes or codepoints might be more relevant.
By the way, what about ASCII control characters? Does carriage return have some intrinsic or clearly well defined notion of „length“ to you?
What about digraphs like ij in Dutch? Are they a singular grapheme cluster? Is this locale dependent? Do you have all scripts and cultures in mind?
The reason this isn't an issue is because it's nearly impossible to think of a legit use case.
But that's because I was thinking about allocation, storage, etc. For logic traversing, comparing, and transforming strings #4 is certainly more useful.
Oh, but you said #2? I guess that is important since it's what the user will most easily notice.
Only those who think that the graphical part of an information system represents the whole of software development.
They only got ruined for people who could not realize that the word is bigger than their backyard.
I don't think this is true. Certainly there is no string-length library I'm aware of that handles it that way. The usual default these days (correct or not) is #4 -- length is the number of unicode code points.
The number of codepoints (which is almost always useless but what some languages return) is available through the unicodeScalars view.
The number of code units (what most languages actually return, and which can at least be argued to be useful) is available through the corresponding encoded views (utf8 and utf16 properties)
$string.encode('UTF-8').bytes; #1
$string.chars; #2
$string.codes; #4
https://course.raku.org/essentials/strings/string-length/Though this was technically correct in 2019, meanwhile the Raku Programming Language has continued to evolve, de-emphasizing its heritage more and more. For example, Covid restrictions allowing, 2022 will see the first European Raku Conference.
Their point is that they would expect number of visble grapheme clusters to be the same when converting between cases. But in some languages that's not true, as their example demonstrates. (An upper case ß does exist in Unicode but culturally it's less correct than SS.)
5. Length in terms of time until complete display when rendered in a given architecture.
6. Length in terms of Braille characters needed to display it.
7. Length in terms of time of lecture at 300 wpm.
String length is overwhelmingly discussed as character length, meaning #2. Length in bytes should only be an issue for data transmission or storage, and people who still work with ASCII. Rendering dimensions are not relevant to the published article.
They don't have a proper concept of characters and diacritics count as a character, not as an accent so you have verticality in a string!
I've come to respect the unicode spec as something with a lot of inherent complexity that you have to understand to work with. Your inner voice will scream "there has to be a better way" all the way through the project, but there actually isn't, you just have to accept that human language and writing is complex and representing it in software is equally complex.
Grasping at straws eh?
There's a fun subtlety in this case too: a single grapheme cluster need not draw as a single "visible character" (or glyph) on-screen. The visual representation of a grapheme cluster is entirely dependent on the text system which draws this, and the meaning that system applies to the cluster itself. This is especially true for multi-element emoji clusters, whose recommended meanings[1] change with evolving versions of Unicode.
To add to this, Unicode 12 simplified the definition of grapheme clusters by actually generalizing them so that they can be matched effectively by a regex. (See the "extended grapheme cluster" definition in TR29[2].) This reduced the overall number of special cases and hard-coded lists of combinations in the definitions of grapheme clusters (particularly around emoji), but it also means that there are now infinitely more valid grapheme clusters that don't necessarily map to a single glyph.
One really simple example of this is, e.g.
©
(Edit: it appears that HN is actually stripping out the ZWJ text from this example and leaving just the Copyright symbol. See below for how to reproduce this text on your machine.)That is,
U+1F434 <horse head> + U+200D <zero width joiner> + U+00A9 <copyright sign>
This cluster trivially matches the definition of extended grapheme cluster := crlf | Control | precore* _core_ postcore*
core := hangul-syllable | ri-sequence | xpicto-sequence | [^Control CR LF]
xpicto-sequence := \p{Extended_Pictographic} (Extend* ZWJ \p{Extended_Pictographic})*
where U+1F434: Extended_Pictographic
U+200D: ZWJ
U+00A9: Extended_Pictographic
(I picked this combination somewhat randomly, but ideally, this is an example that should hopefully last as it feels unlikely that "horse copyright" would have a meaningful glyph definition in the future. As of posting this, the above text shows up as two side-by-side glyphs on my machine (macOS Monterey 21A559): a horse, followed by the copyright sign. This may look similar on your machine, or it may not.)Importantly, you can tell this is actually treated as a real grapheme cluster by the text system on macOS because if you copy that string into a Cocoa text view (e.g., TextEdit), you will only be able to place your cursor on either side of the cluster, but not split it in the middle. A nice interactive way to see this in action is inserting U+1F434 into the document, followed by U+00A9. Then, move your cursor in between those two glyphs and insert U+200D: your cursor should then bounce out from the middle of the newly-formed cluster to the beginning.
This was a pretty short example, but this is arbitrarily extensible: (Edit: Originally I had posted U+2705 <check mark symbol> + U+200D + U+1F434 <horse head> + U+200D + U+1F50B <battery> + U+200D + U+1F9F7 <safety pin> [sorry, no staple emoji] but HN stripped that out too. It does appear correctly in the text area while typing, but HN replaces the sequence with spaces after posting.)
As linked above, Unicode does offer a list of sequences like this that are considered to be "meaningful"[1], which you can largely expect vendors which offer emoji representations to respect (and some vendors may offer glyphs for sequences beyond what is suggested here). If you've ever run into this: additions to this list over time explains why transporting a Unicode sequence which appears as a single glyph on one OS can appear as multiple glyphs on an older one (each individual glyph may be supported, but their combination may or may not have a meaning).
In general, if this is interesting to you, you may enjoy trawling through the Unicode emoji data files [3]. You may discover something new!
[1] https://www.unicode.org/Public/emoji/14.0/emoji-zwj-sequence... [2] https://www.unicode.org/reports/tr29/tr29-35.html#Table_Comb... [3] https://www.unicode.org/reports/tr51/#emoji_data
Makes me wonder how case insensitive file systems handle this...and for more fun, handle the situation where the user changes the system language. I know that the Turkish 'I' delayed at least one big company's Turkish localization efforts for awhile.
They generally don't. It is true that several case-insensitive file systems (including NTFS, exFAT and ext4 [1]) maintain some sort of configurable case-folding maps but they are mostly used to guard against the future Unicode update and do not vary across locales.
[1] https://dfir.ru/2021/07/15/playing-with-case-insensitive-fil... (ext4 supports an optional case insensitivity)
> They are included for compatibility and round-trip convertibility with legacy encodings, but their use is discouraged. Therefore, even with Unicode available, it is recommended to encode ij as two separate letters.
[1] https://eng.getwisdom.io/hacking-github-with-unicode-dotless...
It goes beyond just language... uppercasing can also be locale-dependent. In Microsoft Word, for example, uppercasing an "é" gets you "É" in the French (Canada) locale but "E" in the French (France) locale.
Just because the user changed the system language doesn't mean the system should be expected to change the upcase table though. That operation would need to be very carefully managed; you can't change the rules if there are existing files that would conflict in the new mapping. And you might have symbolic links that matched because of case insensitivity that won't anymore... Pretty tricky.
And of course there are widely recognized problems with time zones too.
https://en.wikipedia.org/wiki/Dotted_I_(Cyrillic)#Computing_...
You mean like language-dependent unified Han glyphs? [1]
[1] https://en.wikipedia.org/wiki/Han_unification#Examples_of_la...
Animated emojis probably aren't too far off the horizon, and I could definitely see a world where multiple glyphs could be combined to affect the animation much like we do for skin tone or the family emojis.
Sometimes I think we've gone too far.
Agreed from a technical standpoint. But also dont forget we have the poop emoji and the love-hotel.
identifier -- printable ASCII characters only, an array of 8-bit chars
ucs16 -- An array of 16-bit chars for compatibility with Windows, Java, and .NET
utf8 -- Normalised, 100% valid UTF-8 with potentially some "reasonableness" constraints
text -- Abstraction over arbitrary code pages, including both Unicode and legacy encodings.
Languages like Rust kinda-sorta implement this. For example, the PathBuf type internally uses a "WTF8" encoding that is vaguely Utf-8 compatible, but allows the invalid code sequences that can turn up in Win32 system API calls.IMHO that's a good try but not ideal. The back-and-forth conversion is complex, requires temporary buffers, and is slow as molasses for many types of API calls.
The ideal would be to have abstractions (traits, interfaces, whatever) that cover all the use-cases. E.g.: it should be possible to test if a 'utf8' string contains an 'identifier' string. It should be possible to compare strings without having to convert their formats. Etc...
# Simple indexed access (often an array, possibly an array of arrays)
raw / octets -- Not-classified sequence of raw bytes
# Fancy strings, which MAY be validated (but don't have to be), and MAY stay validated (if the operations are known to be simple enough), and MAY also have multiple types of index for speedy access to specific points by raw byte, unit run of encoded components, complete display units (a single displayed element), or even a cached last known render left bound on an output.
UTF-8 / WTF8 / UTF8 / ASCII -- A fancy string with octet components of possibly multi-byte (variable) length
UCS-2 / USC-16 / etc -- A legacy string encoding format that no one should use as it too is variable length but suffers from endien confusion in raw data storage.
In an object based language the latter two would probably use the first as a raw storage mechanism for the strings, while they'd also have some associated attributes for the desired encoding, if it's validated, how it is known to be normalized, and storage for different index aids.
Crucially the system libraries should have the same interface. If there isn't library support for converting / normalizing encoded text the results should always be raw octets. If library support is included then WTF8 should probably be the result target of any operations, possibly upgraded to UTF-8 if the results are theoretically still valid.
Just no. Maintaining compatibility with broken implementations that hold incorrect assumptions is not something that should be done. Especially not encoding it into some kind of standard.
Example
enum Commands {
kCOPY,
kCUT,
kPASTE,
}
class CopyCmd : Public Cmd { ... }
class CutCmd : Public Cmd { ... }
class PasteCmd : Public Cmd { ... }
Cmd* MakeCommand(Command cmd) {
switch (cmd) {
case kCut: return new CutCmd();
case kCopy: return new CopyCmd();
case kPaste: return new PasteCmd();
...
The fact that in some places it's COPY, in others Copy, and in probably others copy means work that would disappear if it was just always COPY. All of it superfluous work that someone from a language that doesn't have the concept of upper and lower case would never had even considered when come up with coding standards. Hey, I could just copy and paste this.... oh, the cases need to be fixed. Oh, I could code generate this with a macro.... oh, well, I've got to put every case form of the name in the macro so I can use the correct one, etc...a) Is your tooling not identifier aware? That removes the hassle from remembering the case correctly. And for the matter so does having a consistent standard...
b) When is capitalization ever the thing stopping you from copying and pasting some code?
Capitalization only differs if the semantic meaning differs. Like what's a specific example in your code where this is avoided:
> Hey, I could just copy and paste this.... oh, the cases need to be fixed. Oh, I could code generate this with a macro.... oh, well, I've got to put every case form of the name in the macro so I can use the correct one, etc...
when all the capitalization matches?
There are lots of cases where this conversion ends up causing all kinds of headaches, major and minor, just to keep everything matching the naming convention. Sure, you could choose to ignore the convention in this case but I've rarely seen a code base that does.
Whereas, if the languages had come from a culture with the language that doesn't have the concept of UPPER and lower case then these conventions might never have happened. You'd have maybe something like K_COPY_AND_GO, CLASS C_COPY_AND_GO, etc and copying and pasting ids around or code generating there'd be no hoops to jump through to match the case conventions for different uses of the same id.
> Capitalization only differs if the semantic meaning differs
Yes, and I'm positing that prefixes or suffixes would be better than case differences
1. Assume that some letter X has only a lower-case version. It’s represented with two bytes in UTF-8. 2. A capitalized version is added way later 3. There are no more two-byte codepoints available 4. So it has to use three bytes or more
I see people are jumping on the “oh the wicked complexity” bandwagon in here but I don’t see what the big deal is.
In Norwegian, "ae" is an accepted transliteration of "æ", but "æ" is very clearly considered it's own character and we'd expect the answer to how many characters is "æ" to be 1 (which creates fun sorting issues too - "ae" is expected to sort after "z"), just like "aa" is a transliteration of "å" except when it isn't (it's always a transliteration when outside of names; within names all bets are off - some names traditionally uses "aa", some uses "å" and if represented with "aa" it respresents a transliteration; to make it worse, some names exist in both forms - e.g. Haakon vs. Håkon).
Now the interesting question to ask Norwegians is "how many characters are 'ae'?" On one hand the obvious answer is 2, but I might pause to think "hold on, you meant to write "æ" but transliterated it, and the answer should be 1". Except it might occur to me it's a trick question - but it could be a trick question expecting either answer. Argh.
[I just now realised a search for "å" matches "a" and "å", but "aa" is treated as two matches on "a", and that I definitively hate, though I understand it's a usability issue that it matches on "a", and that matching on "aa" makes no sense if the matched term is in another language.]
[EDIT2: I've also done some genealogy recently, and to be honest, the spelling of priests makes it quite hard to hold on to any desire for precision in find/search]
Also, talking about 'glyphs', one has to clearly separate between what Unicode encodes and what a given font uses; in the context of fonts, 'glyphs' are also called 'glyfs' or 'outlines', and any OTF my choose to render any given string with any number of glyfs/outlines, including using a visual ligature to display 'f+i' = fi but doing so by nudging the outlines for f and i closely together.
Counting code points would be a start and would solve this particular problem. But that’s not glyph count. You really need to count grapheme clusters. For example two strings that are visually identical and contain “é” might have a different number of code points since one might use the combining acute accent codepoint while the other one might use the precomposed “e with accute accent”.
Even a modern language like Rust doesn’t have standard library support for counting grapheme clusters; you have to use a third party one.
And if you do count grapheme clusters then people will eventually complain about that as well (“TIL that getting the length of a String in X takes linear time”).
> str.casefold()
> Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.
> Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".
> The casefolding algorithm is described in section 3.13 of the Unicode Standard.
[1] https://docs.python.org/3/library/stdtypes.html#str.casefold
>>> str.casefold("παράδειγμα")
'παράδειγμα'
>>> str.casefold("ΠΑΡΑΔΕΙΓΜΑ")
'παραδειγμα'
It's at least consistent with this, though: >>> str.upper("παράδειγμα")
'ΠΑΡΆΔΕΙΓΜΑ'
But I'd consider that incorrect, or at least nonstandard. The Greek alphabet does have accented versions of capital letters, but they can only be used as the first letter of a word in mixed case (e.g. if a sentence starts with έλα, you write it Έλα), never in the middle of a capitalized word. However maybe this slides too far to the "language" rather than "encoding" side of the space that Unicode considers outside of its purview.Correct case-folding in Greek is complicated, since it might introduce diaeresis in the next vowel, if the accents are removed: Μάιος - ΜΑΪΟΣ.
All this means that correct handling is not reversible, which introduces a slew of other problems.
>>> for i in range(1_114_112):
... s = chr(i)
... if len(s) != len(s.upper()): print(i, s, s.upper())
...
223 ß SS
329 ʼn ʼN
496 ǰ J̌
912 ΐ Ϊ́
944 ΰ Ϋ́
1415 և ԵՒ
7830 ẖ H̱
...
8188 ῼ ΩΙ
64256 ff FF
64257 fi FI
...
64279 ﬗ ՄԽhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
We've done some pretty fun work at Inscribe ensuring things like this work across multiple languages, in particular for matching names. So we can now verify that a document does indeed belong to "Vladimir" even if the name on the document is "Владимир". The trickier part is not simply matching those, but returning the original raw result, as for that you need to keep track of how your normalization has changed the length of things.
If you're interested in this kind of thing, shoot me a mail at oisin@inscribe.ai. We're growing rapidly and hiring to match.
[1] http://std.dkuug.dk/jtc1/sc2/wg2/docs/n3227.pdf
[2] https://www.unicode.org/policies/stability_policy.html#Case_...
There are also non-invariant case-modifying examples, where uppercase -> lowercase -> uppercase (or l -> u -> l) does not produce the input string.
These are called "bicameral scripts."
Whether Japanese has them or not is arguable - consider katakana, where they switch for externality.
Whether Arabic has it or not is also arguable. Many Arabic letters have alternate forms (English speakers might comparatively call them "modern," "holy", "cursive," and "historic.")
You might argue that English has other alternate cases, such as cursive, handwriting, blackletter, doublestrike, smallcaps, title case, and so forth.
I don't see the connection between cursive, etc. and case at all. Case exists in all those you mention, it's orthogonal.
For a more pure example, consider Bopomofo.
>>> 'Straße'.upper()
'STRASSE'>>> 'Straße'.upper().lower()
'straße'
instead of:
>>> 'Straße'.upper().lower()
'strasse'
For additional fun: Swiss German doesn't use ß at all, so there is no difference between "in Maßen genießen" (to enjoy in moderation) and "in Massen genießen" (to enjoy in large amounts).
Making 'STRASSE'.lower() return 'straße' requires that the caller have knowledge of the written language in us and a lookup through a language dictionary. IIRC, not all German words with two consecutive 's' es are properly written with an 'ß', and I don't know much about other languages that use that character. Blindly changing any SS to ß on lowercasing isn't what anyone wants, but rarely are strings annotated with the written language they contain, and it gets worse because strings can contain multiple written languages, which is only extremely rarely annotated.
(High roller, I know.)
No games, though. If you say "An algorithm to compute the length of the string in number of visible characters," that obviously is designed to pass the test rather than to do anything useful.
Maybe framing it as a bet will break the illusion that string length is ever required.
I guess what I amsaying is:where are you marking the diffefence? any string (and all data) IS at the a series of encoded bites
> I'll paypal $20 to anyone who can name a situation where string length (in number of visible characters) is actually required by any reasonable algorithm.
I've already described above where I've had this exact requirement. The client demands that "50 letters" be allowed in a title field for a website element. He means letters: spaces (and presumably newlines) don't count, neither do punctuation. Emojis were not a concern at the time. I wrote Javascript and PHP validators for client- and server-side validation and stored the string in a VARCHAR(127) to be safe.And this is completely reasonable. He is a human, not "a computer person" (his terminology) and pays me to abstract from him those "computer things" which he has no desire to understand.
Then he might have to learn it's very much a "human", not "computer" thing...
My original response was going to be that you don't actually care about "foo".length in that context, either. You care whether one string is larger than the other, i.e. the actual value doesn't matter -- all that matters is that if a string X is longer than string Y, then the length should increase. But mathematically, that's just a precise definition of requiring the string length, so that logic doesn't work out.
If you email me your paypal/venmo/whatever, you can collect the $20, since you were the first to point out monospaced font. I still feel that monospaced fonts are sidestepping the whole point, but I won't be pedantic about it.
(https://news.ycombinator.com/item?id=29303325 points out why this isn't a sensible operation, if you were curious about why I feel inclined not to concede the bet.)
Just for more context, I was thinking data tables: like this.
E.g., most Asian characters & emoji are 2 cell widths in a fixed with font for a single character. The character "e" is 1 byte in UTF-8, "é" is >1. The "family of four" emoji can be up to 11 code points, 41 bytes (in utf-8), and 2 cell widths (still just an emoji) and is, I presume, a single grapheme cluster.
Which is 99% of the work to also calculate the length in those terms.
I'm still struggling with this in one place, where, for some reason, Cyrillic characters get cut in half.
You may visualize all that by converting your strings to lists of bytes.
If uppercase requires a diacritic, but lower case didn't that doesn't (usually) increase the visible character count, but it likely increases storage space, depending on encodings and normalization forms. Thinking about i to I with dot (which I can't currently type), which would need more storage in utf-8 or as I + dot.
I suppose some terminal rendering (where you're taking in chunks and you might want to be a bit clever about jumping to spaces to figure out where breaks should go).
There is a notion of UTF codepoints that you can index into (see how Python does string indexing), though I generally think that people who whine a lot about string behavior for UTF tend to just not be reaching for the right tools.
"What size does this UI element have to fit this text in our specific mono-spaced font"?
“Full name” and “username” must both have a minimum length of 1.
That's what Twitter's tweet limit ought to be, and if there was an easy, culturally neutral algorithm for it I'm sure that's what they would have done.