<commit_before><commit_msg>add alternate q6<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(0usize));
    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();

        // handles to input and probe, but also both indices so we can compact them.
        let (mut input, mut query, probe, forward) = 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)>();

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

            // 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.

            let forward = IndexStream::from(
                |(a,b)| (a + b) as u64,             // distribute triangles by a + b.
                &dT.map(|((a,b,c),_)| ((a,b),c)),   // initialize with (a,b) keys and c values.
                &Vec::new().to_stream(builder)      // empty update stream.
            );

            // we bind dQ as (v2, v5, v3), exploiting the fact that we have bound each
            let dK4dA = dQ.extend(vec![Box::new(forward.extend_using(|&(v2,v5)| min_max(v2,v5), <_ as PartialOrd>::le))])
                          .flat_map(|((v2,v5),v3s,w)| {
                            let v1s = v3s.clone();
                            v3s.into_iter().map(move |v3| ((v1s.clone(),v2,v3,v5),w))
                          })
                          .extend(vec![Box::new(forward.extend_using(|&(ref _v1s,v2,_v3,v5)| min_max(v2,v5), <_ as PartialOrd>::le)),
                                       Box::new(forward.extend_using(|&(ref _v1s,v2,v3,_v5)| min_max(v2,v3), <_ as PartialOrd>::le))])
                          .map(|((v1s,v2,v3,v5), mut v4s, w)| {
                                v4s.retain(|&v4| v2 != v4 && v3 < v4);
                                ((v1s,v2,v3,v4s,v5),w)
                            })
                          ;
            // if the third argument is "inspect", report triangle counts.
            if inspect {
                dK4dA.inspect_batch(move |_,x| {
                    let mut sum = 0;
                    for &((ref v1s, _v2, v3, ref v4s, _v5),_) in x.iter() {
                        for &v1 in v1s.iter() {
                            if v1 != v3 {
                                for &v4 in v4s.iter() {
                                    if v1 != v4 {
                                        sum += 1;
                                    }
                                }
                            }
                        }
                    }

                    if let Ok(mut bound) = send.lock() {
                        *bound += sum;
                    }
                });
            }

            (graph, query, dK4dA.probe(), forward)
        });

        // 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 mut triangles = Vec::new();

        let mut v1 = root.index();
        while v1 < graph.nodes() {
            let v1f = graph.edges(v1);
            for &v2 in v1f.iter() {
                intersect_and(v1f, graph.edges(v2 as usize), |v3| triangles.push((v1 as u32, v2, v3)));
            }
            v1 += root.peers();
        }

        // drop(graph);

        println!("{:?}\tworker {} computed {} triangles", start.elapsed(), root.index(), triangles.len());

        for &(a,b,c) in triangles.iter() {
            // send each extension
            input.send(((a,b,c), 1));
            input.send(((a,c,b), 1));
            input.send(((b,c,a), 1));
        }

        // synchronize with other workers.
        let prev = query.time().clone();
        input.close();
        query.advance_to(prev.inner + 1);
        while probe.less_than(query.time()) { root.step(); }
        forward.index.borrow_mut().merge_to(&prev);

        println!("{:?}\tworker {} loaded index", start.elapsed(), root.index());

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

        let mut node = 0;
        let mut sent = 0;

        while sent < graph.nodes() {
            node += batch;
            while sent < graph.nodes() && sent < node {
                for &edge in graph.edges(sent) {
                    query.send(((sent as u32, edge), ()));
                }
                // let (a,b,c) = triangles[sent];
                // query.send(((a,b,c), ()));
                // query.send(((a,c,b), ()));
                // query.send(((b,c,a), ()));
                sent += 1;
            }

            // advance input and synchronize.
            let prev = query.time().clone();
            query.advance_to(prev.inner + 1);
            while probe.less_than(query.time()) { root.step(); }

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

        query.close();
        while root.step() { }

        if inspect {
            println!("{:?}\tworker {} complete", start.elapsed(), root.index());
        }

    }).unwrap();

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

    if inspect {
        println!("elapsed: {:?}\ttotal instances at this process: {:?}", start.elapsed(), total);
    }
}

fn min_max<T: Ord>(a: T, b: T) -> (T, T) {
    if a < b { (a, b) } else { (b, a) }
}

fn intersect_and<F: FnMut(u32)>(aaa: &[u32], mut bbb: &[u32], mut func: F) {

    if aaa.len() > bbb.len() {
        intersect_and(bbb, aaa, func);
    }
    else {
        if aaa.len() < bbb.len() / 16 {
            for &a in aaa.iter() {
                bbb = gallop_ge(bbb, &a);
                if bbb.len() > 0 && bbb[0] == a {
                    func(a)
                }
            }
        }
        else {
            for &a in aaa.iter() {
                while bbb.len() > 0 && bbb[0] < a {
                    bbb = &bbb[1..];
                }
                if bbb.len() > 0 && a == bbb[0] {
                    func(a);
                }
            }
        }
    }
}

#[inline(always)]
pub fn gallop_ge<'a, T: Ord>(mut slice: &'a [T], value: &T) -> &'a [T] {
    // if empty slice, or already >= element, return
    if slice.len() > 0 && &slice[0] < value {
        let mut step = 1;
        while step < slice.len() && &slice[step] < value {
            slice = &slice[step..];
            step = step << 1;
        }

        step = step >> 1;
        while step > 0 {
            if step < slice.len() && &slice[step] < value {
                slice = &slice[step..];
            }
            step = step >> 1;
        }

        slice = &slice[1..]; // advance one, as we always stayed < value
    }

    return slice;
}

// #[inline(always)]
// pub fn gallop_gt<'a, T: Ord>(mut slice: &'a [T], value: &T) -> &'a [T] {
//     // if empty slice, or already > element, return
//     if slice.len() > 0 && &slice[0] <= value {
//         let mut step = 1;
//         while step < slice.len() && &slice[step] <= value {
//             slice = &slice[step..];
//             step = step << 1;
//         }

//         step = step >> 1;
//         while step > 0 {
//             if step < slice.len() && &slice[step] <= value {
//                 slice = &slice[step..];
//             }
//             step = step >> 1;
//         }

//         slice = &slice[1..]; // advance one, as we always stayed <= value
//     }

//     return slice;
// }<|endoftext|>


<commit_before><commit_msg>Add an example of the toplevel_ref_arg lint.<commit_after>#![feature(phase)]

#[phase(plugin)]
extern crate rust_clippy;

fn the_answer(ref mut x: u8) {
  *x = 42;
}

fn main() {
  let mut x = 0;
  the_answer(x);
  println!("The answer is {}.", x);
}
<|endoftext|>


<commit_before><commit_msg>(feat) Implemented Response for IronResponse.<commit_after><|endoftext|>


<commit_before><commit_msg>rename protocol to signature to be in line with microsoft spec and set the flags to 0<commit_after><|endoftext|>


<commit_before>// `NanoSecond` is a new name for `u64`.
type NanoSecond = u64;
type Inch = u64;

// Use an attribute to silence warning.
#[allow(non_camel_case_types)]
type u64_t = u64;
// TODO ^ Try removing the attribute

// Use an attribute to silence warnings
#[allow(trivial_numeric_casts)]
fn main() {
    // `NanoSecond` = `Inch` = `u64_t` = `u64`.
    let nanoseconds: NanoSecond = 5 as u64_t;
    let inches: Inch = 2 as u64_t;

    // Note that type aliases *don't* provide any extra type safety, because
    // aliases are *not* new types
    println!("{} nanoseconds + {} inches = {} unit?",
             nanoseconds,
             inches,
             nanoseconds + inches);
}
<commit_msg>5.3: trivial_numeric_casts is now allowed by default<commit_after>// `NanoSecond` is a new name for `u64`.
type NanoSecond = u64;
type Inch = u64;

// Use an attribute to silence warning.
#[allow(non_camel_case_types)]
type u64_t = u64;
// TODO ^ Try removing the attribute

fn main() {
    // `NanoSecond` = `Inch` = `u64_t` = `u64`.
    let nanoseconds: NanoSecond = 5 as u64_t;
    let inches: Inch = 2 as u64_t;

    // Note that type aliases *don't* provide any extra type safety, because
    // aliases are *not* new types
    println!("{} nanoseconds + {} inches = {} unit?",
             nanoseconds,
             inches,
             nanoseconds + inches);
}
<|endoftext|>


<commit_before><commit_msg>First major skeleton of game search DAG.<commit_after>use ::board;
use ::game;

use ::actions::Action;

use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::clone::Clone;
use std::default::Default;
use std::ops::RangeFrom;

#[derive(Clone, Debug, Eq, PartialEq)]
struct ActionId(usize);

