Skip to content

Instantly share code, notes, and snippets.

// HAVE:
let dest = if let Some(ref p) = self.destination {
p.as_ptr() as *const _
} else {
0 as *const _
};
// WANT:
fn main() {
extern "C" fn callback(msg: c_uint, user_data: c_long, p1: c_long, p2: c_long) -> c_int {
let ptr = p1 as *const _;
// turn information into a Rust String
let information = str::from_utf8(unsafe { CStr::from_ptr(ptr) }.to_bytes()).unwrap();
// get user_data (our passed String):
let our_string = str::from_utf8(unsafe { slice::from_raw_parts(user_data as *const u8, 1024) } ).unwrap();
// write information to our_string here...
}
let user_data = String::with_capacity(1024);
impl<F> NetworkConnector for F where F: Fn(&str, u16, &str) -> io::Result<TcpStream> {
type Stream = HttpStream;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
Ok(HttpStream(try!((*self)(host, port, scheme))))
}
}
impl<F> NetworkConnector for F where F: Fn(&str, u16) -> io::Result<TcpStream> {
type Stream = HttpStream;
impl<F> NetworkConnector for F where F: Fn(&str, u16, &str) -> io::Result<TcpStream> {
type Stream = HttpStream;
fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> {
Ok(HttpStream(try!((*self)(host, port, scheme))))
}
}
@muja
muja / conn.rs
Last active August 29, 2015 14:26
pub struct TcpBuilderConnector<F: Fn() -> io::Result<TcpBuilder>> {
pub create: F
}
impl Default for TcpBuilderConnector<fn() -> io::Result<TcpBuilder>> {
fn default() -> Self {
TcpBuilderConnector {
create: TcpBuilder::new_v4
}
struct X {
counter: u32
}
impl X {
fn handler(&self, _: &mut Request) -> IronResult<Response> {
self.counter += 1;
Ok(Response::with((iron::status::Ok, "Hello World")))
}
}
@muja
muja / duktape.rs
Last active August 29, 2015 14:25
ctx = duk_create_heap(None, None, None, ptr::null_mut(), None)
duk_push_string(ctx, "function x() { return '4'; }");
duk_push_string(ctx, "<eval>");
duk_eval_raw(ctx, 0, 0, DUK_COMPILE_FUNCTION);
value = duk_get_string(ctx, 0);
duk_destroy_heap(ctx);
@muja
muja / client.rs
Last active August 29, 2015 14:25
/// Create a new client with a specific connector.
pub fn with_connector<C, S>(connector: C) -> Client
where C: NetworkConnector<Stream=S> + Send + Sync + 'static, S: NetworkStream + Send {
Client::with_protocol(Http11Protocol::with_connector(connector))
}
/// Create a new client with a specific connector.
pub fn with_connector<C, S>(connector: C) -> Client
where C: Into<NetworkConnector<Stream=S>> + Send + Sync + 'static, S: NetworkStream + Send {
fn main () {
for iface in ifaces::Interface::get_all().unwrap().into_iter() {
match iface.addr.unwrap().ip() {
IpAddr::V4(ip) => println!("{}: {:?}", iface.name, ip.is_loopback()),
_ => ()
}
}
}
require 'rexml/document'
module HashToXML
def self.to_xml(any, **options)
document = if any.is_a? REXML::Document
any
else
to_xml_document(any, **options)
end