Learning question: How does a type guarantee something about its contents when the contents are plain bytes?
You have used a newtype since your first Rust program. This article opens String to show the wrapped type, a checked way in, and what happens to data that is refused.
Scope. We read library/alloc/src/string.rs at Rust 1.100.0 [S3]. We do not cover &str, Deref, or the orphan rule. You need structs and Result. Newtype means a struct with one field whose purpose is to be a different type from that field [S2, ch. 10, "The NewType pattern"].
Bytes that expected to be text
Example 1 holds two bytes and the intention that they be a name.
Example 1. Does not compile (compile-fail/cf03_newtype.rs)
fn main() {
let name: String = vec![0x68, 0xFF];
println!("{name}");
}
The vector had two bytes in it, which is all a short name needs. It had been given a name, name, and a type annotation, and it took its place on the line the way a parcel takes its place at a door marked Staff. It understood bytes and strings to be the same kind of thing. The compiler read the annotation and the value and reported that they were not.
error[E0308]: mismatched types
--> cf03_newtype.rs:2:24
|
2 | let name: String = vec![0x68, 0xFF];
| ------ ^^^^^^^^^^^^^^^^ expected `String`, found `Vec<{integer}>`
| |
| expected due to thisPredict
0x68 is the letter h. 0xFF is not valid anywhere in UTF-8 [RFC 3629, section 1]. Suppose there is a function that turns a Vec<u8> into a String. Before reading on: what should it give back for these two bytes, and what should happen to the vector you passed in?
Name the parts
| Part | In std | Where [S3] |
|---|---|---|
| The newtype | pub struct String |
string.rs line 353 |
| The wrapped type | vec: Vec<u8>, a private field |
line 354 |
| The checked constructor | String::from_utf8 |
line 569 |
| The refusal | FromUtf8Error |
line 391 |
| The unchecked constructor | unsafe fn from_utf8_unchecked |
line 1038 |
What is inside a String?
Sometimes two values have the same representation and different rules, and a function that takes one will take the other without complaint. Thankfully, a struct with a private field closes that gap. Take a look at Example 2.
Example 2. The whole definition, and the door (library/alloc/src/string.rs, lines 353 to 355 and 569 to 574, attributes removed [S3])
pub struct String {
vec: Vec<u8>,
}
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
match str::from_utf8(&vec) {
Ok(..) => Ok(String { vec }),
Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
}
}
There are three things to see. String has one field, and the field is not pub, so code outside the module cannot build a String by naming it. from_utf8 takes the vector by value, checks it by lending it to str::from_utf8(&vec), and on success moves it into a new String. And on failure the same vector is moved into the error. That is the answer to the prediction: you get an Err, and your bytes are inside it.
You can also skip the check.
from_utf8_unchecked at line 1038 has the body String { vec: bytes } and nothing else, and it is marked unsafe: the promise that the bytes are UTF-8 moves from the function to whoever calls it.
What transfers, and what does not
A PHP value object with a private property and a validating constructor is the same idea, and you already know why you would write one. Two things do not transfer. The wrapper has no run-time cost of its own in Rust: the Rust patterns book describes the wrapped type as compiling to the same representation as the type inside [S2, ch. 10]. And passing the vector in is a move. There is no second handle to the same bytes left behind for someone to append 0xFF to after the check has passed, which is the hole a handle-based language leaves open.
Where would you rather find out?
So the check runs once, at the door, and every String made by String::from_utf8 has been through it. A newtype of your own, say a TaskId around a String, will also make the mix-up in Example 1 a compile error, and what it will not do, unless you give it a constructor that can say no, is tell you that the text inside is a task ID and not a project ID that somebody wrapped by mistake at the edge of the system, and no amount of type checking further in will notice. Which values in your program have a rule that only a comment knows about?
Practice tier: compiler, once the type exists. Deciding which values deserve their own type is judgment.
Testing
The claim is that invalid bytes are refused and handed back. Example 3 would fail if from_utf8 dropped the vector or repaired it.
Example 3. The refusal returns the bytes (tests/p03_newtype_string.rs)
#[test]
fn invalid_bytes_are_refused_and_handed_back() {
let bytes = vec![0x68, 0xFF];
let err = String::from_utf8(bytes).unwrap_err();
assert_eq!(err.utf8_error().valid_up_to(), 1);
// The rejected Vec<u8> was moved into the error, and comes back out of it.
assert_eq!(err.into_bytes(), vec![0x68, 0xFF]);
}
It passed on rustc 1.100.0, along with a second test that the bytes for hi become the string "hi".
Retrieve
- What is the one field of
String, and why can't your code set it directly? - After
String::from_utf8(bytes)fails, where are the bytes?
Typed results returns to the trick in question 2: an error that carries your value back to you.
TL;DR
String is a struct with one private field, a Vec<u8>. A safe way to make one from bytes is String::from_utf8, which checks the bytes and returns either the String or an error that contains the original vector. The unchecked constructor is unsafe. A newtype gives a value a type of its own, and a checked constructor gives that type a guarantee.