impl ActionId {
    fn as_usize(self) -> usize {
        let ActionId(value) = self;
        value
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct StateId(usize);

impl StateId {
    fn as_usize(self) -> usize {
        let StateId(value) = self;
        value
    }
}

struct StateNamespace {
    state_id_generator: RangeFrom<usize>,
    states: HashMap<game::State, StateId>,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
enum NamespaceInsertion {
    Present(StateId),
    New(StateId),
}

impl NamespaceInsertion {
    fn unwrap(self) -> StateId {
        match self {
            NamespaceInsertion::Present(s) => s,
            NamespaceInsertion::New(s) => s,
        }
    }
}

impl StateNamespace {
    fn new() -> Self {
        StateNamespace {
            state_id_generator: 0..,
            states: HashMap::new(),
        }
    }

    fn next_id(&mut self) -> StateId {
        match self.state_id_generator.next() {
            Some(id) => StateId(id),
            None => panic!("Exhausted state ID namespace"),
        }
    }

    fn get_or_insert(&mut self, state: game::State) -> NamespaceInsertion {
        match self.states.entry(state) {
            Entry::Occupied(e) => NamespaceInsertion::Present(*e.get()),
            Entry::Vacant(e) => NamespaceInsertion::New(*e.insert(self.next_id())),
        }
    }

    fn get(&self, state: &game::State) -> Option<StateId> {
        self.states.get(state).map(|x| *x)
    }
}

struct ActionNamespace {
    action_id_generator: RangeFrom<usize>,
}

impl ActionNamespace {
    fn new() -> Self {
        ActionNamespace {
            action_id_generator: 0..,
        }
    }

    fn next_id(&mut self) -> ActionId {
        match self.action_id_generator.next() {
            Some(id) => ActionId(id),
            None => panic!("Exhausted action ID namespace"),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum ActionTarget {
    Unexpanded,
    Cycle,
    State(StateId),
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct ActionArc {
    action: Action,
    source: StateId,
    target: ActionTarget,
}

pub struct SearchGraph<S, A> where S: Default, A: Default {
    root_id: StateId,
    state_ids: StateNamespace,
    action_ids: ActionNamespace,
    // Also consider making edges into an intrusive linked list, with head an
    // Option<EdgeNode> and EdgeNode<A> { data: A, action: Action, target:
    // StateId, next: Option<EdgeNode> }.
    state_out_edges: Vec<Vec<ActionId>>,  // Indexed by StateId.
    state_in_edges: Vec<Vec<ActionId>>,  // Indexed by StateId.
    action_arcs: Vec<ActionArc>,  // Indexed by ActionId.
    state_data: Vec<S>,  // Indexed by StateId.
    action_data: Vec<A>,  // Indexed by ActionId.
}

impl<S, A> SearchGraph<S, A> where S: Default, A: Default {
    pub fn new(root_state: game::State) -> Self {
        let mut graph = SearchGraph {
            root_id: StateId(0),
            state_ids: StateNamespace::new(),
            action_ids: ActionNamespace::new(),
            state_out_edges: Vec::new(),
            state_in_edges: Vec::new(),
            action_arcs: Vec::new(),
            state_data: Vec::new(),
            action_data: Vec::new(),
        };
        graph.add_state(root_state);
        graph
    }

    fn add_state(&mut self, state: game::State) -> NamespaceInsertion {
        match self.state_ids.get_or_insert(state) {
            (state, NamespaceInsertion::New(state_id)) => {
                self.state_data.push(Default::default());
                self.state_out_edges.push(Vec::new());
                self.state_in_edges.push(Vec::new());
                for action in state.role_actions(state.active_player().role()) {
                    self.add_action_arc(action, state_id, ActionTarget::Unexpanded);
                }
                assert!(self.state_data.len() == state_id.as_usize() + 1);
                assert!(self.state_out_edges.len() == state_id.as_usize() + 1);
                assert!(self.state_in_edges.len() == state_id.as_usize() + 1);
                NamespaceInsertion::New(state_id)
            },
            (_, insertion) => insertion,
        }
    }

    fn add_action_arc(&mut self, action: Action, source: StateId, target: ActionTarget) {
        let arc = ActionArc { action: action, source: source, target: target, };
        let action_id = self.action_ids.next_id();
        self.state_out_edges[source.as_usize()].push(action_id);
        self.action_arcs.push(arc);
        self.action_data.push(Default::default());
        assert!(self.action_arcs.len() == action_id.as_usize() + 1);
        assert!(self.action_data.len() == action_id.as_usize() + 1);
    }

    fn expand_action_target(&mut self, from_state: &game::State, id: ActionId) {
        let arc: &mut ActionArc = &mut self.action_arcs[id.as_usize()];
        match arc.target {
            ActionTarget::Unexpanded => {
                match self.state_ids.states.get(from_state) {
                    Some(source_id) => {
                        if *source_id != arc.source {
                            panic!("Source state ID {:?} does not match action source {:?}",
                                   source_id, arc.source);
                        }
                        let mut target_state = from_state.clone();
                        target_state.do_action(&arc.action);
                        match self.add_state(target_state) {
                            NamespaceInsertion::New(target_id) =>
                                self.state_in_edges[target_id.as_usize()].push(id),
                            NamespaceInsertion::Present(target_id) => {
                                if self.path_exists(target_id, *source_id) {
                                    arc.target = ActionTarget::Cycle;
                                } else {
                                    arc.target = ActionTarget::State(target_id);
                                }
                            },
                        }
                    },
                    None =>
                        panic!("Source state supplied for action {:?} does not match known states",
                               arc),
                }
            },
            _ => panic!("Action {:?} already expanded", arc),
        }
    }

    fn path_exists(self, source: StateId, target: StateId) -> bool {
        let mut frontier = vec![target];
        while !frontier.is_empty() {
            let state = frontier.pop().unwrap();
            if source == state {
                return true
            }
            for arc in self.state_out_edges[state.as_usize()].iter().map(|&x| &self.action_arcs[x.as_usize()]) {
                if let ActionTarget::State(target_id) = arc.target {
                    frontier.push(target_id);
                }
            }
        }
        false
    }

    // pub fn get_state<'s>(&'s mut self, states: game::State) -> StateNode<'s, S, A> {

    // }
}

pub struct StateNode<'a, S: 'a, A: 'a> where S: Default, A: Default {
    graph: &'a mut SearchGraph<S, A>,
    id: StateId,
}

impl<'a, S: 'a, A: 'a> StateNode<'a, S, A> where S: Default, A: Default {
    fn child_actions(&self) -> &[ActionId] {
        &self.graph.state_out_edges[self.id.as_usize()]
    }

    fn parent_actions(&self) -> &[ActionId] {
        &self.graph.state_in_edges[self.id.as_usize()]
    }

    pub fn data(&self) -> &S {
        &self.graph.state_data[self.id.as_usize()]
    }
}
<|endoftext|>


<commit_before><commit_msg>test: Add a test case for the "self" region in enums<commit_after>enum int_wrapper {
    int_wrapper_ctor(&int)
}

fn main() {
    unsafe {
        let x = 3;
        let y = int_wrapper_ctor(&x);
        let z : ∫
        alt y {
            int_wrapper_ctor(zz) { z = zz; }
        }
        log(debug, *z);
    }
}

<|endoftext|>


<commit_before><commit_msg>tink-hybrid: add benchmark<commit_after>// Copyright 2021 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#![feature(test)]
extern crate test;
use test::Bencher;

const MSG: &[u8] = b"this data needs to be encrypted";
const CONTEXT: &[u8] = b"context";

fn setup(
    kt: tink_proto::KeyTemplate,
) -> (
    Box<dyn tink_core::HybridEncrypt>,
    Box<dyn tink_core::HybridDecrypt>,
    Vec<u8>,
) {
    tink_hybrid::init();
    let kh = tink_core::keyset::Handle::new(&kt).unwrap();
    let d = tink_hybrid::new_decrypt(&kh).unwrap();
    let pubkh = kh.public().unwrap();
    let e = tink_hybrid::new_encrypt(&pubkh).unwrap();
    let ct = e.encrypt(MSG, CONTEXT).unwrap();
    (e, d, ct)
}

/// Size of the prefix information in the ciphertext. If this is corrupted, the tag will be
/// rejected immediately without performing any cryptographic operations.
const PREFIX_SIZE: usize = tink_core::cryptofmt::NON_RAW_PREFIX_SIZE;

fn setup_failure(kt: tink_proto::KeyTemplate) -> (Box<dyn tink_core::HybridDecrypt>, Vec<u8>) {
    let (_e, d, ct) = setup(kt);
    (
        d,
        ct.iter()
            .enumerate()
            .map(|(i, b)| if i < PREFIX_SIZE { *b } else { b ^ 0b10101010 })
            .collect(),
    )
}

#[bench]
fn bench_ecies_hkdf_aes128_gcm_encrypt(b: &mut Bencher) {
    let (e, _d, _ct) = setup(tink_hybrid::ecies_hkdf_aes128_gcm_key_template());
    b.iter(|| e.encrypt(MSG, CONTEXT).unwrap())
}

#[bench]
fn bench_ecies_hkdf_aes128_gcm_decrypt(b: &mut Bencher) {
    let (_e, d, ct) = setup(tink_hybrid::ecies_hkdf_aes128_gcm_key_template());
    b.iter(|| d.decrypt(&ct, CONTEXT).unwrap())
}

#[bench]
fn bench_ecies_hkdf_aes128_ctr_hmac_encrypt(b: &mut Bencher) {
    let (e, _d, _ct) = setup(tink_hybrid::ecies_hkdf_aes128_ctr_hmac_sha256_key_template());
    b.iter(|| e.encrypt(MSG, CONTEXT).unwrap())
}

#[bench]
fn bench_ecies_hkdf_aes128_ctr_hmac_decrypt(b: &mut Bencher) {
    let (_e, d, ct) = setup(tink_hybrid::ecies_hkdf_aes128_ctr_hmac_sha256_key_template());
    b.iter(|| d.decrypt(&ct, CONTEXT).unwrap())
}

#[bench]
fn bench_ecies_hkdf_aes128_gcm_decrypt_fail(b: &mut Bencher) {
    let (d, ct) = setup_failure(tink_hybrid::ecies_hkdf_aes128_gcm_key_template());
    b.iter(|| d.decrypt(&ct, CONTEXT).unwrap_err())
}

#[bench]
fn bench_ecies_hkdf_aes128_ctr_hmac_decrypt_fail(b: &mut Bencher) {
    let (d, ct) = setup_failure(tink_hybrid::ecies_hkdf_aes128_ctr_hmac_sha256_key_template());
    b.iter(|| d.decrypt(&ct, CONTEXT).unwrap_err())
}
<|endoftext|>


<commit_before><commit_msg>style: Check for border-image-* initial specified values when serializing border shorthand.<commit_after><|endoftext|>


<commit_before>// xfail-boot
// xfail-stage0
// -*- rust -*-

// Tests for if as expressions returning boxed types

fn test_box() {
  auto res = if (true) { @100 } else { @101 };
  check (*res == 100);
}

fn test_str() {
  auto res = if (true) { "happy" } else { "sad" };
  check (res == "happy");
}

fn main() {
  test_box();
  test_str();
}
<commit_msg>Un-XFAIL expr-if-box.rs<commit_after>// xfail-boot
// -*- rust -*-

// Tests for if as expressions returning boxed types

fn test_box() {
  auto res = if (true) { @100 } else { @101 };
  check (*res == 100);
}

fn test_str() {
  auto res = if (true) { "happy" } else { "sad" };
  check (res == "happy");
}

fn main() {
  test_box();
  test_str();
}
<|endoftext|>


<commit_before><commit_msg>Implemented linear search in rust<commit_after><|endoftext|>


<commit_before><commit_msg>Buffer array wrong item types<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unimplemented argument<commit_after><|endoftext|>


<commit_before><commit_msg>add regression test<commit_after>// Regression test for #56128. When this `pub(super) use...` gets
// exploded in the HIR, we were not handling ids correctly.

mod bar {
    pub(super) use self::baz::{x, y};

    mod baz {
        pub fn x() { }
        pub fn y() { }
    }
}

fn main() { }
<|endoftext|>


<commit_before>iface to_str { fn to_str() -> str; }

impl of to_str for int {
    fn to_str() -> str { int::str(self) }
}
impl of to_str for i8 {
    fn to_str() -> str { i8::str(self) }
}
impl of to_str for i16 {
    fn to_str() -> str { i16::str(self) }
}
impl of to_str for i32 {
    fn to_str() -> str { i32::str(self) }
}
impl of to_str for i64 {
    fn to_str() -> str { i64::str(self) }
}
impl of to_str for uint {
    fn to_str() -> str { uint::str(self) }
}
impl of to_str for u8 {
    fn to_str() -> str { u8::str(self) }
}
impl of to_str for u16 {
    fn to_str() -> str { u16::str(self) }
}
impl of to_str for u32 {
    fn to_str() -> str { u32::str(self) }
}
impl of to_str for u64 {
    fn to_str() -> str { u64::str(self) }
}
impl of to_str for float {
    fn to_str() -> str { float::to_str(self, 4u) }
}
impl of to_str for bool {
    fn to_str() -> str { bool::to_str(self) }
}
impl of to_str for () {
    fn to_str() -> str { "()" }
}
impl of to_str for str {
    fn to_str() -> str { self }
}

impl <A: to_str copy, B: to_str copy> of to_str for (A, B) {
    fn to_str() -> str {
        let (a, b) = self;
        "(" + a.to_str() + ", " + b.to_str() + ")"
    }
}
impl <A: to_str copy, B: to_str copy, C: to_str copy> of to_str for (A, B, C){
    fn to_str() -> str {
        let (a, b, c) = self;
        "(" + a.to_str() + ", " + b.to_str() + ", " + c.to_str() + ")"
    }
}

impl <A: to_str> of to_str for ~[A] {
    fn to_str() -> str {
        let mut acc = "[", first = true;
        for vec::each(self) |elt| {
            if first { first = false; }
            else { str::push_str(acc, ", "); }
            str::push_str(acc, elt.to_str());
        }
        str::push_char(acc, ']');
        acc
    }
}

impl <A: to_str> of to_str for @A {
    fn to_str() -> str { "@" + (*self).to_str() }
}
impl <A: to_str> of to_str for ~A {
    fn to_str() -> str { "~" + (*self).to_str() }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_simple_types() {
        assert 1.to_str() == "1";
        assert (-1).to_str() == "-1";
        assert 200u.to_str() == "200";
        assert 2u8.to_str() == "2";
        assert true.to_str() == "true";
        assert false.to_str() == "false";
        assert ().to_str() == "()";
        assert "hi".to_str() == "hi";
    }

    #[test]
    fn test_tuple_types() {
        assert (1, 2).to_str() == "(1, 2)";
        assert ("a", "b", false).to_str() == "(a, b, false)";
        assert ((), ((), 100)).to_str() == "((), ((), 100))";
    }

    #[test]
    fn test_vectors() {
        let x: ~[int] = ~[];
        assert x.to_str() == "~[]";
        assert (~[1]).to_str() == "~[1]";
        assert (~[1, 2, 3]).to_str() == "~[1, 2, 3]";
        assert (~[~[], ~[1], ~[1, 1]]).to_str() ==
               "~[~[], ~[1], ~[1, 1]]";
    }

    #[test]
    fn test_pointer_types() {
        assert (@1).to_str() == "@1";
        assert (~(true, false)).to_str() == "~(true, false)";
    }
}
<commit_msg>core: Ignore to_str::test_vectors. It's busted<commit_after>iface to_str { fn to_str() -> str; }

impl of to_str for int {
    fn to_str() -> str { int::str(self) }
}
impl of to_str for i8 {
    fn to_str() -> str { i8::str(self) }
}
impl of to_str for i16 {
    fn to_str() -> str { i16::str(self) }
}
impl of to_str for i32 {
    fn to_str() -> str { i32::str(self) }
}
impl of to_str for i64 {
    fn to_str() -> str { i64::str(self) }
}
impl of to_str for uint {
    fn to_str() -> str { uint::str(self) }
}
impl of to_str for u8 {
    fn to_str() -> str { u8::str(self) }
}
impl of to_str for u16 {
    fn to_str() -> str { u16::str(self) }
}
impl of to_str for u32 {
    fn to_str() -> str { u32::str(self) }
}
impl of to_str for u64 {
    fn to_str() -> str { u64::str(self) }
}
impl of to_str for float {
    fn to_str() -> str { float::to_str(self, 4u) }
}
impl of to_str for bool {
    fn to_str() -> str { bool::to_str(self) }
}
impl of to_str for () {
    fn to_str() -> str { "()" }
}
impl of to_str for str {
    fn to_str() -> str { self }
}

impl <A: to_str copy, B: to_str copy> of to_str for (A, B) {
    fn to_str() -> str {
        let (a, b) = self;
        "(" + a.to_str() + ", " + b.to_str() + ")"
    }
}
impl <A: to_str copy, B: to_str copy, C: to_str copy> of to_str for (A, B, C){
    fn to_str() -> str {
        let (a, b, c) = self;
        "(" + a.to_str() + ", " + b.to_str() + ", " + c.to_str() + ")"
    }
}

impl <A: to_str> of to_str for ~[A] {
    fn to_str() -> str {
        let mut acc = "[", first = true;
        for vec::each(self) |elt| {
            if first { first = false; }
            else { str::push_str(acc, ", "); }
            str::push_str(acc, elt.to_str());
        }
        str::push_char(acc, ']');
        acc
    }
}

impl <A: to_str> of to_str for @A {
    fn to_str() -> str { "@" + (*self).to_str() }
}
impl <A: to_str> of to_str for ~A {
    fn to_str() -> str { "~" + (*self).to_str() }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_simple_types() {
        assert 1.to_str() == "1";
        assert (-1).to_str() == "-1";
        assert 200u.to_str() == "200";
        assert 2u8.to_str() == "2";
        assert true.to_str() == "true";
        assert false.to_str() == "false";
        assert ().to_str() == "()";
        assert "hi".to_str() == "hi";
    }

    #[test]
    fn test_tuple_types() {
        assert (1, 2).to_str() == "(1, 2)";
        assert ("a", "b", false).to_str() == "(a, b, false)";
        assert ((), ((), 100)).to_str() == "((), ((), 100))";
    }

    #[test]
    #[ignore]
    fn test_vectors() {
        let x: ~[int] = ~[];
        assert x.to_str() == "~[]";
        assert (~[1]).to_str() == "~[1]";
        assert (~[1, 2, 3]).to_str() == "~[1, 2, 3]";
        assert (~[~[], ~[1], ~[1, 1]]).to_str() ==
               "~[~[], ~[1], ~[1, 1]]";
    }

    #[test]
    fn test_pointer_types() {
        assert (@1).to_str() == "@1";
        assert (~(true, false)).to_str() == "~(true, false)";
    }
}
<|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.

/*! Utility implementations of Reader and Writer */

use prelude::*;
use cmp;
use io;
use boxed::Box;
use slice::bytes::MutableByteVector;

/// Wraps a `Reader`, limiting the number of bytes that can be read from it.
pub struct LimitReader<R> {
    limit: uint,
    inner: R
}

impl<R: Reader> LimitReader<R> {
    /// Creates a new `LimitReader`
    pub fn new(r: R, limit: uint) -> LimitReader<R> {
        LimitReader { limit: limit, inner: r }
    }

    /// Consumes the `LimitReader`, returning the underlying `Reader`.
    pub fn unwrap(self) -> R { self.inner }

    /// Returns the number of bytes that can be read before the `LimitReader`
    /// will return EOF.
    ///
    /// # Note
    ///
    /// The reader may reach EOF after reading fewer bytes than indicated by
    /// this method if the underlying reader reaches EOF.
    pub fn limit(&self) -> uint { self.limit }
}

impl<R: Reader> Reader for LimitReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        if self.limit == 0 {
            return Err(io::standard_error(io::EndOfFile));
        }

        let len = cmp::min(self.limit, buf.len());
        self.inner.read(buf.mut_slice_to(len)).map(|len| {
            self.limit -= len;
            len
        })
    }
}

impl<R: Buffer> Buffer for LimitReader<R> {
    fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
        let amt = try!(self.inner.fill_buf());
        let buf = amt.slice_to(cmp::min(amt.len(), self.limit));
        if buf.len() == 0 {
            Err(io::standard_error(io::EndOfFile))
        } else {
            Ok(buf)
        }
    }

    fn consume(&mut self, amt: uint) {
        self.limit -= amt;
        self.inner.consume(amt);
    }

}

/// A `Writer` which ignores bytes written to it, like /dev/null.
pub struct NullWriter;

impl Writer for NullWriter {
    #[inline]
    fn write(&mut self, _buf: &[u8]) -> io::IoResult<()> { Ok(()) }
}

/// A `Reader` which returns an infinite stream of 0 bytes, like /dev/zero.
pub struct ZeroReader;

impl Reader for ZeroReader {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        buf.set_memory(0);
        Ok(buf.len())
    }
}

impl Buffer for ZeroReader {
    fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
        static DATA: [u8, ..64] = [0, ..64];
        Ok(DATA.as_slice())
    }
    fn consume(&mut self, _amt: uint) {}
}

/// A `Reader` which is always at EOF, like /dev/null.
pub struct NullReader;

impl Reader for NullReader {
    #[inline]
    fn read(&mut self, _buf: &mut [u8]) -> io::IoResult<uint> {
        Err(io::standard_error(io::EndOfFile))
    }
}

impl Buffer for NullReader {
    fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
        Err(io::standard_error(io::EndOfFile))
    }
    fn consume(&mut self, _amt: uint) {}
}

