<commit_before>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use LinkerFlavor;
use target::{Target, TargetResult};

pub fn target() -> TargetResult {
    let mut base = super::solaris_base::opts();
    base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]);
    // llvm calls this "v9"
    base.cpu = "v9".to_string();
    base.max_atomic_width = Some(64);

    Ok(Target {
        llvm_target: "sparcv9-sun-solaris".to_string(),
        target_endian: "big".to_string(),
        target_pointer_width: "64".to_string(),
        target_c_int_width: "32".to_string(),
        data_layout: "E-m:e-i64:64-n32:64-S128".to_string(),
        // Use "sparc64" instead of "sparcv9" here, since the former is already
        // used widely in the source base.  If we ever needed ABI
        // differentiation from the sparc64, we could, but that would probably
        // just be confusing.
        arch: "sparc64".to_string(),
        target_os: "solaris".to_string(),
        target_env: "".to_string(),
        target_vendor: "sun".to_string(),
        linker_flavor: LinkerFlavor::Gcc,
        options: base,
    })
}
<commit_msg>Rollup merge of #45508 - bgermann:master, r=alexcrichton<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use LinkerFlavor;
use target::{Target, TargetResult};

pub fn target() -> TargetResult {
    let mut base = super::solaris_base::opts();
    base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]);
    // llvm calls this "v9"
    base.cpu = "v9".to_string();
    base.max_atomic_width = Some(64);
    base.exe_allocation_crate = None;

    Ok(Target {
        llvm_target: "sparcv9-sun-solaris".to_string(),
        target_endian: "big".to_string(),
        target_pointer_width: "64".to_string(),
        target_c_int_width: "32".to_string(),
        data_layout: "E-m:e-i64:64-n32:64-S128".to_string(),
        // Use "sparc64" instead of "sparcv9" here, since the former is already
        // used widely in the source base.  If we ever needed ABI
        // differentiation from the sparc64, we could, but that would probably
        // just be confusing.
        arch: "sparc64".to_string(),
        target_os: "solaris".to_string(),
        target_env: "".to_string(),
        target_vendor: "sun".to_string(),
        linker_flavor: LinkerFlavor::Gcc,
        options: base,
    })
}
<|endoftext|>


<commit_before><commit_msg>get command options<commit_after><|endoftext|>


<commit_before><commit_msg>Added notes on loops<commit_after>// A compilation of notes and lessons from https://doc.rust-lang.org/book/loops.html

fn main() {
    // The simplest type of loop is simply called "loop". It is an infinite loop (but can be broken out of)
    loop {
        println!("going and going and going...");
        break;
    }

    // While loops are fairly standard
    let mut go = true;

    while go {
        go = false;
    }

    // It's fairly important that you do not use "while true" to do an infinite loop - using 'loop' instead allows
    // for compiler optimizations since it knows it will not need to check a conditional every time it loops

    // 'for' loops are not C-style on purpose. Instead they are of the type for *var* in *exp*, where exp is an
    // item that can be turned into an iterator
    for num in 0..10 {
        // this prints 0 through 9, not 10
        println!("{}", num);
    }

    // We can use the enumerate() method to tell how many times we've already looped
    for (num_times_looped, i) in (5..10).enumerate() {
        println!("num_times_looped is {}, i is {}", num_times_looped, i);
    }

    // Note: I originally wanted to do this with an array instead of copying the website example. However, we can't iterate over
    // stock arrays in the way you'd expect. Something to do with the types contained in the array. It'll come up later when
    // discussing iterators
    let lines = "hello\nworld".lines();

    for (linenumber, line) in lines.enumerate() {
        println!("linenumber is {}, line is {}", linenumber, line);
    }

    // 'break' and 'continue' work as you'd imagine they would by default. You can, however, make things more interesting with
    // loop labels. These allow 'break' and 'continue' to apply to any of several named nested loops
    let mut count = 0;
    'outer: for x in 0..10 {
        'inner: for y in 0..10 {
            // Only count if both are even
            if x % 2 == 1 {
                continue 'outer;
            }
            if y % 2 == 1 {
                continue 'inner;
            }
            count = count + 1;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>client rust<commit_after>//  o2client.c - part of performance benchmark
//
//  see o2server.c for details

//#include "o2.h"
extern crate o2;

const max_msg_count: i32 = 50000;

fn main(){
    let server_addresses: Vec<std::ffi::CString> = vec![];
    let mut msg_count = 0;
    let mut running = true;

    if let Some(arg) = std::env::args().nth(1){
        o2::debug_flags();
    }

    let o2 = o2::new("test");
    o2.service_new("client");

    for i in 0..N_ADDRS{
        let mut cs = CString::new();
        write!(&mut cs, b"server/benchmark/{}", i).unwrap();
        server_addresses.push(cs);
    }

    while o2.status("server") < O2_REMOTE {
        o2.poll();
        std::thread::sleep( std::time::Duration::from_millis(2) ); // 2ms
    }
    println!("We discovered the server.\ntime is {}.\n", o2.time_get());

    // Demonstrate delay 1 second
    let now = o2.time_get();
    while (o2.time_get() < now + 1) {
        o2.poll();
        std::thread::sleep( std::time::Duration::from_millis(2) );
    }

    println!("Here we go! ...\ntime is {}.\n", o2_time_get());

    o2.send("!server/benchmark/0", 0, "i", 1);

    while running {
        o2.poll();
        //usleep(2000); // 2ms // as fast as possible
        for event in o2.poll_events() {
            match (event.path, event.ty) {
                ("/client/benchmark/foo", OscType::Int(i)) => {
                },
                ("/client/bar/baz", OscType::String(s)) => {
                },
            }
        }
    }

    o2.finish();
    println("CLIENT DONE");
}
<|endoftext|>


<commit_before><commit_msg>Add FS Items placeholder<commit_after>
<|endoftext|>


<commit_before>extern crate hyper;
extern crate debug;

use std::io::{IoResult};
use std::io::util::copy;
use std::io::net::ip::Ipv4Addr;

use hyper::{Get, Post};
use hyper::server::{Server, Handler, Request, Response};
use hyper::header::ContentLength;

struct Echo;

impl Handler for Echo {
    fn handle(&mut self, mut req: Request, mut res: Response) -> IoResult<()> {
        match req.uri {
            hyper::uri::AbsolutePath(ref path) => match (&req.method, path.as_slice()) {
                (&Get, "/") | (&Get, "/echo") => {
                    let out = b"Try POST /echo";

                    res.headers.set(ContentLength(out.len()));
                    try!(res.write(out));
                    return res.end();
                },
                (&Post, "/echo") => (), // fall through, fighting mutable borrows
                _ => {
                    res.status = hyper::status::NotFound;
                    return res.end();
                }
            },
            _ => return res.end()
        };

        try!(copy(&mut req, &mut res));
        res.end()
    }
}

fn main() {
    let server = Server::http(Ipv4Addr(127, 0, 0, 1), 1337);
    server.listen(Echo).unwrap();
}
<commit_msg>Updated example for new Handler trait<commit_after>#![feature(macro_rules)]

extern crate hyper;
extern crate debug;

use std::io::util::copy;
use std::io::net::ip::Ipv4Addr;

use hyper::{Get, Post};
use hyper::server::{Server, Handler, Incoming};
use hyper::header::ContentLength;

struct Echo;

macro_rules! try_continue(
    ($e:expr) => {{
        match $e {
            Ok(v) => v,
            Err(e) => { println!("Error: {}", e); continue; }
        }
    }}
)

impl Handler for Echo {
    fn handle(self, mut incoming: Incoming) {
        for (mut req, mut res) in incoming {
            match req.uri {
                hyper::uri::AbsolutePath(ref path) => match (&req.method, path.as_slice()) {
                    (&Get, "/") | (&Get, "/echo") => {
                        let out = b"Try POST /echo";

                        res.headers.set(ContentLength(out.len()));
                        try_continue!(res.write(out));
                        try_continue!(res.end());
                        continue;
                    },
                    (&Post, "/echo") => (), // fall through, fighting mutable borrows
                    _ => {
                        res.status = hyper::status::NotFound;
                        try_continue!(res.end());
                        continue;
                    }
                },
                _ => {
                    try_continue!(res.end());
                    continue;
                }
            };

            try_continue!(copy(&mut req, &mut res));
            try_continue!(res.end());
        }
    }
}

fn main() {
    let server = Server::http(Ipv4Addr(127, 0, 0, 1), 1337);
    server.listen(Echo).unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Add test for braced-macro followed by `.` or `?`.<commit_after>// check-pass

use std::io::Write;

fn main() -> Result<(), std::io::Error> {
    vec! { 1, 2, 3 }.len();
    write! { vec![], "" }?;
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Add some program-related tests<commit_after>#![feature(phase)]

#[phase(plugin)]
extern crate glium_macros;

extern crate glutin;
extern crate glium;

use glium::DisplayBuild;

#[test]
fn program_creation() {
    let display = glutin::HeadlessRendererBuilder::new(1024, 768)
        .build_glium().unwrap();

    // compiling shaders and linking them together
    glium::Program::new(&display,
        // vertex shader
        "
            #version 110

            uniform mat4 matrix;

            attribute vec2 position;
            attribute vec3 color;

            varying vec3 vColor;

            void main() {
                gl_Position = vec4(position, 0.0, 1.0) * matrix;
                vColor = color;
            }
        ",

        // fragment shader
        "
            #version 110
            varying vec3 vColor;

            void main() {
                gl_FragColor = vec4(vColor, 1.0);
            }
        ",

        // geometry shader
        None).unwrap();
}

#[test]
fn program_compilation_error() {
    let display = glutin::HeadlessRendererBuilder::new(1024, 768)
        .build_glium().unwrap();

    // compiling shaders and linking them together
    let program = glium::Program::new(&display,
        // vertex shader
        "invalid glsl code",

        // fragment shader
        "
            #version 110
            varying vec3 vColor;

            void main() {
                gl_FragColor = vec4(vColor, 1.0);
            }
        ",

        // geometry shader
        None);

    match program {
        Err(glium::CompilationError(_)) => (),
        _ => fail!()
    };
}

/*
This test is disabled because some OpenGL drivers don't catch
the linking error (even though they are supposed to)

#[test]
fn program_linking_error() {
    let display = glutin::HeadlessRendererBuilder::new(1024, 768)
        .build_glium().unwrap();

    // compiling shaders and linking them together
    let program = glium::Program::new(&display,
        // vertex shader
        "
            #version 110

            varying vec3 output1;

            void main() {
                gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
                output1 = vec3(0.0, 0.0, 0.0);
            }
        ",

        // fragment shader
        "
            #version 110
            varying vec3 output2;

            void main() {
                gl_FragColor = vec4(output2, 1.0);
            }
        ",

        // geometry shader
        None);

    match program {
        Err(glium::LinkingError(_)) => (),
        _ => fail!()
    };
}
*/
<|endoftext|>


<commit_before><commit_msg>Update to current rust: stop using RefCell::with_mut().<commit_after><|endoftext|>


<commit_before><commit_msg>Create phone_metadata.rs<commit_after><|endoftext|>


<commit_before>#![macro_use]

use super::packets;
use super::server;
use super::test_server;
use std::net;

//This macro generates a test, passing the second argument a server and ip.
//The macro then checks to see if we sent all the packets after the block.
//Per the Rust IRC this has to be before the mods.
macro_rules! responder_test {
    ($name: ident, $test: expr, $($expected: expr),*) => {
        #[test]
        fn $name() {
            let mut server = test_server::TestServer::new();
            let ip = net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1));
            $test(&mut server, ip);
            let mut i = server.sent_packets.iter();
            $(assert_eq!(&(ip, $expected), i.next().unwrap());)*
        }
    }
}

mod connection;
mod echo;
mod heartbeat;
mod status;

//We have significanty less tests than the packets module.
//Consequently, they're in with the types they test.

pub use self::connection::*;
pub use self::echo::*;
pub use self::heartbeat::*;
pub use self::status::*;

pub trait PacketResponder {
    //Return true if and only if this handler handles the packet.
    //This function is called if and only if the packet is destined for an already-established connection and this handler is associated with it.
    //The server handles the initial association when connections are created.
    fn handle_incoming_packet<T: server::Server>(&mut self, packet: &packets::Packet, server: &mut T)->bool {
        false
    }
    //This variant is called when the packet is not for a connection.
    fn handle_incoming_packet_connectionless<T: server::Server>(&mut self, packet: &packets::Packet, ip: net::IpAddr, server: &mut T)->bool {
        false
    }
    //This variant is called in both cases, and is used primarily for the status responses.
    //It is called before either handle_incoming_packet or handle_incoming_packet_connectionless.
    fn handle_incoming_packet_always<T: server::Server>(&mut self, packet: &packets::Packet, ip: net::IpAddr, server: &mut T)->bool {
        false
    }
    //This happens if and only if get_tick_frequency returns a time.
    fn tick<T: server::Server>(&mut self, server: &mut T) {
    }
    //Return a time in MS.
    fn get_tick_frequency(&self)->Option<u32> {
        None
    }
}
<commit_msg>Responders should only be triggered on incoming packets, at least for now. Kill ticking in the trait.<commit_after>#![macro_use]

use super::packets;
use super::server;
use super::test_server;
use std::net;

//This macro generates a test, passing the second argument a server and ip.
//The macro then checks to see if we sent all the packets after the block.
//Per the Rust IRC this has to be before the mods.
macro_rules! responder_test {
    ($name: ident, $test: expr, $($expected: expr),*) => {
        #[test]
        fn $name() {
            let mut server = test_server::TestServer::new();
            let ip = net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1));
            $test(&mut server, ip);
            let mut i = server.sent_packets.iter();
            $(assert_eq!(&(ip, $expected), i.next().unwrap());)*
        }
    }
}

