Skip to content

str::from_utf8_mut

str methods · Strings

Level: reference · for working programmers

One line: from_utf8 over a &mut [u8], yielding &mut str — validated once, then editable.

pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error>

Stable since 1.87.0. Usable in a const context.

Same scan, same Utf8Error, and the result borrows the buffer mutably. That combination is useful when you own a byte buffer, want to treat it as text, and want to edit it in place — decoding a network frame and upper-casing a field without copying it.

The validity promise is established at the call and must be preserved by whatever you do afterwards. Since the result is a &mut str, the safe API surface is exactly the ASCII in-place edits, which cannot break it.

The mutable borrow of the buffer lasts as long as the &mut str, so the bytes cannot be touched directly in the meantime.

Example

str_from_utf8_mut.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let mut buf = *b"hello world";

    let text = str::from_utf8_mut(&mut buf).unwrap();
    text.make_ascii_uppercase();
    println!("{:?}", str::from_utf8(&buf).unwrap());

    // Editing one field of a decoded frame, in place.
    let mut frame = *b"name=alice";
    {
        let s = str::from_utf8_mut(&mut frame).unwrap();
        if let Some(i) = s.find('=') {
            s[i + 1..].make_ascii_uppercase();
        }
    }
    println!("{:?}", str::from_utf8(&frame).unwrap());

    // Invalid input is refused, with the same error detail.
    let mut bad = [104, 0xff];
    println!("{:?}", str::from_utf8_mut(&mut bad).unwrap_err().valid_up_to());
}

Verified output of str_from_utf8_mut.rs — regenerated by tools/run_examples.py, never hand-typed.

"HELLO WORLD"
"name=ALICE"
1

See also

str::from_utf8_mut in the standard library ↗

Po polsku

str::from_utf8_mut to ta sama kontrola co from_utf8, tylko nad &mut [u8]: obietnica poprawnego UTF-8 jest sprawdzana raz, przy wejściu, a potem masz &mut str i możesz przerabiać bufor w miejscu, bez kopiowania. Cena jest taka, że bezpieczne API &mut str sprowadza się w praktyce do przeróbek ASCII — tylko one na pewno nie zmieniają liczby bajtów i nie mogą złamać obietnicy — i to jest pułapka dla polskiego tekstu: make_ascii_uppercase() na buforze z „żółw” da „żółW”, bo litery z ogonkiem i kreską nie są ASCII i metoda ich po prostu nie dotyka. Do prawdziwej zmiany wielkości liter trzeba to_uppercase(), które alokuje nowy String, bo w Unicode zmiana wielkości potrafi zmienić długość w bajtach — a tego edycja w miejscu z definicji nie udźwignie. Pamiętaj też, że referencja mutowalna trzyma bufor wyłącznie dla siebie przez cały czas życia &mut str: do surowych bajtów w międzyczasie nie zajrzysz.

Szukaj po polsku: zmiana wielkości liter · edycja w miejscu · referencja mutowalna · rust from_utf8_mut · rust make_ascii_uppercase non-ascii