<commit_before><commit_msg>got the macro to generate for multiple types<commit_after><|endoftext|>


<commit_before>// Copyright 2013 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 std::cast;
use std::ptr;
use std::sys;

fn addr_of<T>(ptr: &T) -> uint {
    let ptr = ptr::to_unsafe_ptr(ptr);
    unsafe { ptr as uint }
}

fn is_aligned<T>(ptr: &T) -> bool {
    unsafe {
        let addr: uint = ::cast::transmute(ptr);
        (addr % sys::min_align_of::<T>()) == 0
    }
}

pub fn main() {
    let x = Some(0u64);
    match x {
        None => fail!(),
        Some(ref y) => assert!(is_aligned(y))
    }
}
<commit_msg>test: Fix problem with check-fast. rs=burningtree<commit_after>// Copyright 2013 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 std::cast;
use std::ptr;
use std::sys;

fn addr_of<T>(ptr: &T) -> uint {
    let ptr = ptr::to_unsafe_ptr(ptr);
    unsafe { ptr as uint }
}

fn is_aligned<T>(ptr: &T) -> bool {
    unsafe {
        let addr: uint = cast::transmute(ptr);
        (addr % sys::min_align_of::<T>()) == 0
    }
}

pub fn main() {
    let x = Some(0u64);
    match x {
        None => fail!(),
        Some(ref y) => assert!(is_aligned(y))
    }
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2441<commit_after>// https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/
pub fn find_max_k(nums: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", find_max_k(vec![-1, 2, -3, 3])); // 3
    println!("{}", find_max_k(vec![-1, 10, 6, 7, -7, 1])); // 7
    println!("{}", find_max_k(vec![-10, 8, 6, 7, -2, -3])); // -1
}
<|endoftext|>


<commit_before><commit_msg>Add test for macro disambiguators<commit_after>#![crate_name = "foo"]
#![deny(rustdoc::broken_intra_doc_links)]

//! [foo!()]
// @has foo/index.html '//a[@href="macro.foo.html"]' 'foo!()'

//! [foo!{}]
// @has - '//a[@href="macro.foo.html"]' 'foo!{}'

//! [foo![]](foo![])
// @has - '//a[@href="macro.foo.html"]' 'foo![]'

//! [foo1](foo!())
// @has - '//a[@href="macro.foo.html"]' 'foo1'

//! [foo2](foo!{})
// @has - '//a[@href="macro.foo.html"]' 'foo2'

//! [foo3](foo![])
// @has - '//a[@href="macro.foo.html"]' 'foo3'

#[macro_export]
macro_rules! foo {
    () => {};
}
<|endoftext|>


<commit_before>use redox::{Vec, String, ToString};
use redox::collections::{BTreeMap, VecDeque};

use super::dvaddr::DVAddr;
use super::zio;

/// MRU - Most Recently Used cache
struct Mru {
    // TODO: keep track of use counts. So mru_map becomes (use_count: u64, Vec<u8>)
    map: BTreeMap<DVAddr, (u64, Vec<u8>)>,
    queue: VecDeque<DVAddr>, // Oldest DVAddrs are at the end
    size: usize, // Max mru cache size in bytes
    used: usize, // Used bytes in mru cache
}

impl Mru {
    pub fn new() -> Self {
        Mru {
            map: BTreeMap::new(),
            queue: VecDeque::new(),
            size: 1000,
            used: 0,
        }
    }

    fn cache_block(&mut self, dva: &DVAddr, block: Vec<u8>) -> Result<Vec<u8>, String> {
        // If necessary, make room for the block in the cache
        while self.used + block.len() > self.size {
            let last_dva = match self.queue.pop_back() {
                Some(dva) => dva,
                None => return Err("No more ARC MRU items to free".to_string()),
            };
            self.map.remove(&last_dva);
            self.used -= last_dva.asize() as usize;
        }

        // Add the block to the cache
        self.used += block.len();
        self.map.insert(*dva, (0, block));
        self.queue.push_front(*dva);
        Ok(self.map.get(dva).unwrap().1.clone())
    }
}

/// MFU - Most Frequently Used cache
struct Mfu {
    // TODO: Keep track of use counts. So mfu_map becomes (use_count: u64, Vec<u8>). Reset the use
    // count every once in a while. For instance, every 1000 reads. This will probably end up being
    // a knob for the user.
    // TODO: Keep track of minimum frequency and corresponding DVA
    map: BTreeMap<DVAddr, (u64, Vec<u8>)>,
    size: usize, // Max mfu cache size in bytes
    used: usize, // Used bytes in mfu cache
}

impl Mfu {
    pub fn new() -> Self {
        Mfu {
            map: BTreeMap::new(),
            size: 1000,
            used: 0,
        }
    }

    // TODO: cache_block. Remove the DVA with the lowest frequency
    /*
    fn cache_block(&mut self, dva: &DVAddr, block: Vec<u8>) -> Result<Vec<u8>, String> {
    }
    */
}

// Our implementation of the Adaptive Replacement Cache (ARC) is set up to allocate
// its buffer on the heap rather than in a private pool thing. This makes it much
// simpler to implement, but defers the fragmentation problem to the heap allocator.
// We named the type `ArCache` to avoid confusion with Rust's `Arc` reference type.
pub struct ArCache {
    mru: Mru,
    mfu: Mfu,
}

impl ArCache {
    pub fn new() -> Self {
        ArCache {
            mru: Mru::new(),
            mfu: Mfu::new(),
        }
    }

    pub fn read(&mut self, reader: &mut zio::Reader, dva: &DVAddr) -> Result<Vec<u8>, String> {
        if let Some(block) = self.mru.map.get_mut(dva) {
            // TODO: Keep track of MRU DVA use count. If it gets used a second time, move the block into
            // the MFU cache.

            block.0 += 1;

            // Block is cached
            return Ok(block.1.clone());
        }
        if let Some(block) = self.mfu.map.get_mut(dva) {
            // TODO: keep track of DVA use count
            // Block is cached

            block.0 += 1;

            return Ok(block.1.clone());
        }

        // Block isn't cached, have to read it from disk
        let block = reader.read(dva.sector() as usize, dva.asize() as usize);

        // Blocks start in MRU cache
        self.mru.cache_block(dva, block)
    }
}
<commit_msg>Cache the MRU block to the MFU when read + cleanup<commit_after>use redox::{Vec, String, ToString};
use redox::collections::{BTreeMap, VecDeque};

use super::dvaddr::DVAddr;
use super::zio;

/// MRU - Most Recently Used cache
struct Mru {
    map: BTreeMap<DVAddr, Vec<u8>>,
    queue: VecDeque<DVAddr>, // Oldest DVAddrs are at the end
    size: usize, // Max mru cache size in bytes
    used: usize, // Used bytes in mru cache
}

impl Mru {
    pub fn new() -> Self {
        Mru {
            map: BTreeMap::new(),
            queue: VecDeque::new(),
            size: 1000,
            used: 0,
        }
    }

    fn cache_block(&mut self, dva: &DVAddr, block: Vec<u8>) -> Result<Vec<u8>, String> {
        // If necessary, make room for the block in the cache
        while self.used + block.len() > self.size {
            let last_dva = match self.queue.pop_back() {
                Some(dva) => dva,
                None => return Err("No more ARC MRU items to free".to_string()),
            };
            self.map.remove(&last_dva);
            self.used -= last_dva.asize() as usize;
        }

        // Add the block to the cache
        self.used += block.len();
        self.map.insert(*dva, block);
        self.queue.push_front(*dva);
        Ok(self.map.get(dva).unwrap().clone())
    }
}

/// MFU - Most Frequently Used cache
struct Mfu {
    // TODO: Keep track of use counts. So mfu_map becomes (use_count: u64, Vec<u8>). Reset the use
    // count every once in a while. For instance, every 1000 reads. This will probably end up being
    // a knob for the user.
    // TODO: Keep track of minimum frequency and corresponding DVA
    map: BTreeMap<DVAddr, (u64, Vec<u8>)>,
    size: usize, // Max mfu cache size in bytes
    used: usize, // Used bytes in mfu cache
}

impl Mfu {
    pub fn new() -> Self {
        Mfu {
            map: BTreeMap::new(),
            size: 1000,
            used: 0,
        }
    }

    // TODO: cache_block. Remove the DVA with the lowest frequency
    /*
    fn cache_block(&mut self, dva: &DVAddr, block: Vec<u8>) -> Result<Vec<u8>, String> {
    }
    */
}

// Our implementation of the Adaptive Replacement Cache (ARC) is set up to allocate
// its buffer on the heap rather than in a private pool thing. This makes it much
// simpler to implement, but defers the fragmentation problem to the heap allocator.
// We named the type `ArCache` to avoid confusion with Rust's `Arc` reference type.
pub struct ArCache {
    mru: Mru,
    mfu: Mfu,
}

impl ArCache {
    pub fn new() -> Self {
        ArCache {
            mru: Mru::new(),
            mfu: Mfu::new(),
        }
    }

    pub fn read(&mut self, reader: &mut zio::Reader, dva: &DVAddr) -> Result<Vec<u8>, String> {
        if let Some(block) = self.mru.map.remove(dva) {
            self.mfu.map.insert(*dva, (0, block.clone()));

            // Block is cached
            return Ok(block);
        }
        if let Some(block) = self.mfu.map.get_mut(dva) {
            // Block is cached
            if block.0 > 1000 {
                block.0 = 0;
            } else {
                block.0 += 1;
            }

            return Ok(block.1.clone());
        }

        // Block isn't cached, have to read it from disk
        let block = reader.read(dva.sector() as usize, dva.asize() as usize);

        // Blocks start in MRU cache
        self.mru.cache_block(dva, block)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for #16465<commit_after>// Copyright 2014 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.

// Used to cause an ICE

struct Foo<T>{
    x : T
}

type FooInt = Foo<int>;

impl Drop for FooInt {
//~^ ERROR cannot implement a destructor on a structure with type parameters
    fn drop(&mut self){}
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #22312<commit_after>// Copyright 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 std::ops::Index;

pub trait Array2D: Index<usize> {
    fn rows(&self) -> usize;
    fn columns(&self) -> usize;
    fn get<'a>(&'a self, y: usize, x: usize) -> Option<&'a <Self as Index<usize>>::Output> {
        if y >= self.rows() || x >= self.columns() {
            return None;
        }
        let i = y * self.columns() + x;
        let indexer = &(*self as &Index<usize, Output = <Self as Index<usize>>::Output>);
        //~^ERROR non-scalar cast
        Some(indexer.index(i))
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>match<commit_after><|endoftext|>


<commit_before><commit_msg>Call default command if no command is passed<commit_after><|endoftext|>


<commit_before>extern crate common;

use common::session::Session;
use common::types::{i32_ty, f32_ty, Ty};
use common::rows::{ROWBATCH_SIZE};
use common::input::InputSource;
use common::storage::RandomTable;
use common::storage::MemTable;

#[test]
pub fn test_memtable()
{
  let types: Vec<Ty> = vec![
    i32_ty(),
    f32_ty()
  ];

  let session = Session;
  let mut generator = RandomTable::new(&session, &types, ROWBATCH_SIZE);
  let mut memtable  = MemTable::new(&session, &types, &vec!["x", "y"]);

  {
		let page = generator.next().unwrap();
		memtable.write(page).ok().unwrap();
  }
  assert_eq!(ROWBATCH_SIZE, memtable.row_num());
  generator.close().ok().unwrap();
  memtable.close().ok().unwrap();
}<commit_msg>Add memtable writing unit tests.<commit_after>extern crate common;

use common::session::Session;
use common::types::{i32_ty, f32_ty, Ty};
use common::rows::{ROWBATCH_SIZE};
use common::input::InputSource;
use common::storage::{MemTable, RandomTable};

macro_rules! assert_write_rows {
	($gen:expr, $mem:expr, $num:expr, $total_row:expr) => {
		{
		  let page = $gen.next().unwrap();
		  assert_eq!($num, page.value_count());
		  $mem.write(page).ok().unwrap();
		  assert_eq!($total_row, $mem.row_num());
  	}
	}
}

#[test]
pub fn test_next_once()
{
  let types: Vec<Ty> = vec![
    i32_ty(),
    f32_ty()
  ];

  let session = Session;
  let mut gen = RandomTable::new(&session, &types, 5);
  let mut mem = MemTable::new(&session, &types, &vec!["x","y"]);

  assert_write_rows!(gen, mem, 5, 5);
  assert_write_rows!(gen, mem, 0, 5);
}

#[test]
pub fn test_next_once2()
{
  let types: Vec<Ty> = vec![
    i32_ty(),
    f32_ty()
  ];

  let session = Session;
  let mut gen = RandomTable::new(&session, &types, ROWBATCH_SIZE);
  let mut mem = MemTable::new(&session, &types, &vec!["x","y"]);

  assert_write_rows!(gen, mem, ROWBATCH_SIZE, ROWBATCH_SIZE);
  assert_write_rows!(gen, mem, 0,             ROWBATCH_SIZE);
}

#[test]
pub fn test_next_multiple()
{
  let types: Vec<Ty> = vec![
    i32_ty(),
    f32_ty()
  ];

  let session = Session;
  let mut gen = RandomTable::new(&session, &types, (ROWBATCH_SIZE * 2) + 100);
  let mut mem = MemTable::new(&session, &types, &vec!["x","y"]);

  assert_write_rows!(gen, mem, ROWBATCH_SIZE, ROWBATCH_SIZE);
  assert_write_rows!(gen, mem, ROWBATCH_SIZE, ROWBATCH_SIZE * 2);
  assert_write_rows!(gen, mem, 100,           ROWBATCH_SIZE * 2 + 100);
  assert_write_rows!(gen, mem, 0,             ROWBATCH_SIZE * 2 + 100);
}<|endoftext|>


<commit_before><commit_msg>oops.. sanitized.<commit_after><|endoftext|>


<commit_before><commit_msg>Adding dumb locking for the global span heap.<commit_after><|endoftext|>


<commit_before><commit_msg>seed example<commit_after>extern crate timely;
extern crate graph_map;
extern crate alg3_dynamic;

use std::sync::{Arc, Mutex};

use alg3_dynamic::*;

use timely::dataflow::operators::*;

use graph_map::GraphMMap;

#[allow(non_snake_case)]
fn main () {

    let start = ::std::time::Instant::now();

    let send = Arc::new(Mutex::new(0));
    let send2 = send.clone();

    let inspect = ::std::env::args().find(|x| x == "inspect").is_some();

    timely::execute_from_args(std::env::args(), move |root| {

        let send = send.clone();

        // used to partition graph loading
        let index = root.index();
        let peers = root.peers();

        // handles to input and probe, but also both indices so we can compact them.
        let (mut input, probe, forward, reverse) = root.dataflow::<u32,_,_>(|builder| {

            // A stream of changes to the set of *triangles*, where a < b < c.
            let (graph, dT) = builder.new_input::<((u32, u32, u32), i32)>();

            // Our query is K4(w,x,y,z) := T(w,x,y), T(w,x,z), T(w,y,z), T(x,y,z)
            //
            // This query is technically redundant, because the middle two constraints imply the fourth,
            // so let's slim it down to
            //
            //    K4(w,x,y,z) := T(w,x,y), T(w,x,z), T(w,y,z)
            //
            // This seems like it could be a bit more complicated than triangles, in determining the rules
            // for incremental updates. I'm going to write them down first, and we'll see which indices we
            // actually need. I'll use A, B, and C for the instances of T above.
            //
            //    dK4dA(w,x,y,z) := dA(w,x,y), B(w,x,z), C(w,y,z)
            //    dK4dB(w,x,y,z) := dB(w,x,z), A(w,x,y), C(w,y,z)
            //    dK4dC(w,x,y,z) := dC(w,y,z), A(w,x,y), B(w,x,z)
            //
            // Looking at this, it seems like we will need
            //
            //    dK4dA : indices on (w,x,_) and (w,_,y)
            //    dK4dB : indices on (w,x,_) and (w,_,z)
            //    dK4dC : indices on (w,_,y) and (w,_,z)
            //
            // All of this seems to boil down to a "forward" and a "reverse" index, just as for triangles,
            // but where `w` is always present as part of the key. We just might want the first or second
            // field that follows it.

            // create two indices, one "forward" from (a,b) to c, and one "reverse" from (a,c) to b.
            let forward = IndexStream::from(|(a,b)| (a + b) as u64, &Vec::new().to_stream(builder), &dT.map(|((a,b,c),wgt)| (((a,b),c),wgt)));
            let reverse = IndexStream::from(|(a,c)| (a + c) as u64, &Vec::new().to_stream(builder), &dT.map(|((a,b,c),wgt)| (((a,c),b),wgt)));

            // dK4dA(w,x,y,z) := dA(w,x,y), B(w,x,z), C(w,y,z)
            let dK4dA = dT.extend(vec![Box::new(forward.extend_using(|&(w,x,y)| (w,x), <_ as PartialOrd>::lt)),
                                       Box::new(forward.extend_using(|&(w,x,y)| (w,y), <_ as PartialOrd>::lt))])
                          .flat_map(|((w,x,y), zs, wgt)| zs.into_iter().map(move |z| ((w,x,y,z),wgt)));

            // dK4dB(w,x,y,z) := dB(w,x,z), A(w,x,y), C(w,y,z)
            let dK4dB = dT.extend(vec![Box::new(forward.extend_using(|&(w,x,z)| (w,x), <_ as PartialOrd>::le)),
                                       Box::new(reverse.extend_using(|&(w,x,z)| (w,z), <_ as PartialOrd>::lt))])
                          .flat_map(|((w,x,z), ys, wgt)| ys.into_iter().map(move |y| ((w,x,y,z),wgt)));

            // dK4dC(w,x,y,z) := dC(w,y,z), A(w,x,y), B(w,x,z)
            let dK4dC = dT.extend(vec![Box::new(reverse.extend_using(|&(w,y,z)| (w,y), <_ as PartialOrd>::le)),
                                       Box::new(reverse.extend_using(|&(w,y,z)| (w,z), <_ as PartialOrd>::le))])
                          .flat_map(|((w,y,z), xs, wgt)| xs.into_iter().map(move |x| ((w,x,y,z),wgt)));

            let dK4 = dK4dA.concat(&dK4dB).concat(&dK4dC);

            // if the third argument is "inspect", report triangle counts.
            if inspect {
                dK4.exchange(|x| (x.0).0 as u64)
                       // .inspect_batch(|t,x| println!("{:?}: {:?}", t, x))
                       .count()
                       .inspect_batch(move |t,x| println!("{:?}: {:?}", t, x))
                       .inspect_batch(move |_,x| {
                            if let Ok(mut bound) = send.lock() {
                                *bound += x[0];
                            }
                        });
            }

            (graph, dK4.probe(), forward, reverse)
        });

        // // load fragment of input graph into memory to avoid io while running.
        // let filename = std::env::args().nth(1).unwrap();
        // let graph = GraphMMap::new(&filename);

        // let nodes = graph.nodes();
        // let mut triangles = Vec::new();

        // for node in 0 .. graph.nodes() {
        //     if node % peers == index {
        //         edges.push(graph.edges(node).to_vec());
        //     }
        // }

        // drop(graph);

        // // synchronize with other workers.
        // let prev = input.time().clone();
        // input.advance_to(prev.inner + 1);
        // root.step_while(|| probe.less_than(input.time()));

        // // number of nodes introduced at a time
        // let batch: usize = std::env::args().nth(2).unwrap().parse().unwrap();

        // // start the experiment!
        // let start = ::std::time::Instant::now();
        // for node in 0 .. nodes {

        //     // introduce the node if it is this worker's responsibility
        //     if node % peers == index {
        //         for &edge in &edges[node / peers] {
        //             input.send(((node as u32, edge), 1));
        //         }
        //     }

        //     // if at a batch boundary, advance time and do work.
        //     if node % batch == (batch - 1) {
        //         let prev = input.time().clone();
        //         input.advance_to(prev.inner + 1);
        //         root.step_while(|| probe.less_than(input.time()));

        //         // merge all of the indices we maintain.
        //         forward.index.borrow_mut().merge_to(&prev);
        //         reverse.index.borrow_mut().merge_to(&prev);
        //     }
        // }

        // input.close();
        // while root.step() { }

        // if inspect {
        //     println!("worker {} elapsed: {:?}", index, start.elapsed());
        // }

    }).unwrap();

    let total = if let Ok(lock) = send2.lock() {
        *lock
    }
    else { 0 };

    if inspect {
        println!("elapsed: {:?}\ttotal triangles at this process: {:?}", start.elapsed(), total);
    }
}
<|endoftext|>


<commit_before><commit_msg>Initial commit.<commit_after>extern crate stomp;
use stomp::frame::Frame;
use stomp::subscription::{Ack, AckOrNack, Auto};

const NUMBER_OF_THREADS : uint = 10;
const TOPIC : &'static str = "/queue/QUEUE_NAME";

fn main() {

  fn on_message(frame: &Frame) -> AckOrNack {
    Ack
  }

  let mut receivers : Vec<Receiver<()>> = Vec::with_capacity(NUMBER_OF_THREADS);

  for thread_number in range(0, NUMBER_OF_THREADS) {
    let (tx, rx): (Sender<()>, Receiver<()>) = channel();
    receivers.push(rx);
    spawn(proc() {
      let mut session = match stomp::connect("127.0.0.1", 61613) {
        Ok(session)  => session,
        Err(error) => panic!("Could not connect to the server: {}", error)
      };
      session.subscribe(TOPIC, Auto, on_message);
      println!("Session #{} created. Subscribed to {}", thread_number, TOPIC);
      session.listen(); // Loops infinitely, awaiting messages
      tx.send(());
    });
  }

  let _ = receivers.iter().map(|rx| (*rx).recv());
}
<|endoftext|>


<commit_before><commit_msg>Change Product rendering to unit size on canvas.<commit_after><|endoftext|>


<commit_before><commit_msg>Added macro for files, set default vector size<commit_after><|endoftext|>


<commit_before><commit_msg>Some tests for attempt of fixing a problem with EOF error during parsing json<commit_after><|endoftext|>


<commit_before><commit_msg>wait need to back up and check smth<commit_after><|endoftext|>


<commit_before><commit_msg>add pihex::util module<commit_after>pub fn powmod(n: u64, m: u32, d: u64) -> u64 {
    if m == 0 {
        1 % d
    } else if m == 1 {
        n % d
    } else {
        let k: u64 = powmod(n, m / 2, d);
        if m % 2 == 0 {
            (k * k) % d
        } else {
            (k * k * n) % d
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>questlog<commit_after><|endoftext|>


<commit_before><commit_msg>add log file to nyaa<commit_after><|endoftext|>


<commit_before><commit_msg>add dumb Executor<commit_after>//
// Copyright (c) 2016, Boris Popov <popov@whitekefir.ru>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

use logger;
use env;

pub struct Executor {
}

impl Executor {
    pub fn new() -> Executor {
        //
        //TODO
        //
        Executor{}
    }

    pub fn start(&self, l: &logger::Logger, e: &env::Env) {
        //
        //TODO
        //
    }
}
<|endoftext|>


<commit_before><commit_msg>Moved `Colored` to its own module<commit_after>use internal::{ Color, ColorComponent };
use math::{
    hsv,
    margin_rectangle,
    relative_rectangle,
    relative_source_rectangle,
    Scalar,
};
use radians::Radians;

/// Should be implemented by contexts that have rectangle information.
pub trait Rectangled: Sized {
    /// Shrinks the current rectangle equally by all sides.
    fn margin(&self, m: Scalar) -> Self;

    /// Expands the current rectangle equally by all sides.
    #[inline(always)]
    fn expand(&self, m: Scalar) -> Self {
        self.margin(-m)
    }

    /// Moves to a relative rectangle using the current rectangle as tile.
    fn rel(&self, x: Scalar, y: Scalar) -> Self;
}

/*
impl<T: Get<Rect> + Set<Rect> + Clone> Rectangled for T {
    #[inline(always)]
    fn margin(&self, m: Scalar) -> Self {
        let Rect(val) = self.get();
        self.clone().set(Rect(margin_rectangle(val, m)))
    }

    #[inline(always)]
    fn rel(&self, x: Scalar, y: Scalar) -> Self {
        let Rect(val) = self.get();
        self.clone().set(Rect(relative_rectangle(val, [x, y])))
    }
}
*/

/// Should be implemented by contexts that
/// have source rectangle information.
pub trait SourceRectangled {
    /// Adds a source rectangle.
    fn src_rect(&self, x: i32, y: i32, w: i32, h: i32) -> Self;

    /// Moves to a relative source rectangle using
    /// the current source rectangle as tile.
    fn src_rel(&self, x: i32, y: i32) -> Self;

    /// Flips the source rectangle horizontally.
    fn src_flip_h(&self) -> Self;

    /// Flips the source rectangle vertically.
    fn src_flip_v(&self) -> Self;

    /// Flips the source rectangle horizontally and vertically.
    fn src_flip_hv(&self) -> Self;
}

/*
impl<T: Get<SrcRect>
      + Set<SrcRect>
      + Clone
> SourceRectangled for T {
    #[inline(always)]
    fn src_rect(&self, x: i32, y: i32, w: i32, h: i32) -> Self {
        self.clone().set(SrcRect([x, y, w, h]))
    }

    #[inline(always)]
    fn src_rel(&self, x: i32, y: i32) -> Self {
        let SrcRect(val) = self.get();
        self.clone().set(SrcRect(
            relative_source_rectangle(val, x, y)
        ))
    }

    #[inline(always)]
    fn src_flip_h(&self) -> Self {
        let SrcRect(source_rect) = self.get();
        self.clone().set(SrcRect([
            source_rect[0] + source_rect[2],
            source_rect[1],
            -source_rect[2],
            source_rect[3]
        ]))
    }

    #[inline(always)]
    fn src_flip_v(&self) -> Self {
        let SrcRect(source_rect) = self.get();
        self.clone().set(SrcRect([
            source_rect[0],
            source_rect[1] + source_rect[3],
            source_rect[2],
            -source_rect[3]
        ]))
    }

    #[inline(always)]
    fn src_flip_hv(&self) -> Self {
        let SrcRect(source_rect) = self.get();
        self.clone().set(SrcRect([
            source_rect[0] + source_rect[2],
            source_rect[1] + source_rect[3],
            -source_rect[2],
            -source_rect[3]
        ]))
    }
}
*/
<|endoftext|>


<commit_before><commit_msg>Minor whitespace cleanup<commit_after><|endoftext|>


<commit_before><commit_msg>Fix(test): update for create_syncfile<commit_after><|endoftext|>


<commit_before><commit_msg>Add integration test for macro<commit_after>//! Having these as an integration test checks that the visibility of the macros
//! and their dependencies is valid for use by external libraries.

#[macro_use]
// Rename the import to check that the macros don't use the literal crate name
extern crate hamlet as willy;

// I would really like to do:
//
// ```
// #![no_std]
// #![no_implicit_prelude]
// #[macro_use]
// extern crate std as bob;
// ```
//
// but macros are too unhygienic :(

// We don't `use` anything here to check the macros only use fully qualified
// paths.

#[test]
fn empty_attr_set() {
    assert_eq!(attr_set!().0.into_owned(), vec![]);
}

#[test]
fn single_attr() {
    assert_eq!(
        attr_set!(id = "foo").0.into_owned(),
        vec![
            willy::Attribute::new("id", "foo"),
        ]);
}

#[test]
fn multi_attr() {
    assert_eq!(
        attr_set!(id = "foo", class = "bar").0.into_owned(),
        vec![
            willy::Attribute::new("id", "foo"),
            willy::Attribute::new("class", "bar"),
        ]);
}
<|endoftext|>


<commit_before>
fn add(uint x, uint y) -> uint { ret x + y; }
fn sub(uint x, uint y) -> uint { ret x - y; }
fn mul(uint x, uint y) -> uint { ret x * y; }
fn div(uint x, uint y) -> uint { ret x / y; }
fn rem(uint x, uint y) -> uint { ret x % y; }

fn lt(uint x, uint y) -> bool { ret x < y; }
fn le(uint x, uint y) -> bool { ret x <= y; }
fn eq(uint x, uint y) -> bool { ret x == y; }
fn ne(uint x, uint y) -> bool { ret x != y; }
fn ge(uint x, uint y) -> bool { ret x >= y; }
fn gt(uint x, uint y) -> bool { ret x > y; }

iter range(uint lo, uint hi) -> uint {
    auto lo_ = lo;
    while (lo_ < hi) {
        put lo_;
        lo_ += 1u;
    }
}

fn next_power_of_two(uint n) -> uint {
    // FIXME change |* uint(4)| below to |* uint(8) / uint(2)| and watch the
    // world explode.
    let uint halfbits = sys::rustrt::size_of[uint]() * 4u;
    let uint tmp = n - 1u;
    let uint shift = 1u;
    while (shift <= halfbits) {
        tmp |= tmp >> shift;
        shift <<= 1u;
    }
    ret tmp + 1u;
}

fn parse_buf(vec[u8] buf, uint radix) -> uint {
    if (vec::len[u8](buf) == 0u) {
        log_err "parse_buf(): buf is empty";
        fail;
    }

    auto i = vec::len[u8](buf) - 1u;
    auto power = 1u;
    auto n = 0u;
    while (true) {
        n += (((buf.(i)) - ('0' as u8)) as uint) * power;
        power *= radix;
        if (i == 0u) { ret n; }
        i -= 1u;
    }

    fail;
}

fn to_str(uint num, uint radix) -> str
{
    auto n = num;

    assert (0u < radix && radix <= 16u);
    fn digit(uint n) -> char {
        alt (n) {
            case (0u) { ret '0'; }
            case (1u) { ret '1'; }
            case (2u) { ret '2'; }
            case (3u) { ret '3'; }
            case (4u) { ret '4'; }
            case (5u) { ret '5'; }
            case (6u) { ret '6'; }
            case (7u) { ret '7'; }
            case (8u) { ret '8'; }
            case (9u) { ret '9'; }
            case (10u) { ret 'a'; }
            case (11u) { ret 'b'; }
            case (12u) { ret 'c'; }
            case (13u) { ret 'd'; }
            case (14u) { ret 'e'; }
            case (15u) { ret 'f'; }
        }
        fail;
    }

    if (n == 0u) { ret "0"; }

    let str s = "";
    while (n != 0u) {
        s += str::unsafe_from_byte(digit(n % radix) as u8);
        n /= radix;
    }

    let str s1 = "";
    let uint len = str::byte_len(s);
    while (len != 0u) {
        len -= 1u;
        s1 += str::unsafe_from_byte(s.(len));
    }
    ret s1;

}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>stdlib: Use if/alt expressions in std::uint<commit_after>
fn add(uint x, uint y) -> uint { ret x + y; }
fn sub(uint x, uint y) -> uint { ret x - y; }
fn mul(uint x, uint y) -> uint { ret x * y; }
fn div(uint x, uint y) -> uint { ret x / y; }
fn rem(uint x, uint y) -> uint { ret x % y; }

fn lt(uint x, uint y) -> bool { ret x < y; }
fn le(uint x, uint y) -> bool { ret x <= y; }
fn eq(uint x, uint y) -> bool { ret x == y; }
fn ne(uint x, uint y) -> bool { ret x != y; }
fn ge(uint x, uint y) -> bool { ret x >= y; }
fn gt(uint x, uint y) -> bool { ret x > y; }

iter range(uint lo, uint hi) -> uint {
    auto lo_ = lo;
    while (lo_ < hi) {
        put lo_;
        lo_ += 1u;
    }
}

fn next_power_of_two(uint n) -> uint {
    // FIXME change |* uint(4)| below to |* uint(8) / uint(2)| and watch the
    // world explode.
    let uint halfbits = sys::rustrt::size_of[uint]() * 4u;
    let uint tmp = n - 1u;
    let uint shift = 1u;
    while (shift <= halfbits) {
        tmp |= tmp >> shift;
        shift <<= 1u;
    }
    ret tmp + 1u;
}

fn parse_buf(vec[u8] buf, uint radix) -> uint {
    if (vec::len[u8](buf) == 0u) {
        log_err "parse_buf(): buf is empty";
        fail;
    }

    auto i = vec::len[u8](buf) - 1u;
    auto power = 1u;
    auto n = 0u;
    while (true) {
        n += (((buf.(i)) - ('0' as u8)) as uint) * power;
        power *= radix;
        if (i == 0u) { ret n; }
        i -= 1u;
    }

    fail;
}

fn to_str(uint num, uint radix) -> str
{
    auto n = num;

    assert (0u < radix && radix <= 16u);
    fn digit(uint n) -> char {
        ret alt (n) {
            case (0u) { '0' }
            case (1u) { '1' }
            case (2u) { '2' }
            case (3u) { '3' }
            case (4u) { '4' }
            case (5u) { '5' }
            case (6u) { '6' }
            case (7u) { '7' }
            case (8u) { '8' }
            case (9u) { '9' }
            case (10u) { 'a' }
            case (11u) { 'b' }
            case (12u) { 'c' }
            case (13u) { 'd' }
            case (14u) { 'e' }
            case (15u) { 'f' }
            case (_) { fail }
        };
    }

    if (n == 0u) { ret "0"; }

    let str s = "";
    while (n != 0u) {
        s += str::unsafe_from_byte(digit(n % radix) as u8);
        n /= radix;
    }

    let str s1 = "";
    let uint len = str::byte_len(s);
    while (len != 0u) {
        len -= 1u;
        s1 += str::unsafe_from_byte(s.(len));
    }
    ret s1;

}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before>use core::ops::Deref;
use core_collections::borrow::ToOwned;
use io::{Read, Error, Result, Write, Seek, SeekFrom};
use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use mem;
use path::{PathBuf, Path};
use str;
use string::String;
use sys_common::AsInner;
use vec::Vec;

use system::syscall::{sys_open, sys_dup, sys_close, sys_fpath, sys_ftruncate, sys_read,
              sys_write, sys_lseek, sys_fsync, sys_mkdir, sys_rmdir, sys_stat, sys_unlink};
use system::syscall::{O_RDWR, O_RDONLY, O_WRONLY, O_APPEND, O_CREAT, O_TRUNC, MODE_DIR, MODE_FILE, SEEK_SET, SEEK_CUR, SEEK_END, Stat};

/// A Unix-style file
pub struct File {
    /// The id for the file
    fd: usize,
}

impl File {
    /// Open a new file using a path
    pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_RDONLY, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Create a new file using a path
    pub fn create<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_CREAT | O_RDWR | O_TRUNC, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Duplicate the file
    pub fn dup(&self) -> Result<File> {
        sys_dup(self.fd).map(|fd| unsafe { File::from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
    }

    /// Get the canonical path of the file
    pub fn path(&self) -> Result<PathBuf> {
        let mut buf: [u8; 4096] = [0; 4096];
        match sys_fpath(self.fd, &mut buf) {
            Ok(count) => Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[0..count])) })),
            Err(err) => Err(Error::from_sys(err)),
        }
    }

    /// Flush the file data and metadata
    pub fn sync_all(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Flush the file data
    pub fn sync_data(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Truncates the file
    pub fn set_len(&mut self, size: u64) -> Result<()> {
        sys_ftruncate(self.fd, size as usize).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl AsRawFd for File {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl FromRawFd for File {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        File {
            fd: fd
        }
    }
}

impl IntoRawFd for File {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.fd;
        mem::forget(self);
        fd
    }
}

impl Read for File {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        sys_read(self.fd, buf).map_err(|x| Error::from_sys(x))
    }
}

impl Write for File {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        sys_write(self.fd, buf).map_err(|x| Error::from_sys(x))
    }

    // TODO buffered fs
    fn flush(&mut self) -> Result<()> { Ok(()) }
}

impl Seek for File {
    /// Seek a given position
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let (whence, offset) = match pos {
            SeekFrom::Start(offset) => (SEEK_SET, offset as isize),
            SeekFrom::Current(offset) => (SEEK_CUR, offset as isize),
            SeekFrom::End(offset) => (SEEK_END, offset as isize),
        };

        sys_lseek(self.fd, offset, whence).map(|position| position as u64).map_err(|x| Error::from_sys(x))
    }
}

impl Drop for File {
    fn drop(&mut self) {
        let _ = sys_close(self.fd);
    }
}

pub struct FileType {
    dir: bool,
    file: bool,
}

impl FileType {
    pub fn is_dir(&self) -> bool {
        self.dir
    }

    pub fn is_file(&self) -> bool {
        self.file
    }
}

pub struct OpenOptions {
    read: bool,
    write: bool,
    append: bool,
    create: bool,
    truncate: bool,
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
            read: false,
            write: false,
            append: false,
            create: false,
            truncate: false,
        }
    }

    pub fn read(&mut self, read: bool) -> &mut OpenOptions {
        self.read = read;
        self
    }

    pub fn write(&mut self, write: bool) -> &mut OpenOptions {
        self.write = write;
        self
    }

    pub fn append(&mut self, append: bool) -> &mut OpenOptions {
        self.append = append;
        self
    }

    pub fn create(&mut self, create: bool) -> &mut OpenOptions {
        self.create = create;
        self
    }

    pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
        self.truncate = truncate;
        self
    }

    pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let mut flags = 0;

        if self.read && self.write {
            flags |= O_RDWR;
        } else if self.read {
            flags |= O_RDONLY;
        } else if self.write {
            flags |= O_WRONLY;
        }

        if self.append {
            flags |= O_APPEND;
        }

        if self.create {
            flags |= O_CREAT;
        }

        if self.truncate {
            flags |= O_TRUNC;
        }

        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), flags, 0).map(|fd| File::from_raw_fd(fd))
        }.map_err(|x| Error::from_sys(x))
    }
}