mod connection;
mod echo;
mod heartbeat;
mod status;

//We have significanty less tests than the packets module.
//Consequently, they're in with the types they test.

pub use self::connection::*;
pub use self::echo::*;
pub use self::heartbeat::*;
pub use self::status::*;

pub trait PacketResponder {
    //Return true if and only if this handler handles the packet.
    //This function is called if and only if the packet is destined for an already-established connection and this handler is associated with it.
    //The server handles the initial association when connections are created.
    fn handle_incoming_packet<T: server::Server>(&mut self, packet: &packets::Packet, server: &mut T)->bool {
        false
    }
    //This variant is called when the packet is not for a connection.
    fn handle_incoming_packet_connectionless<T: server::Server>(&mut self, packet: &packets::Packet, ip: net::IpAddr, server: &mut T)->bool {
        false
    }
    //This variant is called in both cases, and is used primarily for the status responses.
    //It is called before either handle_incoming_packet or handle_incoming_packet_connectionless.
    fn handle_incoming_packet_always<T: server::Server>(&mut self, packet: &packets::Packet, ip: net::IpAddr, server: &mut T)->bool {
        false
    }
}
<|endoftext|>


<commit_before>#![allow(dead_code)]
// Copyright 2012-2014 Dustin Hiatt. See the COPYRIGHT
// file at the top-level directory.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
//! A statically-sized ring buffer that acts as an MPMC queue.  Differs
//! from the ring buffer-backed VecDeque in that this structure
//! is lockless and threadsafe.  Threadsafety is achieved using only
//! CAS operations, making this queue ideal for high throughput.  This
//! queue is not ideal for situations where a long wait is expected
//! as any getter is blocked in a spinlock until an item is put.  Locks
//! due to resource starvation are avoided by yielding the spin lock to
//! the scheduler every few thousand iterations.  This queue is cache-aware
//! and performs best with cache line sizes of 64 bytes.
//!
//! Because this queue is threadsafe, it is safe to pass an Arc around
//! to spawned threads and call put, without wrapping the struct itself
//! in a mutex.

//! Benchmarks:
//! test ringbuffer::rbtest::bench_rb_batch     ... bench:    443876 ns/iter (+/- 19276)
//! ringbuffer::rbtest::bench_rb_get       ... bench:        42 ns/iter (+/- 2)
//! ringbuffer::rbtest::bench_rb_lifecycle ... bench:        24 ns/iter (+/- 0)
//! ringbuffer::rbtest::bench_rb_put       ... bench:        36 ns/iter (+/- 5)
//! ringbuffer::rbtest::bench_vecdeque     ... bench:      2934 ns/iter (+/- 394)
//!
//! The final benchmark is comparable to the bench_rb_lifecycle in terms
//! of functionality.

/// #Examples
///
/// ```
/// use marble::ringbuffer::RingBuffer;
///
/// use std::sync::Arc;
/// use std::thread;
///
/// let rb = Arc::new(RingBuffer::new(1));
///
/// let rbc = rb.clone();
/// let join = thread::spawn(move || {
/// 	loop {
/// 		let result = rbc.get();
/// 		match result {
/// 			Err(_) => break,
/// 			_ => ()
///			}
///		}
/// });
///
/// rb.put(1);
/// rb.dispose();
/// join.join();
/// ```

use std::cell::UnsafeCell;
use std::default::Default;
use std::marker;
use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering};
use std::thread::yield_now;
use std::vec::Vec;

// Node will wrap items in the buffer and keep track of enough
// meta data to know if queue and dequere are referencing the
// correct item.  This is achieved through the atomic position
// field.
struct Node<T> {
	item: 	  Option<T>,
	position: AtomicUsize,
}

impl<T> Node<T> {
	// new creates a new node with its atomic position set to
	// position.  No item by default.
	fn new(position: usize) -> Node<T> {
		Node {
			position: AtomicUsize::new(position),
			item: None,
		}
	}
}

/// RingBuffer is a threadsafe MPMC queue that's statically-sized.
/// Puts are blocked on a full queue and gets are blocked on an empty
/// queue.  In either case, calling dispose will free any blocked threads
/// and return an error.
#[repr(C)]
pub struct RingBuffer<T> {
	queue: 	   AtomicUsize,
	// padding is here to ensure that queue and dequeue end on different
	// cache lines to prevent false sharing.
	_padding0: [u64;8],
	dequeue:   AtomicUsize,
	_padding1: [u64;8],
	disposed:  AtomicUsize,
	_padding2: [u64;8],
	mask:      usize,
	// positions is unsafecell so we can grab a node mutably in the
	// put and get functions, which themselves can be called on an
	// immutable ring buffer.
	positions: UnsafeCell<Vec<Node<T>>>,
}

// these implementations are required to access a ringbuffer in a separate
// lifetime and thread using only a wrapping Arc.
unsafe impl<T> marker::Send for RingBuffer<T> {}
unsafe impl<T> marker::Sync for RingBuffer<T> {}

