<commit_before>use std::io::{self, ErrorKind, Read, Write};
use std::net::{UdpSocket, SocketAddr};
use std::time::Duration;
use hyper::net::{NetworkStream};

/// A type that wraps a UdpSocket and a SocketAddr and implements the NetworkStream
/// trait.
///
/// Note that reading from this stream will generate an error, this object is
/// used for intercepting Http messages from Hyper and sending them out via Udp.
/// The response(s) from client(s) are to be handled by some other object that
/// has a cloned handle to our internal UdpSocket handle.
pub struct UdpSender {
    udp: UdpSocket,
    dst: SocketAddr
}

impl UdpSender {
    /// Creates a new UdpSender object.
    pub fn new(udp: UdpSocket, dst: SocketAddr) -> UdpSender {
        UdpSender{ udp: udp, dst: dst }
    }
}

impl NetworkStream for UdpSender {
    fn peer_addr(&mut self) -> io::Result<SocketAddr> {
        Ok(self.dst)
    }
    fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
        Ok(())
    }
    fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
        Ok(())
    }
}

unsafe impl Send for UdpSender { }

impl Read for UdpSender {
    fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
        // Simulate Some Network Error So Our Process Doesnt Hang
        Err(io::Error::new(ErrorKind::ConnectionAborted, "UdpSender Can Not Be Read From"))
    }
}

impl Write for UdpSender {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        // Hyper will generate a request with a /, we need to intercept that.
        let mut buffer = vec![0u8; buf.len()];

        let mut found = false;
        for (src, dst) in buf.iter().zip(buffer.iter_mut()) {
            if *src == b'/' && !found && buf[0] != b'H' {
                *dst = b'*';
                found = true;
            } else {
                *dst = *src;
            }
        }
        debug!("Sent HTTP Request:\n{}", String::from_utf8_lossy(&buffer[..]));

        self.udp.send_to(&buffer[..], self.dst)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl Clone for UdpSender {
    fn clone(&self) -> UdpSender {
        let udp_clone = self.udp.try_clone().unwrap();

        UdpSender{ udp: udp_clone, dst: self.dst }
    }

    fn clone_from(&mut self, source: &UdpSender) {
        let udp_clone = source.udp.try_clone().unwrap();

        self.udp = udp_clone;
        self.dst = source.dst;
    }
}
<commit_msg>Fix Broken Write Impl For UdpSender Since Hyper No Longer Buffers Whole Messages<commit_after>use std::io::{self, ErrorKind, Read, Write};
use std::net::{UdpSocket, SocketAddr};
use std::time::Duration;
use hyper::net::{NetworkStream};

/// A type that wraps a UdpSocket and a SocketAddr and implements the NetworkStream
/// trait.
///
/// Note that reading from this stream will generate an error, this object is
/// used for intercepting Http messages from Hyper and sending them out via Udp.
/// The response(s) from client(s) are to be handled by some other object that
/// has a cloned handle to our internal UdpSocket handle.
pub struct UdpSender {
    udp: UdpSocket,
    dst: SocketAddr,
    buf: Vec<u8>
}

impl UdpSender {
    /// Creates a new UdpSender object.
    pub fn new(udp: UdpSocket, dst: SocketAddr) -> UdpSender {
        UdpSender{ udp: udp, dst: dst, buf: Vec::new() }
    }
}

impl NetworkStream for UdpSender {
    fn peer_addr(&mut self) -> io::Result<SocketAddr> {
        Ok(self.dst)
    }
    fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
        Ok(())
    }
    fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
        Ok(())
    }
}

unsafe impl Send for UdpSender { }

impl Read for UdpSender {
    fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
        // Simulate Some Network Error So Our Process Doesnt Hang
        Err(io::Error::new(ErrorKind::ConnectionAborted, "UdpSender Can Not Be Read From"))
    }
}

impl Write for UdpSender {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        // Hyper will generate a request with a /, we need to intercept that.
        let mut buffer = vec![0u8; buf.len()];

        let mut found = false;
        for (src, dst) in buf.iter().zip(buffer.iter_mut()) {
            if *src == b'/' && !found && buf[0] != b'H' {
                *dst = b'*';
                found = true;
            } else {
                *dst = *src;
            }
        }

        self.buf.append(&mut buffer);

        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        debug!("Sent HTTP Request:\n{}", String::from_utf8_lossy(&self.buf[..]));

        let result = self.udp.send_to(&self.buf[..], self.dst);
        self.buf.clear();

        result.map(|_| ())
    }
}

impl Clone for UdpSender {
    fn clone(&self) -> UdpSender {
        let udp_clone = self.udp.try_clone().unwrap();

        UdpSender{ udp: udp_clone, dst: self.dst, buf: self.buf.clone() }
    }

    fn clone_from(&mut self, source: &UdpSender) {
        let udp_clone = source.udp.try_clone().unwrap();

        self.udp = udp_clone;
        self.dst = source.dst;
    }
}
<|endoftext|>


<commit_before>use super::{Tokenizer,Token};

use ir;
use ir::{Module,Value,Expression};

/// An IR parser.
pub struct Parser<I: Iterator<Item=char>>
{
    tokenizer: Tokenizer<I>,
    module: Module,
}

impl<I> Parser<I>
    where I: Iterator<Item=char>
{
    /// Creates a new parser.
    pub fn new(chars: I) -> Self {
        Parser {
            tokenizer: Tokenizer::new(chars),
            module: Module::empty(),
        }
    }

    /// Gets parser which preserves comments.
    pub fn preserve_comments(mut self) -> Self {
        self.tokenizer = self.tokenizer.preserve_comments();
        self
    }

    pub fn parse(mut self) -> Result<Module,String> {
        let first_token = try!(util::expect(self.tokenizer.peek()));

        if first_token == keywords::global() {
            try!(self.parse_global());
        } else {
            return Err(format!("unexpected token: {}", first_token));
        }

        Ok(self.module)
    }

    fn parse_global(&mut self) -> Result<(),String> {
        self.assert(keywords::global());

        let name = try!(self.expect_word());
        try!(self.expect(Token::equal_sign()));
        let value = try!(self.parse_value());

        self.module.add_global(ir::Global::new(name, value));
        Ok(())
    }

    fn parse_value(&mut self) -> Result<Value,String> {
        self.parse_expression().map(|expr| Value::new(expr))
    }

    fn parse_expression(&mut self) -> Result<Expression,String> {
        let first_token = try!(self.expect_something());

        match first_token {
            Token::Word(word) => self.parse_word_expression(word),
            _ => Err("unknown token for expression".into()),
        }
    }

    fn parse_word_expression(&mut self, first_word: String)
        -> Result<Expression,String> {
        if first_word.starts_with('i') || first_word.starts_with('u') {
            self.parse_integer_expression(first_word)
        } else {
            Err("unknown token for expression".into())
        }
    }

    fn parse_integer_expression(&mut self, type_word: String)
        -> Result<Expression,String> {
        debug_assert!(type_word.starts_with('i') || type_word.starts_with('u'));

        let ty = try!(self.parse_integer_type(type_word));
        let value = try!(self.expect_integer());

        Ok(Expression::integer(ty, value).unwrap())
    }

    fn parse_integer_type(&mut self, type_str: String)
        -> Result<ir::types::Integer,String> {
        let kind = match type_str.chars().next().unwrap() {
            'i' => ::util::IntegerKind::Signed,
            'u' => ::util::IntegerKind::Unsigned,
            _ => unreachable!(),
        };

        let width_str: String = type_str.chars().skip(1).collect();
        let width = try!(util::parse_integer(&width_str, 10));

        Ok(ir::types::Integer::new(kind, width as u16))
    }

    fn assert(&mut self, expected: Token) {
        self.expect(expected).unwrap();
    }

    fn expect_something(&mut self) -> Result<Token,String> {
        util::expect(self.tokenizer.next())
    }

    fn expect(&mut self, expected: Token) -> Result<Token,String> {
        // TODO: this could be a more descriptive error message
        self.expect_one_of(&[expected])
    }

    fn expect_one_of(&mut self, expected: &[Token]) -> Result<Token,String> {
        let token = try!(util::expect(self.tokenizer.next()));

        if expected.iter().any(|e| e==&token) {
            Ok(token)
        } else {
            Err(format!("expected one of {} but got {}",
                        ::util::comma_separated_values(expected.iter()),
                        token))
        }
    }

    fn expect_word(&mut self) -> Result<String,String> {
        match self.expect_something() {
            Ok(ref token) => match *token {
                Token::Word(ref w) => Ok(w.clone()),
                _ => Err("expected a word".into()),
            },
            Err(e) => Err(e),
        }
    }

    fn expect_integer(&mut self) -> Result<i64,String> {
        match self.expect_something() {
            Ok(ref token) => match *token {
                Token::Integer(i) => Ok(i),
                _ => Err("expected an integer".into()),
            },
            Err(e) => Err(e),
        }
    }
}

pub mod util
{
    /// Expects that an `Option<Result>` is `Some`.
    // TODO: give this a name that doesn't clash with Parser::expect
    pub fn expect<T>(val: Option<Result<T,String>>) -> Result<T,String> {
        match val {
            Some(result) => result,
            None => Err("expected a token".into()),
        }
    }

    pub fn parse_integer(string: &str, radix: u32) -> Result<i64,String> {
        match i64::from_str_radix(string, radix) {
            Ok(i) => Ok(i),
            Err(..) => Err("could not parse integer".into()),
        }
    }
}

pub mod keywords
{
    use ir::read::Token;

    pub fn global() -> Token {
        Token::word("global")
    }
}

#[allow(unused_imports)]
mod test
{
    use super::Parser;

    #[cfg(test)]
    fn parse(text: &str) -> ::ir::Module {
        Parser::new(text.chars()).parse().expect("parsing failed")
    }

    #[test]
    fn globals() {
        let module = parse("global ABCD = i32 4");

        assert_eq!(module.globals().next().unwrap().name(), "ABCD");

    }
}
<commit_msg>[IR] Wrote global parsing tests<commit_after>use super::{Tokenizer,Token};

