<commit_before>#![no_std]

pub trait BitfieldRegister {
    type Data;
    const REGISTER_SIZE: usize;
    fn data(&self) -> & Self::Data;
}

pub trait FromBitfield<Array> {
    fn from_bitfield(array:Array) -> Self;
}

pub trait IntoBitfield<Array> {
    fn into_bitfield(self) -> Array;
}

impl FromBitfield<[u8;1]> for u8 {
    fn from_bitfield(array: [u8;1]) -> Self {
        return array[0];
    }
}

impl IntoBitfield<[u8;1]> for u8 {
    fn into_bitfield(self) -> [u8;1]{
        return [self;1];
    }
}

impl FromBitfield<[u8;1]> for bool {
    fn from_bitfield(array: [u8;1]) -> Self {
        return (array[0] & 1) != 0;
    }
}

impl IntoBitfield<[u8;1]> for bool {
    fn into_bitfield(self) -> [u8;1]{
        // If you cast a bool into an integer, true will be 1 and false will be 0.
        // https://doc.rust-lang.org/std/primitive.bool.html
        return [self as u8;1];
    }
}

mod tests {
    use super::{FromBitfield, IntoBitfield};

    macro_rules! test_into {
        ($value:expr, $expected_array:expr) => (
            assert_eq!(
                $value.into_bitfield(),
                $expected_array
            );
        )
    }

    macro_rules! test_from {
        ($value_type:ty, $array_len:expr, $array:expr, $expected_value:expr) => (
            assert_eq!(
                <$value_type as FromBitfield<[u8;$array_len]>>::from_bitfield($array),
                $expected_value
            );
        )
    }

    #[test]
    fn bool_test() {
        test_into!(
            false,
            [0;1]
        );
        test_into!(
            true,
            [1;1]
        );

        test_from!(
            bool, 1,
            [0;1], false
        );
        test_from!(
            bool, 1,
            [1;1], true
        );
        test_from!(
            bool, 1,
            [0b11111110;1], false
        );
        test_from!(
            bool, 1,
            [0b11111111;1], true
        );
    }

    #[test]
    fn u8_test() {
        test_into!(
            (0 as u8),
            [0;1]
        );
        test_into!(
            (1 as u8),
            [1;1]
        );
        test_into!(
            (0xFF as u8),
            [0xFF;1]
        );

        test_from!(
            u8, 1,
            [0;1], 0
        );
        test_from!(
            u8, 1,
            [1;1], 1
        );
        test_from!(
            u8, 1,
            [0xFF;1], 0xFF
        );
    }
}<commit_msg>add into/from for u16,u32. Test only for u16<commit_after>#![no_std]

pub trait BitfieldRegister {
    type Data;
    const REGISTER_SIZE: usize;
    fn data(&self) -> & Self::Data;
}

pub trait FromBitfield<Array> {
    fn from_bitfield(array:Array) -> Self;
}

pub trait IntoBitfield<Array> {
    fn into_bitfield(self) -> Array;
}

// u8
impl FromBitfield<[u8;1]> for u8 {
    fn from_bitfield(array: [u8;1]) -> Self {
        return array[0];
    }
}

impl IntoBitfield<[u8;1]> for u8 {
    fn into_bitfield(self) -> [u8;1]{
        return [self;1];
    }
}

// u16
impl FromBitfield<[u8;2]> for u16 {
    fn from_bitfield(array: [u8;2]) -> Self {
        return
            (array[0] as u16) |
            (array[1] as u16) << 8;
    }
}

impl IntoBitfield<[u8;2]> for u16 {
    fn into_bitfield(self) -> [u8;2]{
        return [
            (self.0 & 0xFF) as u8,
            (self.0 >> 8 & 0xFF) as u8,
        ];
    }
}

// u32 :3
impl IntoBitfield<[u8;3]> for u32 {
    fn into_bitfield(self) -> [u8;3]{
        return [
            (self.0 & 0xFF) as u8,
            (self.0 >> 8 & 0xFF) as u8,
            (self.0 >> 16 & 0xFF) as u8,
        ];
    }
}

impl FromBitfield<[u8;3]> for u32 {
    fn from_bitfield(array: [u8;3]) -> Self {
        return
            (array[0] as u32)      |
            (array[1] as u32) << 8 |
            (array[2] as u32) << 16;
    }
}

// u32 :4
impl IntoBitfield<[u8;4]> for u32 {
    fn into_bitfield(self) -> [u8;4]{
        return [
            (self.0 & 0xFF) as u8,
            (self.0 >> 8 & 0xFF) as u8,
            (self.0 >> 16 & 0xFF) as u8,
            (self.0 >> 24 & 0xFF) as u8
        ];
    }
}

impl FromBitfield<[u8;4]> for u32 {
    fn from_bitfield(array: [u8;4]) -> Self {
        return
            (array[0] as u32)       |
            (array[1] as u32) << 8  |
            (array[2] as u32) << 16 |
            (array[3] as u32) << 24;

    }
}

impl FromBitfield<[u8;1]> for bool {
    fn from_bitfield(array: [u8;1]) -> Self {
        return (array[0] & 1) != 0;
    }
}

impl IntoBitfield<[u8;1]> for bool {
    fn into_bitfield(self) -> [u8;1]{
        // If you cast a bool into an integer, true will be 1 and false will be 0.
        // https://doc.rust-lang.org/std/primitive.bool.html
        return [self as u8;1];
    }
}

mod tests {
    use super::{FromBitfield, IntoBitfield};

    macro_rules! test_into {
        ($value:expr, $expected_array:expr) => (
            assert_eq!(
                $value.into_bitfield(),
                $expected_array
            );
        )
    }

    macro_rules! test_from {
        ($value_type:ty, $array_len:expr, $array:expr, $expected_value:expr) => (
            assert_eq!(
                <$value_type as FromBitfield<[u8;$array_len]>>::from_bitfield($array),
                $expected_value
            );
        )
    }

    #[test]
    fn bool_test() {
        test_into!(
            false,
            [0;1]
        );
        test_into!(
            true,
            [1;1]
        );

        test_from!(
            bool, 1,
            [0;1], false
        );
        test_from!(
            bool, 1,
            [1;1], true
        );
        test_from!(
            bool, 1,
            [0b11111110;1], false
        );
        test_from!(
            bool, 1,
            [0b11111111;1], true
        );
    }

    #[test]
    fn u8_test() {
        test_into!(
            (0 as u8),
            [0;1]
        );
        test_into!(
            (1 as u8),
            [1;1]
        );
        test_into!(
            (0xFF as u8),
            [0xFF;1]
        );

        test_from!(
            u8, 1,
            [0;1], 0
        );
        test_from!(
            u8, 1,
            [1;1], 1
        );
        test_from!(
            u8, 1,
            [0xFF;1], 0xFF
        );
    }

    #[test]
    fn u16_test() {
        test_into!(
            (0 as u16),
            { static x = &[0x00u8, 0x00u8]; &x },
        );
        test_into!(
            (1 as u16),
            { static x = &[0x01u8, 0x00u8]; &x },
        );
        test_into!(
            (0xFF as u16),
            { static x = &[0xFFu8, 0x00u8]; &x },
        );

        test_from!(
            u16, 2,
            { static x = &[0x00u8, 0x00u8]; &x }, 0
        );
        test_from!(
            u16, 2,
            { static x = &[0x01u8, 0x00u8]; &x },, 1
        );
        test_from!(
            u16, 2,
            { static x = &[0xFFu8, 0x00u8]; &x }, 0xFF
        );
    }
}<|endoftext|>


<commit_before>use std::cell::RefCell;
use std::borrow::Cow;

thread_local! {
    static TL_BUF: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(128))
}

/// Logger
///
/// Loggers are thread-safe and reference counted, so can be freely
/// passed around the code.
///
/// Each logger is built with a set of key-values.
///
/// Child loggers are build from existing loggers, and copy
/// all the key-values from their parents
///
/// Loggers form hierarchies sharing a drain. Setting a drain on
/// any logger will change it on all loggers in given hierarchy.
#[derive(Clone)]
pub struct Logger {
    drain: Arc<Drain>,
    values: Arc<OwnedKeyValueList>,
}

/// A type that can be translated into `Msg`
pub trait IntoMsg {
    /// Convert to the `&str`
    fn as_str(&self) -> Cow<str>;
}

// TODO: why does this conflict with &'a str?
// impl<T : AsRef<str>> IntoMsg for T {
// fn as_str(&self) -> Cow<str> {
// Cow::Borrowed(self.as_ref())
// }
// }
//

impl<'a> IntoMsg for &'a str {
    fn as_str(&self) -> Cow<str> {
        Cow::Borrowed(self)
    }
}

impl<'a> IntoMsg for String {
    fn as_str(&self) -> Cow<str> {
        Cow::Borrowed(self.as_str())
    }
}

impl<'a> IntoMsg for fmt::Arguments<'a> {
    fn as_str(&self) -> Cow<str> {
        let mut s = String::new();
        fmt::write(&mut s, *self).unwrap();
        Cow::Owned(s)
    }
}

impl Logger {
    /// Build a root logger
    ///
    /// All children and their children and so on form one hierarchy
    /// sharing a common drain.
    ///
    /// Use `o!` macro to help build `values`
    ///
    /// ```
    /// #[macro_use]
    /// extern crate slog;
    ///
    /// fn main() {
    ///     let root = slog::Logger::root(
    ///         slog::discard(),
    ///         o!("key1" => "value1", "key2" => "value2"),
    ///     );
    /// }
    pub fn root<D: 'static + Drain + Sized>(d: D, values: Vec<OwnedKeyValue>) -> Logger {
        Logger {
            drain: Arc::new(d),
            values: Arc::new(OwnedKeyValueList::root(values)),
        }
    }

    /// Build a child logger
    ///
    /// Child logger copies all existing values from the parent.
    ///
    /// All children, their children and so on, form one hierarchy sharing
    /// a common drain.
    ///
    /// Use `o!` macro to help build `values`
    ///
    /// ```
    /// #[macro_use]
    /// extern crate slog;
    ///
    /// fn main() {
    ///     let root = slog::Logger::root(slog::discard(),
    ///         o!("key1" => "value1", "key2" => "value2"));
    ///     let log = root.new(o!("key" => "value"));
    /// }
    pub fn new(&self, values: Vec<OwnedKeyValue>) -> Logger {
        Logger {
            drain: self.drain.clone(),
            values: Arc::new(OwnedKeyValueList::new(values, self.values.clone())),
        }
    }

    /// Log one logging record
    ///
    /// Use specific logging functions instead.
    pub fn log(&self, record: &Record) {

        // By default errors in loggers are ignored
        TL_BUF.with(|buf| {
            let mut buf = buf.borrow_mut();
            let _ = self.drain.log(&mut *buf, &record, &*self.values);
            // TODO: Double check if this will not zero the old bytes as it costs time
            debug_assert!(buf.is_empty());
        });
    }
}

/// Logging record
pub struct Record<'a> {
    /// Lazily initialized timestamp
    ///
    /// Since getting current time requires a
    /// syscall and most log records won't make it to the final drain it will be
    /// delayed until ts is actually needed.
    ts: RefCell<Option<chrono::DateTime<chrono::UTC>>>,
    /// Logging level
    level: Level,
    /// Message
    msg: &'a IntoMsg,
    /// File
    file: &'a str,
    /// Line
    line: u32,
    /// Module
    module: &'a str,
    /// Values
    values: &'a [BorrowedKeyValue<'a>],
}