impl<T> Default for RingBuffer<T> {
	// this is convenient so we don't have to create 0 for atomics
	// and empty arrays with every constructor call.
	fn default() -> RingBuffer<T> {
		RingBuffer{
			queue:     ATOMIC_USIZE_INIT,
			_padding0: [0;8],
			dequeue:   ATOMIC_USIZE_INIT,
			_padding1: [0;8],
			disposed:  ATOMIC_USIZE_INIT,
			_padding2: [0;8],
			mask: 	   0,
			positions: UnsafeCell::new(vec![]),
		}
	}
}

/// RingBufferError is returned when a thread gets or puts on a disposed
/// RingBuffer.  Any blocked threads will be freed and will received this
/// error.
pub enum RingBufferError { Disposed }

impl<T> RingBuffer<T> {
	/// new creates a new RingBuffer with the specified capacity.  It
	/// is important to note that capacity will be rounded up to the next
	/// power of two.  This is done to improve performance by avoiding a
	/// costly modulo call.  To get the actual capacity of the ring buffer
	/// call cap().
	pub fn new(cap: usize) -> RingBuffer<T> {
		let calculated_capacity = cap.next_power_of_two();
		let mut positions = Vec::<Node<T>>::with_capacity(calculated_capacity);

		for i in 0..calculated_capacity {
			positions.push(Node::new(i as usize));
		}

		RingBuffer{
			mask: calculated_capacity-1,
			positions: UnsafeCell::new(positions),
			..Default::default()
		}
	}

	/// cap returns the actual capacity of the ring buffer.  This
	/// different than length, which returns the actual number of
	/// items in the ring buffer.  If cap == len, then the ring
	/// buffer is full.
	pub fn cap(&self) -> usize {
		unsafe {
			let positions = self.positions.get();
			(*positions).len()
		}
	}

	/// len returns the number of items in the ring buffer at this
	/// moment.
	pub fn len(&self) -> usize {
		self.queue.load(Ordering::Relaxed) - self.dequeue.load(Ordering::Relaxed)
	}

	/// dispose frees any resources consumed by this ring buffer and
	/// releases any threads that are currently in spin locks.  Any subsequent
	/// calls to put or get will return an error.
	pub fn dispose(&self) {
		self.disposed.store(1, Ordering::Relaxed);
	}

	/// put will add item to the ring buffer.  If the ring buffer is full
	/// this operation blocks until it can be put.  Returns an error if
	/// this ring buffer is disposed.
	pub fn put(&self, item: T) -> Result<(), RingBufferError> {
		unsafe {
			let mut position = self.queue.load(Ordering::Relaxed);
			let mut i = 0;

			loop {
				if self.disposed.load(Ordering::Relaxed) == 1 {
					return Err(RingBufferError::Disposed);
				}

				let positions = self.positions.get();
				let n = (*positions).get_unchecked_mut(position&self.mask);
				let diff = n.position.load(Ordering::Acquire) - position;
				if diff == 0 {
					if self.queue.compare_and_swap(position, position+1, Ordering::Relaxed) == position {
						n.item = Some(item);
						n.position.store(position+1, Ordering::Release);
						return Ok(());
					}
				} else {
					position = self.queue.load(Ordering::Relaxed);
				}

				if i == 10000 {
					i = 0;
					yield_now();
				} else {
					i += 1;
				}
			}
		}
	}

	/// get retrieves the next item from the ring buffer.  This method blocks
	/// if the ring buffer is empty until an item is placed.  Returns an error
	/// if the ring buffer is disposed.
	pub fn get(&self) -> Result<T, RingBufferError> {
		unsafe {
			let mut position = self.dequeue.load(Ordering::Relaxed);
			let mut i = 0;
			loop {
				if self.disposed.load(Ordering::SeqCst) == 1 {
					return Err(RingBufferError::Disposed);
				}
				let positions = self.positions.get();
				let n = (*positions).get_unchecked_mut(position&self.mask);
				let diff = n.position.load(Ordering::Acquire) - (position + 1);
				if diff == 0 {
					if self.dequeue.compare_and_swap(position, position+1, Ordering::Relaxed) == position {
						let data = n.item.take().unwrap();
						n.position.store(position+self.mask+1, Ordering::Release);
						return Ok(data);
					}
				} else {
					position = self.dequeue.load(Ordering::Relaxed);
				}

				if i == 10000 {
					i = 0;
					yield_now();
				} else {
					i += 1;
				}
			}
		}
	}
}

#[cfg(test)]
#[allow(unused_must_use)]
mod rbtest {
	extern crate test;

	use self::test::Bencher;

	use std::collections::vec_deque::VecDeque;
	use std::sync::{Arc, Mutex};
	use std::sync::atomic::{AtomicUsize, Ordering};
	use std::sync::mpsc::channel;
	use std::thread;

    use super::*;

   	#[test]
	fn test_simple_put_get() {
		let rb = RingBuffer::new(10);
		let number = 5;
		rb.put(number);
		assert_eq!(1, rb.len());
		let result = rb.get();
		match result {
			Ok(x) => assert_eq!(x, 5),
			Err(x) => panic!(x)
		}
	}

	#[test]
	fn test_fill_and_empty() {
		let rb = RingBuffer::new(8);
		for i in 0..rb.cap() {
			rb.put(i);
		}

		for i in 0..rb.cap() {
			let result = rb.get();
			match result {
				Ok(x) => assert_eq!(x, i),
				Err(x) => panic!(x)
			}
		}

		assert_eq!(0, rb.len());
	}

	#[test]
	fn test_fill_and_dispose() {
		let rb = RingBuffer::new(8);
		let arb = Arc::new(rb);
		let mut vec = vec![];

		for i in 0..arb.cap()+1 {
			let trb = arb.clone();
			let join = thread::spawn(move || {
				trb.put(i);
			});

			vec.push(join);
		}

		arb.dispose();
		for j in vec {
			j.join();
		}
	}

	#[test]
	fn test_get_put_on_dispose() {
		let rb = RingBuffer::new(2);
		rb.dispose();

		let result = rb.get();
		match result {
			Ok(_) => panic!("Should return error."),
			_ => ()
		}

		let result = rb.put(3);
		match result {
			Ok(_) => panic!("Should return error."),
			_ => ()
		}
	}

	#[bench]
	fn bench_rb_put(b: &mut Bencher) {
		b.iter(|| {
			let rb = RingBuffer::new(2);
			rb.put(1);
		});
	}

	#[bench]
	fn bench_rb_get(b: &mut Bencher) {
		b.iter(|| {
			let rb = RingBuffer::new(2);
			rb.put(1);
			rb.get();
		});
	}

	#[bench]
	fn bench_rb_batch(b: &mut Bencher) {
		b.iter(|| {
			const NUM_ITEMS:usize = 1000;
			let rb = Arc::new(RingBuffer::new(NUM_ITEMS));
			let num_done = Arc::new(AtomicUsize::new(0));
			let num_sent = Arc::new(AtomicUsize::new(0));
			let (tx, rx) = channel();

			for _ in 0..8 {
				let rb = rb.clone();
				let tx = tx.clone();
				let num_done = num_done.clone();
				thread::spawn(move || {
					loop {
						let result = rb.get();

						match result {
							Ok(x) => {
								num_done.fetch_add(1, Ordering::SeqCst);
								if x == NUM_ITEMS-2 {
									tx.send(()).unwrap();
								}
							},
							_ => break
						}
					}
				});
			}

			for _ in 0..8 {
				let rb = rb.clone();
				let num_sent = num_sent.clone();
				thread::spawn(move || {
					loop {
						let previous = num_sent.fetch_add(1, Ordering::SeqCst);
						if previous >= NUM_ITEMS {
							break
						}
						rb.put(previous);
					}
				});
			}

			rx.recv().unwrap();
			rb.dispose();
		});
	}

	#[bench]
	fn bench_rb_lifecycle(b: &mut Bencher) {
		let rb = Arc::new(RingBuffer::new(1));

		let rbc = rb.clone();
		let join = thread::spawn(move || {
			loop {
				let result = rbc.get();
				match result {
					Err(_) => break,
					_ => ()
				}
			}
		});

		b.iter(|| {
			let rb = rb.clone();
			rb.put(1);
		});

		rb.dispose();
		join.join();
	}

	#[bench]
	fn bench_vecdeque(b: &mut Bencher) {
		let rb = VecDeque::new();
		let arc = Arc::new(Mutex::new(rb));

		let clone = arc.clone();
		thread::spawn(move || {
			loop {
				let mut rb = clone.lock().unwrap();
				let result = rb.pop_front();
				match result {
					Some(x) => {if x == 2 { break }},
					None => ()
				}
			}
		});

		b.iter(|| {
			let mut rb = arc.lock().unwrap();
			rb.push_back(1);
		});

		let mut rb = arc.lock().unwrap();
		rb.push_back(2);
	}
}<commit_msg>Added attribution.<commit_after>#![allow(dead_code)]
// Copyright 2012-2014 Dustin Hiatt. See the COPYRIGHT
// file at the top-level directory.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
//! This buffer is similar to the buffer
//! described here: http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue
//! with some minor additions.
//!
//! A statically-sized ring buffer that acts as an MPMC queue.  Differs
//! from the ring buffer-backed VecDeque in that this structure
//! is lockless and threadsafe.  Threadsafety is achieved using only
//! CAS operations, making this queue ideal for high throughput.  This
//! queue is not ideal for situations where a long wait is expected
//! as any getter is blocked in a spinlock until an item is put.  Locks
//! due to resource starvation are avoided by yielding the spin lock to
//! the scheduler every few thousand iterations.  This queue is cache-aware
//! and performs best with cache line sizes of 64 bytes.
//!
//! Because this queue is threadsafe, it is safe to pass an Arc around
//! to spawned threads and call put, without wrapping the struct itself
//! in a mutex.