/// A `Writer` which multiplexes writes to a set of `Writers`.
pub struct MultiWriter {
    writers: Vec<Box<Writer>>
}

impl MultiWriter {
    /// Creates a new `MultiWriter`
    pub fn new(writers: Vec<Box<Writer>>) -> MultiWriter {
        MultiWriter { writers: writers }
    }
}

impl Writer for MultiWriter {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::IoResult<()> {
        let mut ret = Ok(());
        for writer in self.writers.mut_iter() {
            ret = ret.and(writer.write(buf));
        }
        return ret;
    }

    #[inline]
    fn flush(&mut self) -> io::IoResult<()> {
        let mut ret = Ok(());
        for writer in self.writers.mut_iter() {
            ret = ret.and(writer.flush());
        }
        return ret;
    }
}

/// A `Reader` which chains input from multiple `Readers`, reading each to
/// completion before moving onto the next.
pub struct ChainedReader<I, R> {
    readers: I,
    cur_reader: Option<R>,
}

impl<R: Reader, I: Iterator<R>> ChainedReader<I, R> {
    /// Creates a new `ChainedReader`
    pub fn new(mut readers: I) -> ChainedReader<I, R> {
        let r = readers.next();
        ChainedReader { readers: readers, cur_reader: r }
    }
}

impl<R: Reader, I: Iterator<R>> Reader for ChainedReader<I, R> {
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        loop {
            let err = match self.cur_reader {
                Some(ref mut r) => {
                    match r.read(buf) {
                        Ok(len) => return Ok(len),
                        Err(ref e) if e.kind == io::EndOfFile => None,
                        Err(e) => Some(e),
                    }
                }
                None => break
            };
            self.cur_reader = self.readers.next();
            match err {
                Some(e) => return Err(e),
                None => {}
            }
        }
        Err(io::standard_error(io::EndOfFile))
    }
}

/// A `Reader` which forwards input from another `Reader`, passing it along to
/// a `Writer` as well. Similar to the `tee(1)` command.
pub struct TeeReader<R, W> {
    reader: R,
    writer: W,
}

impl<R: Reader, W: Writer> TeeReader<R, W> {
    /// Creates a new `TeeReader`
    pub fn new(r: R, w: W) -> TeeReader<R, W> {
        TeeReader { reader: r, writer: w }
    }

    /// Consumes the `TeeReader`, returning the underlying `Reader` and
    /// `Writer`.
    pub fn unwrap(self) -> (R, W) {
        let TeeReader { reader, writer } = self;
        (reader, writer)
    }
}

impl<R: Reader, W: Writer> Reader for TeeReader<R, W> {
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        self.reader.read(buf).and_then(|len| {
            self.writer.write(buf.slice_to(len)).map(|()| len)
        })
    }
}

/// Copies all data from a `Reader` to a `Writer`.
pub fn copy<R: Reader, W: Writer>(r: &mut R, w: &mut W) -> io::IoResult<()> {
    let mut buf = [0, ..super::DEFAULT_BUF_SIZE];
    loop {
        let len = match r.read(buf) {
            Ok(len) => len,
            Err(ref e) if e.kind == io::EndOfFile => return Ok(()),
            Err(e) => return Err(e),
        };
        try!(w.write(buf.slice_to(len)));
    }
}

/// A `Reader` which converts an `Iterator<u8>` into a `Reader`.
pub struct IterReader<T> {
    iter: T,
}

impl<T: Iterator<u8>> IterReader<T> {
    /// Create a new `IterReader` which will read from the specified `Iterator`.
    pub fn new(iter: T) -> IterReader<T> {
        IterReader {
            iter: iter,
        }
    }
}

impl<T: Iterator<u8>> Reader for IterReader<T> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        let mut len = 0;
        for (slot, elt) in buf.mut_iter().zip(self.iter.by_ref()) {
            *slot = elt;
            len += 1;
        }
        if len == 0 {
            Err(io::standard_error(io::EndOfFile))
        } else {
            Ok(len)
        }
    }
}