impl<'a> Record<'a> {
    /// Create a new `Record`
    #[inline]
    pub fn new(level: Level,
               msg: &'a IntoMsg,
               file: &'a str,
               line: u32,
               module: &'a str,
               values: &'a [BorrowedKeyValue<'a>])
               -> Self {
        Record {
            ts: RefCell::new(None),
            level: level,
            msg: msg,
            file: file,
            line: line,
            module: module,
            values: values,
        }
    }

    /// Timestamp
    ///
    /// Lazily evaluated timestamp
    pub fn ts(&self) -> chrono::DateTime<chrono::UTC> {
        let mut ts = self.ts.borrow_mut();
        match *ts {
            None => {
                let now = chrono::UTC::now();
                *ts = Some(now);
                now
            }
            Some(ts) => ts,
        }
    }

    /// Set timestamp
    ///
    /// Useful for manually forcing timestamp value (eg. in testing).
    pub fn set_ts(&self, ts: chrono::DateTime<chrono::UTC>) {
        *self.ts.borrow_mut() = Some(ts);
    }

    /// Get a log record message
    pub fn msg(&self) -> Cow<str> {
        self.msg.as_str()
    }

    /// Get record logging level
    pub fn level(&self) -> Level {
        self.level
    }

    /// Get line number
    pub fn line(&self) -> u32 {
        self.line
    }

    /// Get file path
    pub fn file(&self) -> &str {
        self.file

    }

    /// Get module
    pub fn module(&self) -> &str {
        self.module
    }

    /// Record value-key pairs
    pub fn values(&self) -> &'a [BorrowedKeyValue<'a>] {
        self.values
    }
}
<commit_msg>Change `IntoMsg` into `Message`<commit_after>use std::cell::RefCell;
use std::borrow::Cow;
use std::io::Write;

thread_local! {
    static TL_BUF: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(128))
}

/// Logger
///
/// Loggers are thread-safe and reference counted, so can be freely
/// passed around the code.
///
/// Each logger is built with a set of key-values.
///
/// Child loggers are build from existing loggers, and copy
/// all the key-values from their parents
///
/// Loggers form hierarchies sharing a drain. Setting a drain on
/// any logger will change it on all loggers in given hierarchy.
#[derive(Clone)]
pub struct Logger {
    drain: Arc<Drain>,
    values: Arc<OwnedKeyValueList>,
}

/// Log Record message
pub trait Message {
    /// Take a string
    fn as_str(&self) -> Cow<str>;

    /// Write it into `io` (which might be fast than `as_str()` it does not
    /// need to allocate anything in certain cases.
    fn write_to(&self, io : &mut Write) -> Result<()> {
        try!(write!(io, "{}", self.as_str()));
        Ok(())
    }

}

// TODO: why does this conflict with &'a str?
// impl<T : AsRef<str>> Into<Cow<'a, str>> for T {
// fn as_str(&self) -> Cow<str> {
// Cow::Borrowed(self.as_ref())
// }
// }
//

impl<'a> Message for &'a str {
    fn as_str(&self) -> Cow<str> {
        Cow::Borrowed(self)
    }
}

impl Message for String {
    fn as_str(&self) -> Cow<str> {
        Cow::Borrowed(self.as_str())
    }
}

impl<'a> Message for fmt::Arguments<'a> {
    fn as_str(&self) -> Cow<str> {
        let mut s = String::new();
        fmt::write(&mut s, *self).unwrap();
        Cow::Owned(s)
    }

    fn write_to(&self, io : &mut Write) -> Result<()> {
        try!(write!(io, "{}", self));
        Ok(())
    }
}

impl Logger {
    /// Build a root logger
    ///
    /// All children and their children and so on form one hierarchy
    /// sharing a common drain.
    ///
    /// Use `o!` macro to help build `values`
    ///
    /// ```
    /// #[macro_use]
    /// extern crate slog;
    ///
    /// fn main() {
    ///     let root = slog::Logger::root(
    ///         slog::discard(),
    ///         o!("key1" => "value1", "key2" => "value2"),
    ///     );
    /// }
    pub fn root<D: 'static + Drain + Sized>(d: D, values: Vec<OwnedKeyValue>) -> Logger {
        Logger {
            drain: Arc::new(d),
            values: Arc::new(OwnedKeyValueList::root(values)),
        }
    }

    /// Build a child logger
    ///
    /// Child logger copies all existing values from the parent.
    ///
    /// All children, their children and so on, form one hierarchy sharing
    /// a common drain.
    ///
    /// Use `o!` macro to help build `values`
    ///
    /// ```
    /// #[macro_use]
    /// extern crate slog;
    ///
    /// fn main() {
    ///     let root = slog::Logger::root(slog::discard(),
    ///         o!("key1" => "value1", "key2" => "value2"));
    ///     let log = root.new(o!("key" => "value"));
    /// }
    pub fn new(&self, values: Vec<OwnedKeyValue>) -> Logger {
        Logger {
            drain: self.drain.clone(),
            values: Arc::new(OwnedKeyValueList::new(values, self.values.clone())),
        }
    }

    /// Log one logging record
    ///
    /// Use specific logging functions instead.
    pub fn log(&self, record: &Record) {

        // By default errors in loggers are ignored
        TL_BUF.with(|buf| {
            let mut buf = buf.borrow_mut();
            let _ = self.drain.log(&mut *buf, &record, &*self.values);
            // TODO: Double check if this will not zero the old bytes as it costs time
            debug_assert!(buf.is_empty());
        });
    }
}

/// Logging record
pub struct Record<'a> {
    /// Lazily initialized timestamp
    ///
    /// Since getting current time requires a
    /// syscall and most log records won't make it to the final drain it will be
    /// delayed until ts is actually needed.
    ts: RefCell<Option<chrono::DateTime<chrono::UTC>>>,
    /// Logging level
    level: Level,
    /// Message
    msg: &'a Message,
    /// File
    file: &'a str,
    /// Line
    line: u32,
    /// Module
    module: &'a str,
    /// Values
    values: &'a [BorrowedKeyValue<'a>],
}

impl<'a> Record<'a> {
    /// Create a new `Record`
    #[inline]
    pub fn new(level: Level,
               msg: &'a Message,
               file: &'a str,
               line: u32,
               module: &'a str,
               values: &'a [BorrowedKeyValue<'a>])
               -> Self {
        Record {
            ts: RefCell::new(None),
            level: level,
            msg: msg,
            file: file,
            line: line,
            module: module,
            values: values,
        }
    }

    /// Timestamp
    ///
    /// Lazily evaluated timestamp
    pub fn ts(&self) -> chrono::DateTime<chrono::UTC> {
        let mut ts = self.ts.borrow_mut();
        match *ts {
            None => {
                let now = chrono::UTC::now();
                *ts = Some(now);
                now
            }
            Some(ts) => ts,
        }
    }

    /// Set timestamp
    ///
    /// Useful for manually forcing timestamp value (eg. in testing).
    pub fn set_ts(&self, ts: chrono::DateTime<chrono::UTC>) {
        *self.ts.borrow_mut() = Some(ts);
    }

    /// Get a log record message
    pub fn msg(&self) -> Cow<str> {
        self.msg.as_str()
    }

    /// Get record logging level
    pub fn level(&self) -> Level {
        self.level
    }

    /// Get line number
    pub fn line(&self) -> u32 {
        self.line
    }

    /// Get file path
    pub fn file(&self) -> &str {
        self.file

    }

    /// Get module
    pub fn module(&self) -> &str {
        self.module
    }

    /// Record value-key pairs
    pub fn values(&self) -> &'a [BorrowedKeyValue<'a>] {
        self.values
    }
}
<|endoftext|>


<commit_before>use std::iter::repeat;
use std::collections::VecDeque;
use std::collections::BinaryHeap;
use std::cmp::Ordering;

fn max(a: u32, b: u32) -> u32 { if a > b { a } else { b } }

#[derive(Clone)]
struct Edge {
    vertex: u32,
    weight: f32,
}

impl Edge {
    pub fn new(vertex_: u32, weight_: f32) -> Edge {
        Edge{vertex: vertex_, weight: weight_,}
    }
}

impl Ord for Edge {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl Eq for Edge {}

impl PartialOrd for Edge {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        (self.weight, self.vertex).partial_cmp(&(other.weight, other.vertex))
    }
}

impl PartialEq for Edge {
    fn eq(&self, other: &Self) -> bool {
        (self.weight, &self.vertex) == (other.weight, &other.vertex)
    }
}

struct Graph {
    nodes: Vec<Vec<Edge>>,
}

impl Graph {
    pub fn new() -> Graph { Graph{nodes: Vec::new(),} }

    pub fn add_edge(&mut self, src: u32, dst: u32, weight: f32) {
        let len = self.nodes.len();

        if (max(src, dst)) > len as u32 {
            let new_len = (max(src, dst) + 1) as usize;
            self.nodes.extend(repeat(Vec::new()).take(new_len - len))
        }
        self.nodes[src as usize].push(Edge::new(dst, weight));
    }
    pub fn bfs(&self, src: u32) {
        let mut queue: VecDeque<u32> = VecDeque::new();
        let len = self.nodes.len();
        let mut visited = vec!(false ; len);

        queue.push_front(src);

        while let Some(current) = queue.pop_back() {
            if !visited[current as usize] {
                println!("current: {}" , current);
                visited[current as usize] = true;
            } else { continue ; }

            for n in &self.nodes[current as usize] {
                let neighbor: u32 = n.vertex;
                queue.push_front(neighbor);
            }
        }
    }
    pub fn dfs(&self, src: u32) {
        let mut stack: Vec<u32> = Vec::new();
        let len = self.nodes.len() as usize;
        let mut visited = vec!(false ; len);

        stack.push(src);

        while let Some(current) = stack.pop() {
            if !visited[current as usize] {
                println!("current: {}" , current);
                visited[current as usize] = true;
            } else { continue ; }

            for n in &self.nodes[current as usize] {
                let neighbor: u32 = n.vertex;
                stack.push(neighbor);
            }
        }
    }

    pub fn dijkstra(&self, src: u32, dst: u32) {
      let mut dist: Vec<f32> = Vec::new();
      let mut prev: Vec<u32> = Vec::new();
      let mut q = BinaryHeap::new();
      const max_weight: f32 = std::f32::MAX;

      // init dist, prev table
      for i in 0..self.nodes.len() {
        dist.push(max_weight);
        prev.push(0);
      }

      // We're at `start`, with a zero cost
      dist[src as usize] = 0.0;
      q.push(Edge::new(src, dist[src as usize]));

      //while (!q.is_empty()) {
      while let Some(u) = q.pop() {
        //let u: Edge = el.unwrap();

        // loop for all edges connected to
        for v in self.nodes[u.vertex as usize].iter() {

          let alt: f32 = dist[u.vertex as usize] + v.weight; // accumulate shortest dist from source

          if (alt < dist[v.vertex as usize]) {
            dist[v.vertex as usize] = alt; // keep the shortest dist from src to v
            prev[v.vertex as usize] = u.vertex;

            q.push(Edge::new(v.vertex, dist[v.vertex as usize])); // Add unvisited v into the Q to be processed
          }
        }
      }

      let mut shortestPath: Vec<u32> = Vec::new();
      let mut curr: u32 = dst;

      shortestPath.push(curr);

      while (curr != src) {
        curr = prev[curr as usize];
        shortestPath.push(curr);
      }

      shortestPath.reverse();

      for v in shortestPath.iter() {
        println!("{}", v);
      }
    }
}