//! Benchmarks:
//! test ringbuffer::rbtest::bench_rb_batch     ... bench:    443876 ns/iter (+/- 19276)
//! ringbuffer::rbtest::bench_rb_get       ... bench:        42 ns/iter (+/- 2)
//! ringbuffer::rbtest::bench_rb_lifecycle ... bench:        24 ns/iter (+/- 0)
//! ringbuffer::rbtest::bench_rb_put       ... bench:        36 ns/iter (+/- 5)
//! ringbuffer::rbtest::bench_vecdeque     ... bench:      2934 ns/iter (+/- 394)
//!
//! The final benchmark is comparable to the bench_rb_lifecycle in terms
//! of functionality.

/// #Examples
///
/// ```
/// use marble::ringbuffer::RingBuffer;
///
/// use std::sync::Arc;
/// use std::thread;
///
/// let rb = Arc::new(RingBuffer::new(1));
///
/// let rbc = rb.clone();
/// let join = thread::spawn(move || {
/// 	loop {
/// 		let result = rbc.get();
/// 		match result {
/// 			Err(_) => break,
/// 			_ => ()
///			}
///		}
/// });
///
/// rb.put(1);
/// rb.dispose();
/// join.join();
/// ```

use std::cell::UnsafeCell;
use std::default::Default;
use std::marker;
use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering};
use std::thread::yield_now;
use std::vec::Vec;

// Node will wrap items in the buffer and keep track of enough
// meta data to know if queue and dequere are referencing the
// correct item.  This is achieved through the atomic position
// field.
struct Node<T> {
	item: 	  Option<T>,
	position: AtomicUsize,
}

impl<T> Node<T> {
	// new creates a new node with its atomic position set to
	// position.  No item by default.
	fn new(position: usize) -> Node<T> {
		Node {
			position: AtomicUsize::new(position),
			item: None,
		}
	}
}

/// RingBuffer is a threadsafe MPMC queue that's statically-sized.
/// Puts are blocked on a full queue and gets are blocked on an empty
/// queue.  In either case, calling dispose will free any blocked threads
/// and return an error.
#[repr(C)]
pub struct RingBuffer<T> {
	queue: 	   AtomicUsize,
	// padding is here to ensure that queue and dequeue end on different
	// cache lines to prevent false sharing.
	_padding0: [u64;8],
	dequeue:   AtomicUsize,
	_padding1: [u64;8],
	disposed:  AtomicUsize,
	_padding2: [u64;8],
	mask:      usize,
	// positions is unsafecell so we can grab a node mutably in the
	// put and get functions, which themselves can be called on an
	// immutable ring buffer.
	positions: UnsafeCell<Vec<Node<T>>>,
}

// these implementations are required to access a ringbuffer in a separate
// lifetime and thread using only a wrapping Arc.
unsafe impl<T> marker::Send for RingBuffer<T> {}
unsafe impl<T> marker::Sync for RingBuffer<T> {}

impl<T> Default for RingBuffer<T> {
	// this is convenient so we don't have to create 0 for atomics
	// and empty arrays with every constructor call.
	fn default() -> RingBuffer<T> {
		RingBuffer{
			queue:     ATOMIC_USIZE_INIT,
			_padding0: [0;8],
			dequeue:   ATOMIC_USIZE_INIT,
			_padding1: [0;8],
			disposed:  ATOMIC_USIZE_INIT,
			_padding2: [0;8],
			mask: 	   0,
			positions: UnsafeCell::new(vec![]),
		}
	}
}

/// RingBufferError is returned when a thread gets or puts on a disposed
/// RingBuffer.  Any blocked threads will be freed and will received this
/// error.
pub enum RingBufferError { Disposed }

impl<T> RingBuffer<T> {
	/// new creates a new RingBuffer with the specified capacity.  It
	/// is important to note that capacity will be rounded up to the next
	/// power of two.  This is done to improve performance by avoiding a
	/// costly modulo call.  To get the actual capacity of the ring buffer
	/// call cap().
	pub fn new(cap: usize) -> RingBuffer<T> {
		let calculated_capacity = cap.next_power_of_two();
		let mut positions = Vec::<Node<T>>::with_capacity(calculated_capacity);

		for i in 0..calculated_capacity {
			positions.push(Node::new(i as usize));
		}

		RingBuffer{
			mask: calculated_capacity-1,
			positions: UnsafeCell::new(positions),
			..Default::default()
		}
	}

	/// cap returns the actual capacity of the ring buffer.  This
	/// different than length, which returns the actual number of
	/// items in the ring buffer.  If cap == len, then the ring
	/// buffer is full.
	pub fn cap(&self) -> usize {
		unsafe {
			let positions = self.positions.get();
			(*positions).len()
		}
	}

	/// len returns the number of items in the ring buffer at this
	/// moment.
	pub fn len(&self) -> usize {
		self.queue.load(Ordering::Relaxed) - self.dequeue.load(Ordering::Relaxed)
	}

	/// dispose frees any resources consumed by this ring buffer and
	/// releases any threads that are currently in spin locks.  Any subsequent
	/// calls to put or get will return an error.
	pub fn dispose(&self) {
		self.disposed.store(1, Ordering::Relaxed);
	}

	/// put will add item to the ring buffer.  If the ring buffer is full
	/// this operation blocks until it can be put.  Returns an error if
	/// this ring buffer is disposed.
	pub fn put(&self, item: T) -> Result<(), RingBufferError> {
		unsafe {
			let mut position = self.queue.load(Ordering::Relaxed);
			let mut i = 0;

			loop {
				if self.disposed.load(Ordering::Relaxed) == 1 {
					return Err(RingBufferError::Disposed);
				}

				let positions = self.positions.get();
				let n = (*positions).get_unchecked_mut(position&self.mask);
				let diff = n.position.load(Ordering::Acquire) - position;
				if diff == 0 {
					if self.queue.compare_and_swap(position, position+1, Ordering::Relaxed) == position {
						n.item = Some(item);
						n.position.store(position+1, Ordering::Release);
						return Ok(());
					}
				} else {
					position = self.queue.load(Ordering::Relaxed);
				}

				if i == 10000 {
					i = 0;
					yield_now();
				} else {
					i += 1;
				}
			}
		}
	}

	/// get retrieves the next item from the ring buffer.  This method blocks
	/// if the ring buffer is empty until an item is placed.  Returns an error
	/// if the ring buffer is disposed.
	pub fn get(&self) -> Result<T, RingBufferError> {
		unsafe {
			let mut position = self.dequeue.load(Ordering::Relaxed);
			let mut i = 0;
			loop {
				if self.disposed.load(Ordering::SeqCst) == 1 {
					return Err(RingBufferError::Disposed);
				}
				let positions = self.positions.get();
				let n = (*positions).get_unchecked_mut(position&self.mask);
				let diff = n.position.load(Ordering::Acquire) - (position + 1);
				if diff == 0 {
					if self.dequeue.compare_and_swap(position, position+1, Ordering::Relaxed) == position {
						let data = n.item.take().unwrap();
						n.position.store(position+self.mask+1, Ordering::Release);
						return Ok(data);
					}
				} else {
					position = self.dequeue.load(Ordering::Relaxed);
				}

				if i == 10000 {
					i = 0;
					yield_now();
				} else {
					i += 1;
				}
			}
		}
	}
}

#[cfg(test)]
#[allow(unused_must_use)]
mod rbtest {
	extern crate test;

	use self::test::Bencher;

	use std::collections::vec_deque::VecDeque;
	use std::sync::{Arc, Mutex};
	use std::sync::atomic::{AtomicUsize, Ordering};
	use std::sync::mpsc::channel;
	use std::thread;

    use super::*;

   	#[test]
	fn test_simple_put_get() {
		let rb = RingBuffer::new(10);
		let number = 5;
		rb.put(number);
		assert_eq!(1, rb.len());
		let result = rb.get();
		match result {
			Ok(x) => assert_eq!(x, 5),
			Err(x) => panic!(x)
		}
	}

	#[test]
	fn test_fill_and_empty() {
		let rb = RingBuffer::new(8);
		for i in 0..rb.cap() {
			rb.put(i);
		}

		for i in 0..rb.cap() {
			let result = rb.get();
			match result {
				Ok(x) => assert_eq!(x, i),
				Err(x) => panic!(x)
			}
		}

		assert_eq!(0, rb.len());
	}

	#[test]
	fn test_fill_and_dispose() {
		let rb = RingBuffer::new(8);
		let arb = Arc::new(rb);
		let mut vec = vec![];

		for i in 0..arb.cap()+1 {
			let trb = arb.clone();
			let join = thread::spawn(move || {
				trb.put(i);
			});

			vec.push(join);
		}

		arb.dispose();
		for j in vec {
			j.join();
		}
	}

	#[test]
	fn test_get_put_on_dispose() {
		let rb = RingBuffer::new(2);
		rb.dispose();

		let result = rb.get();
		match result {
			Ok(_) => panic!("Should return error."),
			_ => ()
		}

		let result = rb.put(3);
		match result {
			Ok(_) => panic!("Should return error."),
			_ => ()
		}
	}

	#[bench]
	fn bench_rb_put(b: &mut Bencher) {
		b.iter(|| {
			let rb = RingBuffer::new(2);
			rb.put(1);
		});
	}