use ir;
use ir::{Module,Value,Expression};

/// An IR parser.
pub struct Parser<I: Iterator<Item=char>>
{
    tokenizer: Tokenizer<I>,
    module: Module,
}

impl<I> Parser<I>
    where I: Iterator<Item=char>
{
    /// Creates a new parser.
    pub fn new(chars: I) -> Self {
        Parser {
            tokenizer: Tokenizer::new(chars),
            module: Module::empty(),
        }
    }

    /// Gets parser which preserves comments.
    pub fn preserve_comments(mut self) -> Self {
        self.tokenizer = self.tokenizer.preserve_comments();
        self
    }

    pub fn parse(mut self) -> Result<Module,String> {
        let first_token = try!(util::expect(self.tokenizer.peek()));

        if first_token == keywords::global() {
            try!(self.parse_global());
        } else {
            return Err(format!("unexpected token: {}", first_token));
        }

        Ok(self.module)
    }

    fn parse_global(&mut self) -> Result<(),String> {
        self.assert(keywords::global());

        let name = try!(self.expect_word());
        try!(self.expect(Token::equal_sign()));
        let value = try!(self.parse_value());

        self.module.add_global(ir::Global::new(name, value));
        Ok(())
    }

    fn parse_value(&mut self) -> Result<Value,String> {
        self.parse_expression().map(|expr| Value::new(expr))
    }

    fn parse_expression(&mut self) -> Result<Expression,String> {
        let first_token = try!(self.expect_something());

        match first_token {
            Token::Word(word) => self.parse_word_expression(word),
            _ => Err("unknown token for expression".into()),
        }
    }

    fn parse_word_expression(&mut self, first_word: String)
        -> Result<Expression,String> {
        if first_word.starts_with('i') || first_word.starts_with('u') {
            self.parse_integer_expression(first_word)
        } else {
            Err("unknown token for expression".into())
        }
    }

    fn parse_integer_expression(&mut self, type_word: String)
        -> Result<Expression,String> {
        debug_assert!(type_word.starts_with('i') || type_word.starts_with('u'));

        let ty = try!(self.parse_integer_type(type_word));
        let value = try!(self.expect_integer());

        Ok(Expression::integer(ty, value).unwrap())
    }

    fn parse_integer_type(&mut self, type_str: String)
        -> Result<ir::types::Integer,String> {
        let kind = match type_str.chars().next().unwrap() {
            'i' => ::util::IntegerKind::Signed,
            'u' => ::util::IntegerKind::Unsigned,
            _ => unreachable!(),
        };

        let width_str: String = type_str.chars().skip(1).collect();
        let width = try!(util::parse_integer(&width_str, 10));

        Ok(ir::types::Integer::new(kind, width as u16))
    }

    fn assert(&mut self, expected: Token) {
        self.expect(expected).unwrap();
    }

    fn expect_something(&mut self) -> Result<Token,String> {
        util::expect(self.tokenizer.next())
    }

    fn expect(&mut self, expected: Token) -> Result<Token,String> {
        // TODO: this could be a more descriptive error message
        self.expect_one_of(&[expected])
    }

    fn expect_one_of(&mut self, expected: &[Token]) -> Result<Token,String> {
        let token = try!(util::expect(self.tokenizer.next()));

        if expected.iter().any(|e| e==&token) {
            Ok(token)
        } else {
            Err(format!("expected one of {} but got {}",
                        ::util::comma_separated_values(expected.iter()),
                        token))
        }
    }

    fn expect_word(&mut self) -> Result<String,String> {
        match self.expect_something() {
            Ok(ref token) => match *token {
                Token::Word(ref w) => Ok(w.clone()),
                _ => Err("expected a word".into()),
            },
            Err(e) => Err(e),
        }
    }

    fn expect_integer(&mut self) -> Result<i64,String> {
        match self.expect_something() {
            Ok(ref token) => match *token {
                Token::Integer(i) => Ok(i),
                _ => Err("expected an integer".into()),
            },
            Err(e) => Err(e),
        }
    }
}

pub mod util
{
    /// Expects that an `Option<Result>` is `Some`.
    // TODO: give this a name that doesn't clash with Parser::expect
    pub fn expect<T>(val: Option<Result<T,String>>) -> Result<T,String> {
        match val {
            Some(result) => result,
            None => Err("expected a token".into()),
        }
    }

    pub fn parse_integer(string: &str, radix: u32) -> Result<i64,String> {
        match i64::from_str_radix(string, radix) {
            Ok(i) => Ok(i),
            Err(..) => Err("could not parse integer".into()),
        }
    }
}

pub mod keywords
{
    use ir::read::Token;

    pub fn global() -> Token {
        Token::word("global")
    }
}

#[allow(unused_imports)]
mod test
{
    use super::Parser;
    use ir::Value;

    #[cfg(test)]
    fn parse(text: &str) -> ::ir::Module {
        Parser::new(text.chars()).parse().expect("parsing failed")
    }

    macro_rules! expect_global {
        ($input:expr => $name:expr, $value:expr) => {
            {
                let module = parse($input);

                let global = module.globals().next().unwrap();
                assert_eq!(global.name(), $name);
                assert_eq!(global.value(), &$value);
            }
        }
    }

    #[test]
    fn globals() {
        expect_global!("global ABCD = i32 5" => "ABCD", Value::i32(5));

        expect_global!("global hello_world = u127 38"
                       => "hello_world", Value::u(127, 38));

        expect_global!("global ewf = i16 52" => "ewf", Value::i(16, 52));
    }
}

<|endoftext|>


<commit_before>use std::cmp;
use std::collections::BTreeMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

mod from_str;
// mod relabel;

pub mod negra;

/// Variable or terminal symbol in an MCFG.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
pub enum VarT<T> {
    /// `Var(i, j)` represents the `j`th component of the `i`th successor.
    /// Indexing starts from `0`.
    Var(usize, usize),
    T(T),
}

/// Composition function in an MCFG.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
pub struct Composition<T> {
    pub composition: Vec<Vec<VarT<T>>>,
}

impl<T> From<Vec<Vec<VarT<T>>>> for Composition<T> {
    fn from(encapsulated_value: Vec<Vec<VarT<T>>>) -> Self {
        Composition { composition: encapsulated_value }
    }
}

/// Rule of a weighted MCFG.
#[derive(Debug, PartialOrd, Ord, Clone)]
pub struct PMCFGRule<N, T, W> {
    pub head: N,
    pub tail: Vec<N>,
    pub composition: Composition<T>,
    pub weight: W,
}

impl<N, T, W> PMCFGRule<N, T, W>
    where T: Clone,
          W: Clone,
{
    pub fn map_nonterminals<F, M>(&self, f: F) -> PMCFGRule<M, T, W>
        where F: Fn(&N) -> M,
    {
        PMCFGRule {
            head: f(&self.head),
            tail: self.tail.iter().map(f).collect(),
            composition: self.composition.clone(),
            weight: self.weight.clone()
        }
    }
}

/// A weighted MCFG.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct PMCFG<N, T, W> {
    pub _dummy: PhantomData<T>,
    pub initial: Vec<N>,
    pub rules: Vec<PMCFGRule<N, T, W>>,
}

impl<N: Hash, T: Hash, W> Hash for PMCFGRule<N, T, W> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.head.hash(state);
        self.tail.hash(state);
        self.composition.hash(state);
    }
}

impl<N: PartialEq, T: PartialEq, W> PartialEq for PMCFGRule<N, T, W> {
    fn eq(&self, other: &Self) -> bool {
        self.head == other.head && self.tail == other.tail && self.composition == other.composition
    }
}

impl<N: Eq, T: Eq, W> Eq for PMCFGRule<N, T, W> {}

impl<T: fmt::Display> fmt::Display for Composition<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buffer = "".to_string();

        let mut iter0 = self.composition.iter().peekable();
        let mut iter1;

        buffer.push_str("[");
        while let Some(proj) = iter0.next() {
            iter1 = proj.into_iter().peekable();
            buffer.push_str("[");
            while let Some(vart) = iter1.next() {
                buffer.push_str(format!("{}", vart).as_str());
                if iter1.peek().is_some() {
                    buffer.push_str(", ");
                }
            }
            buffer.push_str("]");
            if iter0.peek().is_some() {
                buffer.push_str(", ");
            }
        }
        buffer.push_str("]");

        write!(f, "{}", buffer)
    }
}

impl<T: fmt::Display> fmt::Display for VarT<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            VarT::Var(i, j) => {
                write!(f, "Var {} {}", i, j)
            },
            VarT::T(ref x) => {
                write!(f, "T \"{}\"", x)
            },
        }
    }
}

impl<N: fmt::Display, T: fmt::Display, W: fmt::Display> fmt::Display for PMCFGRule<N, T, W> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
           let mut buffer = "".to_string();

           let mut iter = self.tail.iter().peekable();

           buffer.push_str("(");
           while let Some(nt) = iter.next() {
               buffer.push_str(format!("\"{}\"", nt).as_str());
               if iter.peek().is_some() {
                   buffer.push_str(", ");
               }
           }
           buffer.push_str(")");

        write!(f, "\"{}\" → {} {}  # {}", self.head, self.composition, buffer, self.weight)
        // write!(f, "\"{}\" → {}", self.head, self.composition)
    }
}

impl<N: fmt::Display, T: fmt::Display, W: fmt::Display> fmt::Display for PMCFG<N, T, W> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buffer = "".to_string();

        let mut iter = self.initial.iter().peekable();

        buffer.push_str("initial: [");
        while let Some(nt) = iter.next() {
            buffer.push_str(format!("\"{}\"", nt).as_str());
            if iter.peek().is_some() {
                buffer.push_str(", ");
            }
        }
        buffer.push_str("]\n\n");

        for r in &self.rules {
            buffer.push_str(format!("{}\n", r).as_str());
        }

        write!(f, "{}", buffer)
    }
}

pub fn evaluate<T: Clone + fmt::Debug>(term_map: &BTreeMap<Vec<usize>, Composition<T>>)
        -> Composition<T>
{
    evaluate_pos(term_map, vec![])
}