#[cfg(test)]
mod test {
    use io::{MemReader, MemWriter, BufReader};
    use io;
    use boxed::Box;
    use super::*;
    use prelude::*;

    #[test]
    fn test_limit_reader_unlimited() {
        let mut r = MemReader::new(vec!(0, 1, 2));
        {
            let mut r = LimitReader::new(r.by_ref(), 4);
            assert_eq!(vec!(0, 1, 2), r.read_to_end().unwrap());
        }
    }

    #[test]
    fn test_limit_reader_limited() {
        let mut r = MemReader::new(vec!(0, 1, 2));
        {
            let mut r = LimitReader::new(r.by_ref(), 2);
            assert_eq!(vec!(0, 1), r.read_to_end().unwrap());
        }
        assert_eq!(vec!(2), r.read_to_end().unwrap());
    }

    #[test]
    fn test_limit_reader_limit() {
        let r = MemReader::new(vec!(0, 1, 2));
        let mut r = LimitReader::new(r, 3);
        assert_eq!(3, r.limit());
        assert_eq!(0, r.read_byte().unwrap());
        assert_eq!(2, r.limit());
        assert_eq!(vec!(1, 2), r.read_to_end().unwrap());
        assert_eq!(0, r.limit());
    }

    #[test]
    fn test_null_writer() {
        let mut s = NullWriter;
        let buf = vec![0, 0, 0];
        s.write(buf.as_slice()).unwrap();
        s.flush().unwrap();
    }

    #[test]
    fn test_zero_reader() {
        let mut s = ZeroReader;
        let mut buf = vec![1, 2, 3];
        assert_eq!(s.read(buf.as_mut_slice()), Ok(3));
        assert_eq!(vec![0, 0, 0], buf);
    }

    #[test]
    fn test_null_reader() {
        let mut r = NullReader;
        let mut buf = vec![0];
        assert!(r.read(buf.as_mut_slice()).is_err());
    }

    #[test]
    fn test_multi_writer() {
        static mut writes: uint = 0;
        static mut flushes: uint = 0;

        struct TestWriter;
        impl Writer for TestWriter {
            fn write(&mut self, _buf: &[u8]) -> io::IoResult<()> {
                unsafe { writes += 1 }
                Ok(())
            }

            fn flush(&mut self) -> io::IoResult<()> {
                unsafe { flushes += 1 }
                Ok(())
            }
        }

        let mut multi = MultiWriter::new(vec!(box TestWriter as Box<Writer>,
                                              box TestWriter as Box<Writer>));
        multi.write([1, 2, 3]).unwrap();
        assert_eq!(2, unsafe { writes });
        assert_eq!(0, unsafe { flushes });
        multi.flush().unwrap();
        assert_eq!(2, unsafe { writes });
        assert_eq!(2, unsafe { flushes });
    }

    #[test]
    fn test_chained_reader() {
        let rs = vec!(MemReader::new(vec!(0, 1)), MemReader::new(vec!()),
                      MemReader::new(vec!(2, 3)));
        let mut r = ChainedReader::new(rs.move_iter());
        assert_eq!(vec!(0, 1, 2, 3), r.read_to_end().unwrap());
    }

    #[test]
    fn test_tee_reader() {
        let mut r = TeeReader::new(MemReader::new(vec!(0, 1, 2)),
                                   MemWriter::new());
        assert_eq!(vec!(0, 1, 2), r.read_to_end().unwrap());
        let (_, w) = r.unwrap();
        assert_eq!(vec!(0, 1, 2), w.unwrap());
    }

    #[test]
    fn test_copy() {
        let mut r = MemReader::new(vec!(0, 1, 2, 3, 4));
        let mut w = MemWriter::new();
        copy(&mut r, &mut w).unwrap();
        assert_eq!(vec!(0, 1, 2, 3, 4), w.unwrap());
    }

    #[test]
    fn limit_reader_buffer() {
        let data = "0123456789\n0123456789\n";
        let mut r = BufReader::new(data.as_bytes());
        {
            let mut r = LimitReader::new(r.by_ref(), 3);
            assert_eq!(r.read_line(), Ok("012".to_string()));
            assert_eq!(r.limit(), 0);
            assert_eq!(r.read_line().err().unwrap().kind, io::EndOfFile);
        }
        {
            let mut r = LimitReader::new(r.by_ref(), 9);
            assert_eq!(r.read_line(), Ok("3456789\n".to_string()));
            assert_eq!(r.limit(), 1);
            assert_eq!(r.read_line(), Ok("0".to_string()));
        }
        {
            let mut r = LimitReader::new(r.by_ref(), 100);
            assert_eq!(r.read_char(), Ok('1'));
            assert_eq!(r.limit(), 99);
            assert_eq!(r.read_line(), Ok("23456789\n".to_string()));
        }
    }

    #[test]
    fn test_iter_reader() {
        let mut r = IterReader::new(range(0u8, 8));
        let mut buf = [0, 0, 0];
        let len = r.read(buf).unwrap();
        assert_eq!(len, 3);
        assert!(buf == [0, 1, 2]);

        let len = r.read(buf).unwrap();
        assert_eq!(len, 3);
        assert!(buf == [3, 4, 5]);

        let len = r.read(buf).unwrap();
        assert_eq!(len, 2);
        assert!(buf == [6, 7, 5]);

        assert_eq!(r.read(buf).unwrap_err().kind, io::EndOfFile);
    }
}
<commit_msg>auto merge of #16513 : sfackler/rust/io-util-cleanup, r=alexcrichton<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.

/*! Utility implementations of Reader and Writer */

use prelude::*;
use cmp;
use io;
use boxed::Box;
use slice::bytes::MutableByteVector;

/// Wraps a `Reader`, limiting the number of bytes that can be read from it.
pub struct LimitReader<R> {
    limit: uint,
    inner: R
}

impl<R: Reader> LimitReader<R> {
    /// Creates a new `LimitReader`
    pub fn new(r: R, limit: uint) -> LimitReader<R> {
        LimitReader { limit: limit, inner: r }
    }

    /// Consumes the `LimitReader`, returning the underlying `Reader`.
    pub fn unwrap(self) -> R { self.inner }

    /// Returns the number of bytes that can be read before the `LimitReader`
    /// will return EOF.
    ///
    /// # Note
    ///
    /// The reader may reach EOF after reading fewer bytes than indicated by
    /// this method if the underlying reader reaches EOF.
    pub fn limit(&self) -> uint { self.limit }
}

impl<R: Reader> Reader for LimitReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        if self.limit == 0 {
            return Err(io::standard_error(io::EndOfFile));
        }

        let len = cmp::min(self.limit, buf.len());
        let res = self.inner.read(buf.mut_slice_to(len));
        match res {
            Ok(len) => self.limit -= len,
            _ => {}
        }
        res
    }
}

impl<R: Buffer> Buffer for LimitReader<R> {
    fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
        let amt = try!(self.inner.fill_buf());
        let buf = amt.slice_to(cmp::min(amt.len(), self.limit));
        if buf.len() == 0 {
            Err(io::standard_error(io::EndOfFile))
        } else {
            Ok(buf)
        }
    }

    fn consume(&mut self, amt: uint) {
        // Don't let callers reset the limit by passing an overlarge value
        let amt = cmp::min(amt, self.limit);
        self.limit -= amt;
        self.inner.consume(amt);
    }

}

/// A `Writer` which ignores bytes written to it, like /dev/null.
pub struct NullWriter;

impl Writer for NullWriter {
    #[inline]
    fn write(&mut self, _buf: &[u8]) -> io::IoResult<()> { Ok(()) }
}

/// A `Reader` which returns an infinite stream of 0 bytes, like /dev/zero.
pub struct ZeroReader;

impl Reader for ZeroReader {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        buf.set_memory(0);
        Ok(buf.len())
    }
}

impl Buffer for ZeroReader {
    fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
        static DATA: [u8, ..64] = [0, ..64];
        Ok(DATA.as_slice())
    }

    fn consume(&mut self, _amt: uint) {}
}

/// A `Reader` which is always at EOF, like /dev/null.
pub struct NullReader;

impl Reader for NullReader {
    #[inline]
    fn read(&mut self, _buf: &mut [u8]) -> io::IoResult<uint> {
        Err(io::standard_error(io::EndOfFile))
    }
}

impl Buffer for NullReader {
    fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
        Err(io::standard_error(io::EndOfFile))
    }
    fn consume(&mut self, _amt: uint) {}
}

/// A `Writer` which multiplexes writes to a set of `Writer`s.
///
/// The `Writer`s are delegated to in order. If any `Writer` returns an error,
/// that error is returned immediately and remaining `Writer`s are not called.
pub struct MultiWriter {
    writers: Vec<Box<Writer>>
}

impl MultiWriter {
    /// Creates a new `MultiWriter`
    pub fn new(writers: Vec<Box<Writer>>) -> MultiWriter {
        MultiWriter { writers: writers }
    }
}

impl Writer for MultiWriter {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::IoResult<()> {
        for writer in self.writers.mut_iter() {
            try!(writer.write(buf));
        }
        Ok(())
    }

    #[inline]
    fn flush(&mut self) -> io::IoResult<()> {
        for writer in self.writers.mut_iter() {
            try!(writer.flush());
        }
        Ok(())
    }
}

/// A `Reader` which chains input from multiple `Reader`s, reading each to
/// completion before moving onto the next.
pub struct ChainedReader<I, R> {
    readers: I,
    cur_reader: Option<R>,
}

impl<R: Reader, I: Iterator<R>> ChainedReader<I, R> {
    /// Creates a new `ChainedReader`
    pub fn new(mut readers: I) -> ChainedReader<I, R> {
        let r = readers.next();
        ChainedReader { readers: readers, cur_reader: r }
    }
}

impl<R: Reader, I: Iterator<R>> Reader for ChainedReader<I, R> {
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        loop {
            let err = match self.cur_reader {
                Some(ref mut r) => {
                    match r.read(buf) {
                        Ok(len) => return Ok(len),
                        Err(ref e) if e.kind == io::EndOfFile => None,
                        Err(e) => Some(e),
                    }
                }
                None => break
            };
            self.cur_reader = self.readers.next();
            match err {
                Some(e) => return Err(e),
                None => {}
            }
        }
        Err(io::standard_error(io::EndOfFile))
    }
}

/// A `Reader` which forwards input from another `Reader`, passing it along to
/// a `Writer` as well. Similar to the `tee(1)` command.
pub struct TeeReader<R, W> {
    reader: R,
    writer: W,
}

impl<R: Reader, W: Writer> TeeReader<R, W> {
    /// Creates a new `TeeReader`
    pub fn new(r: R, w: W) -> TeeReader<R, W> {
        TeeReader { reader: r, writer: w }
    }

    /// Consumes the `TeeReader`, returning the underlying `Reader` and
    /// `Writer`.
    pub fn unwrap(self) -> (R, W) {
        let TeeReader { reader, writer } = self;
        (reader, writer)
    }
}

impl<R: Reader, W: Writer> Reader for TeeReader<R, W> {
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        self.reader.read(buf).and_then(|len| {
            self.writer.write(buf.slice_to(len)).map(|()| len)
        })
    }
}

/// Copies all data from a `Reader` to a `Writer`.
pub fn copy<R: Reader, W: Writer>(r: &mut R, w: &mut W) -> io::IoResult<()> {
    let mut buf = [0, ..super::DEFAULT_BUF_SIZE];
    loop {
        let len = match r.read(buf) {
            Ok(len) => len,
            Err(ref e) if e.kind == io::EndOfFile => return Ok(()),
            Err(e) => return Err(e),
        };
        try!(w.write(buf.slice_to(len)));
    }
}

