Terminology (9)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Encoding
- A mapping from Unicode scalar values to code-unit sequences, such as UTF-8 or UTF-16.
- Code unit
- The storage unit of an encoding: a byte in UTF-8, a 16-bit value in UTF-16.
- Code point
- One Unicode number, written U+0000 to U+10FFFF, such as U+00E9 for é.
- Unicode scalar value
- A code point outside U+D800 through U+DFFF, the surrogate range. Rust char represents scalar values.
- UTF-8
- An encoding of each Unicode scalar value in one to four bytes; ASCII stays one byte.
- UTF-16
- An encoding of each Unicode scalar value in one or two 16-bit units.
- Surrogate pair
- Two UTF-16 units that together encode one code point above U+FFFF.
- Grapheme cluster
- What a reader perceives as one character; it can contain several code points.
- Continuation byte
- A UTF-8 byte of the form 10xxxxxx, which continues a multi-byte sequence.
Bytes, code points and visible symbols
Unicode assigns numbers called code points to text elements. An encoding such as UTF-8 or UTF-16 represents them using bytes or code units. A grapheme cluster groups code points into a unit readers commonly perceive as one symbol; it can contain more than one code point.
Length, iteration and slicing need not use the same unit. A byte budget, a code-point limit and a visible-symbol preview are different contracts. Identify the selected API’s unit and valid boundaries before applying an index from one operation to another.
01Length
Each language’s length counts a different unit
A notification service reports message length in Unicode code points. Its preview must keep a requested number of those points, while the push gateway limits UTF-8 bytes. The same text passes through all three operations. Check what the language’s default length measures before using it for the service’s counter.
Use café 🙂 to check the counter: it includes an accented letter and an emoji. The service asks for code points, but the default length operation may count another unit. Predict what this operation reports before choosing it for the counter.
std::string holds bytes. The lab compiler stores these string literals as UTF-8.
#include <iostream>
#include <string>
int main() {
std::string label = "café 🙂";
std::cout << label.size() << '\n';
}
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main
Use the selected language’s setup from the first reading and replace the file for each experiment. Save source files as UTF-8; the C++ target also uses UTF-8 for ordinary string literals and 8-bit char units. Service inputs in this lesson are valid UTF-8, with nonnegative whole-number limits. Malformed-input validation and grapheme-preserving previews are separate requirements.
02Code points and graphemes
One visible symbol can be several code points
A notification can include 👍🏽. The service contract counts code points, even when several draw as one symbol. A code point is a Unicode number, such as U+1F44D for 👍; the skin-tone modifier has its own number. Measure this message fragment to distinguish the policy from a visible-symbol counter.
The program prints the size and each byte in hexadecimal. The standard library has no code-point or grapheme counting for std::string.
#include <iomanip>
#include <iostream>
#include <string>
int main() {
std::string thumbs = "👍🏽";
std::cout << thumbs.size() << ':';
for (unsigned char byte : thumbs) {
std::cout << ' ' << std::hex << std::setw(2) << std::setfill('0') << +byte;
}
std::cout << '\n';
}
03Iterating
Loops and indexes use the string’s own unit
The preview receives a limit in code points, but native slices may expect a different index. Walk through 🙂! to find how a point’s position maps to those indexes. Predict the positions, or the loop’s step count in C++.
A range-for over std::string visits each char. The program counts the steps instead of positions.
#include <iostream>
#include <string>
int main() {
std::string text = "🙂!";
int steps = 0;
for ([[maybe_unused]] char unit : text) {
++steps;
}
std::cout << steps << '\n';
}
04Slicing
A slice can end inside a character
Try the preview’s simplest candidate: keep the first native unit of 🙂 ok. The result tests whether the slicing API protects point boundaries or leaves that job to the caller. Predict what the cut produces.
substr(0, 1) keeps one byte; the program prints its size and its value in hexadecimal.
#include <iostream>
#include <string>
int main() {
std::string text = "🙂 ok";
std::string cut = text.substr(0, 1);
std::cout << cut.size() << ' ' << std::hex << +static_cast<unsigned char>(cut[0])
<< '\n';
}
05Repair the notifications
Count, preview, then fit a byte budget
Repair the same notification service’s counter, preview and sender. Here characters means Unicode code points, not grapheme clusters. Count each message, construct a prefix with a requested point count, then keep the longest prefix that fits a UTF-8 byte budget. Inputs are valid UTF-8 and limits are nonnegative whole numbers.
The lab opens in your reading language and has its own language control. Each file contains its imports, types, reader and complete main. Later levels supply the earlier correct helpers.
Repair the notification tool
Counting code points, cutting by code points, then cutting by bytes without splitting a character.
In the frontend Does a textarea limit enforce the service’s code-point policy? Optional
The web composer labels its limit as 80 code points. These candidates bind the message to a textarea and set its native maximum length to 80. Check whether the browser attribute measures the same unit as the service.
"use client";
import { useState } from "react";
export default function NotificationComposer() {
const [message, setMessage] = useState("");
return (
<label>
Notification (80 code points)
<textarea
maxLength={80}
value={message}
onChange={(event) => setMessage(event.target.value)}
/>
</label>
);
}
React’s value and onChange keep the message in component state. They do not change HTML maxlength’s UTF-16 code-unit measurement. Forty 🙂 code points occupy 80 units, so the native limit and the label describe different policies. The attribute governs user input; it is not a replacement for the service’s own code-point validation.
Sources: HTML: limiting user input length,React: textarea,Svelte: bind:value.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?