pub fn evaluate_pos<T>(term_map: &BTreeMap<Vec<usize>, Composition<T>>, address: Vec<usize>)
        -> Composition<T>
    where T: Clone + fmt::Debug,
{
    let unexpanded_composition = &term_map.get(&address).unwrap().composition;
    let mut expanded_nonterminals: BTreeMap<_, Vec<Vec<VarT<T>>>> = BTreeMap::new();
    let mut expanded_composition = Vec::new();

    for component in unexpanded_composition {
        let mut expanded_component = Vec::new();

        for variable in component {
            match variable {
                &VarT::Var(num_nonter, num_compon) => {
                    if !expanded_nonterminals.contains_key(&num_nonter) {
                        let mut child_address = address.clone();
                        child_address.push(num_nonter);
                        let nonter_compos = evaluate_pos(term_map, child_address).composition;
                        expanded_nonterminals.insert(num_nonter, nonter_compos);
                    }

                    let nonter_compos = expanded_nonterminals.get(&num_nonter).unwrap();

                    if let Some(compon) = nonter_compos.get(num_compon) {
                        for terminal in compon {
                            expanded_component.push(terminal.clone());
                        }
                    } else {
                        panic!("{:?}: use of {}-th component of nonterminal {} that has only {} components!",
                               unexpanded_composition, num_compon, num_nonter, nonter_compos.len());
                    }

                },
                &VarT::T(ref terminal) => {
                    expanded_component.push(VarT::T(terminal.clone()));
                },
            }
        }

        expanded_composition.push(expanded_component);
    }

    Composition::from(expanded_composition)
}

pub fn to_term<K, H, T, W>(tree_map: &BTreeMap<K, PMCFGRule<H, T, W>>)
        -> (BTreeMap<K, Composition<T>>, BTreeMap<K, H>)
    where K: Clone + cmp::Ord,
          H: Clone, T: Clone,
{
    let mut term_map = BTreeMap::new();
    let mut head_map = BTreeMap::new();

    for (address, rule) in tree_map {
        let &PMCFGRule { ref head, tail: _, ref composition, weight: _ } = rule;
        term_map.insert(address.clone(), composition.clone());
        head_map.insert(address.clone(), head.clone());
    }

    (term_map, head_map)
}

#[cfg(test)]
mod tests {
    use super::*;
    use self::VarT::{Var, T};
    use std::str::FromStr;

    pub fn example_tree_map() -> BTreeMap<Vec<usize>, PMCFGRule<String, char, usize>> {
        let mut tree_map: BTreeMap<Vec<usize>, _> = BTreeMap::new();

        tree_map.insert(vec![], PMCFGRule::from_str(
            "S -> [[Var 0 0, Var 1 0, Var 0 1, Var 1 1]] (A, B) # 1"
        ).unwrap());
        tree_map.insert(vec![0], PMCFGRule::from_str(
            "A -> [[Var 1 0, Var 0 0], [Var 2 0, Var 0 1]] (A, a, c) # 1"
        ).unwrap());
        tree_map.insert(vec![0, 0], PMCFGRule::from_str(
            "A -> [[Var 1 0, Var 0 0], [Var 2 0, Var 0 1]] (A, a, c) # 1"
        ).unwrap());
        tree_map.insert(vec![0, 0, 0], PMCFGRule::from_str(
            "A -> [[], []] () # 1"
        ).unwrap());
        tree_map.insert(vec![0, 0, 1], PMCFGRule::from_str(
            "a -> [[T a]] () # 1"
        ).unwrap());
        tree_map.insert(vec![0, 0, 2], PMCFGRule::from_str(
            "c -> [[T c]] () # 1"
        ).unwrap());
        tree_map.insert(vec![0, 1], PMCFGRule::from_str(
            "a -> [[T a]] () # 1"
        ).unwrap());
        tree_map.insert(vec![0, 2], PMCFGRule::from_str(
            "c -> [[T c]] () # 1"
        ).unwrap());
        tree_map.insert(vec![1], PMCFGRule::from_str(
            "B -> [[Var 1 0, Var 0 0], [Var 2 0, Var 0 1]] (B, b, d) # 1"
        ).unwrap());
        tree_map.insert(vec![1, 0], PMCFGRule::from_str(
            "B -> [[], []] () # 1"
        ).unwrap());
        tree_map.insert(vec![1, 1], PMCFGRule::from_str(
            "b -> [[T b]] () # 1"
        ).unwrap());
        tree_map.insert(vec![1, 2], PMCFGRule::from_str(
            "d -> [[T d]] () # 1"
        ).unwrap());

        tree_map
    }

    #[test]
    fn test_evaluate() {
        let mut term_map: BTreeMap<Vec<usize>, _> = BTreeMap::new();
        term_map.insert(vec![], Composition::from(vec![
            vec![Var(0, 0), Var(1, 0), Var(0, 1), Var(1, 1)]
        ]));
        term_map.insert(vec![0], Composition::from(vec![
            vec![Var(1, 0), Var(0, 0)],
            vec![Var(2, 0), Var(0, 1)]
        ]));
        term_map.insert(vec![0, 0], Composition::from(vec![
            vec![Var(1, 0), Var(0, 0)],
            vec![Var(2, 0), Var(0, 1)]
        ]));
        term_map.insert(vec![0, 0, 0], Composition::from(vec![
            vec![],
            vec![]
        ]));
        term_map.insert(vec![0, 0, 1], Composition::from(vec![
            vec![T('a')]
        ]));
        term_map.insert(vec![0, 0, 2], Composition::from(vec![
            vec![T('c')]
        ]));
        term_map.insert(vec![0, 1], Composition::from(vec![
            vec![T('a')]
        ]));
        term_map.insert(vec![0, 2], Composition::from(vec![
            vec![T('c')]
        ]));
        term_map.insert(vec![1], Composition::from(vec![
            vec![Var(1, 0), Var(0, 0)],
            vec![Var(2, 0), Var(0, 1)]
        ]));
        term_map.insert(vec![1, 0], Composition::from(vec![
            vec![],
            vec![]
        ]));
        term_map.insert(vec![1, 1], Composition::from(vec![
            vec![T('b')]
        ]));
        term_map.insert(vec![1, 2], Composition::from(vec![
            vec![T('d')]
        ]));

        let expanded_compos = Composition::from(vec![
            vec![T('a'), T('a'), T('b'), T('c'), T('c'), T('d')]
        ]);

        assert_eq!(expanded_compos, evaluate(&term_map));
    }

    #[test]
    #[should_panic(expected =
        "[[Var(0, 0), Var(0, 1)]]: use of 1-th component of nonterminal 0 that has only 1 components!"
    )]
    fn test_evaluate_invalid_composition() {
        let mut term_map: BTreeMap<Vec<usize>, _> = BTreeMap::new();
        term_map.insert(vec![], Composition::from(vec![
            vec![Var(0, 0), Var(0, 1)]
        ]));
        term_map.insert(vec![0], Composition::from(vec![
            vec![T('a')]
        ]));

        evaluate(&term_map);
    }

    pub fn to_dummy_pmcfg_rule<N, T>(head: N, composition: Composition<T>) -> PMCFGRule<N, T, usize> {
        PMCFGRule {
            head,
            tail: vec![],
            composition,
            weight: 0,
        }
    }

    #[test]
    fn test_to_term() {
        let compos0 = Composition::from(vec![
            vec![Var(0, 0), T("a"), Var(0, 1), T("b")]
        ]);
        let compos1 = Composition::from(vec![
            vec![Var(1, 0)],
            vec![T("c")]
        ]);
        let compos2 = Composition::from(vec![
            vec![],
            vec![]
        ]);

        let mut tree_map = BTreeMap::new();
        tree_map.insert(vec![], to_dummy_pmcfg_rule("A", compos0.clone()));
        tree_map.insert(vec![0], to_dummy_pmcfg_rule("B", compos1.clone()));
        tree_map.insert(vec![0, 1], to_dummy_pmcfg_rule("C", compos2.clone()));

        let mut term_map = BTreeMap::new();
        term_map.insert(vec![], compos0);
        term_map.insert(vec![0], compos1);
        term_map.insert(vec![0, 1], compos2);

        let mut head_map = BTreeMap::new();
        head_map.insert(vec![], "A");
        head_map.insert(vec![0], "B");
        head_map.insert(vec![0, 1], "C");

        assert_eq!((term_map, head_map), to_term(&tree_map));
    }
}
<commit_msg>src/pmcfg/mod.rs: adapted tests to changes<commit_after>use std::cmp;
use std::collections::BTreeMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

mod from_str;
// mod relabel;

pub mod negra;

/// Variable or terminal symbol in an MCFG.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
pub enum VarT<T> {
    /// `Var(i, j)` represents the `j`th component of the `i`th successor.
    /// Indexing starts from `0`.
    Var(usize, usize),
    T(T),
}

/// Composition function in an MCFG.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
pub struct Composition<T> {
    pub composition: Vec<Vec<VarT<T>>>,
}

impl<T> From<Vec<Vec<VarT<T>>>> for Composition<T> {
    fn from(encapsulated_value: Vec<Vec<VarT<T>>>) -> Self {
        Composition { composition: encapsulated_value }
    }
}

/// Rule of a weighted MCFG.
#[derive(Debug, PartialOrd, Ord, Clone)]
pub struct PMCFGRule<N, T, W> {
    pub head: N,
    pub tail: Vec<N>,
    pub composition: Composition<T>,
    pub weight: W,
}

impl<N, T, W> PMCFGRule<N, T, W>
    where T: Clone,
          W: Clone,
{
    pub fn map_nonterminals<F, M>(&self, f: F) -> PMCFGRule<M, T, W>
        where F: Fn(&N) -> M,
    {
        PMCFGRule {
            head: f(&self.head),
            tail: self.tail.iter().map(f).collect(),
            composition: self.composition.clone(),
            weight: self.weight.clone()
        }
    }
}