/// An adaptor converting an `Iterator<u8>` to a `Reader`.
pub struct IterReader<T> {
    iter: T,
}

impl<T: Iterator<u8>> IterReader<T> {
    /// Creates a new `IterReader` which will read from the specified
    /// `Iterator`.
    pub fn new(iter: T) -> IterReader<T> {
        IterReader { iter: iter }
    }
}

impl<T: Iterator<u8>> Reader for IterReader<T> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        let mut len = 0;
        for (slot, elt) in buf.mut_iter().zip(self.iter.by_ref()) {
            *slot = elt;
            len += 1;
        }
        if len == 0 && buf.len() != 0 {
            Err(io::standard_error(io::EndOfFile))
        } else {
            Ok(len)
        }
    }
}

#[cfg(test)]
mod test {
    use io::{MemReader, MemWriter, BufReader};
    use io;
    use boxed::Box;
    use super::*;
    use prelude::*;

    #[test]
    fn test_limit_reader_unlimited() {
        let mut r = MemReader::new(vec!(0, 1, 2));
        {
            let mut r = LimitReader::new(r.by_ref(), 4);
            assert_eq!(vec!(0, 1, 2), r.read_to_end().unwrap());
        }
    }

    #[test]
    fn test_limit_reader_limited() {
        let mut r = MemReader::new(vec!(0, 1, 2));
        {
            let mut r = LimitReader::new(r.by_ref(), 2);
            assert_eq!(vec!(0, 1), r.read_to_end().unwrap());
        }
        assert_eq!(vec!(2), r.read_to_end().unwrap());
    }

    #[test]
    fn test_limit_reader_limit() {
        let r = MemReader::new(vec!(0, 1, 2));
        let mut r = LimitReader::new(r, 3);
        assert_eq!(3, r.limit());
        assert_eq!(0, r.read_byte().unwrap());
        assert_eq!(2, r.limit());
        assert_eq!(vec!(1, 2), r.read_to_end().unwrap());
        assert_eq!(0, r.limit());
    }

    #[test]
    fn test_limit_reader_overlong_consume() {
        let mut r = MemReader::new(vec![0, 1, 2, 3, 4, 5]);
        let mut r = LimitReader::new(r.by_ref(), 1);
        r.consume(2);
        assert_eq!(vec![], r.read_to_end().unwrap());
    }

    #[test]
    fn test_null_writer() {
        let mut s = NullWriter;
        let buf = vec![0, 0, 0];
        s.write(buf.as_slice()).unwrap();
        s.flush().unwrap();
    }

    #[test]
    fn test_zero_reader() {
        let mut s = ZeroReader;
        let mut buf = vec![1, 2, 3];
        assert_eq!(s.read(buf.as_mut_slice()), Ok(3));
        assert_eq!(vec![0, 0, 0], buf);
    }

    #[test]
    fn test_null_reader() {
        let mut r = NullReader;
        let mut buf = vec![0];
        assert!(r.read(buf.as_mut_slice()).is_err());
    }

    #[test]
    fn test_multi_writer() {
        static mut writes: uint = 0;
        static mut flushes: uint = 0;

        struct TestWriter;
        impl Writer for TestWriter {
            fn write(&mut self, _buf: &[u8]) -> io::IoResult<()> {
                unsafe { writes += 1 }
                Ok(())
            }

            fn flush(&mut self) -> io::IoResult<()> {
                unsafe { flushes += 1 }
                Ok(())
            }
        }

        let mut multi = MultiWriter::new(vec!(box TestWriter as Box<Writer>,
                                              box TestWriter as Box<Writer>));
        multi.write([1, 2, 3]).unwrap();
        assert_eq!(2, unsafe { writes });
        assert_eq!(0, unsafe { flushes });
        multi.flush().unwrap();
        assert_eq!(2, unsafe { writes });
        assert_eq!(2, unsafe { flushes });
    }

    #[test]
    fn test_chained_reader() {
        let rs = vec!(MemReader::new(vec!(0, 1)), MemReader::new(vec!()),
                      MemReader::new(vec!(2, 3)));
        let mut r = ChainedReader::new(rs.move_iter());
        assert_eq!(vec!(0, 1, 2, 3), r.read_to_end().unwrap());
    }

    #[test]
    fn test_tee_reader() {
        let mut r = TeeReader::new(MemReader::new(vec!(0, 1, 2)),
                                   MemWriter::new());
        assert_eq!(vec!(0, 1, 2), r.read_to_end().unwrap());
        let (_, w) = r.unwrap();
        assert_eq!(vec!(0, 1, 2), w.unwrap());
    }

    #[test]
    fn test_copy() {
        let mut r = MemReader::new(vec!(0, 1, 2, 3, 4));
        let mut w = MemWriter::new();
        copy(&mut r, &mut w).unwrap();
        assert_eq!(vec!(0, 1, 2, 3, 4), w.unwrap());
    }

    #[test]
    fn limit_reader_buffer() {
        let data = "0123456789\n0123456789\n";
        let mut r = BufReader::new(data.as_bytes());
        {
            let mut r = LimitReader::new(r.by_ref(), 3);
            assert_eq!(r.read_line(), Ok("012".to_string()));
            assert_eq!(r.limit(), 0);
            assert_eq!(r.read_line().err().unwrap().kind, io::EndOfFile);
        }
        {
            let mut r = LimitReader::new(r.by_ref(), 9);
            assert_eq!(r.read_line(), Ok("3456789\n".to_string()));
            assert_eq!(r.limit(), 1);
            assert_eq!(r.read_line(), Ok("0".to_string()));
        }
        {
            let mut r = LimitReader::new(r.by_ref(), 100);
            assert_eq!(r.read_char(), Ok('1'));
            assert_eq!(r.limit(), 99);
            assert_eq!(r.read_line(), Ok("23456789\n".to_string()));
        }
    }

    #[test]
    fn test_iter_reader() {
        let mut r = IterReader::new(range(0u8, 8));
        let mut buf = [0, 0, 0];
        let len = r.read(buf).unwrap();
        assert_eq!(len, 3);
        assert!(buf == [0, 1, 2]);

        let len = r.read(buf).unwrap();
        assert_eq!(len, 3);
        assert!(buf == [3, 4, 5]);

        let len = r.read(buf).unwrap();
        assert_eq!(len, 2);
        assert!(buf == [6, 7, 5]);

        assert_eq!(r.read(buf).unwrap_err().kind, io::EndOfFile);
    }

    #[test]
    fn iter_reader_zero_length() {
        let mut r = IterReader::new(range(0u8, 8));
        let mut buf = [];
        assert_eq!(Ok(0), r.read(buf));
    }
}
<|endoftext|>


<commit_before><commit_msg>Query and calculate time offsets based on a specified date.<commit_after><|endoftext|>


<commit_before><commit_msg>Rename functions to actions.<commit_after><|endoftext|>


<commit_before>use common::string::*;
use common::vec::*;

use syscall::call::*;

/// File seek
pub enum Seek {
    /// The start point
    Start(usize),
    /// The current point
    Current(isize),
    /// The end point
    End(isize),
}

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

impl File {
    /// Open a new file using a path
    // TODO: Why &String and not String
    // TODO: Return Option<File>
    pub fn open(path: &String) -> File {
        unsafe {
            let c_str: *const u8 = path.to_c_str();
            let ret = File {
                path: path.clone(),
                fd: sys_open(c_str, 0, 0),
            };
            sys_unalloc(c_str as usize);
            ret
        }
    }

    /// Return the url to the file
    pub fn url(&self) -> String {
        //TODO
        self.path.clone()
    }

    /// Write to the file
    pub fn write(&mut self, buf: &[u8]) -> Option<usize> {
        unsafe {
            let count = sys_write(self.fd, buf.as_ptr(), buf.len());
            if count == 0xFFFFFFFF {
                Option::None
            } else {
                Option::Some(count)
            }
        }
    }

    /// Seek a given position
    pub fn seek(&mut self, pos: Seek) -> Option<usize> {
        let (whence, offset) = match pos {
            Seek::Start(offset) => (0, offset as isize),
            Seek::Current(offset) => (1, offset),
            Seek::End(offset) => (2, offset),
        };

        let position = unsafe { sys_lseek(self.fd, offset, whence) };
        if position == 0xFFFFFFFF {
            Option::None
        } else {
            Option::Some(position)
        }
    }

    /// Flush the io
    pub fn sync(&mut self) -> bool {
        unsafe { sys_fsync(self.fd) == 0 }
    }
}

pub trait Read {

    /// Read a file to a buffer
    fn read(&mut self, buf: &mut [u8]) -> Option<usize>;

    /// Read the file to the end
    fn read_to_end(&mut self, vec: &mut Vec<u8>) -> Option<usize> {
        let mut read = 0;
        loop {
            let mut bytes = [0; 1024];
            match self.read(&mut bytes) {
                Option::Some(0) => return Option::Some(read),
                Option::None => return Option::None,
                Option::Some(count) => {
                    for i in 0..count {
                        vec.push(bytes[i]);
                    }
                    read += count;
                }
            }
        }
    }
    // /// Return an iterator of the bytes
    //fn bytes(&'a mut self) -> BytesIter<'a> {
    //    BytesIter {
    //        reader: self,
    //    }
    //}
}

impl Read for File {
    fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        unsafe {
            let count = sys_read(self.fd, buf.as_mut_ptr(), buf.len());
            if count == 0xFFFFFFFF {
                Option::None
            } else {
                Option::Some(count)
            }
        }
    }
}

impl Drop for File {
    fn drop(&mut self) {
        unsafe {
            sys_close(self.fd);
        }
    }
}
<commit_msg>Add butes method<commit_after>use common::string::*;
use common::vec::*;

use syscall::call::*;

/// File seek
pub enum Seek {
    /// The start point
    Start(usize),
    /// The current point
    Current(isize),
    /// The end point
    End(isize),
}

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

impl File {
    /// Open a new file using a path
    // TODO: Why &String and not String
    // TODO: Return Option<File>
    pub fn open(path: &String) -> File {
        unsafe {
            let c_str: *const u8 = path.to_c_str();
            let ret = File {
                path: path.clone(),
                fd: sys_open(c_str, 0, 0),
            };
            sys_unalloc(c_str as usize);
            ret
        }
    }

    /// Return the url to the file
    pub fn url(&self) -> String {
        //TODO
        self.path.clone()
    }

    /// Write to the file
    pub fn write(&mut self, buf: &[u8]) -> Option<usize> {
        unsafe {
            let count = sys_write(self.fd, buf.as_ptr(), buf.len());
            if count == 0xFFFFFFFF {
                Option::None
            } else {
                Option::Some(count)
            }
        }
    }

    /// Seek a given position
    pub fn seek(&mut self, pos: Seek) -> Option<usize> {
        let (whence, offset) = match pos {
            Seek::Start(offset) => (0, offset as isize),
            Seek::Current(offset) => (1, offset),
            Seek::End(offset) => (2, offset),
        };

        let position = unsafe { sys_lseek(self.fd, offset, whence) };
        if position == 0xFFFFFFFF {
            Option::None
        } else {
            Option::Some(position)
        }
    }

    /// Flush the io
    pub fn sync(&mut self) -> bool {
        unsafe { sys_fsync(self.fd) == 0 }
    }
}