pub struct Metadata {
    stat: Stat
}

impl Metadata {
    pub fn file_type(&self) -> FileType {
        FileType {
            dir: self.stat.st_mode & MODE_DIR == MODE_DIR,
            file: self.stat.st_mode & MODE_FILE == MODE_FILE
        }
    }

    pub fn is_dir(&self) -> bool {
        self.stat.st_mode & MODE_DIR == MODE_DIR
    }

    pub fn is_file(&self) -> bool {
        self.stat.st_mode & MODE_FILE == MODE_FILE
    }

    pub fn len(&self) -> u64 {
        self.stat.st_size
    }
}

pub struct DirEntry {
    path: String,
    dir: bool,
    file: bool,
}

impl DirEntry {
    pub fn file_name(&self) -> &Path {
        unsafe { mem::transmute(self.path.deref()) }
    }

    pub fn file_type(&self) -> Result<FileType> {
        Ok(FileType {
            dir: self.dir,
            file: self.file,
        })
    }

    pub fn path(&self) -> PathBuf {
        PathBuf::from(self.path.clone())
    }
}

pub struct ReadDir {
    file: File,
}

impl Iterator for ReadDir {
    type Item = Result<DirEntry>;
    fn next(&mut self) -> Option<Result<DirEntry>> {
        let mut path = String::new();
        let mut buf: [u8; 1] = [0; 1];
        loop {
            match self.file.read(&mut buf) {
                Ok(0) => break,
                Ok(count) => {
                    if buf[0] == 10 {
                        break;
                    } else {
                        path.push_str(unsafe { str::from_utf8_unchecked(&buf[..count]) });
                    }
                }
                Err(_err) => break,
            }
        }
        if path.is_empty() {
            None
        } else {
            let dir = path.ends_with('/');
            if dir {
                path.pop();
            }
            Some(Ok(DirEntry {
                path: path,
                dir: dir,
                file: !dir,
            }))
        }
    }
}