/// A weighted MCFG.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct PMCFG<N, T, W> {
    pub _dummy: PhantomData<T>,
    pub initial: Vec<N>,
    pub rules: Vec<PMCFGRule<N, T, W>>,
}

impl<N: Hash, T: Hash, W> Hash for PMCFGRule<N, T, W> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.head.hash(state);
        self.tail.hash(state);
        self.composition.hash(state);
    }
}

impl<N: PartialEq, T: PartialEq, W> PartialEq for PMCFGRule<N, T, W> {
    fn eq(&self, other: &Self) -> bool {
        self.head == other.head && self.tail == other.tail && self.composition == other.composition
    }
}

impl<N: Eq, T: Eq, W> Eq for PMCFGRule<N, T, W> {}

impl<T: fmt::Display> fmt::Display for Composition<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buffer = "".to_string();

        let mut iter0 = self.composition.iter().peekable();
        let mut iter1;

        buffer.push_str("[");
        while let Some(proj) = iter0.next() {
            iter1 = proj.into_iter().peekable();
            buffer.push_str("[");
            while let Some(vart) = iter1.next() {
                buffer.push_str(format!("{}", vart).as_str());
                if iter1.peek().is_some() {
                    buffer.push_str(", ");
                }
            }
            buffer.push_str("]");
            if iter0.peek().is_some() {
                buffer.push_str(", ");
            }
        }
        buffer.push_str("]");

        write!(f, "{}", buffer)
    }
}

impl<T: fmt::Display> fmt::Display for VarT<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            VarT::Var(i, j) => {
                write!(f, "Var {} {}", i, j)
            },
            VarT::T(ref x) => {
                write!(f, "T \"{}\"", x)
            },
        }
    }
}

impl<N: fmt::Display, T: fmt::Display, W: fmt::Display> fmt::Display for PMCFGRule<N, T, W> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
           let mut buffer = "".to_string();

           let mut iter = self.tail.iter().peekable();

           buffer.push_str("(");
           while let Some(nt) = iter.next() {
               buffer.push_str(format!("\"{}\"", nt).as_str());
               if iter.peek().is_some() {
                   buffer.push_str(", ");
               }
           }
           buffer.push_str(")");

        write!(f, "\"{}\" → {} {}  # {}", self.head, self.composition, buffer, self.weight)
        // write!(f, "\"{}\" → {}", self.head, self.composition)
    }
}

impl<N: fmt::Display, T: fmt::Display, W: fmt::Display> fmt::Display for PMCFG<N, T, W> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buffer = "".to_string();

        let mut iter = self.initial.iter().peekable();

        buffer.push_str("initial: [");
        while let Some(nt) = iter.next() {
            buffer.push_str(format!("\"{}\"", nt).as_str());
            if iter.peek().is_some() {
                buffer.push_str(", ");
            }
        }
        buffer.push_str("]\n\n");

        for r in &self.rules {
            buffer.push_str(format!("{}\n", r).as_str());
        }

        write!(f, "{}", buffer)
    }
}

pub fn evaluate<T: Clone + fmt::Debug>(term_map: &BTreeMap<Vec<usize>, Composition<T>>)
        -> Composition<T>
{
    evaluate_pos(term_map, vec![])
}

pub fn evaluate_pos<T>(term_map: &BTreeMap<Vec<usize>, Composition<T>>, address: Vec<usize>)
        -> Composition<T>
    where T: Clone + fmt::Debug,
{
    let unexpanded_composition = &term_map.get(&address).unwrap().composition;
    let mut expanded_nonterminals: BTreeMap<_, Vec<Vec<VarT<T>>>> = BTreeMap::new();
    let mut expanded_composition = Vec::new();

    for component in unexpanded_composition {
        let mut expanded_component = Vec::new();

        for variable in component {
            match variable {
                &VarT::Var(num_nonter, num_compon) => {
                    if !expanded_nonterminals.contains_key(&num_nonter) {
                        let mut child_address = address.clone();
                        child_address.push(num_nonter);
                        let nonter_compos = evaluate_pos(term_map, child_address).composition;
                        expanded_nonterminals.insert(num_nonter, nonter_compos);
                    }

                    let nonter_compos = expanded_nonterminals.get(&num_nonter).unwrap();

                    if let Some(compon) = nonter_compos.get(num_compon) {
                        for terminal in compon {
                            expanded_component.push(terminal.clone());
                        }
                    } else {
                        panic!("{:?}: use of {}-th component of nonterminal {} that has only {} components!",
                               unexpanded_composition, num_compon, num_nonter, nonter_compos.len());
                    }

                },
                &VarT::T(ref terminal) => {
                    expanded_component.push(VarT::T(terminal.clone()));
                },
            }
        }

        expanded_composition.push(expanded_component);
    }

    Composition::from(expanded_composition)
}

pub fn to_term<K, H, T, W>(tree_map: &BTreeMap<K, PMCFGRule<H, T, W>>)
        -> (BTreeMap<K, Composition<T>>, BTreeMap<K, H>)
    where K: Clone + cmp::Ord,
          H: Clone, T: Clone,
{
    let mut term_map = BTreeMap::new();
    let mut head_map = BTreeMap::new();

    for (address, rule) in tree_map {
        let &PMCFGRule { ref head, tail: _, ref composition, weight: _ } = rule;
        term_map.insert(address.clone(), composition.clone());
        head_map.insert(address.clone(), head.clone());
    }

    (term_map, head_map)
}

#[cfg(test)]
mod tests {
    use super::*;
    use self::VarT::{Var, T};
    use std::str::FromStr;

    pub fn example_tree_map() -> BTreeMap<Vec<usize>, PMCFGRule<String, char, usize>> {
        let mut tree_map: BTreeMap<Vec<usize>, _> = BTreeMap::new();

        tree_map.insert(vec![], PMCFGRule::from_str(
            "S -> [[Var 0 0, Var 1 0, Var 0 1, Var 1 1]] (A, B) # 1"
        ).unwrap());
        tree_map.insert(vec![0], PMCFGRule::from_str(
            "A -> [[Var 1 0, Var 0 0], [Var 2 0, Var 0 1]] (A, a, c) # 1"
        ).unwrap());
        tree_map.insert(vec![0, 0], PMCFGRule::from_str(
            "A -> [[Var 1 0, Var 0 0], [Var 2 0, Var 0 1]] (A, a, c) # 1"
        ).unwrap());
        tree_map.insert(vec![0, 0, 0], PMCFGRule::from_str(
            "A -> [[], []] () # 1"
        ).unwrap());
        tree_map.insert(vec![0, 0, 1], PMCFGRule::from_str(
            "a -> [[T a]] () # 1"
        ).unwrap());
        tree_map.insert(vec![0, 0, 2], PMCFGRule::from_str(
            "c -> [[T c]] () # 1"
        ).unwrap());
        tree_map.insert(vec![0, 1], PMCFGRule::from_str(
            "a -> [[T a]] () # 1"
        ).unwrap());
        tree_map.insert(vec![0, 2], PMCFGRule::from_str(
            "c -> [[T c]] () # 1"
        ).unwrap());
        tree_map.insert(vec![1], PMCFGRule::from_str(
            "B -> [[Var 1 0, Var 0 0], [Var 2 0, Var 0 1]] (B, b, d) # 1"
        ).unwrap());
        tree_map.insert(vec![1, 0], PMCFGRule::from_str(
            "B -> [[], []] () # 1"
        ).unwrap());
        tree_map.insert(vec![1, 1], PMCFGRule::from_str(
            "b -> [[T b]] () # 1"
        ).unwrap());
        tree_map.insert(vec![1, 2], PMCFGRule::from_str(
            "d -> [[T d]] () # 1"
        ).unwrap());

        tree_map
    }

    #[test]
    fn test_evaluate() {
        let tree_map = example_tree_map();
        let mut term_map = BTreeMap::new();

        for (address, PMCFGRule { head: _, tail: _, composition, weight: _ }) in tree_map {
            term_map.insert(address, composition);
        }

        let expanded_compos = Composition::from(vec![
            vec![T('a'), T('a'), T('b'), T('c'), T('c'), T('d')]
        ]);

        assert_eq!(expanded_compos, evaluate(&term_map));
    }

    #[test]
    #[should_panic(expected =
        "[[Var(0, 0), Var(0, 1)]]: use of 1-th component of nonterminal 0 that has only 1 components!"
    )]
    fn test_evaluate_invalid_composition() {
        let mut term_map: BTreeMap<Vec<usize>, _> = BTreeMap::new();
        term_map.insert(vec![], Composition::from(vec![
            vec![Var(0, 0), Var(0, 1)]
        ]));
        term_map.insert(vec![0], Composition::from(vec![
            vec![T('a')]
        ]));

        evaluate(&term_map);
    }

    #[test]
    fn test_to_term() {
        let mut tree_map: BTreeMap<_, PMCFGRule<String, char, usize>> = BTreeMap::new();

        tree_map.insert(vec![], PMCFGRule::from_str(
            "A -> [[Var 0 0, T a, Var 0 1, T b]] (B) # 1"
        ).unwrap());
        tree_map.insert(vec![0], PMCFGRule::from_str(
            "B -> [[Var 1 0], [T c]] (C) # 1"
        ).unwrap());
        tree_map.insert(vec![0, 1], PMCFGRule::from_str(
            "C -> [[], []] () # 1"
        ).unwrap());

        let mut term_map = BTreeMap::new();
        term_map.insert(vec![], Composition::from(vec![
            vec![Var(0, 0), T('a'), Var(0, 1), T('b')]
        ]));
        term_map.insert(vec![0], Composition::from(vec![
            vec![Var(1, 0)],
            vec![T('c')]
        ]));
        term_map.insert(vec![0, 1], Composition::from(vec![
            vec![],
            vec![]
        ]));

        let mut head_map = BTreeMap::new();
        head_map.insert(vec![], String::from("A"));
        head_map.insert(vec![0], String::from("B"));
        head_map.insert(vec![0, 1], String::from("C"));

        assert_eq!((term_map, head_map), to_term(&tree_map));
    }
}
<|endoftext|>


