RingDotNetfor Ring

Unicode and encodings

Why len() of a text is not the number of letters you see, what UTF-8 and UTF-16 are, and what goes wrong when the wrong encoding is used.

What you will learn#

The three levels#

An encoding turns text into bytes. UTF-8 uses 1 byte for English letters and up to 4 for others; it is the standard for files and the web. UTF-16 is what .NET uses inside. A Ring text is a sequence of bytes (the text of a program and of most files is UTF-8), so len() counts bytes.

The program#

samples/UsingDotNet/tutorials/ch02_unicode.ring
# Unicode and text encodings - characters, code points, bytes, and why len() is not the number of letters
load "dotnet.ring"

using {
	"System"
	"System.Globalization"
	"System.Text"
}

func main

	oUtf8 = new Encoding().UTF8
	oUtf16 = new Encoding().Unicode              # .NET's own text format: UTF-16
	oLatin1 = new Encoding().Latin1

	? "Ring len() | UTF-8 bytes | UTF-16 bytes | letters you see | text"
	aSamples = ["Ring","café","Привет","مرحبا","日本語","😀"]
	for cText in aSamples
		oInfo = textElements(cText)
		? padRight("" + len(cText),11) + " | " + padRight("" + len(oUtf8.GetBytes(cText)),11) + " | " + padRight("" + len(oUtf16.GetBytes(cText)),12) + " | " + padRight("" + oInfo.LengthInTextElements,16) + " | " + cText
	next

	# 1. A Ring text is a list of BYTES in UTF-8: len() counts bytes. 'é' is two bytes, the Arabic letters two bytes each, Japanese three, an emoji four.
	#    So left(text, 4) may cut a letter in the middle. Count and cut with the .NET classes when the text can have such letters.
	cWord = "café"
	? nl + "1. len('café') = " + len(cWord) + " (bytes), but " + textElements(cWord).LengthInTextElements + " letters"

	# 2. Encodings: the same text, different bytes. Reading with the WRONG encoding gives garbage ("mojibake")
	cBytes = oUtf8.GetBytes("é")
	? nl + "2. 'é' in UTF-8 is " + len(cBytes) + " bytes: " + ascii(cBytes[1]) + " and " + ascii(cBytes[2])
	? "   the same bytes read as Latin-1 give: " + oLatin1.GetString(cBytes) + "  (two wrong letters)"
	? "   read as UTF-8 again: " + oUtf8.GetString(cBytes)

	# 3. A round trip: text -> bytes -> text, with the same encoding, gives the same text
	cArabic = "مرحبا بالعالم"
	? nl + "3. Arabic text survives the round trip: " + yesNo(oUtf8.GetString(oUtf8.GetBytes(cArabic)) = cArabic)

	# 4. One letter you see can be several code points: 'é' can be e + a combining accent. An emoji with a skin color is two.
	cDecomposed = "e" + char(204) + char(129)        # the bytes of 'e' followed by U+0301 (combining acute accent)
	oShown = textElements(cDecomposed)
	? nl + "4. 'e' + a combining accent: " + len(cDecomposed) + " bytes, " + oShown.LengthInTextElements + " letter shown: " + cDecomposed

	# 5. Comparing texts: "é" typed in the two ways looks the same but the bytes differ. Normalize before comparing.
	cComposed = "é"
	? nl + "5. Looks the same, but equal as bytes? " + yesNo(cComposed = cDecomposed)
	nSame = new String().Compare([ :strA = cComposed, :strB = cDecomposed, :ignoreCase = False, :culture = new CultureInfo("en-US") ])
	? "   Compared as TEXT with a culture (en-US): " + yesNo(nSame = 0)

	# 6. Categories: .NET knows what kind of character something is
	for cChar in ["A","7","€","!"]
		? "   '" + cChar + "' is: " + new CharUnicodeInfo().GetUnicodeCategory(cChar)
	next

# text padded with spaces on the right (the columns of the table)
func padRight cText, nWidth

	cResult = cText
	while len(cResult) < nWidth
		cResult += " "
	end
	return cResult

# a StringInfo knows the letters you see (text elements) of a text
func textElements cText

	return new StringInfo().@New([ :value = cText ])

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
Ring len() | UTF-8 bytes | UTF-16 bytes | letters you see | text
4           | 4           | 8            | 4                | Ring
5           | 5           | 8            | 4                | café
12          | 12          | 12           | 6                | Привет
10          | 10          | 10           | 5                | مرحبا
9           | 9           | 6            | 3                | 日本語
4           | 4           | 4            | 1                | 😀

1. len('café') = 5 (bytes), but 4 letters

2. 'é' in UTF-8 is 2 bytes: 195 and 169
   the same bytes read as Latin-1 give: é  (two wrong letters)
   read as UTF-8 again: é

3. Arabic text survives the round trip: yes

4. 'e' + a combining accent: 3 bytes, 1 letter shown: é

5. Looks the same, but equal as bytes? no
   Compared as TEXT with a culture (en-US): yes
   'A' is: UppercaseLetter
   '7' is: DecimalDigitNumber
   '€' is: CurrencySymbol
   '!' is: OtherPunctuation

How it works#

The table compares four counts for six texts. For Ring they are all the same; for café the byte count is 5 but you see 4 letters; Russian and Arabic use two bytes per letter; Japanese three; an emoji four (two units in UTF-16). StringInfo.LengthInTextElements counts what a person sees. Its constructor that takes the text is written new StringInfo().@New([ :value = cText ]).

Step 2 turns é into two bytes (195 and 169) and reads them again as Latin-1: the result is é, the classic mojibake. The rule: the encoding that wrote the bytes must be the one that reads them. When you read text files, say it: File.ReadAllText(path, encoding).

Steps 4 and 5 show that é can be one code point or two. They look the same, but compared as bytes they differ. Compare with a culture-aware method (String.Compare) when users type text.

Note

left(), right() and substr() of Ring work on bytes. For text with accents or other alphabets do not cut by number; use .NET classes or split on spaces and separators.

What you learned#

Exercises#

  1. Write a text to a file in UTF-8 and in UTF-16 and compare the file sizes.
  2. Count the letters of your own name with len() and with StringInfo.
  3. Find out what Encoding.ASCII.GetBytes("é") returns, and why.

Next#

Text files and encodings

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.