/// Find the canonical path of a file
pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    match File::open(path) {
        Ok(file) => {
            match file.path() {
                Ok(realpath) => Ok(realpath),
                Err(err) => Err(err)
            }
        },
        Err(err) => Err(err)
    }
}

pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    let mut stat = Stat {
        st_mode: 0,
        st_size: 0
    };
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        try!(sys_stat(path_c.as_ptr(), &mut stat).map_err(|x| Error::from_sys(x)));
    }
    Ok(Metadata {
        stat: stat
    })
}

/// Create a new directory, using a path
/// The default mode of the directory is 744
pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_mkdir(path_c.as_ptr(), 755).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir> {
    File::open(path).map(|file| ReadDir { file: file })
}

pub fn remove_dir(path: &str) -> Result<()> {
    let path_c = path.to_owned() + "\0";
    unsafe {
        sys_rmdir(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}

pub fn remove_file(path: &str) -> Result<()> {
    let path_c = path.to_owned() + "\0";
    unsafe {
        sys_unlink(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}
<commit_msg>Fix remove_file/dir signature<commit_after>use core::ops::Deref;
use core_collections::borrow::ToOwned;
use io::{Read, Error, Result, Write, Seek, SeekFrom};
use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use mem;
use path::{PathBuf, Path};
use str;
use string::String;
use sys_common::AsInner;
use vec::Vec;

use system::syscall::{sys_open, sys_dup, sys_close, sys_fpath, sys_ftruncate, sys_read,
              sys_write, sys_lseek, sys_fsync, sys_mkdir, sys_rmdir, sys_stat, sys_unlink};
use system::syscall::{O_RDWR, O_RDONLY, O_WRONLY, O_APPEND, O_CREAT, O_TRUNC, MODE_DIR, MODE_FILE, SEEK_SET, SEEK_CUR, SEEK_END, Stat};

/// A Unix-style file
pub struct File {
    /// The id for the file
    fd: usize,
}

impl File {
    /// Open a new file using a path
    pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_RDONLY, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Create a new file using a path
    pub fn create<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_CREAT | O_RDWR | O_TRUNC, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Duplicate the file
    pub fn dup(&self) -> Result<File> {
        sys_dup(self.fd).map(|fd| unsafe { File::from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
    }

    /// Get the canonical path of the file
    pub fn path(&self) -> Result<PathBuf> {
        let mut buf: [u8; 4096] = [0; 4096];
        match sys_fpath(self.fd, &mut buf) {
            Ok(count) => Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[0..count])) })),
            Err(err) => Err(Error::from_sys(err)),
        }
    }

    /// Flush the file data and metadata
    pub fn sync_all(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Flush the file data
    pub fn sync_data(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Truncates the file
    pub fn set_len(&mut self, size: u64) -> Result<()> {
        sys_ftruncate(self.fd, size as usize).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl AsRawFd for File {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl FromRawFd for File {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        File {
            fd: fd
        }
    }
}

impl IntoRawFd for File {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.fd;
        mem::forget(self);
        fd
    }
}

impl Read for File {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        sys_read(self.fd, buf).map_err(|x| Error::from_sys(x))
    }
}

impl Write for File {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        sys_write(self.fd, buf).map_err(|x| Error::from_sys(x))
    }

    // TODO buffered fs
    fn flush(&mut self) -> Result<()> { Ok(()) }
}

impl Seek for File {
    /// Seek a given position
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let (whence, offset) = match pos {
            SeekFrom::Start(offset) => (SEEK_SET, offset as isize),
            SeekFrom::Current(offset) => (SEEK_CUR, offset as isize),
            SeekFrom::End(offset) => (SEEK_END, offset as isize),
        };

        sys_lseek(self.fd, offset, whence).map(|position| position as u64).map_err(|x| Error::from_sys(x))
    }
}

impl Drop for File {
    fn drop(&mut self) {
        let _ = sys_close(self.fd);
    }
}

pub struct FileType {
    dir: bool,
    file: bool,
}

impl FileType {
    pub fn is_dir(&self) -> bool {
        self.dir
    }

    pub fn is_file(&self) -> bool {
        self.file
    }
}

pub struct OpenOptions {
    read: bool,
    write: bool,
    append: bool,
    create: bool,
    truncate: bool,
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
            read: false,
            write: false,
            append: false,
            create: false,
            truncate: false,
        }
    }

    pub fn read(&mut self, read: bool) -> &mut OpenOptions {
        self.read = read;
        self
    }

    pub fn write(&mut self, write: bool) -> &mut OpenOptions {
        self.write = write;
        self
    }

    pub fn append(&mut self, append: bool) -> &mut OpenOptions {
        self.append = append;
        self
    }

    pub fn create(&mut self, create: bool) -> &mut OpenOptions {
        self.create = create;
        self
    }

    pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
        self.truncate = truncate;
        self
    }

    pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let mut flags = 0;

        if self.read && self.write {
            flags |= O_RDWR;
        } else if self.read {
            flags |= O_RDONLY;
        } else if self.write {
            flags |= O_WRONLY;
        }

        if self.append {
            flags |= O_APPEND;
        }

        if self.create {
            flags |= O_CREAT;
        }

        if self.truncate {
            flags |= O_TRUNC;
        }

        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), flags, 0).map(|fd| File::from_raw_fd(fd))
        }.map_err(|x| Error::from_sys(x))
    }
}