<commit_before>use azure_sdk_core::errors::AzureError;
use http::header;
use http::HeaderMap;
use serde::de::DeserializeOwned;
use serde::Serialize;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableEntry<T> {
    #[serde(rename = "RowKey")]
    pub row_key: String,
    #[serde(rename = "PartitionKey")]
    pub partition_key: String,
    pub etag: Option<String>, // none means etag check is disabled
    #[serde(flatten)]
    pub payload: T, // raw, partition key is not included
}

impl<T> TableEntry<T>
where
    T: Serialize + DeserializeOwned,
{
    pub fn new(
        row_key: String,
        partition_key: String,
        etag: Option<String>,
        payload: T,
    ) -> TableEntry<T> {
        TableEntry {
            row_key,
            partition_key,
            etag,
            payload,
        }
    }
}

impl<T> std::convert::TryFrom<(&HeaderMap, &[u8])> for TableEntry<T>
where
    T: Serialize + DeserializeOwned,
{
    type Error = AzureError;

    fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> {
        let headers = value.0;
        let body = value.1;
        debug!("headers == {:?}", headers);
        debug!("body == {:?}", body);

        let mut ret: TableEntry<T> = serde_json::from_slice(&body)?;

        // inject etag if present
        ret.etag = match headers.get(header::ETAG) {
            Some(etag) => Some(etag.to_str()?.to_owned()),
            None => None,
        };

        Ok(ret)
    }
}
<commit_msg>don't serialize etag, it is parsed from header<commit_after>use azure_sdk_core::errors::AzureError;
use http::header;
use http::HeaderMap;
use serde::de::DeserializeOwned;
use serde::Serialize;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableEntry<T> {
    #[serde(rename = "RowKey")]
    pub row_key: String,
    #[serde(rename = "PartitionKey")]
    pub partition_key: String,

    // etag is not serialized, it is parsed from the header
    #[serde(skip_serializing)]
    pub etag: Option<String>,

    #[serde(flatten)]
    pub payload: T,
}

impl<T> TableEntry<T>
where
    T: Serialize + DeserializeOwned,
{
    pub fn new(
        row_key: String,
        partition_key: String,
        etag: Option<String>,
        payload: T,
    ) -> TableEntry<T> {
        TableEntry {
            row_key,
            partition_key,
            etag,
            payload,
        }
    }
}

impl<T> std::convert::TryFrom<(&HeaderMap, &[u8])> for TableEntry<T>
where
    T: Serialize + DeserializeOwned,
{
    type Error = AzureError;

    fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> {
        let headers = value.0;
        let body = value.1;
        debug!("headers == {:?}", headers);
        debug!("body == {:?}", body);

        let mut ret: TableEntry<T> = serde_json::from_slice(&body)?;

        // inject etag if present
        ret.etag = match headers.get(header::ETAG) {
            Some(etag) => Some(etag.to_str()?.to_owned()),
            None => None,
        };

        Ok(ret)
    }
}
<|endoftext|>


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

//! Signaling success or failure states (`Result` type)

use clone::Clone;
use cmp::Eq;
use iter::{Iterator, FromIterator};
use option::{None, Option, Some};

/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Show)]
#[must_use]
pub enum Result<T, E> {
    /// Contains the success value
    Ok(T),

    /// Contains the error value
    Err(E)
}

/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////

impl<T, E> Result<T, E> {
    /////////////////////////////////////////////////////////////////////////
    // Querying the contained values
    /////////////////////////////////////////////////////////////////////////

    /// Returns true if the result is `Ok`
    #[inline]
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }

    /// Returns true if the result is `Err`
    #[inline]
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }

    /////////////////////////////////////////////////////////////////////////
    // Adapter for each variant
    /////////////////////////////////////////////////////////////////////////

    /// Convert from `Result<T, E>` to `Option<T>`
    #[inline]
    pub fn ok(self) -> Option<T> {
        match self {
            Ok(x)  => Some(x),
            Err(_) => None,
        }
    }

    /// Convert from `Result<T, E>` to `Option<E>`
    #[inline]
    pub fn err(self) -> Option<E> {
        match self {
            Ok(_)  => None,
            Err(x) => Some(x),
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Adapter for working with references
    /////////////////////////////////////////////////////////////////////////

    /// Convert from `Result<T, E>` to `Result<&T, &E>`
    #[inline]
    pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
        match *self {
            Ok(ref x) => Ok(x),
            Err(ref x) => Err(x),
        }
    }

    /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
    #[inline]
    pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
        match *self {
            Ok(ref mut x) => Ok(x),
            Err(ref mut x) => Err(x),
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Transforming contained values
    /////////////////////////////////////////////////////////////////////////

    /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
    /// contained `Ok` value, leaving an `Err` value untouched.
    ///
    /// This function can be used to compose the results of two functions.
    ///
    /// Example:
    ///
    ///     let res = read_file(file).map(|buf| {
    ///         parse_bytes(buf)
    ///     })
    #[inline]
    pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
        match self {
          Ok(t) => Ok(op(t)),
          Err(e) => Err(e)
        }
    }

    /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
    /// contained `Err` value, leaving an `Ok` value untouched.
    ///
    /// This function can be used to pass through a successful result while handling
    /// an error.
    #[inline]
    pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
        match self {
          Ok(t) => Ok(t),
          Err(e) => Err(op(e))
        }
    }

    ////////////////////////////////////////////////////////////////////////
    // Boolean operations on the values, eager and lazy
    /////////////////////////////////////////////////////////////////////////

    /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
    #[inline]
    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
        match self {
            Ok(_) => res,
            Err(e) => Err(e),
        }
    }

    /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
    ///
    /// This function can be used for control flow based on result values
    #[inline]
    pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
        match self {
            Ok(t) => op(t),
            Err(e) => Err(e),
        }
    }

    /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
    #[inline]
    pub fn or(self, res: Result<T, E>) -> Result<T, E> {
        match self {
            Ok(_) => self,
            Err(_) => res,
        }
    }

    /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
    ///
    /// This function can be used for control flow based on result values
    #[inline]
    pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
        match self {
            Ok(t) => Ok(t),
            Err(e) => op(e),
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Common special cases
    /////////////////////////////////////////////////////////////////////////

    /// Unwraps a result, yielding the content of an `Ok`.
    /// Fails if the value is an `Err`.
    #[inline]
    pub fn unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(_) => fail!("called `Result::unwrap()` on an `Err` value")
        }
    }

    /// Unwraps a result, yielding the content of an `Err`.
    /// Fails if the value is an `Ok`.
    #[inline]
    pub fn unwrap_err(self) -> E {
        match self {
            Ok(_) => fail!("called `Result::unwrap_err()` on an `Ok` value"),
            Err(e) => e
        }
    }
}

/////////////////////////////////////////////////////////////////////////////
// Free functions
/////////////////////////////////////////////////////////////////////////////

/// Takes each element in the `Iterator`: if it is an `Err`, no further
/// elements are taken, and the `Err` is returned. Should no `Err` occur, a
/// vector containing the values of each `Result` is returned.
///
/// Here is an example which increments every integer in a vector,
/// checking for overflow:
///
///     fn inc_conditionally(x: uint) -> Result<uint, &'static str> {
///         if x == uint::MAX { return Err("overflow"); }
///         else { return Ok(x+1u); }
///     }
///     let v = [1u, 2, 3];
///     let res = collect(v.iter().map(|&x| inc_conditionally(x)));
///     assert!(res == Ok(~[2u, 3, 4]));
#[inline]
pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(iter: Iter) -> Result<V, E> {
    // FIXME(#11084): This should be twice as fast once this bug is closed.
    let mut iter = iter.scan(None, |state, x| {
        match x {
            Ok(x) => Some(x),
            Err(err) => {
                *state = Some(err);
                None
            }
        }
    });

    let v: V = FromIterator::from_iter(iter.by_ref());

    match iter.state {
        Some(err) => Err(err),
        None => Ok(v),
    }
}

/// Perform a fold operation over the result values from an iterator.
///
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, the folded value is returned.
#[inline]
pub fn fold<T,
            V,
            E,
            Iter: Iterator<Result<T, E>>>(
            mut iterator: Iter,
            mut init: V,
            f: |V, T| -> V)
            -> Result<V, E> {
    for t in iterator {
        match t {
            Ok(v) => init = f(init, v),
            Err(u) => return Err(u)
        }
    }
    Ok(init)
}

/// Perform a trivial fold operation over the result values
/// from an iterator.
///
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, a simple `Ok(())` is returned.
#[inline]
pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
    fold(iterator, (), |_, _| ())
}

