gymnerics : the art of pretzelling the generics of a type system to fulfill your nefarious schemes.
https://play.rust-lang.org/?gist=5fbec1ac11432d30f3b0433d93daad59&version=stable&backtrace=0
use std::borrow::Cow; | |
use std::ops::Deref; | |
// - Codegen once - | |
#[derive(Debug)] | |
pub struct Body<'a>(Cow<'a, [u8]>); | |
impl <'a> From<Vec<u8>> for Body<'a> { |
// Our request type. Owned by someone else | |
trait Request { | |
fn url(&self) -> String; | |
} | |
trait IntoRequest<R> where R: Request { | |
fn into_request(self) -> R; | |
} | |
impl <R, I> IntoRequest<R> for I where |
use std::borrow::Cow; | |
// Our wrapper types are basically a thin layer over a &str | |
macro_rules! wrapper { | |
($name:ident) => { | |
pub struct $name<'a>(pub Cow<'a, str>); | |
impl <'a> From<&'a str> for $name<'a> { | |
fn from(value: &'a str) -> $name<'a> { | |
$name(Cow::Borrowed(value)) |
gymnerics : the art of pretzelling the generics of a type system to fulfill your nefarious schemes.
https://play.rust-lang.org/?gist=5fbec1ac11432d30f3b0433d93daad59&version=stable&backtrace=0
//! # My Library | |
//! | |
//! This is a module-level doc comment. | |
//! Standard markdown is supported | |
/// This is a comment for an item. | |
/// | |
/// Code samples are compiled and tested: | |
/// | |
/// ``` |
#[test] | |
fn it_works() { | |
assert!(true); | |
} |
extern crate crossbeam; | |
fn main() { | |
//Here we have a mutable array | |
let mut data = vec![1, 2, 3]; | |
println!("{:?}", data); | |
//With crossbeam magic we can mutate this array concurrently without locks | |
//The crossbeam scope guarantees that the threads inside it will end before the scope does |
use std::sync::{ Arc, RwLock }; | |
use std::thread; | |
fn main() { | |
//Here we have an immutable array with mutable interior cells | |
//The length of the array can't change, but internal values can | |
//We use the Send sync variants for threading | |
let data = Arc::new(vec![ | |
RwLock::new(1), | |
RwLock::new(2), |
#[derive(Debug)] | |
struct Data; | |
//By default, variables must have a value | |
//Option<T> lets you explicitly bind to 'None' | |
fn might_be_null(input: bool) -> Option<Data> { | |
if input { | |
Some(Data) | |
} | |
else { |
fn main() { | |
//The vec! macro is sugar for inline Vec<T> building | |
let vec1 = vec!["a", "b", "c"]; | |
let vec2 = vec![1, 2, 3]; | |
//Rust has iterators, which are usually cheaper than looping | |
for (&x, &y) in vec1.iter().zip(vec2.iter()) { | |
println!("{}, {}", x, y); | |
} | |