fn main() {
    let mut g1 = Graph::new();
    g1.add_edge(0, 1, 1.0);
    g1.add_edge(0, 2, 4.0);
    g1.add_edge(1, 0, 1.0);
    g1.add_edge(1, 2, 2.0);
    g1.add_edge(1, 3, 6.0);
    g1.add_edge(2, 0, 4.0);
    g1.add_edge(2, 1, 2.0);
    g1.add_edge(2, 3, 3.0);
    g1.add_edge(3, 1, 6.0);
    g1.add_edge(3, 2, 3.0);

    g1.bfs(3);

    println!("\n");

    g1.dfs(3);

    g1.dijkstra(0, 2);
}<commit_msg>fixed println<commit_after>use std::iter::repeat;
use std::collections::VecDeque;
use std::collections::BinaryHeap;
use std::cmp::Ordering;

fn max(a: u32, b: u32) -> u32 { if a > b { a } else { b } }

#[derive(Clone)]
struct Edge {
    vertex: u32,
    weight: f32,
}

impl Edge {
    pub fn new(vertex_: u32, weight_: f32) -> Edge {
        Edge{vertex: vertex_, weight: weight_,}
    }
}

impl Ord for Edge {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl Eq for Edge {}

impl PartialOrd for Edge {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        (self.weight, self.vertex).partial_cmp(&(other.weight, other.vertex))
    }
}

impl PartialEq for Edge {
    fn eq(&self, other: &Self) -> bool {
        (self.weight, &self.vertex) == (other.weight, &other.vertex)
    }
}

struct Graph {
    nodes: Vec<Vec<Edge>>,
}

impl Graph {
    pub fn new() -> Graph { Graph{nodes: Vec::new(),} }

    pub fn add_edge(&mut self, src: u32, dst: u32, weight: f32) {
        let len = self.nodes.len();

        if (max(src, dst)) > len as u32 {
            let new_len = (max(src, dst) + 1) as usize;
            self.nodes.extend(repeat(Vec::new()).take(new_len - len))
        }
        self.nodes[src as usize].push(Edge::new(dst, weight));
    }
    pub fn bfs(&self, src: u32) {
        let mut queue: VecDeque<u32> = VecDeque::new();
        let len = self.nodes.len();
        let mut visited = vec!(false ; len);

        queue.push_front(src);

        while let Some(current) = queue.pop_back() {
            if !visited[current as usize] {
                println!("current: {}" , current);
                visited[current as usize] = true;
            } else { continue ; }

            for n in &self.nodes[current as usize] {
                let neighbor: u32 = n.vertex;
                queue.push_front(neighbor);
            }
        }
    }
    pub fn dfs(&self, src: u32) {
        let mut stack: Vec<u32> = Vec::new();
        let len = self.nodes.len() as usize;
        let mut visited = vec!(false ; len);

        stack.push(src);

        while let Some(current) = stack.pop() {
            if !visited[current as usize] {
                println!("current: {}" , current);
                visited[current as usize] = true;
            } else { continue ; }

            for n in &self.nodes[current as usize] {
                let neighbor: u32 = n.vertex;
                stack.push(neighbor);
            }
        }
    }

    pub fn dijkstra(&self, src: u32, dst: u32) {
      let mut dist: Vec<f32> = Vec::new();
      let mut prev: Vec<u32> = Vec::new();
      let mut q = BinaryHeap::new();
      const max_weight: f32 = std::f32::MAX;

      // init dist, prev table
      for i in 0..self.nodes.len() {
        dist.push(max_weight);
        prev.push(0);
      }

      // We're at `start`, with a zero cost
      dist[src as usize] = 0.0;
      q.push(Edge::new(src, dist[src as usize]));

      //while (!q.is_empty()) {
      while let Some(u) = q.pop() {
        //let u: Edge = el.unwrap();

        // loop for all edges connected to
        for v in self.nodes[u.vertex as usize].iter() {

          let alt: f32 = dist[u.vertex as usize] + v.weight; // accumulate shortest dist from source

          if (alt < dist[v.vertex as usize]) {
            dist[v.vertex as usize] = alt; // keep the shortest dist from src to v
            prev[v.vertex as usize] = u.vertex;

            q.push(Edge::new(v.vertex, dist[v.vertex as usize])); // Add unvisited v into the Q to be processed
          }
        }
      }

      let mut shortestPath: Vec<u32> = Vec::new();
      let mut curr: u32 = dst;

      shortestPath.push(curr);

      while (curr != src) {
        curr = prev[curr as usize];
        shortestPath.push(curr);
      }

      shortestPath.reverse();

      for v in shortestPath.iter() {
        println!("{}", v);
      }
    }
}

fn main() {
    let mut g1 = Graph::new();
    g1.add_edge(0, 1, 1.0);
    g1.add_edge(0, 2, 4.0);
    g1.add_edge(1, 0, 1.0);
    g1.add_edge(1, 2, 2.0);
    g1.add_edge(1, 3, 6.0);
    g1.add_edge(2, 0, 4.0);
    g1.add_edge(2, 1, 2.0);
    g1.add_edge(2, 3, 3.0);
    g1.add_edge(3, 1, 6.0);
    g1.add_edge(3, 2, 3.0);

    g1.bfs(3);

    println!("");

    g1.dfs(3);

    println!("");

    g1.dijkstra(0, 3);
}<|endoftext|>


<commit_before>use crate::utils::{iter_input_pats, snippet, span_lint, type_is_unsafe_function};
use matches::matches;
use rustc::hir;
use rustc::hir::def::Def;
use rustc::hir::intravisit;
use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
use rustc::ty;
use rustc::{declare_tool_lint, lint_array};
use rustc_data_structures::fx::FxHashSet;
use rustc_target::spec::abi::Abi;
use syntax::ast;
use syntax::source_map::Span;

/// **What it does:** Checks for functions with too many parameters.
///
/// **Why is this bad?** Functions with lots of parameters are considered bad
/// style and reduce readability (“what does the 5th parameter mean?”). Consider
/// grouping some parameters into a new type.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
///     ..
/// }
/// ```
declare_clippy_lint! {
    pub TOO_MANY_ARGUMENTS,
    complexity,
    "functions with too many arguments"
}

/// **What it does:** Checks for functions with a large amount of lines.
///
/// **Why is this bad?** Functions with a lot of lines are harder to understand
/// due to having to look at a larger amount of code to understand what the
/// function is doing. Consider splitting the body of the function into
/// multiple functions.
///
/// **Known problems:** None.
///
/// **Example:**
/// ``` rust
/// fn im_too_long() {
/// println!("");
/// // ... 100 more LoC
/// println!("");
/// }
/// ```
declare_clippy_lint! {
    pub TOO_MANY_LINES,
    pedantic,
    "functions with too many lines"
}

/// **What it does:** Checks for public functions that dereferences raw pointer
/// arguments but are not marked unsafe.
///
/// **Why is this bad?** The function should probably be marked `unsafe`, since
/// for an arbitrary raw pointer, there is no way of telling for sure if it is
/// valid.
///
/// **Known problems:**
///
/// * It does not check functions recursively so if the pointer is passed to a
/// private non-`unsafe` function which does the dereferencing, the lint won't
/// trigger.
/// * It only checks for arguments whose type are raw pointers, not raw pointers
/// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
/// `some_argument.get_raw_ptr()`).
///
/// **Example:**
/// ```rust
/// pub fn foo(x: *const u8) {
///     println!("{}", unsafe { *x });
/// }
/// ```
declare_clippy_lint! {
    pub NOT_UNSAFE_PTR_ARG_DEREF,
    correctness,
    "public functions dereferencing raw pointer arguments but not marked `unsafe`"
}

#[derive(Copy, Clone)]
pub struct Functions {
    threshold: u64,
    max_lines: u64,
}

impl Functions {
    pub fn new(threshold: u64, max_lines: u64) -> Self {
        Self {
            threshold,
            max_lines
        }
    }
}

impl LintPass for Functions {
    fn get_lints(&self) -> LintArray {
        lint_array!(TOO_MANY_ARGUMENTS, TOO_MANY_LINES, NOT_UNSAFE_PTR_ARG_DEREF)
    }

    fn name(&self) -> &'static str {
        "Functions"
    }
}

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
    fn check_fn(
        &mut self,
        cx: &LateContext<'a, 'tcx>,
        kind: intravisit::FnKind<'tcx>,
        decl: &'tcx hir::FnDecl,
        body: &'tcx hir::Body,
        span: Span,
        nodeid: ast::NodeId,
    ) {
        let is_impl = if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(nodeid)) {
            matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
        } else {
            false
        };

        let unsafety = match kind {
            hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
            hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
            hir::intravisit::FnKind::Closure(_) => return,
        };

        // don't warn for implementations, it's not their fault
        if !is_impl {
            // don't lint extern functions decls, it's not their fault either
            match kind {
                hir::intravisit::FnKind::Method(
                    _,
                    &hir::MethodSig {
                        header: hir::FnHeader { abi: Abi::Rust, .. },
                        ..
                    },
                    _,
                    _,
                )
                | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
                    self.check_arg_number(cx, decl, span)
                },
                _ => {},
            }
        }

        self.check_raw_ptr(cx, unsafety, decl, body, nodeid);
        self.check_line_number(cx, span);
    }

    fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
        if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
            // don't lint extern functions decls, it's not their fault
            if sig.header.abi == Abi::Rust {
                self.check_arg_number(cx, &sig.decl, item.span);
            }

            if let hir::TraitMethod::Provided(eid) = *eid {
                let body = cx.tcx.hir().body(eid);
                self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.id);
            }
        }
    }
}

impl<'a, 'tcx> Functions {
    fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, span: Span) {
        let args = decl.inputs.len() as u64;
        if args > self.threshold {
            span_lint(
                cx,
                TOO_MANY_ARGUMENTS,
                span,
                &format!("this function has too many arguments ({}/{})", args, self.threshold),
            );
        }
    }

    fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span) {
        if in_external_macro(cx.sess(), span) {
            return;
        }

        let code_snippet = snippet(cx, span, "..");
        let mut line_count: u64 = 0;
        let mut in_comment = false;
        let mut code_in_line;

        // Skip the surrounding function decl.
        let start_brace_idx = match code_snippet.find("{") {
            Some(i) => i + 1,
            None => 0,
        };
        let end_brace_idx = match code_snippet.find("}") {
            Some(i) => i,
            None => code_snippet.len(),
        };
        let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();

        for mut line in function_lines {
            code_in_line = false;
            loop {
                line = line.trim_start();
                if line.is_empty() {
                    break;
                }
                if in_comment {
                    match line.find("*/") {
                        Some(i) => {
                            line = &line[i + 2..];
                            in_comment = false;
                            continue;
                        },
                        None => break,
                    }
                } else {
                    let multi_idx = match line.find("/*") {
                        Some(i) => i,
                        None => line.len(),
                    };
                    let single_idx = match line.find("//") {
                        Some(i) => i,
                        None => line.len(),
                    };
                    code_in_line |= multi_idx > 0 && single_idx > 0;
                    // Implies multi_idx is below line.len()
                    if multi_idx < single_idx {
                        line = &line[multi_idx + 2..];
                        in_comment = true;
                        continue;
                    }
                    break;
                }
            }
            if code_in_line {
                line_count += 1;
            }
        }

        if line_count > self.max_lines {
            span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
        }
    }

    fn check_raw_ptr(
        self,
        cx: &LateContext<'a, 'tcx>,
        unsafety: hir::Unsafety,
        decl: &'tcx hir::FnDecl,
        body: &'tcx hir::Body,
        nodeid: ast::NodeId,
    ) {
        let expr = &body.value;
        if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
            let raw_ptrs = iter_input_pats(decl, body)
                .zip(decl.inputs.iter())
                .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
                .collect::<FxHashSet<_>>();

            if !raw_ptrs.is_empty() {
                let tables = cx.tcx.body_tables(body.id());
                let mut v = DerefVisitor {
                    cx,
                    ptrs: raw_ptrs,
                    tables,
                };

                hir::intravisit::walk_expr(&mut v, expr);
            }
        }
    }
}

fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<ast::NodeId> {
    if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
        Some(id)
    } else {
        None
    }
}

struct DerefVisitor<'a, 'tcx: 'a> {
    cx: &'a LateContext<'a, 'tcx>,
    ptrs: FxHashSet<ast::NodeId>,
    tables: &'a ty::TypeckTables<'tcx>,
}

impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
    fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
        match expr.node {
            hir::ExprKind::Call(ref f, ref args) => {
                let ty = self.tables.expr_ty(f);

                if type_is_unsafe_function(self.cx, ty) {
                    for arg in args {
                        self.check_arg(arg);
                    }
                }
            },
            hir::ExprKind::MethodCall(_, _, ref args) => {
                let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
                let base_type = self.cx.tcx.type_of(def_id);

                if type_is_unsafe_function(self.cx, base_type) {
                    for arg in args {
                        self.check_arg(arg);
                    }
                }
            },
            hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
            _ => (),
        }

        hir::intravisit::walk_expr(self, expr);
    }
    fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
        intravisit::NestedVisitorMap::None
    }
}

impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
    fn check_arg(&self, ptr: &hir::Expr) {
        if let hir::ExprKind::Path(ref qpath) = ptr.node {
            if let Def::Local(id) = self.cx.tables.qpath_def(qpath, ptr.hir_id) {
                if self.ptrs.contains(&id) {
                    span_lint(
                        self.cx,
                        NOT_UNSAFE_PTR_ARG_DEREF,
                        ptr.span,
                        "this public function dereferences a raw pointer but is not marked `unsafe`",
                    );
                }
            }
        }
    }
}
<commit_msg>rustfmt<commit_after>use crate::utils::{iter_input_pats, snippet, span_lint, type_is_unsafe_function};
use matches::matches;
use rustc::hir;
use rustc::hir::def::Def;
use rustc::hir::intravisit;
use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
use rustc::ty;
use rustc::{declare_tool_lint, lint_array};
use rustc_data_structures::fx::FxHashSet;
use rustc_target::spec::abi::Abi;
use syntax::ast;
use syntax::source_map::Span;

/// **What it does:** Checks for functions with too many parameters.
///
/// **Why is this bad?** Functions with lots of parameters are considered bad
/// style and reduce readability (“what does the 5th parameter mean?”). Consider
/// grouping some parameters into a new type.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
///     ..
/// }
/// ```
declare_clippy_lint! {
    pub TOO_MANY_ARGUMENTS,
    complexity,
    "functions with too many arguments"
}

/// **What it does:** Checks for functions with a large amount of lines.
///
/// **Why is this bad?** Functions with a lot of lines are harder to understand
/// due to having to look at a larger amount of code to understand what the
/// function is doing. Consider splitting the body of the function into
/// multiple functions.
///
/// **Known problems:** None.
///
/// **Example:**
/// ``` rust
/// fn im_too_long() {
/// println!("");
/// // ... 100 more LoC
/// println!("");
/// }
/// ```
declare_clippy_lint! {
    pub TOO_MANY_LINES,
    pedantic,
    "functions with too many lines"
}

/// **What it does:** Checks for public functions that dereferences raw pointer
/// arguments but are not marked unsafe.
///
/// **Why is this bad?** The function should probably be marked `unsafe`, since
/// for an arbitrary raw pointer, there is no way of telling for sure if it is
/// valid.
///
/// **Known problems:**
///
/// * It does not check functions recursively so if the pointer is passed to a
/// private non-`unsafe` function which does the dereferencing, the lint won't
/// trigger.
/// * It only checks for arguments whose type are raw pointers, not raw pointers
/// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
/// `some_argument.get_raw_ptr()`).
///
/// **Example:**
/// ```rust
/// pub fn foo(x: *const u8) {
///     println!("{}", unsafe { *x });
/// }
/// ```
declare_clippy_lint! {
    pub NOT_UNSAFE_PTR_ARG_DEREF,
    correctness,
    "public functions dereferencing raw pointer arguments but not marked `unsafe`"
}

#[derive(Copy, Clone)]
pub struct Functions {
    threshold: u64,
    max_lines: u64,
}

impl Functions {
    pub fn new(threshold: u64, max_lines: u64) -> Self {
        Self { threshold, max_lines }
    }
}

impl LintPass for Functions {
    fn get_lints(&self) -> LintArray {
        lint_array!(TOO_MANY_ARGUMENTS, TOO_MANY_LINES, NOT_UNSAFE_PTR_ARG_DEREF)
    }

    fn name(&self) -> &'static str {
        "Functions"
    }
}

impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
    fn check_fn(
        &mut self,
        cx: &LateContext<'a, 'tcx>,
        kind: intravisit::FnKind<'tcx>,
        decl: &'tcx hir::FnDecl,
        body: &'tcx hir::Body,
        span: Span,
        nodeid: ast::NodeId,
    ) {
        let is_impl = if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(nodeid)) {
            matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
        } else {
            false
        };

        let unsafety = match kind {
            hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
            hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
            hir::intravisit::FnKind::Closure(_) => return,
        };

        // don't warn for implementations, it's not their fault
        if !is_impl {
            // don't lint extern functions decls, it's not their fault either
            match kind {
                hir::intravisit::FnKind::Method(
                    _,
                    &hir::MethodSig {
                        header: hir::FnHeader { abi: Abi::Rust, .. },
                        ..
                    },
                    _,
                    _,
                )
                | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
                    self.check_arg_number(cx, decl, span)
                },
                _ => {},
            }
        }

        self.check_raw_ptr(cx, unsafety, decl, body, nodeid);
        self.check_line_number(cx, span);
    }

    fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
        if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
            // don't lint extern functions decls, it's not their fault
            if sig.header.abi == Abi::Rust {
                self.check_arg_number(cx, &sig.decl, item.span);
            }

            if let hir::TraitMethod::Provided(eid) = *eid {
                let body = cx.tcx.hir().body(eid);
                self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.id);
            }
        }
    }
}

impl<'a, 'tcx> Functions {
    fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, span: Span) {
        let args = decl.inputs.len() as u64;
        if args > self.threshold {
            span_lint(
                cx,
                TOO_MANY_ARGUMENTS,
                span,
                &format!("this function has too many arguments ({}/{})", args, self.threshold),
            );
        }
    }

    fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span) {
        if in_external_macro(cx.sess(), span) {
            return;
        }

        let code_snippet = snippet(cx, span, "..");
        let mut line_count: u64 = 0;
        let mut in_comment = false;
        let mut code_in_line;

        // Skip the surrounding function decl.
        let start_brace_idx = match code_snippet.find("{") {
            Some(i) => i + 1,
            None => 0,
        };
        let end_brace_idx = match code_snippet.find("}") {
            Some(i) => i,
            None => code_snippet.len(),
        };
        let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();

        for mut line in function_lines {
            code_in_line = false;
            loop {
                line = line.trim_start();
                if line.is_empty() {
                    break;
                }
                if in_comment {
                    match line.find("*/") {
                        Some(i) => {
                            line = &line[i + 2..];
                            in_comment = false;
                            continue;
                        },
                        None => break,
                    }
                } else {
                    let multi_idx = match line.find("/*") {
                        Some(i) => i,
                        None => line.len(),
                    };
                    let single_idx = match line.find("//") {
                        Some(i) => i,
                        None => line.len(),
                    };
                    code_in_line |= multi_idx > 0 && single_idx > 0;
                    // Implies multi_idx is below line.len()
                    if multi_idx < single_idx {
                        line = &line[multi_idx + 2..];
                        in_comment = true;
                        continue;
                    }
                    break;
                }
            }
            if code_in_line {
                line_count += 1;
            }
        }

        if line_count > self.max_lines {
            span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
        }
    }

    fn check_raw_ptr(
        self,
        cx: &LateContext<'a, 'tcx>,
        unsafety: hir::Unsafety,
        decl: &'tcx hir::FnDecl,
        body: &'tcx hir::Body,
        nodeid: ast::NodeId,
    ) {
        let expr = &body.value;
        if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
            let raw_ptrs = iter_input_pats(decl, body)
                .zip(decl.inputs.iter())
                .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
                .collect::<FxHashSet<_>>();

            if !raw_ptrs.is_empty() {
                let tables = cx.tcx.body_tables(body.id());
                let mut v = DerefVisitor {
                    cx,
                    ptrs: raw_ptrs,
                    tables,
                };

                hir::intravisit::walk_expr(&mut v, expr);
            }
        }
    }
}

fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<ast::NodeId> {
    if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
        Some(id)
    } else {
        None
    }
}

struct DerefVisitor<'a, 'tcx: 'a> {
    cx: &'a LateContext<'a, 'tcx>,
    ptrs: FxHashSet<ast::NodeId>,
    tables: &'a ty::TypeckTables<'tcx>,
}

impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
    fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
        match expr.node {
            hir::ExprKind::Call(ref f, ref args) => {
                let ty = self.tables.expr_ty(f);

                if type_is_unsafe_function(self.cx, ty) {
                    for arg in args {
                        self.check_arg(arg);
                    }
                }
            },
            hir::ExprKind::MethodCall(_, _, ref args) => {
                let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
                let base_type = self.cx.tcx.type_of(def_id);

                if type_is_unsafe_function(self.cx, base_type) {
                    for arg in args {
                        self.check_arg(arg);
                    }
                }
            },
            hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
            _ => (),
        }

        hir::intravisit::walk_expr(self, expr);
    }
    fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
        intravisit::NestedVisitorMap::None
    }
}

impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
    fn check_arg(&self, ptr: &hir::Expr) {
        if let hir::ExprKind::Path(ref qpath) = ptr.node {
            if let Def::Local(id) = self.cx.tables.qpath_def(qpath, ptr.hir_id) {
                if self.ptrs.contains(&id) {
                    span_lint(
                        self.cx,
                        NOT_UNSAFE_PTR_ARG_DEREF,
                        ptr.span,
                        "this public function dereferences a raw pointer but is not marked `unsafe`",
                    );
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>use std::f64;
use std::cmp::min;
use std::num::Float;
use std::ops::{Index, IndexMut, Range, RangeTo, RangeFrom, RangeFull};
use elem;
use elem::Molecule;
use error::{CTResult, CTError};
use error::CTErrorKind::InputError;

macro_rules! impl_matrix_index {
    ($idx:ty, $out:ty) => {
        impl Index<$idx> for Matrix {
            type Output = $out;

            fn index(&self, index: &$idx) -> &$out {
                &self.buf[*index]
            }
        }
    }
}

macro_rules! impl_matrix_index_mut {
    ($idx:ty, $out:ty) => {
        impl IndexMut<$idx> for Matrix {
            fn index_mut(&mut self, index: &$idx) -> &mut $out {
                &mut self.buf[*index]
            }
        }
    }
}

pub fn pretty_print_balanced(reaction: &(Vec<Molecule>, Vec<Molecule>), coefs: &Vec<u32>) {
    let &(ref lhs, ref rhs) = reaction;
    print!("{} {}", coefs[0], lhs[0]);
    for (coef, molecule) in coefs.iter().zip(lhs.iter()).skip(1) {
        print!(" + {} {}", coef, molecule);
    }
    print!(" -> ");
    print!("{} {}", coefs[lhs.len()], rhs[0]);
    for (coef, molecule) in coefs.iter().skip(lhs.len()).zip(rhs.iter()).skip(1) {
        print!(" + {} {}", coef, molecule);
    }
    println!("");
}

/// Balances a chemical reaction using Gaussian elimination
pub fn balance_reaction(reaction: &(Vec<Molecule>, Vec<Molecule>)) -> CTResult<Vec<u32>> {
    let reac_mat = Matrix::from_reaction(reaction);
    let reduced_mat = try!(forward_elim(reac_mat));
    let coefs = back_substitute(&reduced_mat);

    // if any of the coefs are 0, then an element in that molecule is missing on the other side
    // of the reaction
    if let Some(pos) = coefs.iter().position(|&c| c == 0.0) {
        let &(ref lhs, ref rhs) = reaction;
        let molecule = lhs.iter().chain(rhs.iter()).nth(pos).unwrap();
        let begin = molecule.first().unwrap().pos;
        let len = molecule.last().unwrap().pos + molecule.last().unwrap().len - begin;
        return Err(CTError {
            kind: InputError,
            desc: format!("An element in {} is missing on the other side of the reaction", molecule),
            pos: Some((begin, len)),
        })
    }

    // we find the minimum element with fold, since f64 does not implement Ord...
    let min = coefs.iter().fold(f64::INFINITY, |crnt, &num| {
        if num < crnt {
            num
        } else {
            crnt
        }
    });
    // now we divide all elements by the minimum to (hopefully) convert them all to intergers
    // after which we do the actual conversion
    // we also reverse the Vec so the coefs are in the right order
    Ok(coefs.iter().rev().map(|n| (n / min) as u32).collect())
}

fn column_abs_max_index(columns: &[Vec<f64>], column: usize) -> usize {
    let mut max = 0;
    for i in 1..columns.len() {
        if columns[i][column].abs() > columns[max][column].abs() {
            max = i;
        }
    }
    max
}

fn forward_elim(mut mat: Matrix) -> CTResult<Matrix> {
    for k in 0..min(mat.width(), mat.height()) {
        // locate the pivot
        let pivot = column_abs_max_index(&mat[k..], k) + k;
        if mat[pivot][k] == 0_f64 {
            return Err(CTError {
                kind: InputError,
                desc: "Could not balance reaction".to_string(),
                pos: None,
            })
        }
        // move the pivot to its new position
        mat.switch_rows(k, pivot);

        // zero out the rest of the column
        for i in k + 1..mat.height() {
            let mult = -(mat[i][k] / mat[k][k]);
            mat.add_row_to_row(i, k, mult);
        }
    }
    Ok(mat)
}

fn back_substitute(mat: &Matrix) -> Vec<f64> {
    let mut vars = Vec::with_capacity(mat.width());
    for k in (0..mat.width()).rev() {
        if k >= mat.height() {
            // if this coef does not have a corresponding row in the matrix, then treat is as a
            // free variable and set it to 1
            vars.push(1_f64);
        } else {
            let mut var = 0f64;
            for i in k + 1..mat.width() {
                var -= mat[k][i] * vars[mat.width() - 1 - i];
            }
            vars.push(var / mat[k][k]);
        }
    }
    vars
}

#[derive(Debug, PartialEq)]
struct Matrix {
    buf: Vec<Vec<f64>>,
    height: usize,
    width: usize,
}

impl Matrix {
    fn from_reaction(reaction: &(Vec<Molecule>, Vec<Molecule>)) -> Matrix {
        let &(ref lhs, ref rhs) = reaction;
        let mut names = Vec::<String>::new();
        for molecule in lhs.iter().chain(rhs.iter()) {
            let grouped = elem::group_elems(molecule.clone());
            for elem in grouped.into_iter() {
                if names.iter().find(|e| **e == elem.name).is_none() {
                    names.push(elem.name);
                }
            }
        }
        let mut buf = Vec::with_capacity(names.len());
        for name in names.iter() {
            let mut row = Vec::with_capacity(lhs.len() + rhs.len());
            for molecule in lhs.iter() {
                row.push(molecule.iter()
                                 .find(|e| e.name == *name)
                                 .and_then(|e| Some(e.coef as f64))
                                 .unwrap_or(0_f64));
            }
            // we loop over rhs seperately, since we need to multiply the coefs with -1
            for molecule in rhs.iter() {
                row.push(molecule.iter()
                                 .find(|e| e.name == *name)
                                 .and_then(|e| Some(-1.0*(e.coef as f64)))
                                 .unwrap_or(0_f64));
            }
            buf.push(row);
        }
        let height = names.len();
        let width = lhs.len() + rhs.len();
        Matrix {
            buf: buf,
            height: height,
            width: width,
        }
    }

    fn add_row_to_row(&mut self, dest: usize, row: usize, mult: f64) {
        for i in 0..self.width {
            let incr = self.buf[row][i] * mult;
            self.buf[dest][i] += incr;
        }
    }

    fn switch_rows(&mut self, row1: usize, row2: usize)  {
        self.buf.swap(row1, row2);
    }

    fn width(&self) -> usize {
        self.width
    }

    fn height(&self) -> usize {
        self.height
    }
}

impl_matrix_index!(usize, Vec<f64>);
impl_matrix_index!(Range<usize>, [Vec<f64>]);
impl_matrix_index!(RangeTo<usize>, [Vec<f64>]);
impl_matrix_index!(RangeFrom<usize>, [Vec<f64>]);
impl_matrix_index!(RangeFull, [Vec<f64>]);

impl_matrix_index_mut!(usize, Vec<f64>);
impl_matrix_index_mut!(Range<usize>, [Vec<f64>]);
impl_matrix_index_mut!(RangeTo<usize>, [Vec<f64>]);
impl_matrix_index_mut!(RangeFrom<usize>, [Vec<f64>]);
impl_matrix_index_mut!(RangeFull, [Vec<f64>]);

#[cfg(test)]
mod test {
    use super::*;
    use elem::PerElem;
    use error::CTErrorKind::InputError;

    macro_rules! dummy_elem(
        ($name:expr) => (
            PerElem { name: $name.to_string(), coef: 1, pos: 0, len: 1 }
        );
        ($name:expr, $coef:expr) => (
            PerElem { name: $name.to_string(), coef: $coef, pos: 0, len: 1 }
        );
    );

    #[test]
    fn balance() {
        // attempt to balance C3H8 + O2 -> CO2 + H2O
        let reaction = (vec!(vec!(dummy_elem!("C", 3), dummy_elem!("H", 8)),
                             vec!(dummy_elem!("O", 2))),
                        vec!(vec!(dummy_elem!("C", 1), dummy_elem!("O", 2)),
                             vec!(dummy_elem!("H", 2), dummy_elem!("O", 1))));
        let result = balance_reaction(&reaction);
        let expected = Ok(vec!(1, 5, 3, 4));
        assert_eq!(result, expected);
    }

    #[test]
    fn no_balance_needed() {
        let reaction = (vec!(vec!(dummy_elem!("C", 1)), vec!(dummy_elem!("H", 1))),
                        vec!(vec!(dummy_elem!("C", 1)), vec!(dummy_elem!("H", 1))));
        let result = balance_reaction(&reaction);
        let expected = Ok(vec!(1, 1, 1, 1));
        assert_eq!(result, expected);
    }

    #[test]
    fn missing_elem() {
        let reaction = (vec!(vec!(dummy_elem!("C", 1)), vec!(dummy_elem!("H", 1))),
                        vec!(vec!(dummy_elem!("C", 1))));
        let result = balance_reaction(&reaction);
        println!("{:?}", result);
        assert!(result.is_err());
        assert_eq!(result.err().unwrap().kind, InputError);
    }
}<commit_msg>Fix small alignment issue<commit_after>use std::f64;
use std::cmp::min;
use std::num::Float;
use std::ops::{Index, IndexMut, Range, RangeTo, RangeFrom, RangeFull};
use elem;
use elem::Molecule;
use error::{CTResult, CTError};
use error::CTErrorKind::InputError;

macro_rules! impl_matrix_index {
    ($idx:ty, $out:ty) => {
        impl Index<$idx> for Matrix {
            type Output = $out;

            fn index(&self, index: &$idx) -> &$out {
                &self.buf[*index]
            }
        }
    }
}

macro_rules! impl_matrix_index_mut {
    ($idx:ty, $out:ty) => {
        impl IndexMut<$idx> for Matrix {
            fn index_mut(&mut self, index: &$idx) -> &mut $out {
                &mut self.buf[*index]
            }
        }
    }
}

pub fn pretty_print_balanced(reaction: &(Vec<Molecule>, Vec<Molecule>), coefs: &Vec<u32>) {
    let &(ref lhs, ref rhs) = reaction;
    print!("{} {}", coefs[0], lhs[0]);
    for (coef, molecule) in coefs.iter().zip(lhs.iter()).skip(1) {
        print!(" + {} {}", coef, molecule);
    }
    print!(" -> ");
    print!("{} {}", coefs[lhs.len()], rhs[0]);
    for (coef, molecule) in coefs.iter().skip(lhs.len()).zip(rhs.iter()).skip(1) {
        print!(" + {} {}", coef, molecule);
    }
    println!("");
}

/// Balances a chemical reaction using Gaussian elimination
pub fn balance_reaction(reaction: &(Vec<Molecule>, Vec<Molecule>)) -> CTResult<Vec<u32>> {
    let reac_mat = Matrix::from_reaction(reaction);
    let reduced_mat = try!(forward_elim(reac_mat));
    let coefs = back_substitute(&reduced_mat);

    // if any of the coefs are 0, then an element in that molecule is missing on the other side
    // of the reaction
    if let Some(pos) = coefs.iter().position(|&c| c == 0.0) {
        let &(ref lhs, ref rhs) = reaction;
        let molecule = lhs.iter().chain(rhs.iter()).nth(pos).unwrap();
        let begin = molecule.first().unwrap().pos;
        let len = molecule.last().unwrap().pos + molecule.last().unwrap().len - begin;
        return Err(CTError {
            kind: InputError,
            desc: format!("An element in {} is missing on the other side of the reaction",
                          molecule),
            pos: Some((begin, len)),
        })
    }

    // we find the minimum element with fold, since f64 does not implement Ord...
    let min = coefs.iter().fold(f64::INFINITY, |crnt, &num| {
        if num < crnt {
            num
        } else {
            crnt
        }
    });
    // now we divide all elements by the minimum to (hopefully) convert them all to intergers
    // after which we do the actual conversion
    // we also reverse the Vec so the coefs are in the right order
    Ok(coefs.iter().rev().map(|n| (n / min) as u32).collect())
}

fn column_abs_max_index(columns: &[Vec<f64>], column: usize) -> usize {
    let mut max = 0;
    for i in 1..columns.len() {
        if columns[i][column].abs() > columns[max][column].abs() {
            max = i;
        }
    }
    max
}

fn forward_elim(mut mat: Matrix) -> CTResult<Matrix> {
    for k in 0..min(mat.width(), mat.height()) {
        // locate the pivot
        let pivot = column_abs_max_index(&mat[k..], k) + k;
        if mat[pivot][k] == 0_f64 {
            return Err(CTError {
                kind: InputError,
                desc: "Could not balance reaction".to_string(),
                pos: None,
            })
        }
        // move the pivot to its new position
        mat.switch_rows(k, pivot);

        // zero out the rest of the column
        for i in k + 1..mat.height() {
            let mult = -(mat[i][k] / mat[k][k]);
            mat.add_row_to_row(i, k, mult);
        }
    }
    Ok(mat)
}

fn back_substitute(mat: &Matrix) -> Vec<f64> {
    let mut vars = Vec::with_capacity(mat.width());
    for k in (0..mat.width()).rev() {
        if k >= mat.height() {
            // if this coef does not have a corresponding row in the matrix, then treat is as a
            // free variable and set it to 1
            vars.push(1_f64);
        } else {
            let mut var = 0f64;
            for i in k + 1..mat.width() {
                var -= mat[k][i] * vars[mat.width() - 1 - i];
            }
            vars.push(var / mat[k][k]);
        }
    }
    vars
}

#[derive(Debug, PartialEq)]
struct Matrix {
    buf: Vec<Vec<f64>>,
    height: usize,
    width: usize,
}

impl Matrix {
    fn from_reaction(reaction: &(Vec<Molecule>, Vec<Molecule>)) -> Matrix {
        let &(ref lhs, ref rhs) = reaction;
        let mut names = Vec::<String>::new();
        for molecule in lhs.iter().chain(rhs.iter()) {
            let grouped = elem::group_elems(molecule.clone());
            for elem in grouped.into_iter() {
                if names.iter().find(|e| **e == elem.name).is_none() {
                    names.push(elem.name);
                }
            }
        }
        let mut buf = Vec::with_capacity(names.len());
        for name in names.iter() {
            let mut row = Vec::with_capacity(lhs.len() + rhs.len());
            for molecule in lhs.iter() {
                row.push(molecule.iter()
                                 .find(|e| e.name == *name)
                                 .and_then(|e| Some(e.coef as f64))
                                 .unwrap_or(0_f64));
            }
            // we loop over rhs seperately, since we need to multiply the coefs with -1
            for molecule in rhs.iter() {
                row.push(molecule.iter()
                                 .find(|e| e.name == *name)
                                 .and_then(|e| Some(-1.0*(e.coef as f64)))
                                 .unwrap_or(0_f64));
            }
            buf.push(row);
        }
        let height = names.len();
        let width = lhs.len() + rhs.len();
        Matrix {
            buf: buf,
            height: height,
            width: width,
        }
    }

    fn add_row_to_row(&mut self, dest: usize, row: usize, mult: f64) {
        for i in 0..self.width {
            let incr = self.buf[row][i] * mult;
            self.buf[dest][i] += incr;
        }
    }

    fn switch_rows(&mut self, row1: usize, row2: usize)  {
        self.buf.swap(row1, row2);
    }

    fn width(&self) -> usize {
        self.width
    }

    fn height(&self) -> usize {
        self.height
    }
}

impl_matrix_index!(usize, Vec<f64>);
impl_matrix_index!(Range<usize>, [Vec<f64>]);
impl_matrix_index!(RangeTo<usize>, [Vec<f64>]);
impl_matrix_index!(RangeFrom<usize>, [Vec<f64>]);
impl_matrix_index!(RangeFull, [Vec<f64>]);

impl_matrix_index_mut!(usize, Vec<f64>);
impl_matrix_index_mut!(Range<usize>, [Vec<f64>]);
impl_matrix_index_mut!(RangeTo<usize>, [Vec<f64>]);
impl_matrix_index_mut!(RangeFrom<usize>, [Vec<f64>]);
impl_matrix_index_mut!(RangeFull, [Vec<f64>]);

#[cfg(test)]
mod test {
    use super::*;
    use elem::PerElem;
    use error::CTErrorKind::InputError;

    macro_rules! dummy_elem(
        ($name:expr) => (
            PerElem { name: $name.to_string(), coef: 1, pos: 0, len: 1 }
        );
        ($name:expr, $coef:expr) => (
            PerElem { name: $name.to_string(), coef: $coef, pos: 0, len: 1 }
        );
    );

    #[test]
    fn balance() {
        // attempt to balance C3H8 + O2 -> CO2 + H2O
        let reaction = (vec!(vec!(dummy_elem!("C", 3), dummy_elem!("H", 8)),
                             vec!(dummy_elem!("O", 2))),
                        vec!(vec!(dummy_elem!("C", 1), dummy_elem!("O", 2)),
                             vec!(dummy_elem!("H", 2), dummy_elem!("O", 1))));
        let result = balance_reaction(&reaction);
        let expected = Ok(vec!(1, 5, 3, 4));
        assert_eq!(result, expected);
    }

    #[test]
    fn no_balance_needed() {
        let reaction = (vec!(vec!(dummy_elem!("C", 1)), vec!(dummy_elem!("H", 1))),
                        vec!(vec!(dummy_elem!("C", 1)), vec!(dummy_elem!("H", 1))));
        let result = balance_reaction(&reaction);
        let expected = Ok(vec!(1, 1, 1, 1));
        assert_eq!(result, expected);
    }

    #[test]
    fn missing_elem() {
        let reaction = (vec!(vec!(dummy_elem!("C", 1)), vec!(dummy_elem!("H", 1))),
                        vec!(vec!(dummy_elem!("C", 1))));
        let result = balance_reaction(&reaction);
        println!("{:?}", result);
        assert!(result.is_err());
        assert_eq!(result.err().unwrap().kind, InputError);
    }
}<|endoftext|>


<commit_before>extern crate env_logger;
extern crate tsutils;

#[macro_use]
extern crate log;

fn main() {
    env_logger::init().unwrap();

    let mut args = std::env::args().skip(1);
    if let Some(input_path) = args.next() {
        if let Some(output_path) = args.next() {
            let input = std::fs::File::open(input_path).unwrap();
            let output = std::fs::File::create(output_path).unwrap();
            drop_av(input, output).unwrap();
            return;
        }
    }
    std::process::exit(1);
}

#[derive(Debug)]
pub enum Error {
    Io(std::io::Error),
    PsiParseError(tsutils::psi::ParseError),
    Custom(std::borrow::Cow<'static, str>),
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

impl From<&'static str> for Error {
    fn from(e: &'static str) -> Self {
        Error::Custom(std::borrow::Cow::from(e))
    }
}

impl From<String> for Error {
    fn from(e: String) -> Self {
        Error::Custom(std::borrow::Cow::from(e))
    }
}

impl From<tsutils::psi::ParseError> for Error {
    fn from(e: tsutils::psi::ParseError) -> Self {
        Error::PsiParseError(e)
    }
}

fn drop_av<R, W>(reader: R, mut writer: W) -> Result<(), Error>
    where R: std::io::Read,
          W: std::io::Write
{
    let mut pat = None;
    let mut payloads: std::collections::HashMap<u16, Vec<u8>> = std::collections::HashMap::new();
    let mut av_pids = std::collections::HashSet::new();
    let mut nonav_pids = std::collections::HashSet::new();

    for buf in tsutils::packet::ts_packets(reader) {
        let buf = try!(buf);
        let packet = tsutils::TsPacket::new(&buf);
        if !packet.check_sync_byte() {
            return Err(Error::from("sync_byte failed"));
        }
        if packet.transport_error_indicator {
            return Err(Error::from("transport_error_indicator is set"));
        }

        if packet.payload_unit_start_indicator {
            if let Some(payload) = payloads.remove(&packet.pid) {
                match packet.pid {
                    0x0000 => {
                        pat = Some(try!(tsutils::ProgramAssociationTable::parse(&payload)));
                    }
                    _ => {
                        if let Some(ref pat) = pat {
                            if let Some(&program_number) = pat.program_map.get(&packet.pid) {
                                let pmt = try!(tsutils::ProgramMapTable::parse(&payload));
                                if pmt.program_number != program_number {
                                    return Err(Error::from(format!("Inconsistent \
                                                                    program_number for PID={}: \
                                                                    PAT says {} but PMT says {}",
                                                                   packet.pid,
                                                                   program_number,
                                                                   pmt.program_number)));
                                }
                                for es in pmt.es_info {
                                    if !av_pids.contains(&es.elementary_pid) &&
                                       !nonav_pids.contains(&es.elementary_pid) {
                                        match es.stream_type {
                                            0x0f => {
                                                // Audio
                                                av_pids.insert(es.elementary_pid);
                                            }
                                            0x02 | 0x1b => {
                                                // Video
                                                av_pids.insert(es.elementary_pid);
                                            }
                                            _ => {
                                                debug!("non-AV stream_type={:x} pid={:x}",
                                                       es.stream_type,
                                                       es.elementary_pid);
                                                nonav_pids.insert(es.elementary_pid);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if let Some(data_bytes) = packet.data_bytes {
            payloads.entry(packet.pid)
                .or_insert(Vec::new())
                .extend_from_slice(data_bytes);
        }

        if !av_pids.contains(&packet.pid) {
            try!(writer.write(&buf));
        }
    }
    Ok(())
}
<commit_msg>Concatenate only tracking PIDs<commit_after>extern crate env_logger;
extern crate tsutils;

#[macro_use]
extern crate log;

fn main() {
    env_logger::init().unwrap();

    let mut args = std::env::args().skip(1);
    if let Some(input_path) = args.next() {
        if let Some(output_path) = args.next() {
            let input = std::fs::File::open(input_path).unwrap();
            let output = std::fs::File::create(output_path).unwrap();
            drop_av(input, output).unwrap();
            return;
        }
    }
    std::process::exit(1);
}

#[derive(Debug)]
pub enum Error {
    Io(std::io::Error),
    PsiParseError(tsutils::psi::ParseError),
    Custom(std::borrow::Cow<'static, str>),
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

impl From<&'static str> for Error {
    fn from(e: &'static str) -> Self {
        Error::Custom(std::borrow::Cow::from(e))
    }
}

impl From<String> for Error {
    fn from(e: String) -> Self {
        Error::Custom(std::borrow::Cow::from(e))
    }
}

impl From<tsutils::psi::ParseError> for Error {
    fn from(e: tsutils::psi::ParseError) -> Self {
        Error::PsiParseError(e)
    }
}

fn drop_av<R, W>(reader: R, mut writer: W) -> Result<(), Error>
    where R: std::io::Read,
          W: std::io::Write
{
    let mut pat = None;
    let mut payloads: std::collections::HashMap<u16, Vec<u8>> = std::collections::HashMap::new();
    let mut av_pids = std::collections::HashSet::new();
    let mut nonav_pids = std::collections::HashSet::new();
    let mut tracking_pids = std::collections::HashSet::new();
    tracking_pids.insert(0);

    for buf in tsutils::packet::ts_packets(reader) {
        let buf = try!(buf);
        let packet = tsutils::TsPacket::new(&buf);
        if !packet.check_sync_byte() {
            return Err(Error::from("sync_byte failed"));
        }
        if packet.transport_error_indicator {
            return Err(Error::from("transport_error_indicator is set"));
        }

        if packet.payload_unit_start_indicator {
            if let Some(payload) = payloads.remove(&packet.pid) {
                match packet.pid {
                    0x0000 => {
                        let t = try!(tsutils::ProgramAssociationTable::parse(&payload));
                        tracking_pids.extend(t.program_map.keys());
                        pat = Some(t);
                    }
                    _ => {
                        if let Some(ref pat) = pat {
                            if let Some(&program_number) = pat.program_map.get(&packet.pid) {
                                let pmt = try!(tsutils::ProgramMapTable::parse(&payload));
                                if pmt.program_number != program_number {
                                    return Err(Error::from(format!("Inconsistent \
                                                                    program_number for PID={}: \
                                                                    PAT says {} but PMT says {}",
                                                                   packet.pid,
                                                                   program_number,
                                                                   pmt.program_number)));
                                }
                                for es in pmt.es_info {
                                    if !av_pids.contains(&es.elementary_pid) &&
                                       !nonav_pids.contains(&es.elementary_pid) {
                                        match es.stream_type {
                                            0x0f => {
                                                // Audio
                                                av_pids.insert(es.elementary_pid);
                                            }
                                            0x02 | 0x1b => {
                                                // Video
                                                av_pids.insert(es.elementary_pid);
                                            }
                                            _ => {
                                                debug!("non-AV stream_type={:x} pid={:x}",
                                                       es.stream_type,
                                                       es.elementary_pid);
                                                nonav_pids.insert(es.elementary_pid);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if tracking_pids.contains(&packet.pid) {
            if let Some(data_bytes) = packet.data_bytes {
                payloads.entry(packet.pid)
                    .or_insert(Vec::new())
                    .extend_from_slice(data_bytes);
            }
        }

        if !av_pids.contains(&packet.pid) {
            try!(writer.write(&buf));
        }
    }
    Ok(())
}
<|endoftext|>


<commit_before>#![ crate_name = "test" ]
#![feature(box_syntax)]
#![feature(rustc_private)]
#![feature(associated_type_defaults)]
#![feature(external_doc)]

extern crate rustc_graphviz;
// A simple rust project

extern crate krate2;
extern crate krate2 as krate3;

use rustc_graphviz::RenderOption;
use std::collections::{HashMap,HashSet};
use std::cell::RefCell;
use std::io::Write;

use sub::sub2 as msalias;
use sub::sub2;
use sub::sub2::nested_struct as sub_struct;

use std::mem::size_of;

use std::char::from_u32;

static uni: &'static str = "Les Miséééééééérables";
static yy: usize = 25;

static bob: Option<rustc_graphviz::RenderOption> = None;

// buglink test - see issue #1337.

fn test_alias<I: Iterator>(i: Option<<I as Iterator>::Item>) {
    let s = sub_struct{ field2: 45u32, };

    // import tests
    fn foo(x: &Write) {}
    let _: Option<_> = from_u32(45);

    let x = 42usize;

    krate2::hello();
    krate3::hello();

    let x = (3isize, 4usize);
    let y = x.1;
}

// Issue #37700
const LUT_BITS: usize = 3;
pub struct HuffmanTable {
    ac_lut: Option<[(i16, u8); 1 << LUT_BITS]>,
}

struct TupStruct(isize, isize, Box<str>);

fn test_tup_struct(x: TupStruct) -> isize {
    x.1
}

fn println(s: &str) {
    std::io::stdout().write_all(s.as_bytes());
}

mod sub {
    pub mod sub2 {
        use std::io::Write;
        pub mod sub3 {
            use std::io::Write;
            pub fn hello() {
                ::println("hello from module 3");
            }
        }
        pub fn hello() {
            ::println("hello from a module");
        }

        pub struct nested_struct {
            pub field2: u32,
        }

        pub enum nested_enum {
            Nest2 = 2,
            Nest3 = 3
        }
    }
}

pub mod SameDir;
pub mod SubDir;

#[path = "SameDir3.rs"]
pub mod SameDir2;

struct nofields;

#[derive(Clone)]
struct some_fields {
    field1: u32,
}

type SF = some_fields;

trait SuperTrait {
    fn qux(&self) { panic!(); }
}

trait SomeTrait: SuperTrait {
    fn Method(&self, x: u32) -> u32;

    fn prov(&self, x: u32) -> u32 {
        println(&x.to_string());
        42
    }
    fn provided_method(&self) -> u32 {
        42
    }
}

trait SubTrait: SomeTrait {
    fn stat2(x: &Self) -> u32 {
        32
    }
}

impl SomeTrait for some_fields {
    fn Method(&self, x: u32) -> u32 {
        println(&x.to_string());
        self.field1
    }
}

impl SuperTrait for some_fields {
}

impl SubTrait for some_fields {}

impl some_fields {
    fn stat(x: u32) -> u32 {
        println(&x.to_string());
        42
    }
    fn stat2(x: &some_fields) -> u32 {
        42
    }

    fn align_to<T>(&mut self) {

    }

    fn test(&mut self) {
        self.align_to::<bool>();
    }
}

impl SuperTrait for nofields {
}
impl SomeTrait for nofields {
    fn Method(&self, x: u32) -> u32 {
        self.Method(x);
        43
    }

    fn provided_method(&self) -> u32 {
        21
    }
}

impl SubTrait for nofields {}

impl SuperTrait for (Box<nofields>, Box<some_fields>) {}

fn f_with_params<T: SomeTrait>(x: &T) {
    x.Method(41);
}

type MyType = Box<some_fields>;

enum SomeEnum<'a> {
    Ints(isize, isize),
    Floats(f64, f64),
    Strings(&'a str, &'a str, &'a str),
    MyTypes(MyType, MyType)
}

#[derive(Copy, Clone)]
enum SomeOtherEnum {
    SomeConst1,
    SomeConst2,
    SomeConst3
}

enum SomeStructEnum {
    EnumStruct{a:isize, b:isize},
    EnumStruct2{f1:MyType, f2:MyType},
    EnumStruct3{f1:MyType, f2:MyType, f3:SomeEnum<'static>}
}

fn matchSomeEnum(val: SomeEnum) {
    match val {
        SomeEnum::Ints(int1, int2) => { println(&(int1+int2).to_string()); }
        SomeEnum::Floats(float1, float2) => { println(&(float2*float1).to_string()); }
        SomeEnum::Strings(.., s3) => { println(s3); }
        SomeEnum::MyTypes(mt1, mt2) => { println(&(mt1.field1 - mt2.field1).to_string()); }
    }
}

fn matchSomeStructEnum(se: SomeStructEnum) {
    match se {
        SomeStructEnum::EnumStruct{a:a, ..} => println(&a.to_string()),
        SomeStructEnum::EnumStruct2{f1:f1, f2:f_2} => println(&f_2.field1.to_string()),
        SomeStructEnum::EnumStruct3{f1, ..} => println(&f1.field1.to_string()),
    }
}

fn matchSomeStructEnum2(se: SomeStructEnum) {
    use SomeStructEnum::*;
    match se {
        EnumStruct{a: ref aaa, ..} => println(&aaa.to_string()),
        EnumStruct2{f1, f2: f2} => println(&f1.field1.to_string()),
        EnumStruct3{f1, f3: SomeEnum::Ints(..), f2} => println(&f1.field1.to_string()),
        _ => {},
    }
}

fn matchSomeOtherEnum(val: SomeOtherEnum) {
    use SomeOtherEnum::{SomeConst2, SomeConst3};
    match val {
        SomeOtherEnum::SomeConst1 => { println("I'm const1."); }
        SomeConst2 | SomeConst3 => { println("I'm const2 or const3."); }
    }
}

fn hello<X: SomeTrait>((z, a) : (u32, String), ex: X) {
    SameDir2::hello(43);

    println(&yy.to_string());
    let (x, y): (u32, u32) = (5, 3);
    println(&x.to_string());
    println(&z.to_string());
    let x: u32 = x;
    println(&x.to_string());
    let x = "hello";
    println(x);

    let x = 32.0f32;
    let _ = (x + ((x * x) + 1.0).sqrt()).ln();

    let s: Box<SomeTrait> = box some_fields {field1: 43};
    let s2: Box<some_fields> =  box some_fields {field1: 43};
    let s3 = box nofields;

    s.Method(43);
    s3.Method(43);
    s2.Method(43);

    ex.prov(43);

    let y: u32 = 56;
    // static method on struct
    let r = some_fields::stat(y);
    // trait static method, calls default
    let r = SubTrait::stat2(&*s3);

    let s4 = s3 as Box<SomeTrait>;
    s4.Method(43);

    s4.provided_method();
    s2.prov(45);

    let closure = |x: u32, s: &SomeTrait| {
        s.Method(23);
        return x + y;
    };

    let z = closure(10, &*s);
}

pub struct blah {
    used_link_args: RefCell<[&'static str; 0]>,
}

#[macro_use]
mod macro_use_test {
    macro_rules! test_rec {
        (q, $src: expr) => {{
            print!("{}", $src);
            test_rec!($src);
        }};
        ($src: expr) => {
            print!("{}", $src);
        };
    }

    macro_rules! internal_vars {
        ($src: ident) => {{
            let mut x = $src;
            x += 100;
        }};
    }
}

fn main() { // foo
    let s = box some_fields {field1: 43};
    hello((43, "a".to_string()), *s);
    sub::sub2::hello();
    sub2::sub3::hello();

    let h = sub2::sub3::hello;
    h();

    // utf8 chars
    let ut = "Les Miséééééééérables";

    // For some reason, this pattern of macro_rules foiled our generated code
    // avoiding strategy.
    macro_rules! variable_str(($name:expr) => (
        some_fields {
            field1: $name,
        }
    ));
    let vs = variable_str!(32);

    let mut candidates: RefCell<HashMap<&'static str, &'static str>> = RefCell::new(HashMap::new());
    let _ = blah {
        used_link_args: RefCell::new([]),
    };
    let s1 = nofields;
    let s2 = SF { field1: 55};
    let s3: some_fields = some_fields{ field1: 55};
    let s4: msalias::nested_struct = sub::sub2::nested_struct{ field2: 55};
    let s4: msalias::nested_struct = sub2::nested_struct{ field2: 55};
    println(&s2.field1.to_string());
    let s5: MyType = box some_fields{ field1: 55};
    let s = SameDir::SameStruct{name: "Bob".to_string()};
    let s = SubDir::SubStruct{name:"Bob".to_string()};
    let s6: SomeEnum = SomeEnum::MyTypes(box s2.clone(), s5);
    let s7: SomeEnum = SomeEnum::Strings("one", "two", "three");
    matchSomeEnum(s6);
    matchSomeEnum(s7);
    let s8: SomeOtherEnum = SomeOtherEnum::SomeConst2;
    matchSomeOtherEnum(s8);
    let s9: SomeStructEnum = SomeStructEnum::EnumStruct2{ f1: box some_fields{ field1:10 },
                                                          f2: box s2 };
    matchSomeStructEnum(s9);

    for x in &vec![1, 2, 3] {
        let _y = x;
    }

    let s7: SomeEnum = SomeEnum::Strings("one", "two", "three");
    if let SomeEnum::Strings(..) = s7 {
        println!("hello!");
    }

    for i in 0..5 {
        foo_foo(i);
    }

    if let Some(x) = None {
        foo_foo(x);
    }

    if false {
    } else if let Some(y) = None {
        foo_foo(y);
    }

    while let Some(z) = None {
        foo_foo(z);
    }

    let mut x = 4;
    test_rec!(q, "Hello");
    assert_eq!(x, 4);
    internal_vars!(x);
}

fn foo_foo(_: i32) {}

impl Iterator for nofields {
    type Item = (usize, usize);

    fn next(&mut self) -> Option<(usize, usize)> {
        panic!()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        panic!()
    }
}

trait Pattern<'a> {
    type Searcher;
}

struct CharEqPattern;

impl<'a> Pattern<'a> for CharEqPattern {
    type Searcher = CharEqPattern;
}

struct CharSearcher<'a>(<CharEqPattern as Pattern<'a>>::Searcher);

pub trait Error {
}

impl Error + 'static {
    pub fn is<T: Error + 'static>(&self) -> bool {
        panic!()
    }
}

impl Error + 'static + Send {
    pub fn is<T: Error + 'static>(&self) -> bool {
        <Error + 'static>::is::<T>(self)
    }
}
extern crate rustc_serialize;
#[derive(Clone, Copy, Hash, RustcEncodable, RustcDecodable,
         PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
struct AllDerives(i32);

fn test_format_args() {
    let x = 1;
    let y = 2;
    let name = "Joe Blogg";
    println!("Hello {}", name);
    print!("Hello {0}", name);
    print!("{0} + {} = {}", x, y);
    print!("x is {}, y is {1}, name is {n}", x, y, n = name);
}

union TestUnion {
    f1: u32
}

struct FrameBuffer;

struct SilenceGenerator;

impl Iterator for SilenceGenerator {
    type Item = FrameBuffer;

    fn next(&mut self) -> Option<Self::Item> {
        panic!();
    }
}

trait Foo {
    type Bar = FrameBuffer;
}

#[doc(include="extra-docs.md")]
struct StructWithDocs;
<commit_msg>Fix run-make test<commit_after>#![crate_name = "test"]
#![feature(box_syntax)]
#![feature(rustc_private)]
#![feature(associated_type_defaults)]
#![feature(external_doc)]

extern crate rustc_graphviz;
// A simple rust project

extern crate krate2;
extern crate krate2 as krate3;

use rustc_graphviz::RenderOption;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::io::Write;

use sub::sub2 as msalias;
use sub::sub2;
use sub::sub2::nested_struct as sub_struct;

use std::mem::size_of;

use std::char::from_u32;

static uni: &'static str = "Les Miséééééééérables";
static yy: usize = 25;

static bob: Option<rustc_graphviz::RenderOption> = None;

// buglink test - see issue #1337.

fn test_alias<I: Iterator>(i: Option<<I as Iterator>::Item>) {
    let s = sub_struct { field2: 45u32 };

    // import tests
    fn foo(x: &Write) {}
    let _: Option<_> = from_u32(45);

    let x = 42usize;

    krate2::hello();
    krate3::hello();

    let x = (3isize, 4usize);
    let y = x.1;
}

// Issue #37700
const LUT_BITS: usize = 3;
pub struct HuffmanTable {
    ac_lut: Option<[(i16, u8); 1 << LUT_BITS]>,
}

struct TupStruct(isize, isize, Box<str>);

fn test_tup_struct(x: TupStruct) -> isize {
    x.1
}

fn println(s: &str) {
    std::io::stdout().write_all(s.as_bytes());
}

mod sub {
    pub mod sub2 {
        use std::io::Write;
        pub mod sub3 {
            use std::io::Write;
            pub fn hello() {
                ::println("hello from module 3");
            }
        }
        pub fn hello() {
            ::println("hello from a module");
        }

        pub struct nested_struct {
            pub field2: u32,
        }

        pub enum nested_enum {
            Nest2 = 2,
            Nest3 = 3,
        }
    }
}

pub mod SameDir;
pub mod SubDir;

#[path = "SameDir3.rs"]
pub mod SameDir2;

struct nofields;

#[derive(Clone)]
struct some_fields {
    field1: u32,
}

type SF = some_fields;

trait SuperTrait {
    fn qux(&self) {
        panic!();
    }
}

trait SomeTrait: SuperTrait {
    fn Method(&self, x: u32) -> u32;

    fn prov(&self, x: u32) -> u32 {
        println(&x.to_string());
        42
    }
    fn provided_method(&self) -> u32 {
        42
    }
}

trait SubTrait: SomeTrait {
    fn stat2(x: &Self) -> u32 {
        32
    }
}

impl SomeTrait for some_fields {
    fn Method(&self, x: u32) -> u32 {
        println(&x.to_string());
        self.field1
    }
}

impl SuperTrait for some_fields {}

impl SubTrait for some_fields {}

impl some_fields {
    fn stat(x: u32) -> u32 {
        println(&x.to_string());
        42
    }
    fn stat2(x: &some_fields) -> u32 {
        42
    }

    fn align_to<T>(&mut self) {}

    fn test(&mut self) {
        self.align_to::<bool>();
    }
}

impl SuperTrait for nofields {}
impl SomeTrait for nofields {
    fn Method(&self, x: u32) -> u32 {
        self.Method(x);
        43
    }

    fn provided_method(&self) -> u32 {
        21
    }
}

impl SubTrait for nofields {}

impl SuperTrait for (Box<nofields>, Box<some_fields>) {}

fn f_with_params<T: SomeTrait>(x: &T) {
    x.Method(41);
}

type MyType = Box<some_fields>;

enum SomeEnum<'a> {
    Ints(isize, isize),
    Floats(f64, f64),
    Strings(&'a str, &'a str, &'a str),
    MyTypes(MyType, MyType),
}

#[derive(Copy, Clone)]
enum SomeOtherEnum {
    SomeConst1,
    SomeConst2,
    SomeConst3,
}

enum SomeStructEnum {
    EnumStruct { a: isize, b: isize },
    EnumStruct2 { f1: MyType, f2: MyType },
    EnumStruct3 { f1: MyType, f2: MyType, f3: SomeEnum<'static> },
}

fn matchSomeEnum(val: SomeEnum) {
    match val {
        SomeEnum::Ints(int1, int2) => {
            println(&(int1 + int2).to_string());
        }
        SomeEnum::Floats(float1, float2) => {
            println(&(float2 * float1).to_string());
        }
        SomeEnum::Strings(.., s3) => {
            println(s3);
        }
        SomeEnum::MyTypes(mt1, mt2) => {
            println(&(mt1.field1 - mt2.field1).to_string());
        }
    }
}

fn matchSomeStructEnum(se: SomeStructEnum) {
    match se {
        SomeStructEnum::EnumStruct { a: a, .. } => println(&a.to_string()),
        SomeStructEnum::EnumStruct2 { f1: f1, f2: f_2 } => println(&f_2.field1.to_string()),
        SomeStructEnum::EnumStruct3 { f1, .. } => println(&f1.field1.to_string()),
    }
}

fn matchSomeStructEnum2(se: SomeStructEnum) {
    use SomeStructEnum::*;
    match se {
        EnumStruct { a: ref aaa, .. } => println(&aaa.to_string()),
        EnumStruct2 { f1, f2: f2 } => println(&f1.field1.to_string()),
        EnumStruct3 { f1, f3: SomeEnum::Ints(..), f2 } => println(&f1.field1.to_string()),
        _ => {}
    }
}

fn matchSomeOtherEnum(val: SomeOtherEnum) {
    use SomeOtherEnum::{SomeConst2, SomeConst3};
    match val {
        SomeOtherEnum::SomeConst1 => {
            println("I'm const1.");
        }
        SomeConst2 | SomeConst3 => {
            println("I'm const2 or const3.");
        }
    }
}

fn hello<X: SomeTrait>((z, a): (u32, String), ex: X) {
    SameDir2::hello(43);

    println(&yy.to_string());
    let (x, y): (u32, u32) = (5, 3);
    println(&x.to_string());
    println(&z.to_string());
    let x: u32 = x;
    println(&x.to_string());
    let x = "hello";
    println(x);

    let x = 32.0f32;
    let _ = (x + ((x * x) + 1.0).sqrt()).ln();

    let s: Box<SomeTrait> = box some_fields { field1: 43 };
    let s2: Box<some_fields> = box some_fields { field1: 43 };
    let s3 = box nofields;

    s.Method(43);
    s3.Method(43);
    s2.Method(43);

    ex.prov(43);

    let y: u32 = 56;
    // static method on struct
    let r = some_fields::stat(y);
    // trait static method, calls default
    let r = SubTrait::stat2(&*s3);

    let s4 = s3 as Box<SomeTrait>;
    s4.Method(43);

    s4.provided_method();
    s2.prov(45);

    let closure = |x: u32, s: &SomeTrait| {
        s.Method(23);
        return x + y;
    };

    let z = closure(10, &*s);
}

pub struct blah {
    used_link_args: RefCell<[&'static str; 0]>,
}

#[macro_use]
mod macro_use_test {
    macro_rules! test_rec {
        (q, $src: expr) => {{
            print!("{}", $src);
            test_rec!($src);
        }};
        ($src: expr) => {
            print!("{}", $src);
        };
    }

    macro_rules! internal_vars {
        ($src: ident) => {{
            let mut x = $src;
            x += 100;
        }};
    }
}

fn main() {
    // foo
    let s = box some_fields { field1: 43 };
    hello((43, "a".to_string()), *s);
    sub::sub2::hello();
    sub2::sub3::hello();

    let h = sub2::sub3::hello;
    h();

    // utf8 chars
    let ut = "Les Miséééééééérables";

    // For some reason, this pattern of macro_rules foiled our generated code
    // avoiding strategy.
    macro_rules! variable_str(($name:expr) => (
        some_fields {
            field1: $name,
        }
    ));
    let vs = variable_str!(32);

    let mut candidates: RefCell<HashMap<&'static str, &'static str>> = RefCell::new(HashMap::new());
    let _ = blah { used_link_args: RefCell::new([]) };
    let s1 = nofields;
    let s2 = SF { field1: 55 };
    let s3: some_fields = some_fields { field1: 55 };
    let s4: msalias::nested_struct = sub::sub2::nested_struct { field2: 55 };
    let s4: msalias::nested_struct = sub2::nested_struct { field2: 55 };
    println(&s2.field1.to_string());
    let s5: MyType = box some_fields { field1: 55 };
    let s = SameDir::SameStruct { name: "Bob".to_string() };
    let s = SubDir::SubStruct { name: "Bob".to_string() };
    let s6: SomeEnum = SomeEnum::MyTypes(box s2.clone(), s5);
    let s7: SomeEnum = SomeEnum::Strings("one", "two", "three");
    matchSomeEnum(s6);
    matchSomeEnum(s7);
    let s8: SomeOtherEnum = SomeOtherEnum::SomeConst2;
    matchSomeOtherEnum(s8);
    let s9: SomeStructEnum =
        SomeStructEnum::EnumStruct2 { f1: box some_fields { field1: 10 }, f2: box s2 };
    matchSomeStructEnum(s9);

    for x in &vec![1, 2, 3] {
        let _y = x;
    }

    let s7: SomeEnum = SomeEnum::Strings("one", "two", "three");
    if let SomeEnum::Strings(..) = s7 {
        println!("hello!");
    }

    for i in 0..5 {
        foo_foo(i);
    }

    if let Some(x) = None {
        foo_foo(x);
    }

    if false {
    } else if let Some(y) = None {
        foo_foo(y);
    }

    while let Some(z) = None {
        foo_foo(z);
    }

    let mut x = 4;
    test_rec!(q, "Hello");
    assert_eq!(x, 4);
    internal_vars!(x);
}

fn foo_foo(_: i32) {}

impl Iterator for nofields {
    type Item = (usize, usize);

    fn next(&mut self) -> Option<(usize, usize)> {
        panic!()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        panic!()
    }
}

trait Pattern<'a> {
    type Searcher;
}

struct CharEqPattern;

impl<'a> Pattern<'a> for CharEqPattern {
    type Searcher = CharEqPattern;
}

struct CharSearcher<'a>(<CharEqPattern as Pattern<'a>>::Searcher);

pub trait Error {}

impl Error + 'static {
    pub fn is<T: Error + 'static>(&self) -> bool {
        panic!()
    }
}

impl Error + 'static + Send {
    pub fn is<T: Error + 'static>(&self) -> bool {
        <Error + 'static>::is::<T>(self)
    }
}
extern crate rustc_serialize;
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
struct AllDerives(i32);

fn test_format_args() {
    let x = 1;
    let y = 2;
    let name = "Joe Blogg";
    println!("Hello {}", name);
    print!("Hello {0}", name);
    print!("{0} + {} = {}", x, y);
    print!("x is {}, y is {1}, name is {n}", x, y, n = name);
}

union TestUnion {
    f1: u32,
}

struct FrameBuffer;

struct SilenceGenerator;

impl Iterator for SilenceGenerator {
    type Item = FrameBuffer;

    fn next(&mut self) -> Option<Self::Item> {
        panic!();
    }
}

trait Foo {
    type Bar = FrameBuffer;
}

#[doc(include = "extra-docs.md")]
struct StructWithDocs;
<|endoftext|>