/////////////////////////////////////////////////////////////////////////////
// Tests
/////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;
    use prelude::*;

    use iter::range;

    pub fn op1() -> Result<int, ~str> { Ok(666) }
    pub fn op2() -> Result<int, ~str> { Err(~"sadface") }

    #[test]
    pub fn test_and() {
        assert_eq!(op1().and(Ok(667)).unwrap(), 667);
        assert_eq!(op1().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"bad");

        assert_eq!(op2().and(Ok(667)).unwrap_err(), ~"sadface");
        assert_eq!(op2().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"sadface");
    }

    #[test]
    pub fn test_and_then() {
        assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
        assert_eq!(op1().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"bad");

        assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(), ~"sadface");
        assert_eq!(op2().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"sadface");
    }

    #[test]
    pub fn test_or() {
        assert_eq!(op1().or(Ok(667)).unwrap(), 666);
        assert_eq!(op1().or(Err(~"bad")).unwrap(), 666);

        assert_eq!(op2().or(Ok(667)).unwrap(), 667);
        assert_eq!(op2().or(Err(~"bad")).unwrap_err(), ~"bad");
    }

    #[test]
    pub fn test_or_else() {
        assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
        assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);

        assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
        assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
    }

    #[test]
    pub fn test_impl_map() {
        assert_eq!(Ok::<~str, ~str>(~"a").map(|x| x + "b"), Ok(~"ab"));
        assert_eq!(Err::<~str, ~str>(~"a").map(|x| x + "b"), Err(~"a"));
    }

    #[test]
    pub fn test_impl_map_err() {
        assert_eq!(Ok::<~str, ~str>(~"a").map_err(|x| x + "b"), Ok(~"a"));
        assert_eq!(Err::<~str, ~str>(~"a").map_err(|x| x + "b"), Err(~"ab"));
    }

    #[test]
    fn test_collect() {
        let v: Result<~[int], ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
        assert_eq!(v, Ok(~[]));

        let v: Result<~[int], ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
        assert_eq!(v, Ok(~[0, 1, 2]));

        let v: Result<~[int], int> = collect(range(0, 3)
                                             .map(|x| if x > 1 { Err(x) } else { Ok(x) }));
        assert_eq!(v, Err(2));

        // test that it does not take more elements than it needs
        let functions = [|| Ok(()), || Err(1), || fail!()];

        let v: Result<~[()], int> = collect(functions.iter().map(|f| (*f)()));
        assert_eq!(v, Err(1));
    }

    #[test]
    fn test_fold() {
        assert_eq!(fold_(range(0, 0)
                        .map(|_| Ok::<(), ()>(()))),
                   Ok(()));
        assert_eq!(fold(range(0, 3)
                        .map(|x| Ok::<int, ()>(x)),
                        0, |a, b| a + b),
                   Ok(3));
        assert_eq!(fold_(range(0, 3)
                        .map(|x| if x > 1 { Err(x) } else { Ok(()) })),
                   Err(2));

        // test that it does not take more elements than it needs
        let functions = [|| Ok(()), || Err(1), || fail!()];

        assert_eq!(fold_(functions.iter()
                        .map(|f| (*f)())),
                   Err(1));
    }

    #[test]
    pub fn test_to_str() {
        let ok: Result<int, ~str> = Ok(100);
        let err: Result<int, ~str> = Err(~"Err");

        assert_eq!(ok.to_str(), ~"Ok(100)");
        assert_eq!(err.to_str(), ~"Err(Err)");
    }

    #[test]
    pub fn test_fmt_default() {
        let ok: Result<int, ~str> = Ok(100);
        let err: Result<int, ~str> = Err(~"Err");

        assert_eq!(format!("{}", ok), ~"Ok(100)");
        assert_eq!(format!("{}", err), ~"Err(Err)");
    }
}
<commit_msg>libstd: Add unwrap_or and unwrap_or_handle to Result<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Signaling success or failure states (`Result` type)

use clone::Clone;
use cmp::Eq;
use iter::{Iterator, FromIterator};
use option::{None, Option, Some};

/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Show)]
#[must_use]
pub enum Result<T, E> {
    /// Contains the success value
    Ok(T),

    /// Contains the error value
    Err(E)
}

/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////

impl<T, E> Result<T, E> {
    /////////////////////////////////////////////////////////////////////////
    // Querying the contained values
    /////////////////////////////////////////////////////////////////////////

    /// Returns true if the result is `Ok`
    #[inline]
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }

    /// Returns true if the result is `Err`
    #[inline]
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }

    /////////////////////////////////////////////////////////////////////////
    // Adapter for each variant
    /////////////////////////////////////////////////////////////////////////

    /// Convert from `Result<T, E>` to `Option<T>`
    #[inline]
    pub fn ok(self) -> Option<T> {
        match self {
            Ok(x)  => Some(x),
            Err(_) => None,
        }
    }

    /// Convert from `Result<T, E>` to `Option<E>`
    #[inline]
    pub fn err(self) -> Option<E> {
        match self {
            Ok(_)  => None,
            Err(x) => Some(x),
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Adapter for working with references
    /////////////////////////////////////////////////////////////////////////

    /// Convert from `Result<T, E>` to `Result<&T, &E>`
    #[inline]
    pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
        match *self {
            Ok(ref x) => Ok(x),
            Err(ref x) => Err(x),
        }
    }

    /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
    #[inline]
    pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
        match *self {
            Ok(ref mut x) => Ok(x),
            Err(ref mut x) => Err(x),
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Transforming contained values
    /////////////////////////////////////////////////////////////////////////

    /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
    /// contained `Ok` value, leaving an `Err` value untouched.
    ///
    /// This function can be used to compose the results of two functions.
    ///
    /// Example:
    ///
    ///     let res = read_file(file).map(|buf| {
    ///         parse_bytes(buf)
    ///     })
    #[inline]
    pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
        match self {
          Ok(t) => Ok(op(t)),
          Err(e) => Err(e)
        }
    }

    /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
    /// contained `Err` value, leaving an `Ok` value untouched.
    ///
    /// This function can be used to pass through a successful result while handling
    /// an error.
    #[inline]
    pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
        match self {
          Ok(t) => Ok(t),
          Err(e) => Err(op(e))
        }
    }

    ////////////////////////////////////////////////////////////////////////
    // Boolean operations on the values, eager and lazy
    /////////////////////////////////////////////////////////////////////////

    /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
    #[inline]
    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
        match self {
            Ok(_) => res,
            Err(e) => Err(e),
        }
    }

    /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
    ///
    /// This function can be used for control flow based on result values
    #[inline]
    pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
        match self {
            Ok(t) => op(t),
            Err(e) => Err(e),
        }
    }

    /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
    #[inline]
    pub fn or(self, res: Result<T, E>) -> Result<T, E> {
        match self {
            Ok(_) => self,
            Err(_) => res,
        }
    }

    /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
    ///
    /// This function can be used for control flow based on result values
    #[inline]
    pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
        match self {
            Ok(t) => Ok(t),
            Err(e) => op(e),
        }
    }

    /////////////////////////////////////////////////////////////////////////
    // Common special cases
    /////////////////////////////////////////////////////////////////////////

    /// Unwraps a result, yielding the content of an `Ok`.
    /// Fails if the value is an `Err`.
    #[inline]
    pub fn unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(_) => fail!("called `Result::unwrap()` on an `Err` value")
        }
    }

    /// Unwraps a result, yielding the content of an `Ok`.
    /// Else it returns `optb`.
    #[inline]
    pub fn unwrap_or(self, optb: T) -> T {
        match self {
            Ok(t) => t,
            Err(_) => optb
        }
    }

    /// Unwraps a result, yielding the content of an `Ok`.
    /// If the value is an `Err` then it calls `op` with its value.
    #[inline]
    pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
        match self {
            Ok(t) => t,
            Err(e) => op(e)
        }
    }

    /// Unwraps a result, yielding the content of an `Err`.
    /// Fails if the value is an `Ok`.
    #[inline]
    pub fn unwrap_err(self) -> E {
        match self {
            Ok(_) => fail!("called `Result::unwrap_err()` on an `Ok` value"),
            Err(e) => e
        }
    }
}

/////////////////////////////////////////////////////////////////////////////
// Free functions
/////////////////////////////////////////////////////////////////////////////

/// Takes each element in the `Iterator`: if it is an `Err`, no further
/// elements are taken, and the `Err` is returned. Should no `Err` occur, a
/// vector containing the values of each `Result` is returned.
///
/// Here is an example which increments every integer in a vector,
/// checking for overflow:
///
///     fn inc_conditionally(x: uint) -> Result<uint, &'static str> {
///         if x == uint::MAX { return Err("overflow"); }
///         else { return Ok(x+1u); }
///     }
///     let v = [1u, 2, 3];
///     let res = collect(v.iter().map(|&x| inc_conditionally(x)));
///     assert!(res == Ok(~[2u, 3, 4]));
#[inline]
pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(iter: Iter) -> Result<V, E> {
    // FIXME(#11084): This should be twice as fast once this bug is closed.
    let mut iter = iter.scan(None, |state, x| {
        match x {
            Ok(x) => Some(x),
            Err(err) => {
                *state = Some(err);
                None
            }
        }
    });

    let v: V = FromIterator::from_iter(iter.by_ref());

    match iter.state {
        Some(err) => Err(err),
        None => Ok(v),
    }
}

/// Perform a fold operation over the result values from an iterator.
///
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, the folded value is returned.
#[inline]
pub fn fold<T,
            V,
            E,
            Iter: Iterator<Result<T, E>>>(
            mut iterator: Iter,
            mut init: V,
            f: |V, T| -> V)
            -> Result<V, E> {
    for t in iterator {
        match t {
            Ok(v) => init = f(init, v),
            Err(u) => return Err(u)
        }
    }
    Ok(init)
}

/// Perform a trivial fold operation over the result values
/// from an iterator.
///
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, a simple `Ok(())` is returned.
#[inline]
pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
    fold(iterator, (), |_, _| ())
}