pub struct Metadata {
    stat: Stat
}

impl Metadata {
    pub fn file_type(&self) -> FileType {
        FileType {
            dir: self.stat.st_mode & MODE_DIR == MODE_DIR,
            file: self.stat.st_mode & MODE_FILE == MODE_FILE
        }
    }

    pub fn is_dir(&self) -> bool {
        self.stat.st_mode & MODE_DIR == MODE_DIR
    }

    pub fn is_file(&self) -> bool {
        self.stat.st_mode & MODE_FILE == MODE_FILE
    }

    pub fn len(&self) -> u64 {
        self.stat.st_size
    }
}

pub struct DirEntry {
    path: String,
    dir: bool,
    file: bool,
}

impl DirEntry {
    pub fn file_name(&self) -> &Path {
        unsafe { mem::transmute(self.path.deref()) }
    }

    pub fn file_type(&self) -> Result<FileType> {
        Ok(FileType {
            dir: self.dir,
            file: self.file,
        })
    }

    pub fn path(&self) -> PathBuf {
        PathBuf::from(self.path.clone())
    }
}

pub struct ReadDir {
    file: File,
}

impl Iterator for ReadDir {
    type Item = Result<DirEntry>;
    fn next(&mut self) -> Option<Result<DirEntry>> {
        let mut path = String::new();
        let mut buf: [u8; 1] = [0; 1];
        loop {
            match self.file.read(&mut buf) {
                Ok(0) => break,
                Ok(count) => {
                    if buf[0] == 10 {
                        break;
                    } else {
                        path.push_str(unsafe { str::from_utf8_unchecked(&buf[..count]) });
                    }
                }
                Err(_err) => break,
            }
        }
        if path.is_empty() {
            None
        } else {
            let dir = path.ends_with('/');
            if dir {
                path.pop();
            }
            Some(Ok(DirEntry {
                path: path,
                dir: dir,
                file: !dir,
            }))
        }
    }
}