pub trait Read {

    /// Read a file to a buffer
    fn read(&mut self, buf: &mut [u8]) -> Option<usize>;

    /// Read the file to the end
    fn read_to_end(&mut self, vec: &mut Vec<u8>) -> Option<usize> {
        let mut read = 0;
        loop {
            let mut bytes = [0; 1024];
            match self.read(&mut bytes) {
                Option::Some(0) => return Option::Some(read),
                Option::None => return Option::None,
                Option::Some(count) => {
                    for i in 0..count {
                        vec.push(bytes[i]);
                    }
                    read += count;
                }
            }
        }
    }
    /// Return an iterator of the bytes
    fn bytes(&'a mut self) -> VecIterator<'a, u8> {
        // TODO: This is only a temporary implementation. Make this read one byte at a time.
        let buf = Vec::new();
        self.read_to_end(&mut buf);

        buf.iter()
    }
}

impl Read for File {
    fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        unsafe {
            let count = sys_read(self.fd, buf.as_mut_ptr(), buf.len());
            if count == 0xFFFFFFFF {
                Option::None
            } else {
                Option::Some(count)
            }
        }
    }
}

impl Drop for File {
    fn drop(&mut self) {
        unsafe {
            sys_close(self.fd);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>continued demacrofication<commit_after><|endoftext|>


<commit_before><commit_msg>examples: Add who_eats_my_hard_drive example<commit_after>extern crate rs_release;

use std::process::Command;

#[derive(Debug)]
enum Error {
    UnknownOs,
    ReadError,
}

fn get_os_id() -> Result<String, Error> {
    match rs_release::get_os_release() {
        Err(_) => Err(Error::ReadError),
        Ok(mut os_release) => os_release.remove("ID").ok_or(Error::UnknownOs)
    }
}

// https://blog.tinned-software.net/show-installed-yum-packages-by-size/
fn show_fedora_packages() {
    let mut command = Command::new("rpm");

    command.arg("--query");
    command.arg("--all");
    command.arg("--queryformat");
    command.arg("%10{size} - %-25{name} \t %{version}\n");

    if let Err(e) = command.spawn() {
        println!("ERROR running rpm: {:?}", e);
    }
}

// http://www.commandlinefu.com/commands/view/3842/list-your-largest-installed-packages-on-debianubuntu
fn show_debian_packages() {
    let mut command = Command::new("dpkg-query");

    command.arg("--show");
    command.arg("--showformat");
    command.arg("${Installed-Size}\t${Package}\n");

    if let Err(e) = command.spawn() {
        println!("ERROR running dpkg-query: {:?}", e);
    }
}

fn main() {
    match get_os_id() {
        Ok(id) => match id.as_str() {
            "fedora" => show_fedora_packages(),
            "debian" => show_debian_packages(),
            _ => println!("ERROR: {:?}", Error::UnknownOs),
        },
        Err(e) => println!("ERROR: {:?}", e),
    }
}
<|endoftext|>


<commit_before>// Copyright 2012-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.

//! The compiler code necessary for `#[derive(Decodable)]`. See encodable.rs for more.

use ast;
use ast::{MetaItem, Item, Expr, MutMutable};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use parse::token;
use ptr::P;

pub fn expand_deriving_rustc_decodable<F>(cx: &mut ExtCtxt,
                                          span: Span,
                                          mitem: &MetaItem,
                                          item: &Item,
                                          push: F) where
    F: FnOnce(P<Item>),
{
    expand_deriving_decodable_imp(cx, span, mitem, item, push, "rustc_serialize")
}

pub fn expand_deriving_decodable<F>(cx: &mut ExtCtxt,
                                    span: Span,
                                    mitem: &MetaItem,
                                    item: &Item,
                                    push: F) where
    F: FnOnce(P<Item>),
{
    expand_deriving_decodable_imp(cx, span, mitem, item, push, "serialize")
}

fn expand_deriving_decodable_imp<F>(cx: &mut ExtCtxt,
                                    span: Span,
                                    mitem: &MetaItem,
                                    item: &Item,
                                    push: F,
                                    krate: &'static str) where
    F: FnOnce(P<Item>),
{
    let trait_def = TraitDef {
        span: span,
        attributes: Vec::new(),
        path: Path::new_(vec!(krate, "Decodable"), None, vec!(), true),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        methods: vec!(
            MethodDef {
                name: "decode",
                generics: LifetimeBounds {
                    lifetimes: Vec::new(),
                    bounds: vec!(("__D", vec!(Path::new_(
                                    vec!(krate, "Decoder"), None,
                                    vec!(), true))))
                },
                explicit_self: None,
                args: vec!(Ptr(box Literal(Path::new_local("__D")),
                            Borrowed(None, MutMutable))),
                ret_ty: Literal(Path::new_(
                    vec!("std", "result", "Result"),
                    None,
                    vec!(box Self, box Literal(Path::new_(
                        vec!["__D", "Error"], None, vec![], false
                    ))),
                    true
                )),
                attributes: Vec::new(),
                combine_substructure: combine_substructure(box |a, b, c| {
                    decodable_substructure(a, b, c, krate)
                }),
            })
    };

    trait_def.expand(cx, mitem, item, push)
}

fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
                          substr: &Substructure,
                          krate: &str) -> P<Expr> {
    let decoder = substr.nonself_args[0].clone();
    let recurse = vec!(cx.ident_of(krate),
                    cx.ident_of("Decodable"),
                    cx.ident_of("decode"));
    // throw an underscore in front to suppress unused variable warnings
    let blkarg = cx.ident_of("_d");
    let blkdecoder = cx.expr_ident(trait_span, blkarg);
    let calldecode = cx.expr_call_global(trait_span, recurse, vec!(blkdecoder.clone()));
    let lambdadecode = cx.lambda_expr_1(trait_span, calldecode, blkarg);

    return match *substr.fields {
        StaticStruct(_, ref summary) => {
            let nfields = match *summary {
                Unnamed(ref fields) => fields.len(),
                Named(ref fields) => fields.len()
            };
            let read_struct_field = cx.ident_of("read_struct_field");

            let path = cx.path_ident(trait_span, substr.type_ident);
            let result = decode_static_fields(cx,
                                              trait_span,
                                              path,
                                              summary,
                                              |cx, span, name, field| {
                cx.expr_try(span,
                    cx.expr_method_call(span, blkdecoder.clone(), read_struct_field,
                                        vec!(cx.expr_str(span, name),
                                          cx.expr_uint(span, field),
                                          lambdadecode.clone())))
            });
            let result = cx.expr_ok(trait_span, result);
            cx.expr_method_call(trait_span,
                                decoder,
                                cx.ident_of("read_struct"),
                                vec!(
                cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
                cx.expr_uint(trait_span, nfields),
                cx.lambda_expr_1(trait_span, result, blkarg)
            ))
        }
        StaticEnum(_, ref fields) => {
            let variant = cx.ident_of("i");

            let mut arms = Vec::new();
            let mut variants = Vec::new();
            let rvariant_arg = cx.ident_of("read_enum_variant_arg");

            for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
                variants.push(cx.expr_str(v_span, token::get_ident(name)));

                let path = cx.path(trait_span, vec![substr.type_ident, name]);
                let decoded = decode_static_fields(cx,
                                                   v_span,
                                                   path,
                                                   parts,
                                                   |cx, span, _, field| {
                    let idx = cx.expr_uint(span, field);
                    cx.expr_try(span,
                        cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg,
                                            vec!(idx, lambdadecode.clone())))
                });

                arms.push(cx.arm(v_span,
                                 vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))),
                                 decoded));
            }

            arms.push(cx.arm_unreachable(trait_span));

            let result = cx.expr_ok(trait_span,
                                    cx.expr_match(trait_span,
                                                  cx.expr_ident(trait_span, variant), arms));
            let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
            let variant_vec = cx.expr_vec(trait_span, variants);
            let variant_vec = cx.expr_addr_of(trait_span, variant_vec);
            let result = cx.expr_method_call(trait_span, blkdecoder,
                                             cx.ident_of("read_enum_variant"),
                                             vec!(variant_vec, lambda));
            cx.expr_method_call(trait_span,
                                decoder,
                                cx.ident_of("read_enum"),
                                vec!(
                cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
                cx.lambda_expr_1(trait_span, result, blkarg)
            ))
        }
        _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
    };
}

/// Create a decoder for a single enum variant/struct:
/// - `outer_pat_path` is the path to this enum variant/struct
/// - `getarg` should retrieve the `uint`-th field with name `@str`.
fn decode_static_fields<F>(cx: &mut ExtCtxt,
                           trait_span: Span,
                           outer_pat_path: ast::Path,
                           fields: &StaticFields,
                           mut getarg: F)
                           -> P<Expr> where
    F: FnMut(&mut ExtCtxt, Span, InternedString, uint) -> P<Expr>,
{
    match *fields {
        Unnamed(ref fields) => {
            let path_expr = cx.expr_path(outer_pat_path);
            if fields.is_empty() {
                path_expr
            } else {
                let fields = fields.iter().enumerate().map(|(i, &span)| {
                    getarg(cx, span,
                           token::intern_and_get_ident(&format!("_field{}", i)[]),
                           i)
                }).collect();

                cx.expr_call(trait_span, path_expr, fields)
            }
        }
        Named(ref fields) => {
            // use the field's span to get nicer error messages.
            let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
                let arg = getarg(cx, span, token::get_ident(name), i);
                cx.field_imm(span, name, arg)
            }).collect();
            cx.expr_struct(trait_span, outer_pat_path, fields)
        }
    }
}
<commit_msg>Avoid unnecessary closures when deriving RustcDecodable<commit_after>// Copyright 2012-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.

//! The compiler code necessary for `#[derive(Decodable)]`. See encodable.rs for more.

use ast;
use ast::{MetaItem, Item, Expr, MutMutable};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use parse::token;
use ptr::P;

pub fn expand_deriving_rustc_decodable<F>(cx: &mut ExtCtxt,
                                          span: Span,
                                          mitem: &MetaItem,
                                          item: &Item,
                                          push: F) where
    F: FnOnce(P<Item>),
{
    expand_deriving_decodable_imp(cx, span, mitem, item, push, "rustc_serialize")
}

pub fn expand_deriving_decodable<F>(cx: &mut ExtCtxt,
                                    span: Span,
                                    mitem: &MetaItem,
                                    item: &Item,
                                    push: F) where
    F: FnOnce(P<Item>),
{
    expand_deriving_decodable_imp(cx, span, mitem, item, push, "serialize")
}