	#[bench]
	fn bench_rb_get(b: &mut Bencher) {
		b.iter(|| {
			let rb = RingBuffer::new(2);
			rb.put(1);
			rb.get();
		});
	}

	#[bench]
	fn bench_rb_batch(b: &mut Bencher) {
		b.iter(|| {
			const NUM_ITEMS:usize = 1000;
			let rb = Arc::new(RingBuffer::new(NUM_ITEMS));
			let num_done = Arc::new(AtomicUsize::new(0));
			let num_sent = Arc::new(AtomicUsize::new(0));
			let (tx, rx) = channel();

			for _ in 0..8 {
				let rb = rb.clone();
				let tx = tx.clone();
				let num_done = num_done.clone();
				thread::spawn(move || {
					loop {
						let result = rb.get();

						match result {
							Ok(x) => {
								num_done.fetch_add(1, Ordering::SeqCst);
								if x == NUM_ITEMS-2 {
									tx.send(()).unwrap();
								}
							},
							_ => break
						}
					}
				});
			}

			for _ in 0..8 {
				let rb = rb.clone();
				let num_sent = num_sent.clone();
				thread::spawn(move || {
					loop {
						let previous = num_sent.fetch_add(1, Ordering::SeqCst);
						if previous >= NUM_ITEMS {
							break
						}
						rb.put(previous);
					}
				});
			}

			rx.recv().unwrap();
			rb.dispose();
		});
	}

	#[bench]
	fn bench_rb_lifecycle(b: &mut Bencher) {
		let rb = Arc::new(RingBuffer::new(1));

		let rbc = rb.clone();
		let join = thread::spawn(move || {
			loop {
				let result = rbc.get();
				match result {
					Err(_) => break,
					_ => ()
				}
			}
		});

		b.iter(|| {
			let rb = rb.clone();
			rb.put(1);
		});

		rb.dispose();
		join.join();
	}

	#[bench]
	fn bench_vecdeque(b: &mut Bencher) {
		let rb = VecDeque::new();
		let arc = Arc::new(Mutex::new(rb));

		let clone = arc.clone();
		thread::spawn(move || {
			loop {
				let mut rb = clone.lock().unwrap();
				let result = rb.pop_front();
				match result {
					Some(x) => {if x == 2 { break }},
					None => ()
				}
			}
		});

		b.iter(|| {
			let mut rb = arc.lock().unwrap();
			rb.push_back(1);
		});

		let mut rb = arc.lock().unwrap();
		rb.push_back(2);
	}
}<|endoftext|>


<commit_before><commit_msg>Got the messages module to compile<commit_after><|endoftext|>


<commit_before><commit_msg>coap work<commit_after><|endoftext|>


<commit_before><commit_msg>Remove bounds checks in vip<commit_after><|endoftext|>


<commit_before><commit_msg>Implement palette reg's<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Improve early-out logic for background pixels"<commit_after><|endoftext|>


<commit_before><commit_msg>Add list var subcommand<commit_after><|endoftext|>


<commit_before>// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use target::Target;

pub fn target() -> Target {
    let mut base = super::openbsd_base::opts();
    base.pre_link_args.push("-m64".to_string());

    Target {
        llvm_target: "x86_64-unknown-openbsd".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "64".to_string(),
        arch: "x86_64".to_string(),
        target_os: "openbsd".to_string(),
        target_env: "".to_string(),
        target_vendor: "unknown".to_string(),
        options: base,
    }
}
<commit_msg>specify the cpu type for LLVM for OpenBSD target<commit_after>// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use target::Target;

pub fn target() -> Target {
    let mut base = super::openbsd_base::opts();
    base.cpu = "x86-64".to_string();
    base.pre_link_args.push("-m64".to_string());

    Target {
        llvm_target: "x86_64-unknown-openbsd".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "64".to_string(),
        arch: "x86_64".to_string(),
        target_os: "openbsd".to_string(),
        target_env: "".to_string(),
        target_vendor: "unknown".to_string(),
        options: base,
    }
}
<|endoftext|>


<commit_before><commit_msg>start new<commit_after>use std::collections::HashMap;

fn changeCoin(value: i32, coinL: &[i32], result: &mut HashMap<i32, i32>) -> i32 {
    if coinL.contains(&value) {
        return 1;
    }
    if let Some(a) = result.get(&value) {
        return *a;
    }

    let mut tempresult: Vec<i32> = Vec::new();
    for c in &coinL {
        if *c <= value {
            tempResult.push(1 + changeCoin(value - 1, coinL, result));
        }
    }

    let mut tempmin = tempresult[0];
    for tt in &tempresult {
        if *tt <= tempmin {
            tempmin = *tt;
        }
    }

    result.insert(value, tempmin);
    return tempmin;
}

fn main() {
    let coinList = [1, 5, 10, 25];
    let mut resultM: HashMap<i32, i32>;

    println!("{}", changeCoin(16));
}
<|endoftext|>


<commit_before><commit_msg>Add test for ograph<commit_after>
extern crate petgraph;

use petgraph::{
    OGraph,
    BreadthFirst,
    dijkstra,
};

use petgraph::ograph::toposort;

#[test]
fn ograph_1()
{
    let mut og = OGraph::new();
    let a = og.add_node(0i);
    let b = og.add_node(1i);
    let c = og.add_node(2i);
    let d = og.add_node(3i);
    let ed1 = og.add_edge(a, b, 0i);
    let ed2 = og.add_edge(a, c, 1);
    og.add_edge(c, a, 2);
    og.add_edge(a, a, 3);
    og.add_edge(b, c, 4);
    og.add_edge(b, a, 5);
    og.add_edge(a, d, 6);
    assert_eq!(og.node_count(), 4);
    assert_eq!(og.edge_count(), 7);

    assert!(og.find_edge(a, b).is_some());
    assert!(og.find_edge(d, a).is_none());
    assert!(og.find_edge(a, a).is_some());

    for no in og.edges(a) {
        println!("Edges {}", no);
    }

    for no in og.edges_both(a) {
        println!("EdgesBoth {}", no);
    }

    println!("{}", og);
    println!("Remove {}", a);
    for no in BreadthFirst::new(&og, a) {
        println!("Visit {}", no);
    }
    og.remove_node(a);
    assert_eq!(og.node_count(), 3);
    assert_eq!(og.edge_count(), 1);
    assert!(og.find_edge(a, b).is_none());
    assert!(og.find_edge(d, a).is_none());
    assert!(og.find_edge(a, a).is_none());
    assert!(og.find_edge(b, c).is_some());
}

#[test]
fn ograph_2()
{
    let mut g = OGraph::<_, f32>::new();
    let a = g.add_node("A");
    let b = g.add_node("B");
    let c = g.add_node("C");
    let d = g.add_node("D");
    let e = g.add_node("E");
    let f = g.add_node("F");
    g.add_edge(a, b, 7.);
    g.add_edge(a, c, 9.);
    g.add_edge(a, d, 14.);
    g.add_edge(b, c, 10.);
    g.add_edge(c, d, 2.);
    g.add_edge(d, e, 9.);
    g.add_edge(b, f, 15.);
    g.add_edge(c, f, 11.);
    g.add_edge(e, f, 6.);
    let scores = dijkstra(&g, a, |gr, n| gr.edges(n).map(|(n, &e)| (n, e)));
    assert_eq!(scores[f], 20.);

    let x = g.add_node("X");
    let y = g.add_node("Y");
    g.add_edge(x, y, 0.);
    println!("{}", toposort(&g));
}
<|endoftext|>


<commit_before><commit_msg>add a blocking bounded queue<commit_after><|endoftext|>


<commit_before>// xfail for now, due to some problem with polymorphic types.

use std;
import std::task;
import std::comm;
import std::comm::chan;
import std::comm::send;
import std::comm::recv;

fn main() { log "===== WITHOUT THREADS ====="; test00(); }

fn test00_start(ch: chan<int>, message: int, count: int) {
    log "Starting test00_start";
    let i: int = 0;
    while i < count {
        log "Sending Message";
        send(ch, message + 0);
        i = i + 1;
    }
    log "Ending test00_start";
}

fn test00() {
    let number_of_tasks: int = 16;
    let number_of_messages: int = 4;

    log "Creating tasks";

    let po = comm::port();
    let ch = chan(po);

    let i: int = 0;

    // Create and spawn tasks...
    let tasks = [];
    while i < number_of_tasks {
        let thunk = bind test00_start(ch, i, number_of_messages);
        tasks += [task::spawn_joinable(thunk)];
        i = i + 1;
    }

    // Read from spawned tasks...
    let sum = 0;
    for t in tasks {
        i = 0;
        while i < number_of_messages {
            let value = recv(po);
            sum += value;
            i = i + 1;
        }
    }

    // Join spawned tasks...
    for t in tasks { task::join(t); }

    log "Completed: Final number is: ";
    log_err sum;
    // assert (sum == (((number_of_tasks * (number_of_tasks - 1)) / 2) *
    //       number_of_messages));
    assert (sum == 480);
}
<commit_msg>Remove bogus comments from run-pass/task-comm-3<commit_after>use std;
import std::task;
import std::comm;
import std::comm::chan;
import std::comm::send;
import std::comm::recv;

fn main() { log "===== WITHOUT THREADS ====="; test00(); }

fn test00_start(ch: chan<int>, message: int, count: int) {
    log "Starting test00_start";
    let i: int = 0;
    while i < count {
        log "Sending Message";
        send(ch, message + 0);
        i = i + 1;
    }
    log "Ending test00_start";
}

