Skip to content

Instantly share code, notes, and snippets.

@kmcallister
kmcallister / void.rs
Created February 18, 2014 19:57
Void type in Rust
enum Void {}
impl Void {
fn unreachable(self) -> ! {
match self { }
}
unsafe fn make() -> Void {
std::unstable::intrinsics::uninit()
}
@kmcallister
kmcallister / gist:9222833
Created February 26, 2014 03:11
faking top level anonymous unions
#include <stdint.h>
#include <stdio.h>
uint32_t u32 = 0;
extern uint8_t u8[4] __attribute__((alias("u32")));
int main() {
printf("%08x\n", u32);
u8[0] = 1;
printf("%08x\n", u32);
@kmcallister
kmcallister / gist:9356218
Last active August 29, 2015 13:57
faking global, constant-after-init structs
use std::cast;
struct FooStatics {
x: int,
}
static mut globalFooStatics: *FooStatics = 0 as *FooStatics;
impl FooStatics {
unsafe fn init() {
@kmcallister
kmcallister / gist:9423251
Created March 8, 2014 00:36
phantom types for fake mut polymorphism
use std::cast;
use std::unstable::raw;
struct Mutable;
struct Immutable;
struct Foobar<'t, Mutability> {
/* priv */ ptr: raw::Slice<u8>
}
@kmcallister
kmcallister / gist:9515601
Created March 12, 2014 20:26
macro sadness
#[feature(macro_rules)];
// Shorthand for state-machine actions.
macro_rules! one (
( inc ) => ( self.counter += 1; );
( print ) => ( println!("counter is {:d}", self.counter); );
)
// A DSL for sequencing shorthand actions.
macro_rules! go (
@kmcallister
kmcallister / gist:9698903
Created March 21, 2014 23:50
non-BMP characters in JSON
extern crate serialize;
use serialize::json;
fn main() {
println!("{:?}", json::from_str("\"\\ud83d\\udca9\""));
}
@kmcallister
kmcallister / gist:9730619
Created March 23, 2014 22:09
test_eq! macro
macro_rules! test_eq( ($name:ident, $left:expr, $right:expr) => (
#[test]
fn $name() {
assert_eq!($left, $right);
}
))
@kmcallister
kmcallister / fizyks.pl
Created March 27, 2014 17:26
physics homework solution generator (I wrote this like 10 years ago…)
#!/usr/bin/perl -w
use strict;
sub shuffle {
my @new;
while(scalar(@_) > 0) {
push @new, (splice @_, rand(scalar(@_)), 1);
}
return @new;
@kmcallister
kmcallister / gist:9907899
Created April 1, 2014 04:51
z3rs early example
fn main() {
let ctx = z3::Context::new();
let x = ctx.new_bool();
let y = ctx.new_bool();
let demorgan = (!(x & y)).iff(!x | !y);
ctx.assert(demorgan);
println!("{:?}", ctx.check()); // => Some(true)
@kmcallister
kmcallister / test.rs
Last active August 29, 2015 13:58
Scanning for ASCII whitespace with SSE 4.2
#[feature(asm, macro_rules)];
extern crate test;
use test::BenchHarness;
static whitespace: &'static [u8] = bytes!("\r\n\t \0 ");
#[inline(never)]
fn has_space_sse(s: &str) -> bool {