Getting back to safety

Like we discussed previously, the preceding examples were intentionally low-level and unsafe. How can we build something similar with the bits and pieces that Rust provides us with? Here's one approach:

use std::{mem, thread}; use std::sync::{Arc, Mutex}; struct Ring { size: usize, data: Vec<Option<u32>>, } impl Ring { fn with_capacity(capacity: usize) -> Ring { let mut data: Vec<Option<u32>> = Vec::with_capacity(capacity); for _ in 0..capacity { data.push(None); } Ring { size: 0, data: data, } } fn capacity(&self) -> usize { self.data.capacity() } fn is_full(&self) -> bool { self.size == self.data.capacity() } fn emplace(&mut self, offset: usize, val: u32) -> Option<u32> { self.size += 1; let res = mem::replace(&mut ...

Get Hands-On Concurrency with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.