fn expand_deriving_decodable_imp<F>(cx: &mut ExtCtxt,
                                    span: Span,
                                    mitem: &MetaItem,
                                    item: &Item,
                                    push: F,
                                    krate: &'static str) where
    F: FnOnce(P<Item>),
{
    let trait_def = TraitDef {
        span: span,
        attributes: Vec::new(),
        path: Path::new_(vec!(krate, "Decodable"), None, vec!(), true),
        additional_bounds: Vec::new(),
        generics: LifetimeBounds::empty(),
        methods: vec!(
            MethodDef {
                name: "decode",
                generics: LifetimeBounds {
                    lifetimes: Vec::new(),
                    bounds: vec!(("__D", vec!(Path::new_(
                                    vec!(krate, "Decoder"), None,
                                    vec!(), true))))
                },
                explicit_self: None,
                args: vec!(Ptr(box Literal(Path::new_local("__D")),
                            Borrowed(None, MutMutable))),
                ret_ty: Literal(Path::new_(
                    vec!("std", "result", "Result"),
                    None,
                    vec!(box Self, box Literal(Path::new_(
                        vec!["__D", "Error"], None, vec![], false
                    ))),
                    true
                )),
                attributes: Vec::new(),
                combine_substructure: combine_substructure(box |a, b, c| {
                    decodable_substructure(a, b, c, krate)
                }),
            })
    };

    trait_def.expand(cx, mitem, item, push)
}

fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
                          substr: &Substructure,
                          krate: &str) -> P<Expr> {
    let decoder = substr.nonself_args[0].clone();
    let recurse = vec!(cx.ident_of(krate),
                    cx.ident_of("Decodable"),
                    cx.ident_of("decode"));
    let exprdecode = cx.expr_path(cx.path_global(trait_span, recurse));
    // throw an underscore in front to suppress unused variable warnings
    let blkarg = cx.ident_of("_d");
    let blkdecoder = cx.expr_ident(trait_span, blkarg);

    return match *substr.fields {
        StaticStruct(_, ref summary) => {
            let nfields = match *summary {
                Unnamed(ref fields) => fields.len(),
                Named(ref fields) => fields.len()
            };
            let read_struct_field = cx.ident_of("read_struct_field");

            let path = cx.path_ident(trait_span, substr.type_ident);
            let result = decode_static_fields(cx,
                                              trait_span,
                                              path,
                                              summary,
                                              |cx, span, name, field| {
                cx.expr_try(span,
                    cx.expr_method_call(span, blkdecoder.clone(), read_struct_field,
                                        vec!(cx.expr_str(span, name),
                                          cx.expr_uint(span, field),
                                          exprdecode.clone())))
            });
            let result = cx.expr_ok(trait_span, result);
            cx.expr_method_call(trait_span,
                                decoder,
                                cx.ident_of("read_struct"),
                                vec!(
                cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
                cx.expr_uint(trait_span, nfields),
                cx.lambda_expr_1(trait_span, result, blkarg)
            ))
        }
        StaticEnum(_, ref fields) => {
            let variant = cx.ident_of("i");

            let mut arms = Vec::new();
            let mut variants = Vec::new();
            let rvariant_arg = cx.ident_of("read_enum_variant_arg");

            for (i, &(name, v_span, ref parts)) in fields.iter().enumerate() {
                variants.push(cx.expr_str(v_span, token::get_ident(name)));

                let path = cx.path(trait_span, vec![substr.type_ident, name]);
                let decoded = decode_static_fields(cx,
                                                   v_span,
                                                   path,
                                                   parts,
                                                   |cx, span, _, field| {
                    let idx = cx.expr_uint(span, field);
                    cx.expr_try(span,
                        cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg,
                                            vec!(idx, exprdecode.clone())))
                });

                arms.push(cx.arm(v_span,
                                 vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))),
                                 decoded));
            }

            arms.push(cx.arm_unreachable(trait_span));

            let result = cx.expr_ok(trait_span,
                                    cx.expr_match(trait_span,
                                                  cx.expr_ident(trait_span, variant), arms));
            let lambda = cx.lambda_expr(trait_span, vec!(blkarg, variant), result);
            let variant_vec = cx.expr_vec(trait_span, variants);
            let variant_vec = cx.expr_addr_of(trait_span, variant_vec);
            let result = cx.expr_method_call(trait_span, blkdecoder,
                                             cx.ident_of("read_enum_variant"),
                                             vec!(variant_vec, lambda));
            cx.expr_method_call(trait_span,
                                decoder,
                                cx.ident_of("read_enum"),
                                vec!(
                cx.expr_str(trait_span, token::get_ident(substr.type_ident)),
                cx.lambda_expr_1(trait_span, result, blkarg)
            ))
        }
        _ => cx.bug("expected StaticEnum or StaticStruct in deriving(Decodable)")
    };
}

/// Create a decoder for a single enum variant/struct:
/// - `outer_pat_path` is the path to this enum variant/struct
/// - `getarg` should retrieve the `uint`-th field with name `@str`.
fn decode_static_fields<F>(cx: &mut ExtCtxt,
                           trait_span: Span,
                           outer_pat_path: ast::Path,
                           fields: &StaticFields,
                           mut getarg: F)
                           -> P<Expr> where
    F: FnMut(&mut ExtCtxt, Span, InternedString, uint) -> P<Expr>,
{
    match *fields {
        Unnamed(ref fields) => {
            let path_expr = cx.expr_path(outer_pat_path);
            if fields.is_empty() {
                path_expr
            } else {
                let fields = fields.iter().enumerate().map(|(i, &span)| {
                    getarg(cx, span,
                           token::intern_and_get_ident(&format!("_field{}", i)[]),
                           i)
                }).collect();

                cx.expr_call(trait_span, path_expr, fields)
            }
        }
        Named(ref fields) => {
            // use the field's span to get nicer error messages.
            let fields = fields.iter().enumerate().map(|(i, &(name, span))| {
                let arg = getarg(cx, span, token::get_ident(name), i);
                cx.field_imm(span, name, arg)
            }).collect();
            cx.expr_struct(trait_span, outer_pat_path, fields)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>continued cleaning up iterator_provider<commit_after><|endoftext|>


<commit_before><commit_msg> #19 MD5 textures are optional<commit_after><|endoftext|>


<commit_before><commit_msg>adds a bench main for instrumentation<commit_after>#![feature(os, collections, rustc_private)]

extern crate getopts;
extern crate selecta;

use getopts::{optopt,getopts};
use selecta::configuration::Configuration;
use selecta::search::Search;
use selecta::tty::TTY;
use selecta::tty::IO;
use selecta::screen::Screen;

#[allow(dead_code)]
fn main() {
    let initial_query = extract_initial_query();
    let lines = read_lines(100000);

    let config = Configuration::from_inputs(lines, initial_query, Some(20));
    let mut search = Search::blank(config);

    search = search.append_to_search("t").backspace().append_to_search("o");
}

fn extract_initial_query() -> Option<String> {
    let args = std::os::args();
    let opts = &[
        optopt("s", "search", "initial search query", ""),
    ];
    let matches = getopts(args.tail(), opts).unwrap();

    matches.opt_str("s")
}

fn one_two_three() -> Vec<String> {
    vec!["one".to_string(),
         "two".to_string(),
         "three".to_string()]
}

fn read_lines(n: usize) -> Vec<String> {
    let mut result: Vec<String> = Vec::new();
    for thing in one_two_three().iter().cycle().take(n) {
        result.push(thing.clone());
    }
    result
}
<|endoftext|>


<commit_before><commit_msg>Lengthen comment<commit_after><|endoftext|>


<commit_before><commit_msg>Added publish example code<commit_after>extern crate diesel_demo;
extern crate diesel;

use self::diesel::prelude::*;
use self::diesel_demo::*;
use self::models::Post;
use std::env::args;

fn main () {
    use diesel_demo::schema::posts::dsl::{posts, published};
    let id = args().nth(1).expect("publish_post requires a post id").parse::<i32>().expect("Invalid ID");
    let connection = establish_connection();

    let post = diesel::update(posts.find(id)).set(published.eq(true)).get_result::<Post>(&connection).expect(&format!("Unable to find post {}", id));

    println!("Published post {}", post.title);
}
<|endoftext|>


<commit_before><commit_msg>test test<commit_after><|endoftext|>


<commit_before><commit_msg>Add metrics for pg-to-tar.<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #70283 - CDirkx:regression-test-70155, r=oli-obk<commit_after>// check-pass
#![allow(incomplete_features)]
#![feature(const_generics)]

// `Range` should be usable within const generics:
struct _Range<const R: std::ops::Range<usize>>;
const RANGE : _Range<{ 0 .. 1000 }> = _Range;

// `RangeFrom` should be usable within const generics:
struct _RangeFrom<const R: std::ops::RangeFrom<usize>>;
const RANGE_FROM : _RangeFrom<{ 0 .. }> = _RangeFrom;

// `RangeFull` should be usable within const generics:
struct _RangeFull<const R: std::ops::RangeFull>;
const RANGE_FULL : _RangeFull<{ .. }> = _RangeFull;

// Regression test for #70155
// `RangeInclusive` should be usable within const generics:
struct _RangeInclusive<const R: std::ops::RangeInclusive<usize>>;
const RANGE_INCLUSIVE : _RangeInclusive<{ 0 ..= 999 }> = _RangeInclusive;

// `RangeTo` should be usable within const generics:
struct _RangeTo<const R: std::ops::RangeTo<usize>>;
const RANGE_TO : _RangeTo<{ .. 1000 }> = _RangeTo;

// `RangeToInclusive` should be usable within const generics:
struct _RangeToInclusive<const R: std::ops::RangeToInclusive<usize>>;
const RANGE_TO_INCLUSIVE : _RangeToInclusive<{ ..= 999 }> = _RangeToInclusive;

pub fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add test for large zip64 files<commit_after>// The following is a hexdump of a zip64 file containing the following files:
// zero4400: 4400 MB of zeroes
// zero100: 100 MB of zeroes
// zero4400_2: 4400 MB of zeroes
//
// 00000000  50 4b 03 04 2d 00 00 00  00 00 1b 6e 51 4d 66 82  |PK..-......nQMf.|
// 00000010  13 da ff ff ff ff ff ff  ff ff 08 00 30 00 7a 65  |............0.ze|
// 00000020  72 6f 34 34 30 30 55 54  09 00 03 a5 21 c7 5b db  |ro4400UT....!.[.|
// 00000030  21 c7 5b 75 78 0b 00 01  04 e8 03 00 00 04 e8 03  |!.[ux...........|
// 00000040  00 00 01 00 10 00 00 00  00 13 01 00 00 00 00 00  |................|
// 00000050  00 13 01 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
// 00000060  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
// *
// 113000050  00 00 00 00 00 00 50 4b  03 04 0a 00 00 00 00 00  |......PK........|
// 113000060  2b 6e 51 4d 98 23 28 4b  00 00 40 06 00 00 40 06  |+nQM.#(K..@...@.|
// 113000070  07 00 1c 00 7a 65 72 6f  31 30 30 55 54 09 00 03  |....zero100UT...|
// 113000080  c2 21 c7 5b c2 21 c7 5b  75 78 0b 00 01 04 e8 03  |.!.[.!.[ux......|
// 113000090  00 00 04 e8 03 00 00 00  00 00 00 00 00 00 00 00  |................|
// 1130000a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
// *
// 119400090  00 00 00 00 00 00 00 50  4b 03 04 2d 00 00 00 00  |.......PK..-....|
// 1194000a0  00 3b 6e 51 4d 66 82 13  da ff ff ff ff ff ff ff  |.;nQMf..........|
// 1194000b0  ff 0a 00 30 00 7a 65 72  6f 34 34 30 30 5f 32 55  |...0.zero4400_2U|
// 1194000c0  54 09 00 03 e2 21 c7 5b  db 21 c7 5b 75 78 0b 00  |T....!.[.!.[ux..|
// 1194000d0  01 04 e8 03 00 00 04 e8  03 00 00 01 00 10 00 00  |................|
// 1194000e0  00 00 13 01 00 00 00 00  00 00 13 01 00 00 00 00  |................|
// 1194000f0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
// *
// 22c4000e0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 50  |...............P|
// 22c4000f0  4b 01 02 1e 03 2d 00 00  00 00 00 1b 6e 51 4d 66  |K....-......nQMf|
// 22c400100  82 13 da ff ff ff ff ff  ff ff ff 08 00 2c 00 00  |.............,..|
// 22c400110  00 00 00 00 00 00 00 a4  81 00 00 00 00 7a 65 72  |.............zer|
// 22c400120  6f 34 34 30 30 55 54 05  00 03 a5 21 c7 5b 75 78  |o4400UT....!.[ux|
// 22c400130  0b 00 01 04 e8 03 00 00  04 e8 03 00 00 01 00 10  |................|
// 22c400140  00 00 00 00 13 01 00 00  00 00 00 00 13 01 00 00  |................|
// 22c400150  00 50 4b 01 02 1e 03 0a  00 00 00 00 00 2b 6e 51  |.PK..........+nQ|
// 22c400160  4d 98 23 28 4b 00 00 40  06 00 00 40 06 07 00 24  |M.#(K..@...@...$|
// 22c400170  00 00 00 00 00 00 00 00  00 a4 81 ff ff ff ff 7a  |...............z|
// 22c400180  65 72 6f 31 30 30 55 54  05 00 03 c2 21 c7 5b 75  |ero100UT....!.[u|
// 22c400190  78 0b 00 01 04 e8 03 00  00 04 e8 03 00 00 01 00  |x...............|
// 22c4001a0  08 00 56 00 00 13 01 00  00 00 50 4b 01 02 1e 03  |..V.......PK....|
// 22c4001b0  2d 00 00 00 00 00 3b 6e  51 4d 66 82 13 da ff ff  |-.....;nQMf.....|
// 22c4001c0  ff ff ff ff ff ff 0a 00  34 00 00 00 00 00 00 00  |........4.......|
// 22c4001d0  00 00 a4 81 ff ff ff ff  7a 65 72 6f 34 34 30 30  |........zero4400|
// 22c4001e0  5f 32 55 54 05 00 03 e2  21 c7 5b 75 78 0b 00 01  |_2UT....!.[ux...|
// 22c4001f0  04 e8 03 00 00 04 e8 03  00 00 01 00 18 00 00 00  |................|
// 22c400200  00 13 01 00 00 00 00 00  00 13 01 00 00 00 97 00  |................|
// 22c400210  40 19 01 00 00 00 50 4b  06 06 2c 00 00 00 00 00  |@.....PK..,.....|
// 22c400220  00 00 1e 03 2d 00 00 00  00 00 00 00 00 00 03 00  |....-...........|
// 22c400230  00 00 00 00 00 00 03 00  00 00 00 00 00 00 27 01  |..............'.|
// 22c400240  00 00 00 00 00 00 ef 00  40 2c 02 00 00 00 50 4b  |........@,....PK|
// 22c400250  06 07 00 00 00 00 16 02  40 2c 02 00 00 00 01 00  |........@,......|
// 22c400260  00 00 50 4b 05 06 00 00  00 00 03 00 03 00 27 01  |..PK..........'.|
// 22c400270  00 00 ff ff ff ff 00 00                           |........|
// 22c400278

extern crate zip;

use std::io::{self, Seek, SeekFrom, Read};

const BLOCK1_LENGTH : u64 = 0x60;
const BLOCK1 : [u8; BLOCK1_LENGTH as usize] = [
    0x50, 0x4b, 0x03, 0x04, 0x2d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x6e, 0x51, 0x4d, 0x66, 0x82,
    0x13, 0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x30, 0x00, 0x7a, 0x65,
    0x72, 0x6f, 0x34, 0x34, 0x30, 0x30, 0x55, 0x54, 0x09, 0x00, 0x03, 0xa5, 0x21, 0xc7, 0x5b, 0xdb,
    0x21, 0xc7, 0x5b, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03,
    0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];

const BLOCK2_LENGTH : u64 = 0x50;
const BLOCK2 : [u8; BLOCK2_LENGTH as usize] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x2b, 0x6e, 0x51, 0x4d, 0x98, 0x23, 0x28, 0x4b, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 0x40, 0x06,
    0x07, 0x00, 0x1c, 0x00, 0x7a, 0x65, 0x72, 0x6f, 0x31, 0x30, 0x30, 0x55, 0x54, 0x09, 0x00, 0x03,
    0xc2, 0x21, 0xc7, 0x5b, 0xc2, 0x21, 0xc7, 0x5b, 0x75, 0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03,
    0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];

const BLOCK3_LENGTH : u64 = 0x60;
const BLOCK3 : [u8; BLOCK3_LENGTH as usize] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x03, 0x04, 0x2d, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x3b, 0x6e, 0x51, 0x4d, 0x66, 0x82, 0x13, 0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0x0a, 0x00, 0x30, 0x00, 0x7a, 0x65, 0x72, 0x6f, 0x34, 0x34, 0x30, 0x30, 0x5f, 0x32, 0x55,
    0x54, 0x09, 0x00, 0x03, 0xe2, 0x21, 0xc7, 0x5b, 0xdb, 0x21, 0xc7, 0x5b, 0x75, 0x78, 0x0b, 0x00,
    0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00,
    0x00, 0x00, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00,
];

const BLOCK4_LENGTH : u64 = 0x198;
const BLOCK4 : [u8; BLOCK4_LENGTH as usize] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50,
    0x4b, 0x01, 0x02, 0x1e, 0x03, 0x2d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x6e, 0x51, 0x4d, 0x66,
    0x82, 0x13, 0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x2c, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x81, 0x00, 0x00, 0x00, 0x00, 0x7a, 0x65, 0x72,
    0x6f, 0x34, 0x34, 0x30, 0x30, 0x55, 0x54, 0x05, 0x00, 0x03, 0xa5, 0x21, 0xc7, 0x5b, 0x75, 0x78,
    0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x01, 0x00, 0x10,
    0x00, 0x00, 0x00, 0x00, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x01, 0x00, 0x00,
    0x00, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x6e, 0x51,
    0x4d, 0x98, 0x23, 0x28, 0x4b, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 0x40, 0x06, 0x07, 0x00, 0x24,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x81, 0xff, 0xff, 0xff, 0xff, 0x7a,
    0x65, 0x72, 0x6f, 0x31, 0x30, 0x30, 0x55, 0x54, 0x05, 0x00, 0x03, 0xc2, 0x21, 0xc7, 0x5b, 0x75,
    0x78, 0x0b, 0x00, 0x01, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x01, 0x00,
    0x08, 0x00, 0x56, 0x00, 0x00, 0x13, 0x01, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x01, 0x02, 0x1e, 0x03,
    0x2d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3b, 0x6e, 0x51, 0x4d, 0x66, 0x82, 0x13, 0xda, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0a, 0x00, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xa4, 0x81, 0xff, 0xff, 0xff, 0xff, 0x7a, 0x65, 0x72, 0x6f, 0x34, 0x34, 0x30, 0x30,
    0x5f, 0x32, 0x55, 0x54, 0x05, 0x00, 0x03, 0xe2, 0x21, 0xc7, 0x5b, 0x75, 0x78, 0x0b, 0x00, 0x01,
    0x04, 0xe8, 0x03, 0x00, 0x00, 0x04, 0xe8, 0x03, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00,
    0x00, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x01, 0x00, 0x00, 0x00, 0x97, 0x00,
    0x40, 0x19, 0x01, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x06, 0x06, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x1e, 0x03, 0x2d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x27, 0x01,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0x00, 0x40, 0x2c, 0x02, 0x00, 0x00, 0x00, 0x50, 0x4b,
    0x06, 0x07, 0x00, 0x00, 0x00, 0x00, 0x16, 0x02, 0x40, 0x2c, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00,
    0x00, 0x00, 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x27, 0x01,
    0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00,
];