/////////////////////////////////////////////////////////////////////////////
// Tests
/////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;
    use prelude::*;

    use iter::range;

    pub fn op1() -> Result<int, ~str> { Ok(666) }
    pub fn op2() -> Result<int, ~str> { Err(~"sadface") }

    #[test]
    pub fn test_and() {
        assert_eq!(op1().and(Ok(667)).unwrap(), 667);
        assert_eq!(op1().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"bad");

        assert_eq!(op2().and(Ok(667)).unwrap_err(), ~"sadface");
        assert_eq!(op2().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"sadface");
    }

    #[test]
    pub fn test_and_then() {
        assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
        assert_eq!(op1().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"bad");

        assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(), ~"sadface");
        assert_eq!(op2().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"sadface");
    }

    #[test]
    pub fn test_or() {
        assert_eq!(op1().or(Ok(667)).unwrap(), 666);
        assert_eq!(op1().or(Err(~"bad")).unwrap(), 666);

        assert_eq!(op2().or(Ok(667)).unwrap(), 667);
        assert_eq!(op2().or(Err(~"bad")).unwrap_err(), ~"bad");
    }

    #[test]
    pub fn test_or_else() {
        assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
        assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);

        assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
        assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
    }

    #[test]
    pub fn test_impl_map() {
        assert_eq!(Ok::<~str, ~str>(~"a").map(|x| x + "b"), Ok(~"ab"));
        assert_eq!(Err::<~str, ~str>(~"a").map(|x| x + "b"), Err(~"a"));
    }

    #[test]
    pub fn test_impl_map_err() {
        assert_eq!(Ok::<~str, ~str>(~"a").map_err(|x| x + "b"), Ok(~"a"));
        assert_eq!(Err::<~str, ~str>(~"a").map_err(|x| x + "b"), Err(~"ab"));
    }

    #[test]
    fn test_collect() {
        let v: Result<~[int], ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
        assert_eq!(v, Ok(~[]));

        let v: Result<~[int], ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
        assert_eq!(v, Ok(~[0, 1, 2]));

        let v: Result<~[int], int> = collect(range(0, 3)
                                             .map(|x| if x > 1 { Err(x) } else { Ok(x) }));
        assert_eq!(v, Err(2));

        // test that it does not take more elements than it needs
        let functions = [|| Ok(()), || Err(1), || fail!()];

        let v: Result<~[()], int> = collect(functions.iter().map(|f| (*f)()));
        assert_eq!(v, Err(1));
    }

    #[test]
    fn test_fold() {
        assert_eq!(fold_(range(0, 0)
                        .map(|_| Ok::<(), ()>(()))),
                   Ok(()));
        assert_eq!(fold(range(0, 3)
                        .map(|x| Ok::<int, ()>(x)),
                        0, |a, b| a + b),
                   Ok(3));
        assert_eq!(fold_(range(0, 3)
                        .map(|x| if x > 1 { Err(x) } else { Ok(()) })),
                   Err(2));

        // test that it does not take more elements than it needs
        let functions = [|| Ok(()), || Err(1), || fail!()];

        assert_eq!(fold_(functions.iter()
                        .map(|f| (*f)())),
                   Err(1));
    }

    #[test]
    pub fn test_to_str() {
        let ok: Result<int, ~str> = Ok(100);
        let err: Result<int, ~str> = Err(~"Err");

        assert_eq!(ok.to_str(), ~"Ok(100)");
        assert_eq!(err.to_str(), ~"Err(Err)");
    }

    #[test]
    pub fn test_fmt_default() {
        let ok: Result<int, ~str> = Ok(100);
        let err: Result<int, ~str> = Err(~"Err");

        assert_eq!(format!("{}", ok), ~"Ok(100)");
        assert_eq!(format!("{}", err), ~"Err(Err)");
    }

    #[test]
    pub fn test_unwrap_or() {
        let ok: Result<int, ~str> = Ok(100);
        let ok_err: Result<int, ~str> = Err(~"Err");

        assert_eq!(ok.unwrap_or(50), 100);
        assert_eq!(ok_err.unwrap_or(50), 50);
    }

    #[test]
    pub fn test_unwrap_or_else() {
        fn handler(msg: ~str) -> int {
            if msg == ~"I got this." {
                50
            } else {
                fail!("BadBad")
            }
        }

        let ok: Result<int, ~str> = Ok(100);
        let ok_err: Result<int, ~str> = Err(~"I got this.");

        assert_eq!(ok.unwrap_or_handle(handler), 100);
        assert_eq!(ok_err.unwrap_or_handle(handler), 50);
    }

    #[test]
    #[should_fail]
    pub fn test_unwrap_or_else_failure() {
        fn handler(msg: ~str) -> int {
            if msg == ~"I got this." {
                50
            } else {
                fail!("BadBad")
            }
        }

        let bad_err: Result<int, ~str> = Err(~"Unrecoverable mess.");
        let _ : int = bad_err.unwrap_or_handle(handler);
    }
}
<|endoftext|>


<commit_before>#![allow(non_snake_case)]

