Strings, Bytes, and Text Encoding

A string holds text according to the language's character model. Encoding produces bytes that files and networks can carry.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Measure both views
  2. Use a limit in the right unit
  3. Follow a complete UTF-8 round trip
  4. Decide which length the interface promises

Measure both views

Python's "é" is one code point. In UTF-8 it occupies two bytes. Encoding a string gives a byte sequence, and decoding that valid byte sequence with the same encoding returns the original string. This boundary can be described as a representation change.

Use a limit in the right unit

A message can fit a limit of ten code points and exceed ten bytes. If a protocol imposes a byte limit, encode first and check the actual byte length. Truncating at an arbitrary byte offset can split the encoded character, so make cut points explicit in the function contract.[1][2]

Follow a complete UTF-8 round trip

The input label café is four Unicode code points when é is the precomposed character. Encoding it in UTF-8 produces the byte sequence 63 61 66 C3 A9. Decoding all five bytes under UTF-8 recovers that label. Taking the first four bytes instead ends after the leading byte of its two-byte sequence, so strict decoding fails. Leading and continuation bytes explain why it is unsafe to cut at an arbitrary byte position.

Decide which length the interface promises

A file format budget might say no more than four bytes. A user interface might count displayed characters, for which grapheme clusters can matter. A function measuring code points can supply useful information for some APIs but answers neither every byte question nor every graphical cursor question. Write the unit in the parameter name and test two strings with the same visible length and different encoded sizes.

Also keep the chosen encoding alongside the serialized bytes when readers cannot infer it from the surrounding format. If invalid input can be replaced, report what information is lost under that rule. Text decoding error policies describe those alternatives.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