Skip to content

Instantly share code, notes, and snippets.

@KodrAus
KodrAus / main.rs
Last active December 5, 2016 07:30
elastic_requests codegen
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> {
@KodrAus
KodrAus / main.rs
Last active November 22, 2016 11:11
elastic_requests API
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))
@KodrAus
KodrAus / main.rs
Last active October 31, 2016 21:23
elastic API
// 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
@KodrAus
KodrAus / post.md
Created August 24, 2016 09:44
Gymnerics with Rust
@KodrAus
KodrAus / playground.rs
Last active August 22, 2016 11:39
Rust Concurrency
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),
@KodrAus
KodrAus / playground.rs
Created August 22, 2016 11:19
Rust Docs
//! # 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:
///
/// ```
@KodrAus
KodrAus / playground.rs
Created August 22, 2016 11:14
Rust Testing
#[test]
fn it_works() {
assert!(true);
}
@KodrAus
KodrAus / playground.rs
Created August 22, 2016 11:09
Rust Crossbeam
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
@KodrAus
KodrAus / playground.rs
Last active August 22, 2016 10:28
Rust References
fn main() {
//String is a (possibly) mutable, growable slice of UTF-8 characters
let mut mutable_string: String = String::from("my owned string");
//We can borrow a String as an immutable &str, because of the Deref trait
let borrowed_str: &str = &mutable_string;
//Vec is a (possibly) mutable, growable contiguous array of things
let mut mutable_vec: Vec<i32> = vec![1, 2, 3];
@KodrAus
KodrAus / playground.rs
Last active August 22, 2016 10:26
Rust Results
fn maybe_works(i: i32) -> Result<(), String> {
//The try! macro makes early return from errors easier. There's a '?' operator coming soon
//Composing error types and implementing Error can suck, so libraries like error_chain help
//Result has similar helpers to Option
try!(must_not_be_negative(i));
Ok(())
}