Skip to content

Instantly share code, notes, and snippets.

View nyinyithann's full-sized avatar
🎩

Nyi Nyi nyinyithann

🎩
View GitHub Profile
@nyinyithann
nyinyithann / newtype_pattern.rs
Created December 23, 2018 07:25
The newtype pattern with Deref/DerefMut trait implementation
/*
To implement a trait on a type, the trait or the type has to be local to the code you work on. It is called the orphan rule.
To get around this restriction, we can use the newtype pattern which involves creating a new type in a tuple struct.
Both Vec<T> and Display trait are from the standard library and neither is local to our code.
We are not able to implement Display trait to Vec<T>. But we can construct a wrapper type holding an instance of Vec<T> and implement Display trait on it.
In the following example, VecWrapper<T> struct wraps Vec<T> and implements Display trait.
To get all the methods of Vec<T> available to VecWrapper, Deref trait is implemented on it.
ref: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html?search=borrow%20and%20asref
*/
@nyinyithann
nyinyithann / basic_router.rs
Created December 24, 2018 16:28
using closure as callback
use std::collections::HashMap;
fn main() {
let mut router = BasicRouter::new();
router.add_route("/", |req| Response {
code: 200,
headers: req.headers.clone(),
body: vec![1, 2, 3, 4, 5],
});
@nyinyithann
nyinyithann / counter.rs
Last active December 25, 2018 11:17
Implement Iterator trait to Counter
/* Counter example can be seen at https://doc.rust-lang.org/std/iter/index.html#implementing-iterator
I just wanna try out implementing Iterator trait on tuple like struct.
Due to the IntoIterator blanket implementation in standard library - "impl<I: Iterator> IntoIterator for I" ,
all Iterator can be treated like IntoIterator. That's why we can call c.into_iter() in the code.
*/
use std::iter::*;
fn main() {
let mut z = 0u32;
let ref mut c = Counter(&mut z);
@nyinyithann
nyinyithann / type_name.rs
Created December 26, 2018 09:02
get type name
#![feature(core_intrinsics)]
fn print_type_of<T>(_: &T) {
println!("{}", unsafe { std::intrinsics::type_name::<T>() });
}
@nyinyithann
nyinyithann / print_low_level_error.rs
Created January 18, 2019 03:14
Print error and its source
use std::error::Error;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::{stderr, Write};
fn main() {
let r = read_file("wrong.test"); // read_file(r"/Users/nyinyithan/Downloads/test.json");
match r {
Ok(txt) => println!("{}", txt),
@nyinyithann
nyinyithann / update_slice_of_vector.rs
Created January 18, 2019 06:58
update a particular slice of vector
let mut v = vec![1, 2, 3, 4, 5];
let r = v
.get_mut(1..=2)
.map(|x| x.iter_mut().for_each(|y| *y *= 10));
if r.is_some() {
println!("Succeed : {:?}", v);
} else {
println!("Not Succeed. Do something here.");
}
@nyinyithann
nyinyithann / semi_monad_function_of_result_type.rs
Last active February 8, 2019 18:45
composition of functions of Result<T,E>
use std::io;
use std::io::prelude::*;
fn main() {
loop {
let r = get_input("Enter the first number: ")
.and_then(|x| get_input("Enter the second number: ")
.and_then(|y| get_input("Enter the third number: ")
.and_then(|z| Ok(x + y + z))));
@nyinyithann
nyinyithann / option_ext.rs
Last active February 6, 2019 13:17
add fold method to Option<T>
use std::borrow::BorrowMut;
pub trait OptionExt<T> {
fn fold<S, F>(&self, state: S, folder: F) -> S
where
F: FnOnce(S, &T) -> S;
}
impl<T> OptionExt<T> for Option<T> {
fn fold<S, F>(&self, state: S, folder: F) -> S
@nyinyithann
nyinyithann / unsafe_freestanding.rs
Created February 13, 2019 15:52
A simple freestanding program using libc
#![feature(start)]
#![no_std]
extern crate libc;
use core::panic::PanicInfo;
use libc::{c_char, c_int, c_void, size_t};
extern "C" {
fn malloc(size: size_t) -> *mut c_void;
fn free(p: *mut c_void);
@nyinyithann
nyinyithann / box_t_to_ref_t_with_unsafe.rs
Last active March 11, 2019 07:18
Convert Box<Trait> To concrete type with unsafe
trait Animal {
fn speak(&self);
}
#[derive(Debug)]
struct Dog {
name: String,
age: u8,
}