/// Find the canonical path of a file
pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    match File::open(path) {
        Ok(file) => {
            match file.path() {
                Ok(realpath) => Ok(realpath),
                Err(err) => Err(err)
            }
        },
        Err(err) => Err(err)
    }
}

pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    let mut stat = Stat {
        st_mode: 0,
        st_size: 0
    };
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        try!(sys_stat(path_c.as_ptr(), &mut stat).map_err(|x| Error::from_sys(x)));
    }
    Ok(Metadata {
        stat: stat
    })
}

/// Create a new directory, using a path
/// The default mode of the directory is 744
pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_mkdir(path_c.as_ptr(), 755).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir> {
    File::open(path).map(|file| ReadDir { file: file })
}

pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_rmdir(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}

pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_unlink(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}
<|endoftext|>


<commit_before><commit_msg>Added an example that draws a star<commit_after>extern crate turtle;

use turtle::Turtle;

fn main() {
    let mut turtle = Turtle::new();

    turtle.right(90.0);
    turtle.set_pen_size(2.0);
    turtle.set_pen_color("yellow");

    for _ in 0..5 {
        turtle.forward(300.0);
        turtle.right(180.0 - (180.0 / 5.0));
    }
}
<|endoftext|>


<commit_before>// Copyright 2012 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 core::prelude::*;

use ast;
use ast::{token_tree, tt_delim, tt_tok, tt_seq, tt_nonterminal,ident};
use codemap::{span, dummy_sp};
use diagnostic::span_handler;
use ext::tt::macro_parser::{named_match, matched_seq, matched_nonterminal};
use parse::token::{EOF, INTERPOLATED, IDENT, Token, nt_ident, ident_interner};
use parse::lexer::TokenAndSpan;

use core::hashmap::HashMap;
use core::option;
use core::vec;

/* FIXME #2811: figure out how to have a uniquely linked stack, and change to
   `~` */
///an unzipping of `token_tree`s
struct TtFrame {
    forest: @mut ~[ast::token_tree],
    idx: uint,
    dotdotdoted: bool,
    sep: Option<Token>,
    up: Option<@mut TtFrame>,
}

pub struct TtReader {
    sp_diag: @span_handler,
    interner: @ident_interner,
    // the unzipped tree:
    stack: @mut TtFrame,
    /* for MBE-style macro transcription */
    interpolations: HashMap<ident, @named_match>,
    repeat_idx: ~[uint],
    repeat_len: ~[uint],
    /* cached: */
    cur_tok: Token,
    cur_span: span
}

/** This can do Macro-By-Example transcription. On the other hand, if
 *  `src` contains no `tt_seq`s and `tt_nonterminal`s, `interp` can (and
 *  should) be none. */
