Stringly Typed

folkert@folkertdev.nl

folkert@tweedegolf.com

Rust on Embedded

Network Time Protocol

Roc

Types as guarantees

  • How many bytes
  • What do the bytes mean
  • who owns those bytes

Let's put that into the types

Types come in pairs

&str String
borrowed owned
immutable mutable/growable

String/&str

struct &str {
    ptr: *const u8,
    length: usize,
}

struct String {
    ptr: *const u8,
    length: usize,
    capacity: usize,
}

String/&str

https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/

String/&str

NULL-termination is evil!

String/&str

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

A string is valid UTF-8

 // "0b00001100"
println!("0b{:08b}", 12);

String/&str

CString/&CStr

use std::ffi::CString;
use std::os::raw::c_char;

extern "C" {
    fn my_printer(s: *const c_char);
}

let c_to_print = CString::new("Hello, world!").unwrap()
unsafe {
    my_printer(c_to_print.as_ptr());
}
  • guarantees the NULL byte
  • has no particular encoding

OsString/&OsStr

PathBuf/&Path

use std::path::PathBuf;

let mut path = PathBuf::new();

path.push(r"C:\");
path.push("windows");
path.push("system32");

path.set_extension("dll");

assert_eq!(path, PathBuf::from(r"C:\windows\system32.dll"));

Summary

Rust uses types to encode invariants

Summary

Invariants are checked at the boundary

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

Summary

Gnarly details must be considered

But tries to wrap them up nicely

Summary

APIs for humans

pub struct Path {
    inner: OsStr,
}

impl Path {
    ...
}

Conclusion

Next Steps

Next Steps

doc.rust-lang.org

Rust intro

By folkert de vries

Rust intro

  • 50