fn test00() {
    let number_of_tasks: int = 16;
    let number_of_messages: int = 4;

    log "Creating tasks";

    let po = comm::port();
    let ch = chan(po);

    let i: int = 0;

    // Create and spawn tasks...
    let tasks = [];
    while i < number_of_tasks {
        let thunk = bind test00_start(ch, i, number_of_messages);
        tasks += [task::spawn_joinable(thunk)];
        i = i + 1;
    }

    // Read from spawned tasks...
    let sum = 0;
    for t in tasks {
        i = 0;
        while i < number_of_messages {
            let value = recv(po);
            sum += value;
            i = i + 1;
        }
    }

    // Join spawned tasks...
    for t in tasks { task::join(t); }

    log "Completed: Final number is: ";
    log_err sum;
    // assert (sum == (((number_of_tasks * (number_of_tasks - 1)) / 2) *
    //       number_of_messages));
    assert (sum == 480);
}
<|endoftext|>


<commit_before><commit_msg>practice<commit_after>fn main() {
    println!("practice")
}
<|endoftext|>


<commit_before><commit_msg>Rust: Problem 2<commit_after>/// # Even Fibonacci numbers
/// ## Problem 2
/// Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
/// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
/// By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

extern crate num;

use std::mem;

struct Fib {
    a: int,
    b: int,
}

impl Iterator<int> for Fib {
    fn next(&mut self) -> Option<int> {
        let new_b = self.a + self.b;
        let new_a = mem::replace(&mut self.b, new_b);

        Some(mem::replace(&mut self.a, new_a))
    }
}

fn main() {
    let fib = Fib {a: 1i, b: 2i};
    let mut total = 0;

    for n in fib.take_while(|&n| n <= 4000000) {
        match n {
            n if n % 2 == 0 => total += n,
            _ => { /* do nothing */ }
        }
    }

    println!("Result: {}", total);
}
<|endoftext|>


<commit_before><commit_msg>Test use of "f" suffix on float initializers.<commit_after><|endoftext|>


<commit_before>use redox::*;

mod cmd;

#[derive(Copy, Clone)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
         if self.offset > 0 {
             window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
             self.string = self.string[0 .. self.offset - 1].to_string() +
                 &self.string[self.offset .. self.string.len()];
             self.offset -= 1;
         }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset + 1].to_string() +
                &self.string[self.offset + 1 .. self.string.len() - 1];
        }
    }

    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window);

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<commit_msg>Fix delete/x command<commit_after>use redox::*;

mod cmd;

#[derive(Copy, Clone)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
         if self.offset > 0 {
             window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
             self.string = self.string[0 .. self.offset - 1].to_string() +
                 &self.string[self.offset .. self.string.len()];
             self.offset -= 1;
         }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     576,
                                     400,
                                      &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window);

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<|endoftext|>


<commit_before><commit_msg>examples: Add a hello_world<commit_after>// This example just prints "Hello Tock World" to the terminal.

#![no_std]

use core::fmt::Write;
use libtock::result::TockResult;

#[libtock::main]
async fn main() -> TockResult<()> {
    let drivers = libtock::retrieve_drivers()?;

    let mut console = drivers.console.create_console();

    writeln!(console, "Hello Tock World")?;

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Add example for decoding toml to struct<commit_after>#![deny(warnings)]
extern crate toml;
extern crate rustc_serialize;

use rustc_serialize::Decodable;

#[derive(Debug,RustcDecodable)]
struct Config {
    global_string: Option<String>,
    global_integer: Option<u64>,
    server: Option<ServerConfig>,
    peers: Option<Vec<PeerConfig>>,
}

#[derive(Debug,RustcDecodable)]
struct ServerConfig {
    ip: Option<String>,
    port: Option<u64>,
}

#[derive(Debug,RustcDecodable)]
struct PeerConfig {
    ip: Option<String>,
    port: Option<u64>,
}

fn main() {
    let toml_str = r#"
            global_string = "test"
            global_integer = 5

            [server]
            ip = "127.0.0.1"
            port = 80

            [[peers]]
            ip = "127.0.0.1"
            port = 8080

            [[peers]]
            ip = "127.0.0.1"
            port = 8081
        "#;

    let toml = toml::Parser::new(&toml_str).parse().unwrap();

    let mut decoder = toml::Decoder::new(toml::Value::Table(toml));
    let decoded = Config::decode(&mut decoder).unwrap();

    println!("{:?}", decoded);
}
<|endoftext|>


<commit_before><commit_msg>src/addressbook.rs: delete address entries<commit_after><|endoftext|>


<commit_before><commit_msg>Split DFA minimization into separate partition and minimize functions for readability and maintenance reasons.<commit_after><|endoftext|>


<commit_before><commit_msg>Add solution to part 7<commit_after>// advent7.rs
// circuit

#[macro_use] extern crate scan_fmt;

use std::io;
use std::collections::HashMap;

fn main() {
    let mut circuit = Circuit::new();
    loop {
        let mut input = String::new();
        let result = io::stdin().read_line(&mut input);
        match result {
            Ok(byte_count) => if byte_count == 0 { break; },
            Err(_) => {
                println!("error reading from stdin");
                break;
            }
        }
        circuit.add(&input.trim());

    }

    let result = circuit.eval("a");
    println!("Part 1 a = {}", result);

    // Part 2
    circuit.cache.clear();
    circuit.add(&format!("{} -> b", result));
    println!("Part 2 a = {}", circuit.eval("a"));
}

#[derive(Debug)]
struct Circuit {
    sym_table: HashMap<String, String>,
    cache: HashMap<String, u16>,
}

impl Circuit {
    fn new() -> Circuit {
        Circuit {sym_table: HashMap::new(), cache: HashMap::new()}
    }

    fn add(&mut self, s: &str) {
        let mut iter = s.splitn(2, " -> ");
        let val = String::from(iter.next().unwrap());
        let symbol = String::from(iter.next().unwrap());
        self.sym_table.insert(symbol, val);
    }

    fn eval(&mut self, expr: &str) -> u16 {
        // If the expression is in the cache, we're done
        if self.cache.contains_key(expr) {
            return *self.cache.get(expr).unwrap();
        }

        // Otherwise further parse the expression
        let result = if let Ok(val) = expr.parse::<u16>() {
            // expression is a u16
            return val;
        } else if self.sym_table.contains_key(expr) {
            // expression is a symbol in our table
            let symbol_val = self.sym_table.get(expr).unwrap().clone();
            self.eval(&symbol_val)
        } else if expr.contains("AND") {
            let v: Vec<&str> = expr.splitn(2, " AND ").collect();
            let (left, right) = (v[0], v[1]);
            self.eval(&left) & self.eval(&right)
        } else if expr.contains("OR") {
            let v: Vec<&str> = expr.splitn(2, " OR ").collect();
            let (left, right) = (v[0], v[1]);
            self.eval(&left) | self.eval(&right)
        } else if expr.contains("LSHIFT") {
            let v: Vec<&str> = expr.splitn(2, " LSHIFT ").collect();
            let (left, right) = (v[0], v[1]);
            self.eval(&left) << self.eval(&right)
        } else if expr.contains("RSHIFT") {
            let v: Vec<&str> = expr.splitn(2, " RSHIFT ").collect();
            let (left, right) = (v[0], v[1]);
            self.eval(&left) >> self.eval(&right)
        } else if expr.contains("NOT") {
            let right = expr.trim_left_matches("NOT ");
            !self.eval(&right)
        } else {
            panic!(format!("couldn't parse expr {}", expr))
        };

        self.cache.insert(String::from(expr), result);
        result
    }
}

#[test]
#[should_panic]
fn test_eval_fail() {
    let mut circuit = Circuit::new();
    circuit.add("123 -> x");
    circuit.add("456 -> y");
    circuit.add("x AND y -> d");
    circuit.add("x OR y -> e");
    circuit.add("x LSHIFT 2 -> f");
    circuit.add("y RSHIFT 2 -> g");
    circuit.add("NOT x -> h");
    circuit.add("NOT y -> i");

    circuit.eval("xyzzy");
}

#[test]
fn test_eval() {
    let mut circuit = Circuit::new();
    circuit.add("123 -> x");
    circuit.add("456 -> y");
    circuit.add("x AND y -> d");
    circuit.add("x OR y -> e");
    circuit.add("x LSHIFT 2 -> f");
    circuit.add("y RSHIFT 2 -> g");
    circuit.add("NOT x -> h");
    circuit.add("NOT y -> i");

    assert_eq!(123, circuit.eval("x"));
    assert_eq!(456, circuit.eval("y"));
    assert_eq!(72, circuit.eval("d"));
    assert_eq!(507, circuit.eval("e"));
    assert_eq!(492, circuit.eval("f"));
    assert_eq!(114, circuit.eval("g"));
    assert_eq!(65412, circuit.eval("h"));
    assert_eq!(65079, circuit.eval("i"));
}

<|endoftext|>


<commit_before><commit_msg>Day 9 part 1<commit_after>// advent9.rs
// simple RLE decompression

use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).ok().expect("Failed to read line");

    let compressed = input.trim();
    let length = calc_decompressed_length(compressed);
    println!("part 1 decompressed length: {}", length);
}