pub fn new_tt_reader(sp_diag: @span_handler,
                     itr: @ident_interner,
                     interp: Option<HashMap<ident,@named_match>>,
                     src: ~[ast::token_tree])
                  -> @mut TtReader {
    let r = @mut TtReader {
        sp_diag: sp_diag,
        interner: itr,
        stack: @mut TtFrame {
            forest: @mut src,
            idx: 0u,
            dotdotdoted: false,
            sep: None,
            up: option::None
        },
        interpolations: match interp { /* just a convienience */
            None => HashMap::new(),
            Some(x) => x
        },
        repeat_idx: ~[],
        repeat_len: ~[],
        /* dummy values, never read: */
        cur_tok: EOF,
        cur_span: dummy_sp()
    };
    tt_next_token(r); /* get cur_tok and cur_span set up */
    return r;
}

fn dup_tt_frame(f: @mut TtFrame) -> @mut TtFrame {
    @mut TtFrame {
        forest: @mut (copy *f.forest),
        idx: f.idx,
        dotdotdoted: f.dotdotdoted,
        sep: copy f.sep,
        up: match f.up {
            Some(up_frame) => Some(dup_tt_frame(up_frame)),
            None => None
        }
    }
}

pub fn dup_tt_reader(r: @mut TtReader) -> @mut TtReader {
    @mut TtReader {
        sp_diag: r.sp_diag,
        interner: r.interner,
        stack: dup_tt_frame(r.stack),
        interpolations: r.interpolations,
        repeat_idx: copy r.repeat_idx,
        repeat_len: copy r.repeat_len,
        cur_tok: copy r.cur_tok,
        cur_span: r.cur_span
    }
}

fn lookup_cur_matched_by_matched(r: &mut TtReader,
                                      start: @named_match)
                                   -> @named_match {
    fn red(ad: @named_match, idx: &uint) -> @named_match {
        match *ad {
          matched_nonterminal(_) => {
            // end of the line; duplicate henceforth
            ad
          }
          matched_seq(ref ads, _) => ads[*idx]
        }
    }
    let r = &mut *r;
    let repeat_idx = &r.repeat_idx;
    vec::foldl(start, *repeat_idx, red)
}

fn lookup_cur_matched(r: &mut TtReader, name: ident) -> @named_match {
    // FIXME (#3850): this looks a bit silly with an extra scope.
    let start;
    { start = *r.interpolations.get(&name); }
    return lookup_cur_matched_by_matched(r, start);
}
enum lis {
    lis_unconstrained, lis_constraint(uint, ident), lis_contradiction(~str)
}

fn lockstep_iter_size(t: token_tree, r: &mut TtReader) -> lis {
    fn lis_merge(lhs: lis, rhs: lis, r: &mut TtReader) -> lis {
        match lhs {
          lis_unconstrained => copy rhs,
          lis_contradiction(_) => copy lhs,
          lis_constraint(l_len, l_id) => match rhs {
            lis_unconstrained => copy lhs,
            lis_contradiction(_) => copy rhs,
            lis_constraint(r_len, _) if l_len == r_len => copy lhs,
            lis_constraint(r_len, r_id) => {
                let l_n = copy *r.interner.get(l_id);
                let r_n = copy *r.interner.get(r_id);
                lis_contradiction(fmt!("Inconsistent lockstep iteration: \
                                       '%s' has %u items, but '%s' has %u",
                                        l_n, l_len, r_n, r_len))
            }
          }
        }
    }
    match t {
      tt_delim(ref tts) | tt_seq(_, ref tts, _, _) => {
        vec::foldl(lis_unconstrained, (*tts), |lis, tt| {
            let lis2 = lockstep_iter_size(*tt, r);
            lis_merge(lis, lis2, r)
        })
      }
      tt_tok(*) => lis_unconstrained,
      tt_nonterminal(_, name) => match *lookup_cur_matched(r, name) {
        matched_nonterminal(_) => lis_unconstrained,
        matched_seq(ref ads, _) => lis_constraint(ads.len(), name)
      }
    }
}

// return the next token from the TtReader.
// EFFECT: advances the reader's token field
pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {
    let ret_val = TokenAndSpan {
        tok: copy r.cur_tok,
        sp: r.cur_span,
    };
    loop {
        {
            let stack = &mut *r.stack;
            let forest = &mut *stack.forest;
            if stack.idx < forest.len() {
                break;
            }
        }

        /* done with this set; pop or repeat? */
        if ! r.stack.dotdotdoted
            || { *r.repeat_idx.last() == *r.repeat_len.last() - 1 } {

            match r.stack.up {
              None => {
                r.cur_tok = EOF;
                return ret_val;
              }
              Some(tt_f) => {
                if r.stack.dotdotdoted {
                    r.repeat_idx.pop();
                    r.repeat_len.pop();
                }

                r.stack = tt_f;
                r.stack.idx += 1u;
              }
            }

        } else { /* repeat */
            r.stack.idx = 0u;
            r.repeat_idx[r.repeat_idx.len() - 1u] += 1u;
            match r.stack.sep {
              Some(copy tk) => {
                r.cur_tok = tk; /* repeat same span, I guess */
                return ret_val;
              }
              None => ()
            }
        }
    }
    loop { /* because it's easiest, this handles `tt_delim` not starting
    with a `tt_tok`, even though it won't happen */
        match r.stack.forest[r.stack.idx] {
          tt_delim(copy tts) => {
            r.stack = @mut TtFrame {
                forest: @mut tts,
                idx: 0u,
                dotdotdoted: false,
                sep: None,
                up: option::Some(r.stack)
            };
            // if this could be 0-length, we'd need to potentially recur here
          }
          tt_tok(sp, copy tok) => {
            r.cur_span = sp;
            r.cur_tok = tok;
            r.stack.idx += 1u;
            return ret_val;
          }
          tt_seq(sp, copy tts, copy sep, zerok) => {
            let t = tt_seq(sp, copy tts, copy sep, zerok);
            match lockstep_iter_size(t, r) {
              lis_unconstrained => {
                r.sp_diag.span_fatal(
                    sp, /* blame macro writer */
                      ~"attempted to repeat an expression \
                        containing no syntax \
                        variables matched as repeating at this depth");
                  }
                  lis_contradiction(ref msg) => {
                      /* FIXME #2887 blame macro invoker instead*/
                      r.sp_diag.span_fatal(sp, (*msg));
                  }
                  lis_constraint(len, _) => {
                    if len == 0 {
                      if !zerok {
                        r.sp_diag.span_fatal(sp, /* FIXME #2887 blame invoker
                        */
                                             ~"this must repeat at least \
                                               once");
                          }

                    r.stack.idx += 1u;
                    return tt_next_token(r);
                } else {
                    r.repeat_len.push(len);
                    r.repeat_idx.push(0u);
                    r.stack = @mut TtFrame {
                        forest: @mut tts,
                        idx: 0u,
                        dotdotdoted: true,
                        sep: sep,
                        up: Some(r.stack)
                    };
                }
              }
            }
          }
          // FIXME #2887: think about span stuff here
          tt_nonterminal(sp, ident) => {
            match *lookup_cur_matched(r, ident) {
              /* sidestep the interpolation tricks for ident because
              (a) idents can be in lots of places, so it'd be a pain
              (b) we actually can, since it's a token. */
              matched_nonterminal(nt_ident(sn,b)) => {
                r.cur_span = sp; r.cur_tok = IDENT(sn,b);
                r.stack.idx += 1u;
                return ret_val;
              }
              matched_nonterminal(ref other_whole_nt) => {
                r.cur_span = sp;
                r.cur_tok = INTERPOLATED(copy *other_whole_nt);
                r.stack.idx += 1u;
                return ret_val;
              }
              matched_seq(*) => {
                r.sp_diag.span_fatal(
                    copy r.cur_span, /* blame the macro writer */
                    fmt!("variable '%s' is still repeating at this depth",
                         *r.interner.get(ident)));
              }
            }
          }
        }
    }

}
<commit_msg>Remove needless FIXME. Fixes #2811.<commit_after>// Copyright 2012 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 core::prelude::*;

use ast;
use ast::{token_tree, tt_delim, tt_tok, tt_seq, tt_nonterminal,ident};
use codemap::{span, dummy_sp};
use diagnostic::span_handler;
use ext::tt::macro_parser::{named_match, matched_seq, matched_nonterminal};
use parse::token::{EOF, INTERPOLATED, IDENT, Token, nt_ident, ident_interner};
use parse::lexer::TokenAndSpan;

use core::hashmap::HashMap;
use core::option;
use core::vec;

///an unzipping of `token_tree`s
struct TtFrame {
    forest: @mut ~[ast::token_tree],
    idx: uint,
    dotdotdoted: bool,
    sep: Option<Token>,
    up: Option<@mut TtFrame>,
}

pub struct TtReader {
    sp_diag: @span_handler,
    interner: @ident_interner,
    // the unzipped tree:
    stack: @mut TtFrame,
    /* for MBE-style macro transcription */
    interpolations: HashMap<ident, @named_match>,
    repeat_idx: ~[uint],
    repeat_len: ~[uint],
    /* cached: */
    cur_tok: Token,
    cur_span: span
}

/** This can do Macro-By-Example transcription. On the other hand, if
 *  `src` contains no `tt_seq`s and `tt_nonterminal`s, `interp` can (and
 *  should) be none. */
pub fn new_tt_reader(sp_diag: @span_handler,
                     itr: @ident_interner,
                     interp: Option<HashMap<ident,@named_match>>,
                     src: ~[ast::token_tree])
                  -> @mut TtReader {
    let r = @mut TtReader {
        sp_diag: sp_diag,
        interner: itr,
        stack: @mut TtFrame {
            forest: @mut src,
            idx: 0u,
            dotdotdoted: false,
            sep: None,
            up: option::None
        },
        interpolations: match interp { /* just a convienience */
            None => HashMap::new(),
            Some(x) => x
        },
        repeat_idx: ~[],
        repeat_len: ~[],
        /* dummy values, never read: */
        cur_tok: EOF,
        cur_span: dummy_sp()
    };
    tt_next_token(r); /* get cur_tok and cur_span set up */
    return r;
}