#[derive(Deserialize, Debug)]
pub struct ConsignmentsetError {
    #[serde(skip_serializing_if="Option::is_none")]
    pub code: Option<i64>,
    pub message: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Senderaddress {
    pub addressLine1: Option<String>,
    pub addressLine2: Option<String>,
    pub postalCode: Option<String>,
    pub city: Option<String>,
    pub countryCode: Option<String>,
    pub country: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Recipientsignature {
    pub name: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct EventsetDefinition {
    pub term: Option<String>,
    pub explanation: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Eventset {
    pub description: String,
    pub status: String,
    pub recipientSignature: Option<Recipientsignature>,
    pub unitId: Option<String>,
    pub unitInformationUrl: Option<String>,
    pub unitType: Option<String>,
    pub postalCode: Option<String>,
    pub city: Option<String>,
    pub countryCode: Option<String>,
    pub country: Option<String>,
    pub dateIso: Option<String>,
    pub displayDate: Option<String>,
    pub displayTime: Option<String>,
    pub consignmentEvent: bool,
    pub definitions: Option<Vec<EventsetDefinition>>
}
#[derive(Deserialize, Debug)]
pub struct Packageset {
    pub statusDescription: String,
    pub descriptions: Vec<String>,
    pub packageNumber: String,
    pub previousPackageNumber: Option<String>,
    pub productName: Option<String>,
    pub productCode: Option<String>,
    pub brand: Option<String>,
    pub lengthInCm: Option<i64>,
    pub widthInCm: Option<i64>,
    pub heightInCm: Option<i64>,
    pub volumeInDm3: Option<f64>,
    pub weightInKgs: Option<f64>,
    pub pickupCode: Option<String>,
    pub dateOfReturn: Option<String>,
    pub senderName: String,
    pub senderAddress: Option<Senderaddress>,
    pub recipientHandlingAddress: Option<Senderaddress>,
    pub eventSet: Vec<Eventset>,
}
#[derive(Deserialize, Debug)]
pub struct Consignmentset {
    pub consignmentId: Option<String>,
    pub previousConsignmentId: Option<String>,
    pub packageSet: Vec<Packageset>,
    pub senderName: Option<String>,
    pub senderAddress: Option<Senderaddress>,
    pub recipientHandlingAddress: Option<Senderaddress>,
    pub senderReference: Option<String>,
    pub totalWeightInKgs: Option<f64>,
    pub totalVolumeInDm3: Option<f64>,
    #[serde(default)]
    pub error: Vec<ConsignmentsetError>, // This probably shouldn't be a Vec?
}
#[derive(Deserialize, Debug)]
pub struct BringResponse {
    pub consignmentSet: Vec<Consignmentset>,
}
<commit_msg>add #[serde(default)] to error<commit_after>#![allow(non_snake_case)]

#[derive(Deserialize, Debug)]
pub struct ConsignmentsetError {
    #[serde(default)]
    pub code: Option<i64>,
    pub message: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Senderaddress {
    pub addressLine1: Option<String>,
    pub addressLine2: Option<String>,
    pub postalCode: Option<String>,
    pub city: Option<String>,
    pub countryCode: Option<String>,
    pub country: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Recipientsignature {
    pub name: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct EventsetDefinition {
    pub term: Option<String>,
    pub explanation: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Eventset {
    pub description: String,
    pub status: String,
    pub recipientSignature: Option<Recipientsignature>,
    pub unitId: Option<String>,
    pub unitInformationUrl: Option<String>,
    pub unitType: Option<String>,
    pub postalCode: Option<String>,
    pub city: Option<String>,
    pub countryCode: Option<String>,
    pub country: Option<String>,
    pub dateIso: Option<String>,
    pub displayDate: Option<String>,
    pub displayTime: Option<String>,
    pub consignmentEvent: bool,
    pub definitions: Option<Vec<EventsetDefinition>>
}
#[derive(Deserialize, Debug)]
pub struct Packageset {
    pub statusDescription: String,
    pub descriptions: Vec<String>,
    pub packageNumber: String,
    pub previousPackageNumber: Option<String>,
    pub productName: Option<String>,
    pub productCode: Option<String>,
    pub brand: Option<String>,
    pub lengthInCm: Option<i64>,
    pub widthInCm: Option<i64>,
    pub heightInCm: Option<i64>,
    pub volumeInDm3: Option<f64>,
    pub weightInKgs: Option<f64>,
    pub pickupCode: Option<String>,
    pub dateOfReturn: Option<String>,
    pub senderName: String,
    pub senderAddress: Option<Senderaddress>,
    pub recipientHandlingAddress: Option<Senderaddress>,
    pub eventSet: Vec<Eventset>,
}
#[derive(Deserialize, Debug)]
pub struct Consignmentset {
    pub consignmentId: Option<String>,
    pub previousConsignmentId: Option<String>,
    pub packageSet: Vec<Packageset>,
    pub senderName: Option<String>,
    pub senderAddress: Option<Senderaddress>,
    pub recipientHandlingAddress: Option<Senderaddress>,
    pub senderReference: Option<String>,
    pub totalWeightInKgs: Option<f64>,
    pub totalVolumeInDm3: Option<f64>,
    #[serde(default)]
    pub error: Vec<ConsignmentsetError>, // This probably shouldn't be a Vec?
}
#[derive(Deserialize, Debug)]
pub struct BringResponse {
    pub consignmentSet: Vec<Consignmentset>,
}
<|endoftext|>


<commit_before>//! Construction of givens rotations.

use alga::general::ComplexField;
use num::{Zero, One};

use crate::base::dimension::{Dim, U2};
use crate::base::constraint::{ShapeConstraint, DimEq};
use crate::base::storage::{Storage, StorageMut};
use crate::base::{Vector, Matrix};

/// A Givens rotation.
#[derive(Debug, Clone, Copy)]
pub struct GivensRotation<N: ComplexField> {
    c: N::RealField,
    s: N
}

// Matrix = UnitComplex * Matrix
impl<N: ComplexField> GivensRotation<N> {
    /// The Givents rotation that does nothing.
    pub fn identity() -> Self {
        Self {
            c: N::RealField::one(),
            s: N::zero()
        }
    }

    /// Initializes a Givens rotation from its components.
    ///
    /// The components are copies as-is. It is not checked whether they describe
    /// an actually valid Givens rotation.
    pub fn new_unchecked(c: N::RealField, s: N) -> Self {
       Self {
           c, s
       }
    }

    /// Initializes a Givens rotation from its non-normalized cosine an sine components.
    pub fn new(c: N, s: N) -> (Self, N) {
        Self::try_new(c, s, N::RealField::zero()).unwrap()
    }

    /// Initializes a Givens rotation form its non-normalized cosine an sine components.
    pub fn try_new(c: N, s: N, eps: N::RealField) -> Option<(Self, N)> {
        let (mod0, sign0) = c.to_exp();
        let denom = (mod0 * mod0 + s.modulus_squared()).sqrt();

        if denom > eps {
            let norm = sign0.scale(denom);
            let c = mod0 / denom;
            let s = s / norm;
            Some((Self { c, s }, norm))
        } else {
            None
        }
    }

    /// Computes the rotation `R` required such that the `y` component of `R * v` is zero.
    ///
    /// Returns `None` if no rotation is needed (i.e. if `v.y == 0`). Otherwise, this returns the norm
    /// of `v` and the rotation `r` such that `R * v = [ |v|, 0.0 ]^t` where `|v|` is the norm of `v`.
    pub fn cancel_y<S: Storage<N, U2>>(v: &Vector<N, U2, S>) -> Option<(Self, N)> {
        if !v[1].is_zero() {
            let (mod0, sign0) = v[0].to_exp();
            let denom = (mod0 * mod0 + v[1].modulus_squared()).sqrt();
            let c = mod0 / denom;
            let s = -v[1] / sign0.scale(denom);
            let r = sign0.scale(denom);
            Some((Self { c, s }, r))
        } else {
            None
        }
    }

    /// Computes the rotation `R` required such that the `x` component of `R * v` is zero.
    ///
    /// Returns `None` if no rotation is needed (i.e. if `v.x == 0`). Otherwise, this returns the norm
    /// of `v` and the rotation `r` such that `R * v = [ 0.0, |v| ]^t` where `|v|` is the norm of `v`.
    pub fn cancel_x<S: Storage<N, U2>>(v: &Vector<N, U2, S>) -> Option<(Self, N)> {
        if !v[0].is_zero() {
            let (mod1, sign1) = v[1].to_exp();
            let denom = (mod1 * mod1 + v[0].modulus_squared()).sqrt();
            let c = mod1 / denom;
            let s = (v[0].conjugate() * sign1).unscale(denom);
            let r = sign1.scale(denom);
            Some((Self { c, s }, r))
        } else {
            None
        }
    }

    /// The cos part of this roration.
    pub fn c(&self) -> N::RealField {
        self.c
    }

    /// The sin part of this roration.
    pub fn s(&self) -> N {
        self.s
    }

    /// The inverse of this givens rotation.
    pub fn inverse(&self) -> Self {
        Self { c: self.c, s: -self.s }
    }

    /// Performs the multiplication `rhs = self * rhs` in-place.
    pub fn rotate<R2: Dim, C2: Dim, S2: StorageMut<N, R2, C2>>(
        &self,
        rhs: &mut Matrix<N, R2, C2, S2>,
    ) where
        ShapeConstraint: DimEq<R2, U2>,
    {
        assert_eq!(
            rhs.nrows(),
            2,
            "Unit complex rotation: the input matrix must have exactly two rows."
        );
        let s = self.s;
        let c = self.c;

        for j in 0..rhs.ncols() {
            unsafe {
                let a = *rhs.get_unchecked((0, j));
                let b = *rhs.get_unchecked((1, j));

                *rhs.get_unchecked_mut((0, j)) = a.scale(c) - s.conjugate() * b;
                *rhs.get_unchecked_mut((1, j)) = s * a + b.scale(c);
            }
        }
    }

    /// Performs the multiplication `lhs = lhs * self` in-place.
    pub fn rotate_rows<R2: Dim, C2: Dim, S2: StorageMut<N, R2, C2>>(
        &self,
        lhs: &mut Matrix<N, R2, C2, S2>,
    ) where
        ShapeConstraint: DimEq<C2, U2>,
    {
        assert_eq!(
            lhs.ncols(),
            2,
            "Unit complex rotation: the input matrix must have exactly two columns."
        );
        let s = self.s;
        let c = self.c;

        // FIXME: can we optimize that to iterate on one column at a time ?
        for j in 0..lhs.nrows() {
            unsafe {
                let a = *lhs.get_unchecked((j, 0));
                let b = *lhs.get_unchecked((j, 1));

                *lhs.get_unchecked_mut((j, 0)) = a.scale(c) + s * b;
                *lhs.get_unchecked_mut((j, 1)) = -s.conjugate() * a + b.scale(c);
            }
        }
    }
}

<commit_msg>GivensRotation::new() should default to (I, 0)<commit_after>//! Construction of givens rotations.

use alga::general::ComplexField;
use num::{Zero, One};

use crate::base::dimension::{Dim, U2};
use crate::base::constraint::{ShapeConstraint, DimEq};
use crate::base::storage::{Storage, StorageMut};
use crate::base::{Vector, Matrix};

/// A Givens rotation.
#[derive(Debug, Clone, Copy)]
pub struct GivensRotation<N: ComplexField> {
    c: N::RealField,
    s: N
}

// Matrix = UnitComplex * Matrix
impl<N: ComplexField> GivensRotation<N> {
    /// The Givents rotation that does nothing.
    pub fn identity() -> Self {
        Self {
            c: N::RealField::one(),
            s: N::zero()
        }
    }

    /// Initializes a Givens rotation from its components.
    ///
    /// The components are copies as-is. It is not checked whether they describe
    /// an actually valid Givens rotation.
    pub fn new_unchecked(c: N::RealField, s: N) -> Self {
       Self {
           c, s
       }
    }

    /// Initializes a Givens rotation from its non-normalized cosine an sine components.
    pub fn new(c: N, s: N) -> (Self, N) {
        Self::try_new(c, s, N::RealField::zero())
            .unwrap_or_else(|| (GivensRotation::identity(), N::zero()))
    }

    /// Initializes a Givens rotation form its non-normalized cosine an sine components.
    pub fn try_new(c: N, s: N, eps: N::RealField) -> Option<(Self, N)> {
        let (mod0, sign0) = c.to_exp();
        let denom = (mod0 * mod0 + s.modulus_squared()).sqrt();

        if denom > eps {
            let norm = sign0.scale(denom);
            let c = mod0 / denom;
            let s = s / norm;
            Some((Self { c, s }, norm))
        } else {
            None
        }
    }

    /// Computes the rotation `R` required such that the `y` component of `R * v` is zero.
    ///
    /// Returns `None` if no rotation is needed (i.e. if `v.y == 0`). Otherwise, this returns the norm
    /// of `v` and the rotation `r` such that `R * v = [ |v|, 0.0 ]^t` where `|v|` is the norm of `v`.
    pub fn cancel_y<S: Storage<N, U2>>(v: &Vector<N, U2, S>) -> Option<(Self, N)> {
        if !v[1].is_zero() {
            let (mod0, sign0) = v[0].to_exp();
            let denom = (mod0 * mod0 + v[1].modulus_squared()).sqrt();
            let c = mod0 / denom;
            let s = -v[1] / sign0.scale(denom);
            let r = sign0.scale(denom);
            Some((Self { c, s }, r))
        } else {
            None
        }
    }

    /// Computes the rotation `R` required such that the `x` component of `R * v` is zero.
    ///
    /// Returns `None` if no rotation is needed (i.e. if `v.x == 0`). Otherwise, this returns the norm
    /// of `v` and the rotation `r` such that `R * v = [ 0.0, |v| ]^t` where `|v|` is the norm of `v`.
    pub fn cancel_x<S: Storage<N, U2>>(v: &Vector<N, U2, S>) -> Option<(Self, N)> {
        if !v[0].is_zero() {
            let (mod1, sign1) = v[1].to_exp();
            let denom = (mod1 * mod1 + v[0].modulus_squared()).sqrt();
            let c = mod1 / denom;
            let s = (v[0].conjugate() * sign1).unscale(denom);
            let r = sign1.scale(denom);
            Some((Self { c, s }, r))
        } else {
            None
        }
    }

    /// The cos part of this roration.
    pub fn c(&self) -> N::RealField {
        self.c
    }

    /// The sin part of this roration.
    pub fn s(&self) -> N {
        self.s
    }

    /// The inverse of this givens rotation.
    pub fn inverse(&self) -> Self {
        Self { c: self.c, s: -self.s }
    }

    /// Performs the multiplication `rhs = self * rhs` in-place.
    pub fn rotate<R2: Dim, C2: Dim, S2: StorageMut<N, R2, C2>>(
        &self,
        rhs: &mut Matrix<N, R2, C2, S2>,
    ) where
        ShapeConstraint: DimEq<R2, U2>,
    {
        assert_eq!(
            rhs.nrows(),
            2,
            "Unit complex rotation: the input matrix must have exactly two rows."
        );
        let s = self.s;
        let c = self.c;

        for j in 0..rhs.ncols() {
            unsafe {
                let a = *rhs.get_unchecked((0, j));
                let b = *rhs.get_unchecked((1, j));

                *rhs.get_unchecked_mut((0, j)) = a.scale(c) - s.conjugate() * b;
                *rhs.get_unchecked_mut((1, j)) = s * a + b.scale(c);
            }
        }
    }

    /// Performs the multiplication `lhs = lhs * self` in-place.
    pub fn rotate_rows<R2: Dim, C2: Dim, S2: StorageMut<N, R2, C2>>(
        &self,
        lhs: &mut Matrix<N, R2, C2, S2>,
    ) where
        ShapeConstraint: DimEq<C2, U2>,
    {
        assert_eq!(
            lhs.ncols(),
            2,
            "Unit complex rotation: the input matrix must have exactly two columns."
        );
        let s = self.s;
        let c = self.c;

        // FIXME: can we optimize that to iterate on one column at a time ?
        for j in 0..lhs.nrows() {
            unsafe {
                let a = *lhs.get_unchecked((j, 0));
                let b = *lhs.get_unchecked((j, 1));

                *lhs.get_unchecked_mut((j, 0)) = a.scale(c) + s * b;
                *lhs.get_unchecked_mut((j, 1)) = -s.conjugate() * a + b.scale(c);
            }
        }
    }
}

<|endoftext|>