// ///////
// Part 1
fn calc_decompressed_length(s: &str) -> usize {
    let mut iter = s.chars();
    let mut length = 0;

    while let Some(c) = iter.next() {
        if c == '(' {
            let count = parse_usize(&mut iter);
            let repeat = parse_usize(&mut iter);
            length += count * repeat;
            // don't forget to skip the part we repeat
            iter.nth(count - 1);
        } else {
            length += 1;
        }
    }
    length
}

// consumes an integer and the next character after it (should be either 'x' or ')')
fn parse_usize(iter: &mut std::str::Chars) -> usize {
    let mut num = 0;
    while let Some(c) = iter.next() {
        if c >= '0' && c <= '9' {
            let digit = c as usize - '0' as usize;
            num = num * 10 + digit;
        } else {
            break;
        }
    }
    num
}

// //////
// Tests

#[test]
fn test_calc_decompressed_length() {
    assert_eq!(6, calc_decompressed_length("ADVENT"));
    assert_eq!(7, calc_decompressed_length("A(1x5)BC"));
    assert_eq!(9, calc_decompressed_length("(3x3)XYZ"));
    assert_eq!(11, calc_decompressed_length("A(2x2)BCD(2x2)EFG"));
    assert_eq!(6, calc_decompressed_length("(6x1)(1x3)A"));
    assert_eq!(18, calc_decompressed_length("X(8x2)(3x3)ABCY"));
}
<|endoftext|>


<commit_before><commit_msg>fixed; draft, not compiles<commit_after><|endoftext|>


<commit_before><commit_msg>Implement and test Drop for ArrayVec<commit_after><|endoftext|>


<commit_before><commit_msg>tests: tests for flag using<commit_after><|endoftext|>


<commit_before><commit_msg>fix: update to rust nightly<commit_after><|endoftext|>


<commit_before><commit_msg>Fix typo.<commit_after><|endoftext|>


<commit_before>use std::fmt;
use std::from_str::FromStr;
use io::{IoHandle, NonBlock};
use error::MioResult;
use buf::{Buf, MutBuf};
use os;

pub use std::io::net::ip::{IpAddr, Port};
pub use std::io::net::ip::Ipv4Addr as IPv4Addr;

pub trait Socket : IoHandle {
    fn linger(&self) -> MioResult<uint> {
        os::linger(self.desc())
    }

    fn set_linger(&self, dur_s: uint) -> MioResult<()> {
        os::set_linger(self.desc(), dur_s)
    }

    fn set_reuseaddr(&self, val: bool) -> MioResult<()> {
        os::set_reuseaddr(self.desc(), val)
    }

    fn set_reuseport(&self, val: bool) -> MioResult<()> {
        os::set_reuseport(self.desc(), val)
    }
}

pub trait MulticastSocket : Socket {
    fn join_multicast_group(&self, addr: &IpAddr, interface: &Option<IpAddr>) -> MioResult<()> {
        os::join_multicast_group(self.desc(), addr, interface)
    }

    fn leave_multicast_group(&self, addr: &IpAddr, interface: &Option<IpAddr>) -> MioResult<()> {
        os::leave_multicast_group(self.desc(), addr, interface)
    }

    fn set_multicast_ttl(&self, val: u8) -> MioResult<()> {
        os::set_multicast_ttl(self.desc(), val)
    }
}

pub trait UnconnectedSocket {
    fn send_to(&mut self, buf: &mut Buf, tgt: &SockAddr) -> MioResult<NonBlock<()>>;
    fn recv_from(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<SockAddr>>;
}

// Types of sockets
pub enum AddressFamily {
    Inet,
    Inet6,
    Unix,
}

pub enum SockAddr {
    UnixAddr(Path),
    InetAddr(IpAddr, Port)
}

impl SockAddr {
    pub fn parse(s: &str) -> Option<SockAddr> {
        use std::io::net::ip;

        let addr: Option<ip::SocketAddr> = FromStr::from_str(s);
        addr.map(|a| InetAddr(a.ip, a.port))
    }
}

impl FromStr for SockAddr {
    fn from_str(s: &str) -> Option<SockAddr> {
        SockAddr::parse(s)
    }
}

impl fmt::Show for SockAddr {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            InetAddr(ip, port) => write!(fmt, "{}:{}", ip, port),
            _ => write!(fmt, "not implemented")
        }
    }
}

pub enum SocketType {
    Dgram,
    Stream,
}

pub mod tcp {
    use os;
    use error::MioResult;
    use buf::{Buf, MutBuf};
    use io;
    use io::{IoHandle, IoAcceptor, IoReader, IoWriter, NonBlock, Ready, WouldBlock};
    use net::{AddressFamily, Socket, SockAddr, Inet, Inet6, Stream};

    #[deriving(Show)]
    pub struct TcpSocket {
        desc: os::IoDesc
    }

    impl TcpSocket {
        pub fn v4() -> MioResult<TcpSocket> {
            TcpSocket::new(Inet)
        }

        pub fn v6() -> MioResult<TcpSocket> {
            TcpSocket::new(Inet6)
        }

        fn new(family: AddressFamily) -> MioResult<TcpSocket> {
            Ok(TcpSocket { desc: try!(os::socket(family, Stream)) })
        }

        pub fn bind(self, addr: &SockAddr) -> MioResult<TcpListener> {
            try!(os::bind(&self.desc, addr))
            Ok(TcpListener { desc: self.desc })
        }
    }

    impl IoHandle for TcpSocket {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    impl IoReader for TcpSocket {
        fn read(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<()>> {
            io::read(self, buf)
        }
    }

    impl IoWriter for TcpSocket {
        fn write(&mut self, buf: &mut Buf) -> MioResult<NonBlock<()>> {
            io::write(self, buf)
        }
    }

    impl Socket for TcpSocket {
    }

    #[deriving(Show)]
    pub struct TcpListener {
        desc: os::IoDesc,
    }

    impl TcpListener {
        pub fn listen(self, backlog: uint) -> MioResult<TcpAcceptor> {
            try!(os::listen(self.desc(), backlog));
            Ok(TcpAcceptor { desc: self.desc })
        }
    }

    impl IoHandle for TcpListener {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    #[deriving(Show)]
    pub struct TcpAcceptor {
        desc: os::IoDesc,
    }

    impl IoHandle for TcpAcceptor {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    impl Socket for TcpAcceptor {
    }

    impl IoAcceptor<TcpSocket> for TcpAcceptor {
        fn accept(&mut self) -> MioResult<NonBlock<TcpSocket>> {
            match os::accept(self.desc()) {
                Ok(sock) => Ok(Ready(TcpSocket { desc: sock })),
                Err(e) => {
                    if e.is_would_block() {
                        return Ok(WouldBlock);
                    }

                    return Err(e);
                }
            }
        }
    }
}

pub mod udp {
    use os;
    use error::MioResult;
    use buf::{Buf, MutBuf};
    use io::{IoHandle, IoReader, IoWriter, NonBlock, Ready, WouldBlock};
    use net::{AddressFamily, Socket, MulticastSocket, SockAddr, Inet, Dgram};
    use super::UnconnectedSocket;

    #[deriving(Show)]
    pub struct UdpSocket {
        desc: os::IoDesc
    }

    impl UdpSocket {
        pub fn v4() -> MioResult<UdpSocket> {
            UdpSocket::new(Inet)
        }

        fn new(family: AddressFamily) -> MioResult<UdpSocket> {
            Ok(UdpSocket { desc: try!(os::socket(family, Dgram)) })
        }

        pub fn bind(&self, addr: &SockAddr) -> MioResult<()> {
            try!(os::bind(&self.desc, addr))
            Ok(())
        }

        pub fn connect(&self, addr: &SockAddr) -> MioResult<bool> {
            os::connect(&self.desc, addr)
        }
    }

    impl IoHandle for UdpSocket {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    impl Socket for UdpSocket {
    }

    impl MulticastSocket for UdpSocket {
    }

    impl IoReader for UdpSocket {
        fn read(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<()>> {
            match os::read(&self.desc, buf.mut_bytes()) {
                Ok(cnt) => {
                    buf.advance(cnt);
                    Ok(Ready(()))
                }
                Err(e) => {
                    if e.is_would_block() {
                        Ok(WouldBlock)
                    } else {
                        Err(e)
                    }
                }
            }
        }
    }

    impl IoWriter for UdpSocket {
        fn write(&mut self, buf: &mut Buf) -> MioResult<NonBlock<()>> {
            match os::write(&self.desc, buf.bytes()) {
                Ok(cnt) => {
                    buf.advance(cnt);
                    Ok(Ready(()))
                }
                Err(e) => {
                    if e.is_would_block() {
                        Ok(WouldBlock)
                    } else {
                        Err(e)
                    }
                }
            }
        }
    }

    // Unconnected socket sender -- trait unique to sockets
    impl UnconnectedSocket for UdpSocket {
        fn send_to(&mut self, buf: &mut Buf, tgt: &SockAddr) -> MioResult<NonBlock<()>> {
            match os::sendto(&self.desc, buf.bytes(), tgt) {
                Ok(cnt) => {
                    buf.advance(cnt);
                    Ok(Ready(()))
                }
                Err(e) => {
                    if e.is_would_block() {
                        Ok(WouldBlock)
                    } else {
                        Err(e)
                    }
                }
            }
        }

        fn recv_from(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<SockAddr>> {
            match os::recvfrom(&self.desc, buf.mut_bytes()) {
                Ok((cnt, saddr)) => {
                    buf.advance(cnt);
                    Ok(Ready(saddr))
                }
                Err(e) => {
                    if e.is_would_block() {
                        Ok(WouldBlock)
                    } else {
                        Err(e)
                    }
                }
            }
        }
    }
}

pub mod pipe {
    use os;
    use io::{IoHandle};
    use net::Socket;

