NewsCrawler.org

How hard is it to check for whitespace?

Sergey Tselovalnikov examines a method from Guava, a popular Java library from Google, that checks whether a character is whitespace and looks far more complex than a simple c == ' ' comparison. The Unicode White_Space property[1] defines 25 characters: besides the familiar space, tab and newline, the set includes NO-BREAK SPACE (U+00A0), which keeps text together when lines wrap, FIGURE SPACE (U+2007), which matches a digit's width in a table, and the progressively narrower THIN SPACE (U+2009) and HAIR SPACE (U+200A). Names can mislead: ZERO WIDTH SPACE (U+200B) is actually a format character, while OGHAM SPACE MARK (U+1680) can appear as a visible horizontal line — in Ogham fonts with a stemline, the space continues that line between letters.

Runtimes disagree on the exact set: Java's Character.isWhitespace() excludes NO-BREAK SPACE (U+00A0) and two other non-breaking spaces, while Python's str.isspace() accepts U+00A0 and also FILE SEPARATOR (U+001C), an ASCII control character that is not part of the Unicode property, bringing Python's total to 29 characters. JavaScript has no direct equivalent; its \s regex class rejects NEXT LINE (U+0085), which Unicode and Python both include, but accepts ZERO WIDTH NO-BREAK SPACE (U+FEFF), which Unicode leaves out. The definition itself evolves: Unicode 6.3 reclassified MONGOLIAN VOWEL SEPARATOR (U+180E) from a space separator to a format character, shrinking the White_Space set from 26 to 25 characters — a challenge for runtimes and libraries that need backwards compatibility.

Guava's implementation relies on a perfect hash function[2]: TABLE is a string of 32 characters acting as a hash table that maps an index to a character and holds all 25 Unicode whitespace characters, with duplicates filling the remaining slots. The index is computed as (1682554634 * c) >>> 27, which shifts a 32-bit product 27 bits to the right to isolate its five most significant bits, yielding a value in the [0, 32) range; a final == c check confirms the lookup. The author could not trace where the multiplier 1682554634 came from, but suitable multipliers can be found by a simple brute-force search, and Guava's git history shows the code evolving from a simpler matcher through a mod-79 version[3], whose downside was a division operation, to the perfect hash. Around the time the article was written, Daniel Lemire published a post on the same topic, with an example of using perfect hashing to check HTTP methods.

Read the original serce.meDiscussion

Sources

Published: First seen: Читать по-русски

Open as a page