fn dup_tt_frame(f: @mut TtFrame) -> @mut TtFrame {
    @mut TtFrame {
        forest: @mut (copy *f.forest),
        idx: f.idx,
        dotdotdoted: f.dotdotdoted,
        sep: copy f.sep,
        up: match f.up {
            Some(up_frame) => Some(dup_tt_frame(up_frame)),
            None => None
        }
    }
}

pub fn dup_tt_reader(r: @mut TtReader) -> @mut TtReader {
    @mut TtReader {
        sp_diag: r.sp_diag,
        interner: r.interner,
        stack: dup_tt_frame(r.stack),
        interpolations: r.interpolations,
        repeat_idx: copy r.repeat_idx,
        repeat_len: copy r.repeat_len,
        cur_tok: copy r.cur_tok,
        cur_span: r.cur_span
    }
}

fn lookup_cur_matched_by_matched(r: &mut TtReader,
                                      start: @named_match)
                                   -> @named_match {
    fn red(ad: @named_match, idx: &uint) -> @named_match {
        match *ad {
          matched_nonterminal(_) => {
            // end of the line; duplicate henceforth
            ad
          }
          matched_seq(ref ads, _) => ads[*idx]
        }
    }
    let r = &mut *r;
    let repeat_idx = &r.repeat_idx;
    vec::foldl(start, *repeat_idx, red)
}

fn lookup_cur_matched(r: &mut TtReader, name: ident) -> @named_match {
    // FIXME (#3850): this looks a bit silly with an extra scope.
    let start;
    { start = *r.interpolations.get(&name); }
    return lookup_cur_matched_by_matched(r, start);
}
enum lis {
    lis_unconstrained, lis_constraint(uint, ident), lis_contradiction(~str)
}

fn lockstep_iter_size(t: token_tree, r: &mut TtReader) -> lis {
    fn lis_merge(lhs: lis, rhs: lis, r: &mut TtReader) -> lis {
        match lhs {
          lis_unconstrained => copy rhs,
          lis_contradiction(_) => copy lhs,
          lis_constraint(l_len, l_id) => match rhs {
            lis_unconstrained => copy lhs,
            lis_contradiction(_) => copy rhs,
            lis_constraint(r_len, _) if l_len == r_len => copy lhs,
            lis_constraint(r_len, r_id) => {
                let l_n = copy *r.interner.get(l_id);
                let r_n = copy *r.interner.get(r_id);
                lis_contradiction(fmt!("Inconsistent lockstep iteration: \
                                       '%s' has %u items, but '%s' has %u",
                                        l_n, l_len, r_n, r_len))
            }
          }
        }
    }
    match t {
      tt_delim(ref tts) | tt_seq(_, ref tts, _, _) => {
        vec::foldl(lis_unconstrained, (*tts), |lis, tt| {
            let lis2 = lockstep_iter_size(*tt, r);
            lis_merge(lis, lis2, r)
        })
      }
      tt_tok(*) => lis_unconstrained,
      tt_nonterminal(_, name) => match *lookup_cur_matched(r, name) {
        matched_nonterminal(_) => lis_unconstrained,
        matched_seq(ref ads, _) => lis_constraint(ads.len(), name)
      }
    }
}