    #[deriving(Show)]
    pub struct UnixSocket {
        desc: os::IoDesc
    }

    impl IoHandle for UnixSocket {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    impl Socket for UnixSocket {
    }
}

<commit_msg>Add shorthands for creating listening sockets<commit_after>use std::fmt;
use std::from_str::FromStr;
use io::{IoHandle, NonBlock};
use error::MioResult;
use buf::{Buf, MutBuf};
use os;

pub use std::io::net::ip::{IpAddr, Port};
pub use std::io::net::ip::Ipv4Addr as IPv4Addr;
pub use std::io::net::ip::Ipv6Addr as IPv6Addr;

pub trait Socket : IoHandle {
    fn linger(&self) -> MioResult<uint> {
        os::linger(self.desc())
    }

    fn set_linger(&self, dur_s: uint) -> MioResult<()> {
        os::set_linger(self.desc(), dur_s)
    }

    fn set_reuseaddr(&self, val: bool) -> MioResult<()> {
        os::set_reuseaddr(self.desc(), val)
    }

    fn set_reuseport(&self, val: bool) -> MioResult<()> {
        os::set_reuseport(self.desc(), val)
    }
}

pub trait MulticastSocket : Socket {
    fn join_multicast_group(&self, addr: &IpAddr, interface: &Option<IpAddr>) -> MioResult<()> {
        os::join_multicast_group(self.desc(), addr, interface)
    }

    fn leave_multicast_group(&self, addr: &IpAddr, interface: &Option<IpAddr>) -> MioResult<()> {
        os::leave_multicast_group(self.desc(), addr, interface)
    }

    fn set_multicast_ttl(&self, val: u8) -> MioResult<()> {
        os::set_multicast_ttl(self.desc(), val)
    }
}

pub trait UnconnectedSocket {
    fn send_to(&mut self, buf: &mut Buf, tgt: &SockAddr) -> MioResult<NonBlock<()>>;
    fn recv_from(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<SockAddr>>;
}

// Types of sockets
pub enum AddressFamily {
    Inet,
    Inet6,
    Unix,
}

pub enum SockAddr {
    UnixAddr(Path),
    InetAddr(IpAddr, Port)
}

impl SockAddr {
    pub fn parse(s: &str) -> Option<SockAddr> {
        use std::io::net::ip;

        let addr: Option<ip::SocketAddr> = FromStr::from_str(s);
        addr.map(|a| InetAddr(a.ip, a.port))
    }

    pub fn family(&self) -> AddressFamily {
        match *self {
            UnixAddr(..) => Unix,
            InetAddr(IPv4Addr(..), _) => Inet,
            InetAddr(IPv6Addr(..), _) => Inet6
        }
    }
}

impl FromStr for SockAddr {
    fn from_str(s: &str) -> Option<SockAddr> {
        SockAddr::parse(s)
    }
}

impl fmt::Show for SockAddr {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            InetAddr(ip, port) => write!(fmt, "{}:{}", ip, port),
            _ => write!(fmt, "not implemented")
        }
    }
}

pub enum SocketType {
    Dgram,
    Stream,
}

pub mod tcp {
    use os;
    use error::MioResult;
    use buf::{Buf, MutBuf};
    use io;
    use io::{IoHandle, IoAcceptor, IoReader, IoWriter, NonBlock, Ready, WouldBlock};
    use net::{AddressFamily, Socket, SockAddr, Inet, Inet6, Stream};

    #[deriving(Show)]
    pub struct TcpSocket {
        desc: os::IoDesc
    }

    impl TcpSocket {
        pub fn v4() -> MioResult<TcpSocket> {
            TcpSocket::new(Inet)
        }

        pub fn v6() -> MioResult<TcpSocket> {
            TcpSocket::new(Inet6)
        }

        fn new(family: AddressFamily) -> MioResult<TcpSocket> {
            Ok(TcpSocket { desc: try!(os::socket(family, Stream)) })
        }

        pub fn bind(self, addr: &SockAddr) -> MioResult<TcpListener> {
            try!(os::bind(&self.desc, addr))
            Ok(TcpListener { desc: self.desc })
        }
    }

    impl IoHandle for TcpSocket {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    impl IoReader for TcpSocket {
        fn read(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<()>> {
            io::read(self, buf)
        }
    }

    impl IoWriter for TcpSocket {
        fn write(&mut self, buf: &mut Buf) -> MioResult<NonBlock<()>> {
            io::write(self, buf)
        }
    }

    impl Socket for TcpSocket {
    }

    #[deriving(Show)]
    pub struct TcpListener {
        desc: os::IoDesc,
    }

    impl TcpListener {
        pub fn listen(self, backlog: uint) -> MioResult<TcpAcceptor> {
            try!(os::listen(self.desc(), backlog));
            Ok(TcpAcceptor { desc: self.desc })
        }
    }

    impl IoHandle for TcpListener {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    #[deriving(Show)]
    pub struct TcpAcceptor {
        desc: os::IoDesc,
    }

    impl TcpAcceptor {
        pub fn new(addr: &SockAddr, backlog: uint) -> MioResult<TcpAcceptor> {
            let sock = try!(TcpSocket::new(addr.family()));
            let listener = try!(sock.bind(addr));
            listener.listen(backlog)
        }
    }

    impl IoHandle for TcpAcceptor {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    impl Socket for TcpAcceptor {
    }

    impl IoAcceptor<TcpSocket> for TcpAcceptor {
        fn accept(&mut self) -> MioResult<NonBlock<TcpSocket>> {
            match os::accept(self.desc()) {
                Ok(sock) => Ok(Ready(TcpSocket { desc: sock })),
                Err(e) => {
                    if e.is_would_block() {
                        return Ok(WouldBlock);
                    }

                    return Err(e);
                }
            }
        }
    }
}

pub mod udp {
    use os;
    use error::MioResult;
    use buf::{Buf, MutBuf};
    use io::{IoHandle, IoReader, IoWriter, NonBlock, Ready, WouldBlock};
    use net::{AddressFamily, Socket, MulticastSocket, SockAddr, Inet, Dgram};
    use super::UnconnectedSocket;

    #[deriving(Show)]
    pub struct UdpSocket {
        desc: os::IoDesc
    }

    impl UdpSocket {
        pub fn v4() -> MioResult<UdpSocket> {
            UdpSocket::new(Inet)
        }

        fn new(family: AddressFamily) -> MioResult<UdpSocket> {
            Ok(UdpSocket { desc: try!(os::socket(family, Dgram)) })
        }

        pub fn bind(&self, addr: &SockAddr) -> MioResult<()> {
            try!(os::bind(&self.desc, addr))
            Ok(())
        }

        pub fn connect(&self, addr: &SockAddr) -> MioResult<bool> {
            os::connect(&self.desc, addr)
        }

        pub fn bound(addr: &SockAddr) -> MioResult<UdpSocket> {
            let sock = try!(UdpSocket::new(addr.family()));
            try!(sock.bind(addr));
            Ok(sock)
        }
    }

    impl IoHandle for UdpSocket {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    impl Socket for UdpSocket {
    }

    impl MulticastSocket for UdpSocket {
    }

    impl IoReader for UdpSocket {
        fn read(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<()>> {
            match os::read(&self.desc, buf.mut_bytes()) {
                Ok(cnt) => {
                    buf.advance(cnt);
                    Ok(Ready(()))
                }
                Err(e) => {
                    if e.is_would_block() {
                        Ok(WouldBlock)
                    } else {
                        Err(e)
                    }
                }
            }
        }
    }

    impl IoWriter for UdpSocket {
        fn write(&mut self, buf: &mut Buf) -> MioResult<NonBlock<()>> {
            match os::write(&self.desc, buf.bytes()) {
                Ok(cnt) => {
                    buf.advance(cnt);
                    Ok(Ready(()))
                }
                Err(e) => {
                    if e.is_would_block() {
                        Ok(WouldBlock)
                    } else {
                        Err(e)
                    }
                }
            }
        }
    }

    // Unconnected socket sender -- trait unique to sockets
    impl UnconnectedSocket for UdpSocket {
        fn send_to(&mut self, buf: &mut Buf, tgt: &SockAddr) -> MioResult<NonBlock<()>> {
            match os::sendto(&self.desc, buf.bytes(), tgt) {
                Ok(cnt) => {
                    buf.advance(cnt);
                    Ok(Ready(()))
                }
                Err(e) => {
                    if e.is_would_block() {
                        Ok(WouldBlock)
                    } else {
                        Err(e)
                    }
                }
            }
        }

        fn recv_from(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<SockAddr>> {
            match os::recvfrom(&self.desc, buf.mut_bytes()) {
                Ok((cnt, saddr)) => {
                    buf.advance(cnt);
                    Ok(Ready(saddr))
                }
                Err(e) => {
                    if e.is_would_block() {
                        Ok(WouldBlock)
                    } else {
                        Err(e)
                    }
                }
            }
        }
    }
}

pub mod pipe {
    use os;
    use io::{IoHandle};
    use net::Socket;

    #[deriving(Show)]
    pub struct UnixSocket {
        desc: os::IoDesc
    }

    impl IoHandle for UnixSocket {
        fn desc(&self) -> &os::IoDesc {
            &self.desc
        }
    }

    impl Socket for UnixSocket {
    }
}

<|endoftext|>