Skip to content

Instantly share code, notes, and snippets.

View dbp's full-sized avatar

Daniel Patterson dbp

View GitHub Profile
@dbp
dbp / gist:3308745
Created August 9, 2012 22:44
Rust Pretty printing closures
// how pretty printer formats closures (I think; I'm unable to build from incoming right now to check)
fn main() {
do something |foo|
{
something_long_enough_to_not;
fit_on_a_single_line;
}
let my_fn = ||
{
something_long_enough_to_not;
@dbp
dbp / bits.rs
Created August 16, 2012 16:39
converting ~[u8] to u32
fn main() {
let bytes : ~[u8] = ~[1,1,1]; // for example
let len = vec::len(bytes)-1;
let mut out: u32 = 0;
do vec::iteri(bytes) |i, b| {
out += (b as u32) << (8*(len-i))
}
io::println(u32::str(out));
}
@dbp
dbp / gist:3442506
Created August 23, 2012 21:58
macro
macro_rules! num_visitor(
($typ:ident) => (
fn visit_$typ() -> bool {
self.align_to::<$typ>();
do self.get::<$typ>() |i| {
self.out += $typ::to_str(i, 10u);
};
self.bump_past::<$typ>();
true
}
@dbp
dbp / gist:3454083
Created August 24, 2012 18:33
enum variant
...
fn visit_enter_enum_variant(_variant: uint,
_disr_val: int,
_n_fields: uint,
_name: &str) -> bool {
do self.get::<int>() |e| {
if e == _disr_val {
self.out += _name;
}
};
@dbp
dbp / gist:3456960
Created August 24, 2012 23:10
visiting vectors
fn visit_evec_uniq(_mtbl: uint, _inner: *tydesc) -> bool {
self.out += ~"~[";
self.align_to::<~[u8]>();
self.visit_unboxed_vec(_mtbl, _inner);
self.bump_past::<~[u8]>();
self.out += ~"]";
true
}
fn visit_unboxed_vec(_mtbl: uint, _inner: *tydesc) -> bool {
@dbp
dbp / gist:3471529
Created August 25, 2012 22:18
visit_estr_fixed
fn visit_estr_fixed(_n: uint, _sz: uint,
_align: uint) -> bool {
self.align(_align);
self.out += ~"\"";
unsafe {
self.out += str::unsafe::from_buf_len(self.ptr as *u8, _n);
}
self.bump(_sz);
self.out += ~"\"";
true
@dbp
dbp / reflect.rs
Created September 1, 2012 02:36
data visitor
import intrinsic::{tydesc, get_tydesc, visit_tydesc, ty_visitor};
import libc::c_void;
trait MovablePtr {
fn move_ptr(adjustment: fn(*c_void) -> *c_void);
}
// FIXME #3262: this is a near-duplicate of code in core::vec.
type VecRepr = {
box_header: (uint, uint, uint, uint),
@dbp
dbp / fmt.rs
Created September 14, 2012 03:17
fmt datavisitor
extern mod std; // for tests
use reflect::*;
enum fmt_visitor = @{
out: io::WriterUtil,
};
// duplicated from syntax/ast.rs so as not to depend on it
enum mutability { m_mutbl, m_imm, m_const, }
@dbp
dbp / copy_type.rs
Created October 7, 2012 21:55
instantiating copy type warning
fn main() {
let x = (~"a",~"b");
io::println(x.second());
}
@dbp
dbp / gist:3856358
Created October 9, 2012 03:12
purity
struct C {mut d: ~[uint]}
fn main() {
let mut c = C {d: ~[1,2,3]};
f(&c);
}
fn f(x: &C) {
for x.d.each |e| {
io::println(~"a");