// return the next token from the TtReader.
// EFFECT: advances the reader's token field
pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {
    let ret_val = TokenAndSpan {
        tok: copy r.cur_tok,
        sp: r.cur_span,
    };
    loop {
        {
            let stack = &mut *r.stack;
            let forest = &mut *stack.forest;
            if stack.idx < forest.len() {
                break;
            }
        }

        /* done with this set; pop or repeat? */
        if ! r.stack.dotdotdoted
            || { *r.repeat_idx.last() == *r.repeat_len.last() - 1 } {

            match r.stack.up {
              None => {
                r.cur_tok = EOF;
                return ret_val;
              }
              Some(tt_f) => {
                if r.stack.dotdotdoted {
                    r.repeat_idx.pop();
                    r.repeat_len.pop();
                }

                r.stack = tt_f;
                r.stack.idx += 1u;
              }
            }

        } else { /* repeat */
            r.stack.idx = 0u;
            r.repeat_idx[r.repeat_idx.len() - 1u] += 1u;
            match r.stack.sep {
              Some(copy tk) => {
                r.cur_tok = tk; /* repeat same span, I guess */
                return ret_val;
              }
              None => ()
            }
        }
    }
    loop { /* because it's easiest, this handles `tt_delim` not starting
    with a `tt_tok`, even though it won't happen */
        match r.stack.forest[r.stack.idx] {
          tt_delim(copy tts) => {
            r.stack = @mut TtFrame {
                forest: @mut tts,
                idx: 0u,
                dotdotdoted: false,
                sep: None,
                up: option::Some(r.stack)
            };
            // if this could be 0-length, we'd need to potentially recur here
          }
          tt_tok(sp, copy tok) => {
            r.cur_span = sp;
            r.cur_tok = tok;
            r.stack.idx += 1u;
            return ret_val;
          }
          tt_seq(sp, copy tts, copy sep, zerok) => {
            let t = tt_seq(sp, copy tts, copy sep, zerok);
            match lockstep_iter_size(t, r) {
              lis_unconstrained => {
                r.sp_diag.span_fatal(
                    sp, /* blame macro writer */
                      ~"attempted to repeat an expression \
                        containing no syntax \
                        variables matched as repeating at this depth");
                  }
                  lis_contradiction(ref msg) => {
                      /* FIXME #2887 blame macro invoker instead*/
                      r.sp_diag.span_fatal(sp, (*msg));
                  }
                  lis_constraint(len, _) => {
                    if len == 0 {
                      if !zerok {
                        r.sp_diag.span_fatal(sp, /* FIXME #2887 blame invoker
                        */
                                             ~"this must repeat at least \
                                               once");
                          }

                    r.stack.idx += 1u;
                    return tt_next_token(r);
                } else {
                    r.repeat_len.push(len);
                    r.repeat_idx.push(0u);
                    r.stack = @mut TtFrame {
                        forest: @mut tts,
                        idx: 0u,
                        dotdotdoted: true,
                        sep: sep,
                        up: Some(r.stack)
                    };
                }
              }
            }
          }
          // FIXME #2887: think about span stuff here
          tt_nonterminal(sp, ident) => {
            match *lookup_cur_matched(r, ident) {
              /* sidestep the interpolation tricks for ident because
              (a) idents can be in lots of places, so it'd be a pain
              (b) we actually can, since it's a token. */
              matched_nonterminal(nt_ident(sn,b)) => {
                r.cur_span = sp; r.cur_tok = IDENT(sn,b);
                r.stack.idx += 1u;
                return ret_val;
              }
              matched_nonterminal(ref other_whole_nt) => {
                r.cur_span = sp;
                r.cur_tok = INTERPOLATED(copy *other_whole_nt);
                r.stack.idx += 1u;
                return ret_val;
              }
              matched_seq(*) => {
                r.sp_diag.span_fatal(
                    copy r.cur_span, /* blame the macro writer */
                    fmt!("variable '%s' is still repeating at this depth",
                         *r.interner.get(ident)));
              }
            }
          }
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>fix: fixes unsafe code count bug in C and C++ files<commit_after><|endoftext|>


<commit_before><commit_msg>Extracts algorithm<commit_after><|endoftext|>


<commit_before><commit_msg>Hide internal structure of Mat<commit_after><|endoftext|>


<commit_before>

// Simple Extensible Binary Markup Language (ebml) reader and writer on a
// cursor model. See the specification here:
//     http://www.matroska.org/technical/specs/rfc/index.html
import option::none;
import option::some;

type ebml_tag = rec(uint id, uint size);

type ebml_state = rec(ebml_tag ebml_tag, uint tag_pos, uint data_pos);

// TODO: When we have module renaming, make "reader" and "writer" separate
// modules within this file.

// ebml reading
type doc = rec(u8[] data, uint start, uint end);

fn vint_at(&u8[] data, uint start) -> tup(uint, uint) {
    auto a = data.(start);
    if (a & 0x80u8 != 0u8) { ret tup(a & 0x7fu8 as uint, start + 1u); }
    if (a & 0x40u8 != 0u8) {
        ret tup((a & 0x3fu8 as uint) << 8u | (data.(start + 1u) as uint),
                start + 2u);
    } else if (a & 0x20u8 != 0u8) {
        ret tup((a & 0x1fu8 as uint) << 16u |
                    (data.(start + 1u) as uint) << 8u |
                    (data.(start + 2u) as uint), start + 3u);
    } else if (a & 0x10u8 != 0u8) {
        ret tup((a & 0x0fu8 as uint) << 24u |
                    (data.(start + 1u) as uint) << 16u |
                    (data.(start + 2u) as uint) << 8u |
                    (data.(start + 3u) as uint), start + 4u);
    } else { log_err "vint too big"; fail; }
}

fn new_doc(&u8[] data) -> doc {
    ret rec(data=data, start=0u, end=ivec::len[u8](data));
}

fn doc_at(&u8[] data, uint start) -> doc {
    auto elt_tag = vint_at(data, start);
    auto elt_size = vint_at(data, elt_tag._1);
    auto end = elt_size._1 + elt_size._0;
    ret rec(data=data, start=elt_size._1, end=end);
}

fn maybe_get_doc(doc d, uint tg) -> option::t[doc] {
    auto pos = d.start;
    while (pos < d.end) {
        auto elt_tag = vint_at(d.data, pos);
        auto elt_size = vint_at(d.data, elt_tag._1);
        pos = elt_size._1 + elt_size._0;
        if (elt_tag._0 == tg) {
            ret some[doc](rec(data=d.data, start=elt_size._1, end=pos));
        }
    }
    ret none[doc];
}

fn get_doc(doc d, uint tg) -> doc {
    alt (maybe_get_doc(d, tg)) {
        case (some(?d)) { ret d; }
        case (none) {
            log_err "failed to find block with tag " + uint::to_str(tg, 10u);
            fail;
        }
    }
}

iter docs(doc d) -> tup(uint, doc) {
    auto pos = d.start;
    while (pos < d.end) {
        auto elt_tag = vint_at(d.data, pos);
        auto elt_size = vint_at(d.data, elt_tag._1);
        pos = elt_size._1 + elt_size._0;
        put tup(elt_tag._0, rec(data=d.data, start=elt_size._1, end=pos));
    }
}

iter tagged_docs(doc d, uint tg) -> doc {
    auto pos = d.start;
    while (pos < d.end) {
        auto elt_tag = vint_at(d.data, pos);
        auto elt_size = vint_at(d.data, elt_tag._1);
        pos = elt_size._1 + elt_size._0;
        if (elt_tag._0 == tg) {
            put rec(data=d.data, start=elt_size._1, end=pos);
        }
    }
}

fn doc_data(doc d) -> u8[] { ret ivec::slice[u8](d.data, d.start, d.end); }

fn be_uint_from_bytes(&u8[] data, uint start, uint size) -> uint {
    auto sz = size;
    assert (sz <= 4u);
    auto val = 0u;
    auto pos = start;
    while (sz > 0u) {
        sz -= 1u;
        val += (data.(pos) as uint) << sz * 8u;
        pos += 1u;
    }
    ret val;
}

fn doc_as_uint(doc d) -> uint {
    ret be_uint_from_bytes(d.data, d.start, d.end - d.start);
}

// ebml writing
type writer = rec(ioivec::buf_writer writer, mutable uint[] size_positions);

fn write_sized_vint(&ioivec::buf_writer w, uint n, uint size) {
    let u8[] buf;
    alt (size) {
        case (1u) { buf = ~[0x80u8 | (n as u8)]; }
        case (2u) { buf = ~[0x40u8 | (n >> 8u as u8), n & 0xffu as u8]; }
        case (3u) {
            buf =
                ~[0x20u8 | (n >> 16u as u8), n >> 8u & 0xffu as u8,
                  n & 0xffu as u8];
        }
        case (4u) {
            buf =
                ~[0x10u8 | (n >> 24u as u8), n >> 16u & 0xffu as u8,
                  n >> 8u & 0xffu as u8, n & 0xffu as u8];
        }
        case (_) { log_err "vint to write too big"; fail; }
    }
    w.write(buf);
}

fn write_vint(&ioivec::buf_writer w, uint n) {
    if (n < 0x7fu) { write_sized_vint(w, n, 1u); ret; }
    if (n < 0x4000u) { write_sized_vint(w, n, 2u); ret; }
    if (n < 0x200000u) { write_sized_vint(w, n, 3u); ret; }
    if (n < 0x10000000u) { write_sized_vint(w, n, 4u); ret; }
    log_err "vint to write too big";
    fail;
}

fn create_writer(&ioivec::buf_writer w) -> writer {
    let uint[] size_positions = ~[];
    ret rec(writer=w, mutable size_positions=size_positions);
}

// TODO: Provide a function to write the standard ebml header.
fn start_tag(&writer w, uint tag_id) {
    // Write the tag ID:

    write_vint(w.writer, tag_id);
    // Write a placeholder four-byte size.

    w.size_positions += ~[w.writer.tell()];
    let u8[] zeroes = ~[0u8, 0u8, 0u8, 0u8];
    w.writer.write(zeroes);
}

fn end_tag(&writer w) {
    auto last_size_pos = ivec::pop[uint](w.size_positions);
    auto cur_pos = w.writer.tell();
    w.writer.seek(last_size_pos as int, ioivec::seek_set);
    write_sized_vint(w.writer, cur_pos - last_size_pos - 4u, 4u);
    w.writer.seek(cur_pos as int, ioivec::seek_set);
}
// TODO: optionally perform "relaxations" on end_tag to more efficiently
// encode sizes; this is a fixed point iteration
<commit_msg>stdlib: Box data in EBML documents<commit_after>

// Simple Extensible Binary Markup Language (ebml) reader and writer on a
// cursor model. See the specification here:
//     http://www.matroska.org/technical/specs/rfc/index.html
import option::none;
import option::some;

type ebml_tag = rec(uint id, uint size);

type ebml_state = rec(ebml_tag ebml_tag, uint tag_pos, uint data_pos);

// TODO: When we have module renaming, make "reader" and "writer" separate
// modules within this file.

// ebml reading
type doc = rec(@u8[] data, uint start, uint end);

fn vint_at(&@u8[] data, uint start) -> tup(uint, uint) {
    auto a = data.(start);
    if (a & 0x80u8 != 0u8) { ret tup(a & 0x7fu8 as uint, start + 1u); }
    if (a & 0x40u8 != 0u8) {
        ret tup((a & 0x3fu8 as uint) << 8u | (data.(start + 1u) as uint),
                start + 2u);
    } else if (a & 0x20u8 != 0u8) {
        ret tup((a & 0x1fu8 as uint) << 16u |
                    (data.(start + 1u) as uint) << 8u |
                    (data.(start + 2u) as uint), start + 3u);
    } else if (a & 0x10u8 != 0u8) {
        ret tup((a & 0x0fu8 as uint) << 24u |
                    (data.(start + 1u) as uint) << 16u |
                    (data.(start + 2u) as uint) << 8u |
                    (data.(start + 3u) as uint), start + 4u);
    } else { log_err "vint too big"; fail; }
}

fn new_doc(&@u8[] data) -> doc {
    ret rec(data=data, start=0u, end=ivec::len[u8](*data));
}

fn doc_at(&@u8[] data, uint start) -> doc {
    auto elt_tag = vint_at(data, start);
    auto elt_size = vint_at(data, elt_tag._1);
    auto end = elt_size._1 + elt_size._0;
    ret rec(data=data, start=elt_size._1, end=end);
}

fn maybe_get_doc(doc d, uint tg) -> option::t[doc] {
    auto pos = d.start;
    while (pos < d.end) {
        auto elt_tag = vint_at(d.data, pos);
        auto elt_size = vint_at(d.data, elt_tag._1);
        pos = elt_size._1 + elt_size._0;
        if (elt_tag._0 == tg) {
            ret some[doc](rec(data=d.data, start=elt_size._1, end=pos));
        }
    }
    ret none[doc];
}

fn get_doc(doc d, uint tg) -> doc {
    alt (maybe_get_doc(d, tg)) {
        case (some(?d)) { ret d; }
        case (none) {
            log_err "failed to find block with tag " + uint::to_str(tg, 10u);
            fail;
        }
    }
}

iter docs(doc d) -> tup(uint, doc) {
    auto pos = d.start;
    while (pos < d.end) {
        auto elt_tag = vint_at(d.data, pos);
        auto elt_size = vint_at(d.data, elt_tag._1);
        pos = elt_size._1 + elt_size._0;
        put tup(elt_tag._0, rec(data=d.data, start=elt_size._1, end=pos));
    }
}

iter tagged_docs(doc d, uint tg) -> doc {
    auto pos = d.start;
    while (pos < d.end) {
        auto elt_tag = vint_at(d.data, pos);
        auto elt_size = vint_at(d.data, elt_tag._1);
        pos = elt_size._1 + elt_size._0;
        if (elt_tag._0 == tg) {
            put rec(data=d.data, start=elt_size._1, end=pos);
        }
    }
}

fn doc_data(doc d) -> u8[] { ret ivec::slice[u8](*d.data, d.start, d.end); }

fn be_uint_from_bytes(&@u8[] data, uint start, uint size) -> uint {
    auto sz = size;
    assert (sz <= 4u);
    auto val = 0u;
    auto pos = start;
    while (sz > 0u) {
        sz -= 1u;
        val += (data.(pos) as uint) << sz * 8u;
        pos += 1u;
    }
    ret val;
}

fn doc_as_uint(doc d) -> uint {
    ret be_uint_from_bytes(d.data, d.start, d.end - d.start);
}

// ebml writing
type writer = rec(ioivec::buf_writer writer, mutable uint[] size_positions);

fn write_sized_vint(&ioivec::buf_writer w, uint n, uint size) {
    let u8[] buf;
    alt (size) {
        case (1u) { buf = ~[0x80u8 | (n as u8)]; }
        case (2u) { buf = ~[0x40u8 | (n >> 8u as u8), n & 0xffu as u8]; }
        case (3u) {
            buf =
                ~[0x20u8 | (n >> 16u as u8), n >> 8u & 0xffu as u8,
                  n & 0xffu as u8];
        }
        case (4u) {
            buf =
                ~[0x10u8 | (n >> 24u as u8), n >> 16u & 0xffu as u8,
                  n >> 8u & 0xffu as u8, n & 0xffu as u8];
        }
        case (_) { log_err "vint to write too big"; fail; }
    }
    w.write(buf);
}

fn write_vint(&ioivec::buf_writer w, uint n) {
    if (n < 0x7fu) { write_sized_vint(w, n, 1u); ret; }
    if (n < 0x4000u) { write_sized_vint(w, n, 2u); ret; }
    if (n < 0x200000u) { write_sized_vint(w, n, 3u); ret; }
    if (n < 0x10000000u) { write_sized_vint(w, n, 4u); ret; }
    log_err "vint to write too big";
    fail;
}

fn create_writer(&ioivec::buf_writer w) -> writer {
    let uint[] size_positions = ~[];
    ret rec(writer=w, mutable size_positions=size_positions);
}

// TODO: Provide a function to write the standard ebml header.
fn start_tag(&writer w, uint tag_id) {
    // Write the tag ID:

    write_vint(w.writer, tag_id);
    // Write a placeholder four-byte size.

    w.size_positions += ~[w.writer.tell()];
    let u8[] zeroes = ~[0u8, 0u8, 0u8, 0u8];
    w.writer.write(zeroes);
}

fn end_tag(&writer w) {
    auto last_size_pos = ivec::pop[uint](w.size_positions);
    auto cur_pos = w.writer.tell();
    w.writer.seek(last_size_pos as int, ioivec::seek_set);
    write_sized_vint(w.writer, cur_pos - last_size_pos - 4u, 4u);
    w.writer.seek(cur_pos as int, ioivec::seek_set);
}
// TODO: optionally perform "relaxations" on end_tag to more efficiently
// encode sizes; this is a fixed point iteration
<|endoftext|>