Experimental browser compiler for Rust, based on rustc 1.99.1
language="rust" (or rs) compiles a Rust program with a modified
rustc 1.99.1, compiled to WebAssembly with a code generator written for code-playpad, and
runs it in a Web Worker. Programs use the standard library; there are no external crates.
The first Run downloads about 57 MB from jsDelivr, the 7 MB linker it shares
with C/C++ included; later runs use Cache Storage.
Not affiliated with or endorsed by the Rust Project or the Rust Foundation.
Hello
fn main() {
let names = ["Ada", "Grace", "Linus"];
for name in names {
println!("Hello, {name}!");
}
}
Reading stdin
Input is prefilled: edit the stdin box before pressing Run.
use std::io::{self, BufRead};
fn main() {
for line in io::stdin().lock().lines() {
let numbers: Vec<i64> = line.unwrap().split_whitespace().map(|n| n.parse().unwrap()).collect();
println!("{} = {}", numbers.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(" + "), numbers.iter().sum::<i64>());
}
}
A practice problem
use std::collections::HashMap;
fn two_sum(numbers: &[i32], target: i32) -> Option<(usize, usize)> {
let mut seen = HashMap::new();
for (i, &n) in numbers.iter().enumerate() {
if let Some(&j) = seen.get(&(target - n)) {
return Some((j, i));
}
seen.insert(n, i);
}
None
}
fn main() {
println!("{:?}", two_sum(&[2, 7, 11, 15], 9));
}
Traits and generics
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String;
}
struct Circle { r: f64 }
struct Rect { w: f64, h: f64 }
impl Shape for Circle {
fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
fn name(&self) -> String { format!("circle r={}", self.r) }
}
impl Shape for Rect {
fn area(&self) -> f64 { self.w * self.h }
fn name(&self) -> String { format!("rect {}x{}", self.w, self.h) }
}
fn largest<'a>(shapes: &'a [Box<dyn Shape>]) -> &'a dyn Shape {
shapes.iter().max_by(|a, b| a.area().total_cmp(&b.area())).unwrap().as_ref()
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle { r: 1.5 }), Box::new(Rect { w: 2.0, h: 3.0 })];
for s in &shapes {
println!("{:<12} {:.2}", s.name(), s.area());
}
println!("largest: {}", largest(&shapes).name());
}
Enums and pattern matching
#[derive(Debug)]
enum Command {
Move { x: i32, y: i32 },
Say(String),
Repeat(u32, Box<Command>),
Quit,
}
fn run(cmd: &Command, pos: &mut (i32, i32)) -> bool {
match cmd {
Command::Move { x, y } if *x == 0 && *y == 0 => println!("stay at {pos:?}"),
Command::Move { x, y } => {
pos.0 += x;
pos.1 += y;
println!("move to {pos:?}");
}
Command::Say(text) => println!("say {text:?}"),
Command::Repeat(n, inner) => {
for _ in 0..*n {
run(inner, pos);
}
}
Command::Quit => return false,
}
true
}
fn main() {
let program = vec![
Command::Say("hello".to_string()),
Command::Move { x: 2, y: 1 },
Command::Move { x: 0, y: 0 },
Command::Repeat(2, Box::new(Command::Move { x: -1, y: 3 })),
Command::Quit,
Command::Say("never printed".to_string()),
];
let mut pos = (0, 0);
for cmd in &program {
if !run(cmd, &mut pos) {
println!("quit after {cmd:?}");
break;
}
}
}
Errors with Result and ?
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum AgeError {
NotANumber(ParseIntError),
TooOld(u32),
}
impl fmt::Display for AgeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AgeError::NotANumber(e) => write!(f, "not a number ({e})"),
AgeError::TooOld(age) => write!(f, "{age} is too old"),
}
}
}
impl From<ParseIntError> for AgeError {
fn from(e: ParseIntError) -> Self {
AgeError::NotANumber(e)
}
}
fn parse_age(text: &str) -> Result<u32, AgeError> {
let age: u32 = text.trim().parse()?;
if age > 150 {
return Err(AgeError::TooOld(age));
}
Ok(age)
}
fn main() {
for input in ["42", " 7 ", "abc", "200", "-3"] {
match parse_age(input) {
Ok(age) => println!("{input:>5} -> {age}"),
Err(e) => println!("{input:>5} -> error: {e}"),
}
}
let total: Result<u32, AgeError> = ["1", "2", "3"].iter().map(|s| parse_age(s)).sum();
println!("sum: {:?}", total.map_err(|e| e.to_string()));
let first = ["x", "4"].iter().find_map(|s| parse_age(s).ok());
println!("first valid: {first:?}");
}
Iterators and closures
fn main() {
let temps = [12.5, 14.0, 9.5, 17.25, 21.0, 19.5, 11.0];
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let warm: Vec<&str> = days.iter().zip(temps).filter(|(_, t)| *t > 15.0).map(|(d, _)| *d).collect();
println!("warm days: {}", warm.join(", "));
let mean = temps.iter().sum::<f64>() / temps.len() as f64;
println!("mean: {mean:.2}");
let (coldest, hottest) = temps.iter().fold((f64::MAX, f64::MIN), |(lo, hi), &t| (lo.min(t), hi.max(t)));
println!("range: {coldest} to {hottest}");
let rises: Vec<String> = temps.windows(2).map(|w| format!("{:+.1}", w[1] - w[0])).collect();
println!("day to day: {}", rises.join(" "));
let mut by_temp: Vec<(&str, f64)> = days.into_iter().zip(temps).collect();
by_temp.sort_by(|a, b| b.1.total_cmp(&a.1));
let top: Vec<_> = by_temp.iter().take(3).map(|(d, t)| format!("{d} {t}")).collect();
println!("top 3: {top:?}");
let squares_of_odds: u32 = (1..=10).filter(|n| n % 2 == 1).map(|n| n * n).sum();
println!("sum of odd squares up to 10: {squares_of_odds}");
}
Counting words with a HashMap
use std::collections::HashMap;
fn main() {
let text = "the quick brown fox jumps over the lazy dog the fox barks";
let mut counts: HashMap<&str, usize> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_default() += 1;
}
let mut ranked: Vec<(&str, usize)> = counts.into_iter().collect();
ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
for (word, n) in ranked.iter().take(5) {
println!("{word:<6} {}", "*".repeat(*n));
}
let distinct = ranked.len();
let longest = ranked.iter().map(|(w, _)| *w).max_by_key(|w| w.len()).unwrap();
println!("{distinct} distinct words; longest: {longest}");
}
Operator overloading
use std::fmt;
use std::ops::{Add, Mul, Neg};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Vec2 {
fn new(x: f64, y: f64) -> Self { Vec2 { x, y } }
fn length(self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() }
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, other: Vec2) -> Vec2 { Vec2::new(self.x + other.x, self.y + other.y) }
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, k: f64) -> Vec2 { Vec2::new(self.x * k, self.y * k) }
}
impl Neg for Vec2 {
type Output = Vec2;
fn neg(self) -> Vec2 { Vec2::new(-self.x, -self.y) }
}
impl fmt::Display for Vec2 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({:.1}, {:.1})", self.x, self.y)
}
}
fn main() {
let a = Vec2::new(3.0, 4.0);
let b = Vec2::new(-1.0, 0.5);
println!("a = {a}, |a| = {}", a.length());
println!("a + b = {}", a + b);
println!("a * 2 = {}", a * 2.0);
println!("-b = {}", -b);
println!("a + b == b + a: {}", a + b == b + a);
let path = [a, b, Vec2::new(0.0, -2.0)];
let end = path.iter().fold(Vec2::new(0.0, 0.0), |acc, &step| acc + step);
println!("end of path: {end}");
}
A generic stack
use std::fmt::Display;
struct Stack<T> {
items: Vec<T>,
}
impl<T: Display> Stack<T> {
fn new() -> Self { Stack { items: Vec::new() } }
fn push(&mut self, item: T) { self.items.push(item); }
fn pop(&mut self) -> Option<T> { self.items.pop() }
fn peek(&self) -> Option<&T> { self.items.last() }
fn len(&self) -> usize { self.items.len() }
fn show(&self) -> String {
self.items.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(" | ")
}
}
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut best = items[0];
for &item in items {
if item > best {
best = item;
}
}
best
}
fn main() {
let mut numbers = Stack::new();
for n in [3, 1, 4, 1, 5] {
numbers.push(n);
}
println!("stack: {}", numbers.show());
println!("pop: {:?}, peek: {:?}, len: {}", numbers.pop(), numbers.peek(), numbers.len());
let mut words: Stack<String> = Stack::new();
words.push("alpha".into());
words.push("beta".into());
println!("words: {}", words.show());
println!("largest i32: {}", largest(&[34, 50, 25, 100, 65]));
println!("largest char: {}", largest(&['y', 'm', 'a', 'q']));
println!("largest f64: {}", largest(&[0.5, 2.25, -1.0]));
}
Shortest paths with a BinaryHeap
use std::cmp::Reverse;
use std::collections::BinaryHeap;
// Shortest distances from node 0 in a weighted, directed graph.
fn dijkstra(n: usize, edges: &[(usize, usize, u32)]) -> Vec<Option<u32>> {
let mut adjacent = vec![Vec::new(); n];
for &(from, to, w) in edges {
adjacent[from].push((to, w));
}
let mut dist = vec![None; n];
let mut heap = BinaryHeap::new();
heap.push(Reverse((0u32, 0usize)));
while let Some(Reverse((d, node))) = heap.pop() {
if dist[node].is_some() {
continue;
}
dist[node] = Some(d);
for &(next, w) in &adjacent[node] {
if dist[next].is_none() {
heap.push(Reverse((d + w, next)));
}
}
}
dist
}
fn main() {
let edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5), (3, 4, 3)];
for (node, d) in dijkstra(6, &edges).iter().enumerate() {
match d {
Some(d) => println!("0 -> {node}: {d}"),
None => println!("0 -> {node}: unreachable"),
}
}
}
Shared state with Rc and RefCell
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
struct Account {
owner: String,
balance: i64,
}
fn main() {
let shared = Rc::new(RefCell::new(Account { owner: "Ada".into(), balance: 100 }));
let wallet = Rc::clone(&shared);
let bank = Rc::clone(&shared);
println!("owners of the account: {}", Rc::strong_count(&shared));
wallet.borrow_mut().balance -= 30;
bank.borrow_mut().balance += 5;
println!("after spending and interest: {}", shared.borrow().balance);
{
let reading = shared.borrow();
let again = shared.try_borrow_mut();
println!("{} is reading; can someone write now? {}", reading.owner, again.is_ok());
}
println!("and after the read ends? {}", shared.try_borrow_mut().is_ok());
drop(wallet);
println!("owners left: {}", Rc::strong_count(&shared));
println!("{:?}", shared.borrow());
}
Recursion: n queens
// Count the ways to place n queens on an n x n board, and draw the first one.
fn solve(n: usize, row: usize, cols: &mut Vec<usize>, count: &mut u32, first: &mut Option<Vec<usize>>) {
if row == n {
*count += 1;
if first.is_none() {
*first = Some(cols.clone());
}
return;
}
for col in 0..n {
let safe = cols.iter().enumerate().all(|(r, &c)| c != col && row - r != col.abs_diff(c));
if safe {
cols.push(col);
solve(n, row + 1, cols, count, first);
cols.pop();
}
}
}
fn main() {
for n in 4..=8 {
let (mut count, mut first) = (0, None);
solve(n, 0, &mut Vec::new(), &mut count, &mut first);
println!("{n} queens: {count} solutions");
if n == 8 {
for &col in first.as_ref().unwrap() {
let line: String = (0..n).map(|c| if c == col { 'Q' } else { '.' }).collect();
println!(" {line}");
}
}
}
}
Strings and Unicode
fn is_palindrome(s: &str) -> bool {
let letters: Vec<char> = s.chars().filter(|c| c.is_alphanumeric()).map(|c| c.to_ascii_lowercase()).collect();
letters.iter().eq(letters.iter().rev())
}
fn caesar(s: &str, shift: u8) -> String {
s.chars()
.map(|c| match c {
'a'..='z' => ((c as u8 - b'a' + shift) % 26 + b'a') as char,
'A'..='Z' => ((c as u8 - b'A' + shift) % 26 + b'A') as char,
_ => c,
})
.collect()
}
fn main() {
for s in ["A man, a plan, a canal: Panama", "Rust", "Was it a car or a cat I saw?"] {
println!("{s:?} palindrome? {}", is_palindrome(s));
}
let secret = caesar("Hello, World!", 3);
println!("{secret} -> {}", caesar(&secret, 23));
let sentence = "the rain in spain stays mainly in the plain";
let title: Vec<String> = sentence
.split(' ')
.map(|w| {
let mut chars = w.chars();
match chars.next() {
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
})
.collect();
println!("{}", title.join(" "));
let word = "héllo wörld";
println!("{word:?}: {} bytes, {} chars, reversed {:?}", word.len(), word.chars().count(), word.chars().rev().collect::<String>());
}
Several files
mod shapes;
use shapes::Rect;
fn main() {
let r = Rect { w: 3, h: 4 };
println!("area {}, perimeter {}", r.area(), r.perimeter());
}
pub struct Rect {
pub w: u32,
pub h: u32,
}
impl Rect {
pub fn area(&self) -> u32 { self.w * self.h }
pub fn perimeter(&self) -> u32 { 2 * (self.w + self.h) }
}
A compiler error
fn main() {
let answer: i32 = "forty-two";
println!("{answer}");
}
A panic
fn main() {
let v = vec![1, 2, 3];
let i = v.len();
println!("{}", v[i]);
}
Stop a runaway loop
fn main() {
println!("Press Stop.");
loop {}
}
Limits
- One
bin crate, edition 2024, built without optimisation (opt-level=0) and with overflow checks; a panic aborts the program. No external crates.
- No threads, networking or files: the program runs as WASI with only stdin, stdout and stderr. Input must be prefilled.
- A Run has 120 seconds, counted from the start of compiling: the first download doesn't count. A compile that overflows the worker's stack is retried on the page, which can't be stopped until it returns.
- Very large functions can exhaust the code generator's memory; deep recursion in a program can overflow sooner in Safari.
- Desktop Chrome, Firefox and Safari are tested. Phones are not.
An independent project. The compiler is modified and experimental: it is not the Rust
Project's compiler, and it may reject or miscompile programs the official compiler accepts.
Not affiliated with or endorsed by the Rust Project or the Rust Foundation.