Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 13 · Testing, macros & unsafe

    13.3unsafe & FFI

    What an unsafe block lets you do and what it doesn't, how to wrap unsafe code in a safe API, and how to call C functions from Rust.

    About 30 minutesAdvanced

    On this page
    1. Concept map
    2. Bounds checks stay on
    3. The five things unsafe unlocks
    4. What unsafe doesn’t turn off
    5. Safe wrappers over unsafe code
    6. Calling C functions
    7. Strings coming back from C
    8. Calling Rust from C
    9. Which one should I use?
    10. Under the hood
    11. What undefined behavior means
    12. A raw pointer is a reference without the promises
    13. Common pitfalls
    14. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Opting out of memory-safety checksNot possible in the language; native addons do it in C or C++unsafe blocks, after enabling AllowUnsafeBlocks for the whole projectunsafe { ... } blocks, allowed in any crate unless it opts out with #![forbid(unsafe_code)]
    PointersNone; object variables hold references the engine tracksint*, &x, and fixed to stop the GC moving an object*const T and *mut T, made with &raw const x and &raw mut x; no pinning needed
    Calling a C functionA Node-API native addon, compiled to a .node fileP/Invoke: [DllImport] or [LibraryImport]An unsafe extern "C" { ... } block that declares the function
    Passing text to CThe addon converts it, for example with napi_get_value_string_utf8The marshaller copies the string to a C string for youYou convert: CString (owned) and CStr (borrowed) are NUL-terminated
    What still gets checked inside the unsafe codeNot applicable; there is no unsafe code to checkTypes; pointer use and lifetimes are up to youTypes, the borrow checker and lifetimes; only the five unlocked operations are up to you

    TypeScript has no way to step outside memory safety: the engine checks every access, and anything lower-level lives in a native addon written in C or C++.C# lets you step outside memory safety with unsafe blocks, pointers and P/Invoke, once you switch on AllowUnsafeBlocks for the project. Rust has an unsafe keyword too, and any crate can use it. It doesn’t switch the compiler’s checks off. It unlocks five specific operations the compiler can’t check, and makes you promise you’ve checked them yourself. This lesson shows what those five are, how the standard library wraps them in safe APIs, and how to call a C function. You’ll rarely write unsafe yourself, but you’ll read it in crates and in the standard library.

    Bounds checks stay on

    Start with something every language does safely: reading past the end of a list.

    TypeScript
    lookup.ts
    const scores = [90, 85, 77];
    const index = 10;
    const score = scores[index]; // undefined, no error
    console.log(score === undefined ? `no score at ${index}` : `score: ${score}`);
    C#
    Lookup.cs
    int[] scores = [90, 85, 77];
    int index = 10;
    // scores[index] would throw IndexOutOfRangeException
    Console.WriteLine(index < scores.Length ? $"score: {scores[index]}" : $"no score at {index}");
    Rust
    let scores = [90, 85, 77];
    let index = 10;
    // scores[index] would panic; .get returns None instead
    match scores.get(index) {
        Some(score) => println!("score: {score}"),
        None => println!("no score at {index}"),
    }

    Output

    no score at 10

    Rust checks every index, like TypeScriptC#. The standard library also has get_unchecked, which skips the check. Reading past the end with it doesn’t panic or return None: it’s undefined behavior (explained below), and in practice it reads whatever memory happens to be there. So get_unchecked is an unsafe function, and you can only call it inside an unsafe block:

    let scores = [90, 85, 77];
    let score = scores.get_unchecked(1);

    Rust doesn't compile this: error E0133

    error[E0133]: call to unsafe function `core::slice::<impl [T]>::get_unchecked` is unsafe and requires unsafe block
     --> main.rs:2:13
      |
    2 | let score = scores.get_unchecked(1);
      |             ^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function
      |
      = note: consult the function's documentation for information on how to avoid undefined behavior

    Wrap the call in unsafe { ... } and it compiles. The block is your promise that the index is in range, and the convention is to write that reasoning down in a // SAFETY: comment right above it:

    let scores = [90, 85, 77];
    // SAFETY: 1 is less than scores.len(), which is 3.
    let score = unsafe { scores.get_unchecked(1) };
    println!("score: {score}");

    Output

    score: 85

    You almost never need get_unchecked. When you loop with an iterator, or the compiler can see the index is in range, it removes the bounds check for you.

    The five things unsafe unlocks

    Unsafe Rust lets you do exactly five things that safe Rust forbids. Implementing an unsafe trait is written unsafe impl; the other four happen inside an unsafe { ... } block:

    OperationExampleWhy the compiler can’t check it
    Dereference a raw pointer*pointer += 5A raw pointer may be null, dangling or misaligned.
    Call an unsafe fnscores.get_unchecked(1), a C functionThe function has rules its signature can’t express.
    Read or write a static mutCOUNTER += 1Another thread could be using it at the same time.
    Implement an unsafe traitunsafe impl Send for Handle {}The trait promises something about your type, such as being safe to send to another thread (Send and Sync).
    Read a union fieldvalue.as_floatThe compiler doesn’t know which field was written last.

    A raw pointer is Rust’s C-style pointer: *const T for reading, *mut T for writing. Here * is part of the type name, not a dereference. Creating one is safe; it’s just an address. Using it is the unsafe part:

    let mut score = 10;
    let pointer: *mut i32 = &raw mut score; // creating a raw pointer is safe
    // SAFETY: `pointer` comes from `score`, which is still alive, and nothing else
    // reads or writes `score` until this block ends.
    unsafe {
        *pointer += 5;
    }
    println!("{score}");

    Output

    15

    That’s C#‘s int* and &score. Here’s the same code in C#:

    Pointer.cs
    int score = 10;
    unsafe
    {
        int* pointer = &score;
        *pointer += 5;
    }
    Console.WriteLine(score);

    Two differences. In C#, &score is the address-of operator; in Rust, &score is a safe borrow, and you write &raw mut score to get a raw pointer. And Rust has no fixed: there’s no garbage collector moving objects around, so a pointer into a Box stays valid until the box is dropped, and a pointer into a Vec until the vector is dropped or grows into a new buffer. (Rust’s Pin type, from the async lesson, solves a different problem.)

    TypeScript has nothing like this. The closest thing is an index into a typed array, and the engine checks every one. A raw pointer is just an address with none of those checks.

    What unsafe doesn’t turn off

    unsafe adds those five abilities and nothing else. Types are still checked, indexing is still bounds-checked, and the borrow checker still runs. Two &mut borrows of one value are an error inside an unsafe block too:

    let mut names = vec![String::from("Ada")];
    unsafe {
        let first = &mut names[0];
        let again = &mut names[0];
        first.push('!');
        again.push('?');
    }

    Rust doesn't compile this: error E0499

    error[E0499]: cannot borrow `names` as mutable more than once at a time
     --> main.rs:4:22
      |
    3 |     let first = &mut names[0];
      |                      ----- first mutable borrow occurs here
    4 |     let again = &mut names[0];
      |                      ^^^^^ second mutable borrow occurs here
    5 |     first.push('!');
      |     ----- first borrow later used here

    So unsafe doesn’t mean “this code is dangerous”. It means “this code does one of the five things, and a person, not the compiler, has checked that it’s correct”. Everything else around it is checked as usual.

    Safe wrappers over unsafe code

    You use unsafe code every day without writing any: Vec, String, HashMap and most of the standard library are built on raw pointers, and expose safe methods on top. TypeScript works the same way: typed arrays and strings are implemented in the engine’s C++.C# works the same way: Span<T>, string and much of the base class library use pointers and unsafe code inside the runtime. Here’s a buffer split into two halves that you change separately:

    TypeScript
    split.ts
    const samples = new Int32Array([1, 2, 3, 4, 5, 6]);
    const left = samples.subarray(0, 3); // two views of one buffer
    const right = samples.subarray(3);
    left[0] = 10;
    right[0] = 40;
    console.log(`[${samples.join(", ")}]`);
    C#
    Split.cs
    int[] samples = [1, 2, 3, 4, 5, 6];
    Span<int> left = samples.AsSpan(0, 3); // two views of one array
    Span<int> right = samples.AsSpan(3);
    left[0] = 10;
    right[0] = 40;
    Console.WriteLine($"[{string.Join(", ", samples)}]");
    Rust
    let mut samples = [1, 2, 3, 4, 5, 6];
    let (left, right) = samples.split_at_mut(3); // two &mut slices of one array
    left[0] = 10;
    right[0] = 40;
    println!("{samples:?}");

    Output

    [10, 2, 3, 40, 5, 6]

    In Rust, two &mut borrows of one array are normally forbidden. split_at_mut gives you two anyway, because they cover parts that don’t overlap. The borrow checker can’t see that, so writing split_at_mut yourself in safe Rust fails:

    fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
        (&mut values[..mid], &mut values[mid..])
    }

    Rust doesn't compile this: error E0499

    error[E0499]: cannot borrow `*values` as mutable more than once at a time
     --> main.rs:2:31
      |
    1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
      |                         - let's call the lifetime of this reference `'1`
    2 |     (&mut values[..mid], &mut values[mid..])
      |     --------------------------^^^^^^--------
      |     |     |                   |
      |     |     |                   second mutable borrow occurs here
      |     |     first mutable borrow occurs here
      |     returning this value requires that `*values` is borrowed for `'1`
      |
      = help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices

    The compiler only knows that both results borrow values mutably. It doesn’t reason about ranges. The standard library’s version uses raw pointers instead, roughly like this:

    use std::slice;
    
    fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
        let len = values.len();
        assert!(mid <= len, "mid is out of range");
        let start = values.as_mut_ptr();
        // SAFETY: `mid <= len`, so both ranges are inside `values` and don't overlap.
        // The two slices borrow `values` mutably, so nothing else can use it while they exist.
        unsafe {
            (
                slice::from_raw_parts_mut(start, mid),
                slice::from_raw_parts_mut(start.add(mid), len - mid),
            )
        }
    }
    
    fn main() {
        let mut samples = [1, 2, 3, 4, 5, 6];
        let (left, right) = split_at_mut(&mut samples, 3);
        left[0] = 10;
        right[0] = 40;
        println!("{samples:?}");
    }

    Output

    [10, 2, 3, 40, 5, 6]

    Look at how it’s built, because every good unsafe API follows this pattern:

    • The function is safe to call. Its signature has no unsafe, so callers can’t misuse it: any mid is either fine or stopped by the assert!.
    • The check comes first. The assert! makes the unsafe block’s promise true for every input. Without it, a caller could pass mid = 100 and get slices that reach past the array.
    • The unsafe block is small, and its // SAFETY: comment says why each requirement of from_raw_parts_mut holds.
    • The signature ties the results to the input. Both slices borrow values, so the borrow checker keeps protecting callers.

    When a function can’t check its own requirements, mark the function itself unsafe fn, and document the rules in a # Safety section so callers know what they’re promising:

    /// Returns the element at `index` without checking the bounds.
    ///
    /// # Safety
    ///
    /// `index` must be less than `values.len()`.
    unsafe fn element_unchecked(values: &[i32], index: usize) -> i32 {
        // SAFETY: the caller promised that `index < values.len()`.
        unsafe { *values.get_unchecked(index) }
    }
    
    let scores = [90, 85, 77];
    // SAFETY: 2 is less than 3.
    let last = unsafe { element_unchecked(&scores, 2) };
    println!("{last}");

    Output

    77

    The body still needs its own unsafe block: since edition 2024, an unsafe fn doesn’t make its whole body unsafe, and the compiler warns if you leave the block out. # Safety is for the caller; // SAFETY: is for whoever reads the call.

    Calling C functions

    FFI (foreign function interface) means calling code written in another language, usually C, because C’s calling convention is what operating systems and most libraries expose.

    In C#, that’s P/Invoke. [DllImport] declares a C function, and the marshaller converts arguments for you, including copying a string into a NUL-terminated C string. Here’s strlen from the C runtime, which is ucrtbase.dll on Windows (the example picks the name at run time). On Linux and macOS the C library has a different file name (libc.so.6 on most Linux distributions, libSystem.dylib on macOS); if the short name libc doesn’t resolve on your system, use that full name in [DllImport]:

    Strlen.cs
    using System.Runtime.InteropServices;
    
    nuint length = OperatingSystem.IsWindows() ? Crt.StrlenWindows("hello") : Crt.StrlenUnix("hello");
    Console.WriteLine(length);
    
    static class Crt
    {
        [DllImport("ucrtbase", EntryPoint = "strlen")]
        public static extern nuint StrlenWindows(string text);
    
        [DllImport("libc", EntryPoint = "strlen")]
        public static extern nuint StrlenUnix(string text);
    }

    Output

    5

    The newer [LibraryImport] generates the marshalling code at compile time instead. It needs a partial method, an explicit string encoding, and AllowUnsafeBlocks, because the generated code uses pointers. (This version names only the Windows library.)

    LibraryImport.cs
    using System.Runtime.InteropServices;
    
    Console.WriteLine(Crt.Strlen("hello"));
    
    static partial class Crt
    {
        [LibraryImport("ucrtbase", EntryPoint = "strlen", StringMarshalling = StringMarshalling.Utf8)]
        public static partial nuint Strlen(string text);
    }

    TypeScript can’t call C directly. Node’s answer is a native addon: a C or C++ library written against Node-API, compiled (usually with node-gyp) to a .node file, and loaded with require. The addon does the unsafe work, converting arguments with calls such as napi_get_value_string_utf8, and your TypeScript sees ordinary functions:

    addon.ts
    import { createRequire } from "node:module";
    
    const require = createRequire(import.meta.url);
    const addon = require("./build/Release/strings.node") as { strlen(text: string): number };
    console.log(addon.strlen("hello"));

    A bug in the addon doesn’t throw an exception you can catch; it can crash the whole Node process. You can also write addons in Rust: the napi-rs crates generate the Node-API glue and the TypeScript types from a #[napi] attribute.

    Rust calls C with no extra tools. You declare the functions in an unsafe extern "C" block, and you convert the arguments yourself:

    use std::ffi::{CString, c_char, c_int};
    
    // Declarations for functions in the C runtime, which every Rust program links to
    unsafe extern "C" {
        fn abs(value: c_int) -> c_int;
        fn strlen(text: *const c_char) -> usize;
    }
    
    fn main() {
        // SAFETY: abs is only undefined for c_int::MIN, and -42 isn't that.
        let distance = unsafe { abs(-42) };
        println!("{distance}");
    
        let text = CString::new("hello").expect("no NUL bytes inside");
        // SAFETY: `text` is a valid NUL-terminated string, and it lives until the end of main.
        let length = unsafe { strlen(text.as_ptr()) };
        println!("{length}");
    }

    Output

    42
    5

    What each piece does:

    • unsafe extern "C" says “these functions exist, with the C calling convention”. The compiler can’t read the C library, so it trusts your signatures; the unsafe on the block is your promise that they’re right. A wrong signature, such as i64 where C takes an int, is undefined behavior. Edition 2024 requires the unsafe here; older code writes plain extern "C".
    • Every function in the block is unsafe to call unless you mark it safe fn. Do that only when every possible argument is fine. abs is not: in C, abs(INT_MIN) is undefined, which is why the call above needed a // SAFETY: comment.
    • c_int, c_char (from std::ffi) are the C types with the right size for the platform. size_t is usize in Rust.
    • CString is the C-compatible version of String: owned, with a NUL byte at the end. CString::new copies your text and returns an error if the text already contains a NUL byte, since C would stop reading there. .as_ptr() gives C a *const c_char that stays valid as long as the CString lives.

    A function C can safely call with any argument can be declared safe fn. Then you call it like any Rust function, with no unsafe block:

    use std::ffi::c_double;
    
    unsafe extern "C" {
        // fabs from the C math library is defined for every double, NaN included
        safe fn fabs(value: c_double) -> c_double;
    }
    
    println!("{}", fabs(-2.5));

    Output

    2.5

    Strings coming back from C

    CStr is to CString what &str is to String: a borrowed view of a NUL-terminated string. When C hands you a *const c_char, CStr::from_ptr wraps it, and .to_str() checks that the bytes are valid UTF-8, because C strings can hold any bytes. A C string literal, written c"...", gives you a &CStr directly:

    use std::ffi::CStr;
    
    let greeting: &CStr = c"hello";
    println!("{} bytes before the NUL", greeting.count_bytes());
    println!("{:?}", greeting.to_str());

    Output

    5 bytes before the NUL
    Ok("hello")

    Strings and UTF-8 covers why Rust’s own strings carry a length instead of a terminator.

    Calling Rust from C

    To go the other way, mark a Rust function extern "C" and keep its name unmangled, so a C linker can find it:

    use std::ffi::c_int;
    
    #[unsafe(no_mangle)]
    pub extern "C" fn add_points(score: c_int, bonus: c_int) -> c_int {
        score + bonus
    }
    
    fn main() {
        println!("{}", add_points(40, 2));
    }

    Output

    42

    #[unsafe(no_mangle)] is an unsafe attribute: two exported functions with the same name in one program are undefined behavior, and the compiler can’t rule that out. Edition 2024 makes you write unsafe(...) around no_mangle, export_name and link_section. The function itself is safe to call from Rust. In a real project you’d build it as a library (crate-type = ["cdylib"] in Cargo.toml) and let C, a Node-API addonP/Invoke or WebAssembly call it.

    You rarely write these declarations by hand for a big C library: bindgen generates them from the C headers, and most popular C libraries already have a -sys crate with the declarations and a safe wrapper crate on top.

    Which one should I use?

    WhatWhenWhyHow
    A safe API from std or a crateAlmost always.Someone has already written and reviewed the unsafe code, often checked with Miri.split_at_mut, Vec, Cell, atomics, bytemuck-style crates.
    A safe function with a small unsafe block insideYou need one of the five operations, and your function can check every requirement itself.Callers can’t misuse it, and the unsafe part is a few lines to review.Check first (assert!, if), then unsafe { ... } with a // SAFETY: comment.
    unsafe fnThe function has a requirement it can’t check, such as “this pointer is valid”.The caller has to make the promise, so the signature says so.unsafe fn plus a # Safety doc section listing the rules.
    unsafe extern "C" blockCalling a C library or the operating system.It’s the only way to call C; Rust can’t check the other side.Declare with C types, convert with CString/CStr, wrap each call in a safe function.
    static with an atomic or MutexGlobal state shared across the program.Safe across threads, no unsafe needed.static COUNTER: AtomicU32 = AtomicU32::new(0); (Variables & mutability)
    static mutPractically never.Every access needs unsafe, and references to it are an error in edition 2024.Use an atomic or Mutex instead.

    Rule of thumb: look for a safe API first, in std and then on crates.io. If you really need unsafe, keep the block as small as possible, put it inside a safe function that checks its inputs, and write a // SAFETY: comment that a reviewer could check line by line.

    Do I need unsafe?
    1. Does the standard library already do it safely: split_at_mut, chunks_mut, swap, Cell, Rc, atomics, Mutex?

      Yes

      Use thatThese are the safe wrappers. Their unsafe code is reviewed and tested far more than yours will be.

      No
    2. Does a well-used crate do it: bindings to the C library, byte casting, a lock-free queue?

      Yes

      Use the crateMany C libraries already have a -sys crate for the raw declarations and a safe crate on top.

      No
    3. Is it only for speed, such as skipping a bounds check?

      Yes

      Measure firstIterators and slices usually let the compiler drop the check by itself. Reach for get_unchecked only after a profiler shows the check matters.

      No
    4. Are you calling C, the operating system, or hardware directly?

      Yes

      Write a small unsafe block inside a safe wrapperDeclare the functions in an unsafe extern block and give every call a // SAFETY: comment.

      No
    5. Otherwise: Restructure the code so the borrow checker can follow it: split a struct into fields, use indexes instead of references, or clone. If you're still stuck, a safe pattern almost certainly exists.

    Under the hood

    What undefined behavior means

    The compiler optimizes your code on the assumption that certain rules always hold: a reference is never null and always points at a live value, a &mut is the only way to reach its value while it’s in use, a bool is always 0 or 1, and no two threads write the same memory at once. Safe Rust can’t break these rules. Unsafe code can, and breaking one is undefined behavior (UB).

    Undefined behavior doesn’t mean “crashes”. It means the compiler’s guarantees about your program are gone. The program might work in a debug build and give wrong answers in a release build, crash somewhere far from the bug, or work until a compiler upgrade changes an optimization. That’s why you can’t test your way to confidence in unsafe code, and why examples of UB on this page are described rather than run.

    Common ways to cause it:

    • Dereferencing a null, dangling or misaligned pointer.
    • Reading memory that was never initialized.
    • Having a &mut and any other reference to the same value in use at the same time.
    • Two threads writing the same data without synchronization (a data race).
    • Calling a C function with the wrong signature, or with an argument it doesn’t accept, like abs(c_int::MIN).

    C# unsafe code has the same problem: a bad pointer can corrupt the managed heap, and the GC may crash much later, far from the bug.Native addons have the same problem: a bad pointer in the C code can corrupt memory and crash Node much later, far from the bug. To catch UB in Rust, run your tests under Miri, an interpreter that checks every memory access against these rules: rustup +nightly component add miri, then cargo +nightly miri test. It’s slow, so run it on the tests that cover your unsafe code.

    A raw pointer is a reference without the promises

    At run time, a raw pointer and a reference are the same thing: an address.

    let score = 85;
    let reference: &i32 = &score;
    let pointer: *const i32 = &raw const score;
    println!("{}", std::ptr::eq(reference, pointer)); // same address?

    Output

    true

    The difference is what the compiler knows. A reference is never null, so Option<&i32> can use the null address to mean None and stays 8 bytes. A raw pointer may be null, so Option<*const i32> needs a separate tag:

    References and raw pointers in memory
    References and raw pointers in memory: each row is one value; each cell's width is its size in bytes.
    Value0123456789101112131415Size
    &i32address8 bytes · pointer8 bytes
    *const i32address8 bytes · pointer8 bytes
    Option<&i32>address, or null for None8 bytes · pointer8 bytes
    Option<*const i32>tag and padding8 bytesaddress8 bytes · pointer16 bytes

    Sizes today, on a 64-bit target. A &i32 and a *const i32 are both a single 8-byte address. Option<&i32> is also 8 bytes, because a reference is never null and None is stored as the null address. Option<*const i32> is 16 bytes: a raw pointer may legitimately be null, so the option needs a separate tag, which takes 8 bytes with padding, before the 8-byte pointer.

    Guarantee&T / &mut T*const T / *mut T
    Never nullYesNo
    Points at a live, initialized valueYesNo
    Correctly alignedYesNo
    &mut is the only access while in useYesNo
    Checked by the borrow checkerYesNo
    Can do arithmetic (.add(n))NoYes

    Converting a reference to a raw pointer is safe: you’re only throwing promises away. Going back (&*pointer) is unsafe, because you’re claiming all the promises hold again.

    Common pitfalls

    Common pitfallA pointer from a temporary CString dangles

    CString::new(text).unwrap().as_ptr() looks fine, but the CString is a temporary that’s dropped at the end of the statement, so the pointer points at freed memory before you pass it to C. Bind the CString to a variable that lives longer than every use of the pointer, as in the strlen example. The compiler warns about this exact pattern (dangling_pointers_from_temporaries); don’t silence it.

    Common pitfallIt ran fine, so it's correct

    Code with undefined behavior often appears to work, until a release build, a new compiler or a different input changes the result. Running it proves nothing. Write down why each requirement holds in the // SAFETY: comment, and run the tests under Miri. If you can’t write the comment, the code isn’t ready.

    Common pitfallsafe fn in an extern block is your claim, not C's

    Marking a C function safe fn lets everyone call it without unsafe. If any argument can cause undefined behavior on the C side, like abs(INT_MIN) or a pointer argument, the declaration is wrong and every safe caller inherits the bug. Leave it unsafe and write a safe wrapper that checks its inputs.

    Common pitfallunsafe is not a project-wide switch

    In C#, AllowUnsafeBlocks is set once for the project and pointers then work anywhere inside an unsafe context. Rust has no switch: each unsafe block is a separate, local promise, and the compiler still checks types, borrows and lifetimes around it. To ban unsafe code from a crate entirely, add #![forbid(unsafe_code)] at the top of lib.rs or main.rs.

    Common pitfallunsafe is not an escape hatch from the type system

    Coming from TypeScript, it’s tempting to read unsafe like as any: a way to silence the compiler. It isn’t. Types, borrows and lifetimes are checked inside unsafe blocks exactly as outside them. If the borrow checker rejects your code, unsafe won’t help; restructure the code instead. To ban unsafe code from a crate entirely, add #![forbid(unsafe_code)] at the top of lib.rs or main.rs.

    Try it yourself

    Exercise: port this to Rust

    Port this program to Rust using the C runtime’s strstr function, which finds needle in haystack and returns a pointer to that position, or null if it isn’t there. Write a safe function find_from(haystack: &str, needle: &str) -> Option<String> that returns the rest of haystack from the first match, and None when either string contains a NUL byte.

    Starting code in TypeScript
    find.ts
    function findFrom(haystack: string, needle: string): string | null {
      if (haystack.includes("\0") || needle.includes("\0")) return null;
      const index = haystack.indexOf(needle);
      return index === -1 ? null : haystack.slice(index);
    }
    
    console.log(findFrom("hello, world", "wor") ?? "not found");
    console.log(findFrom("hello, world", "xyz") ?? "not found");
    console.log(findFrom("hello\0world", "wor") ?? "not found");
    Starting code in C#
    Find.cs
    Console.WriteLine(FindFrom("hello, world", "wor") ?? "not found");
    Console.WriteLine(FindFrom("hello, world", "xyz") ?? "not found");
    Console.WriteLine(FindFrom("hello\0world", "wor") ?? "not found");
    
    static string? FindFrom(string haystack, string needle)
    {
        if (haystack.Contains('\0') || needle.Contains('\0')) return null;
        int index = haystack.IndexOf(needle, StringComparison.Ordinal);
        return index == -1 ? null : haystack[index..];
    }

    Expected output

    world
    not found
    not found
    Show a hint

    Convert both strings with CString::new(...).ok()?, declare strstr(haystack, needle) in an unsafe extern C block returning *const c_char, check the result with is_null(), then wrap it with CStr::from_ptr and convert it with to_string_lossy().

    Show a solution
    use std::ffi::{CStr, CString, c_char};
    
    unsafe extern "C" {
        fn strstr(haystack: *const c_char, needle: *const c_char) -> *const c_char;
    }
    
    fn find_from(haystack: &str, needle: &str) -> Option<String> {
        let haystack = CString::new(haystack).ok()?;
        let needle = CString::new(needle).ok()?;
        // SAFETY: both pointers come from live CStrings, so they're valid and NUL-terminated.
        let found = unsafe { strstr(haystack.as_ptr(), needle.as_ptr()) };
        if found.is_null() {
            return None;
        }
        // SAFETY: strstr returned a pointer into `haystack`, which is still alive and NUL-terminated.
        let rest = unsafe { CStr::from_ptr(found) };
        Some(rest.to_string_lossy().into_owned())
    }
    
    fn main() {
        for (haystack, needle) in [
            ("hello, world", "wor"),
            ("hello, world", "xyz"),
            ("hello\0world", "wor"),
        ] {
            let result = find_from(haystack, needle);
            println!("{}", result.as_deref().unwrap_or("not found"));
        }
    }

    find_from is a safe function: CString::new rejects text with NUL bytes, so the unsafe block only ever sees valid C strings. strstr returns null or a pointer into haystack, and haystack is still alive when CStr::from_ptr reads from it. Each unsafe block has a SAFETY comment saying why. Converting to an owned String means the result doesn't depend on haystack once the function returns.

    Saved in this browser only.