const BLOCK1_START : u64 = 0x000000000;
const BLOCK2_START : u64 = 0x113000050;
const BLOCK3_START : u64 = 0x119400090;
const BLOCK4_START : u64 = 0x22c4000e0;

const BLOCK1_END : u64 = BLOCK1_START + BLOCK1_LENGTH - 1;
const BLOCK2_END : u64 = BLOCK2_START + BLOCK2_LENGTH - 2;
const BLOCK3_END : u64 = BLOCK3_START + BLOCK3_LENGTH - 3;
const BLOCK4_END : u64 = BLOCK4_START + BLOCK4_LENGTH - 4;

const TOTAL_LENGTH : u64 = BLOCK4_START + BLOCK4_LENGTH;

struct Zip64File {
    pointer: u64,
}

impl Zip64File {
    fn new() -> Self {
        Zip64File { pointer: 0 }
    }
}

impl Seek for Zip64File {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        match pos {
            SeekFrom::Start(offset) => { self.pointer = offset; },
            SeekFrom::End(offset) => {
                if offset > 0 || offset < -(TOTAL_LENGTH as i64) {
                    return Err(io::Error::new(io::ErrorKind::Other, "Invalid seek offset"));
                }
                self.pointer = (TOTAL_LENGTH as i64 + offset) as u64;
            },
            SeekFrom::Current(offset) => {
                let seekpos = self.pointer as i64 + offset;
                if seekpos < 0 || seekpos as u64 > TOTAL_LENGTH {
                    return Err(io::Error::new(io::ErrorKind::Other, "Invalid seek offset"));
                }
                self.pointer = seekpos as u64;
            },
        }
        Ok(self.pointer)
    }
}

impl Read for Zip64File {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.pointer >= TOTAL_LENGTH {
            return Ok(0);
        }
        match self.pointer {
            BLOCK1_START ... BLOCK1_END => {
                buf[0] = BLOCK1[(self.pointer - BLOCK1_START) as usize];
            },
            BLOCK2_START ... BLOCK2_END => {
                buf[0] = BLOCK2[(self.pointer - BLOCK2_START) as usize];
            },
            BLOCK3_START ... BLOCK3_END => {
                buf[0] = BLOCK3[(self.pointer - BLOCK3_START) as usize];
            },
            BLOCK4_START ... BLOCK4_END => {
                buf[0] = BLOCK4[(self.pointer - BLOCK4_START) as usize];
            },
            _ => {
                buf[0] = 0;
            },
        }
        self.pointer += 1;
        Ok(1)
    }
}

#[test]
fn zip64_large() {
    let zipfile = Zip64File::new();
    let mut archive = zip::ZipArchive::new(zipfile).unwrap();
    let mut buf = [0u8; 32];

    for i in 0..archive.len() {
        let mut file = archive.by_index(i).unwrap();
        let outpath = file.sanitized_name();
        println!("Entry {} has name \"{}\" ({} bytes)", i, outpath.as_path().display(), file.size());

        match file.read_exact(&mut buf) {
            Ok(()) => println!("The first {} bytes are: {:?}", buf.len(), buf),
            Err(e) => println!("Could not read the file: {:?}", e),
        };
    }
}
<|endoftext|>


<commit_before><commit_msg>Add async filtering example<commit_after>extern crate futures;
extern crate socketcan;
extern crate tokio;
use futures::stream::Stream;
use socketcan::bcm::async::*;
use socketcan::FrameFlags;
use std::time;

fn main() {
    let socket = CanBCMSocket::open_nb("vcan0").unwrap();
    let ival = time::Duration::from_millis(0);
    let f = socket
        .filter_id_incoming_frames(0x123, ival, ival, FrameFlags::empty())
        .unwrap()
        .map_err(|err| eprintln!("IO error {:?}", err))
        .for_each(|frame| {
            println!("Frame {:?}", frame);
            Ok(())
        });
    tokio::run(f);
}
<|endoftext|>