<commit_before>// This is a part of rust-chrono.
// Copyright (c) 2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.

/*!
 * The local (system) time zone.
 */

use stdtime;

use {Datelike, Timelike};
use duration::Duration;
use naive::date::NaiveDate;
use naive::time::NaiveTime;
use naive::datetime::NaiveDateTime;
use date::Date;
use datetime::DateTime;
use super::{TimeZone, LocalResult};
use super::fixed::FixedOffset;

/// Converts a `time::Tm` struct into the timezone-aware `DateTime`.
/// This assumes that `time` is working correctly, i.e. any error is fatal.
fn tm_to_datetime(mut tm: stdtime::Tm) -> DateTime<Local> {
    if tm.tm_sec >= 60 {
        tm.tm_nsec += (tm.tm_sec - 59) * 1_000_000_000;
        tm.tm_sec = 59;
    }

    // from_yo is more efficient than from_ymd (since it's the internal representation).
    let date = NaiveDate::from_yo(tm.tm_year + 1900, tm.tm_yday as u32 + 1);
    let time = NaiveTime::from_hms_nano(tm.tm_hour as u32, tm.tm_min as u32,
                                        tm.tm_sec as u32, tm.tm_nsec as u32);
    let offset = FixedOffset::east(tm.tm_utcoff);
    DateTime::from_utc(date.and_time(time) + Duration::seconds(-tm.tm_utcoff as i64), offset)
}

/// Converts a local `NaiveDateTime` to the `time::Timespec`.
fn datetime_to_timespec(d: &NaiveDateTime, local: bool) -> stdtime::Timespec {
    // well, this exploits an undocumented `Tm::to_timespec` behavior
    // to get the exact function we want (either `timegm` or `mktime`).
    // the number 1 is arbitrary but should be non-zero to trigger `mktime`.
    let tm_utcoff = if local {1} else {0};

    let tm = stdtime::Tm {
        tm_sec: d.second() as i32,
        tm_min: d.minute() as i32,
        tm_hour: d.hour() as i32,
        tm_mday: d.day() as i32,
        tm_mon: d.month0() as i32, // yes, C is that strange...
        tm_year: d.year() - 1900, // this doesn't underflow, we know that d is `NaiveDateTime`.
        tm_wday: 0, // to_local ignores this
        tm_yday: 0, // and this
        tm_isdst: -1,
        tm_utcoff: tm_utcoff,
        tm_nsec: d.nanosecond() as i32,
    };
    tm.to_timespec()
}

/// The local timescale. This is implemented via the standard `time` crate.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub struct Local;

impl Local {
    /// Returns a `Date` which corresponds to the current date.
    pub fn today() -> Date<Local> {
        Local::now().date()
    }

    /// Returns a `DateTime` which corresponds to the current date.
    pub fn now() -> DateTime<Local> {
        tm_to_datetime(stdtime::now())
    }
}

impl TimeZone for Local {
    type Offset = FixedOffset;

    fn from_offset(_offset: &FixedOffset) -> Local { Local }

    // they are easier to define in terms of the finished date and time unlike other offsets
    fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<FixedOffset> {
        self.from_local_date(local).map(|date| *date.offset())
    }
    fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<FixedOffset> {
        self.from_local_datetime(local).map(|datetime| *datetime.offset())
    }

    fn offset_from_utc_date(&self, utc: &NaiveDate) -> FixedOffset {
        *self.from_utc_date(utc).offset()
    }
    fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> FixedOffset {
        *self.from_utc_datetime(utc).offset()
    }

    // override them for avoiding redundant works
    fn from_local_date(&self, local: &NaiveDate) -> LocalResult<Date<Local>> {
        // this sounds very strange, but required for keeping `TimeZone::ymd` sane.
        // in the other words, we use the offset at the local midnight
        // but keep the actual date unaltered (much like `FixedOffset`).
        let midnight = self.from_local_datetime(&local.and_hms(0, 0, 0));
        midnight.map(|datetime| Date::from_utc(*local, datetime.offset().clone()))
    }
    fn from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<DateTime<Local>> {
        let timespec = datetime_to_timespec(local, true);
        LocalResult::Single(tm_to_datetime(stdtime::at(timespec)))
    }

    fn from_utc_date(&self, utc: &NaiveDate) -> Date<Local> {
        let midnight = self.from_utc_datetime(&utc.and_hms(0, 0, 0));
        Date::from_utc(*utc, midnight.offset().clone())
    }
    fn from_utc_datetime(&self, utc: &NaiveDateTime) -> DateTime<Local> {
        let timespec = datetime_to_timespec(utc, false);
        tm_to_datetime(stdtime::at(timespec))
    }
}

<commit_msg>Workaround for rust-lang-deprecated/time#137.<commit_after>// This is a part of rust-chrono.
// Copyright (c) 2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.

/*!
 * The local (system) time zone.
 */

use stdtime;

use {Datelike, Timelike};
use duration::Duration;
use naive::date::NaiveDate;
use naive::time::NaiveTime;
use naive::datetime::NaiveDateTime;
use date::Date;
use datetime::DateTime;
use super::{TimeZone, LocalResult};
use super::fixed::FixedOffset;

/// Converts a `time::Tm` struct into the timezone-aware `DateTime`.
/// This assumes that `time` is working correctly, i.e. any error is fatal.
fn tm_to_datetime(mut tm: stdtime::Tm) -> DateTime<Local> {
    if tm.tm_sec >= 60 {
        tm.tm_nsec += (tm.tm_sec - 59) * 1_000_000_000;
        tm.tm_sec = 59;
    }

    #[cfg(not(windows))]
    fn tm_to_naive_date(tm: &stdtime::Tm) -> NaiveDate {
        // from_yo is more efficient than from_ymd (since it's the internal representation).
        NaiveDate::from_yo(tm.tm_year + 1900, tm.tm_yday as u32 + 1)
    }

    #[cfg(windows)]
    fn tm_to_naive_date(tm: &stdtime::Tm) -> NaiveDate {
        // ...but tm_yday is broken in Windows (issue #85)
        NaiveDate::from_ymd(tm.tm_year + 1900, tm.tm_mon as u32 + 1, tm.tm_mday as u32)
    }

    let date = tm_to_naive_date(&tm);
    let time = NaiveTime::from_hms_nano(tm.tm_hour as u32, tm.tm_min as u32,
                                        tm.tm_sec as u32, tm.tm_nsec as u32);
    let offset = FixedOffset::east(tm.tm_utcoff);
    DateTime::from_utc(date.and_time(time) + Duration::seconds(-tm.tm_utcoff as i64), offset)
}

/// Converts a local `NaiveDateTime` to the `time::Timespec`.
fn datetime_to_timespec(d: &NaiveDateTime, local: bool) -> stdtime::Timespec {
    // well, this exploits an undocumented `Tm::to_timespec` behavior
    // to get the exact function we want (either `timegm` or `mktime`).
    // the number 1 is arbitrary but should be non-zero to trigger `mktime`.
    let tm_utcoff = if local {1} else {0};

    let tm = stdtime::Tm {
        tm_sec: d.second() as i32,
        tm_min: d.minute() as i32,
        tm_hour: d.hour() as i32,
        tm_mday: d.day() as i32,
        tm_mon: d.month0() as i32, // yes, C is that strange...
        tm_year: d.year() - 1900, // this doesn't underflow, we know that d is `NaiveDateTime`.
        tm_wday: 0, // to_local ignores this
        tm_yday: 0, // and this
        tm_isdst: -1,
        tm_utcoff: tm_utcoff,
        tm_nsec: d.nanosecond() as i32,
    };
    tm.to_timespec()
}

/// The local timescale. This is implemented via the standard `time` crate.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub struct Local;

impl Local {
    /// Returns a `Date` which corresponds to the current date.
    pub fn today() -> Date<Local> {
        Local::now().date()
    }

    /// Returns a `DateTime` which corresponds to the current date.
    pub fn now() -> DateTime<Local> {
        tm_to_datetime(stdtime::now())
    }
}

impl TimeZone for Local {
    type Offset = FixedOffset;

    fn from_offset(_offset: &FixedOffset) -> Local { Local }

    // they are easier to define in terms of the finished date and time unlike other offsets
    fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<FixedOffset> {
        self.from_local_date(local).map(|date| *date.offset())
    }
    fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<FixedOffset> {
        self.from_local_datetime(local).map(|datetime| *datetime.offset())
    }

    fn offset_from_utc_date(&self, utc: &NaiveDate) -> FixedOffset {
        *self.from_utc_date(utc).offset()
    }
    fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> FixedOffset {
        *self.from_utc_datetime(utc).offset()
    }

    // override them for avoiding redundant works
    fn from_local_date(&self, local: &NaiveDate) -> LocalResult<Date<Local>> {
        // this sounds very strange, but required for keeping `TimeZone::ymd` sane.
        // in the other words, we use the offset at the local midnight
        // but keep the actual date unaltered (much like `FixedOffset`).
        let midnight = self.from_local_datetime(&local.and_hms(0, 0, 0));
        midnight.map(|datetime| Date::from_utc(*local, datetime.offset().clone()))
    }
    fn from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<DateTime<Local>> {
        let timespec = datetime_to_timespec(local, true);
        LocalResult::Single(tm_to_datetime(stdtime::at(timespec)))
    }

    fn from_utc_date(&self, utc: &NaiveDate) -> Date<Local> {
        let midnight = self.from_utc_datetime(&utc.and_hms(0, 0, 0));
        Date::from_utc(*utc, midnight.offset().clone())
    }
    fn from_utc_datetime(&self, utc: &NaiveDateTime) -> DateTime<Local> {
        let timespec = datetime_to_timespec(utc, false);
        tm_to_datetime(stdtime::at(timespec))
    }
}

<|endoftext|>


<commit_before>//! Type represents a data type. Its implementation is pluggable.
//! So, Types are loaded from the packages.
//!

use std::fmt;
use std::mem;
use std::cmp::Ordering;
use std::rc::Rc;

use itertools::Itertools;

use err::Result;
use page::Chunk;

pub type TypeFactory = Rc<Fn(&str) -> Result<Ty>>;

pub mod name {
  pub static BOOL: &'static str = "bool";
  pub static U8: &'static str = "u8";
  pub static I8: &'static str = "i8";
  pub static I16: &'static str = "i16";
  pub static I32: &'static str = "i32";
  pub static I64: &'static str = "i64";
  pub static F32: &'static str = "f32";
  pub static F64: &'static str = "f64";
  pub static Array: &'static str = "Array";
  pub static Tuple: &'static str = "Tuple";
}

pub static BOOL: &'static Ty = &Ty::Bool;
pub static U8: &'static Ty = &Ty::U8;
pub static I8: &'static Ty = &Ty::I8;
pub static I16: &'static Ty = &Ty::I16;
pub static I32: &'static Ty = &Ty::I32;
pub static I64: &'static Ty = &Ty::I64;
pub static F32: &'static Ty = &Ty::F32;
pub static F64: &'static Ty = &Ty::F64;

/// Types
///
/// * Bool
/// * U8 : unsigned 8 bit integer
/// * I8 : signed 8 bit integer
/// * I16: signed 16 bit integer
/// * I32: signed 32 bit integer
/// * I64: signed 64 bit integer
/// * F32: single precision floating type
/// * F64: double precision floating type
/// * Array: multi-dimensional array of same elements
/// * Tuple: an ordered list of arbtrary type values
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug)]
pub enum Ty {
  Bool,
  U8,
  I8,
  I16,
  I32,
  I64,
  F32,
  F64,
  Array(Box<Ty>, Vec<usize>),
  Tuple(Vec<Ty>),
}

impl Ty {
  /// Get a base name
  pub fn base(&self) -> &str {
    match *self {
      Ty::Bool => name::BOOL,
      Ty::U8 => name::U8,
      Ty::I8 => name::I8,
      Ty::I16 => name::I16,
      Ty::I32 => name::I32,
      Ty::I64 => name::I64,
      Ty::F32 => name::F32,
      Ty::F64 => name::F64,
      Ty::Array(..) => panic!("unsupported type: vector"),
      Ty::Tuple(_) => panic!("unsupported type: tuple"),
    }
  }

  #[inline(always)]
  pub fn is_int(&self) -> bool {
    self.is_sint() || self.is_uint()
  }

  pub fn is_sint(&self) -> bool {
    match *self {
      Ty::Bool |
      Ty::I8 |
      Ty::I16 |
      Ty::I32 |
      Ty::I64 => true,
      _ => false,
    }
  }

  pub fn is_uint(&self) -> bool {
    *self == Ty::U8
  }

  pub fn is_float(&self) -> bool {
    *self == Ty::F32 || *self == Ty::F64
  }

  pub fn size_of(&self) -> usize {
    match *self {
      Ty::Bool => 1,
      Ty::U8 | Ty::I8 => 1,
      Ty::I16 => 2,
      Ty::I32 | Ty::F32 => 4,
      Ty::I64 | Ty::F64 => 8,
      Ty::Array(ref ty, ref dims) => dims.iter().fold(0, |acc, dim| acc + (ty.size_of() * dim)),
      Ty::Tuple(ref tys) => tys.iter().fold(0, |acc, ty| acc + ty.size_of()),
    }
  }

  pub fn is_variable(&self) -> bool {
    false
  }
}

pub fn u(size: u32) -> &'static Ty {
  match size {
    8 => U8,
    _ => panic!("unsupported integer type: i{}", size),
  }
}

pub fn i(size: u32) -> &'static Ty {
  match size {
    8 => I8,
    16 => I16,
    32 => I32,
    64 => I64,
    _ => panic!("unsupported integer type: i{}", size),
  }
}

pub fn f(size: u32) -> &'static Ty {
  match size {
    32 => F32,
    64 => F64,
    _ => panic!("unsupported integer type: f{}", size),
  }
}

/// Typed implementation
pub trait HasType {
  fn ty(&self) -> &Ty;
}

impl fmt::Display for Ty {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match *self {
      Ty::Bool => write!(f, "bool"),
      Ty::I8 => write!(f, "i8"),
      Ty::U8 => write!(f, "u8"),
      Ty::I16 => write!(f, "i16"),
      Ty::I32 => write!(f, "i32"),
      Ty::I64 => write!(f, "i64"),
      Ty::F32 => write!(f, "f32"),
      Ty::F64 => write!(f, "f64"),
      Ty::Array(ref ty, ref dims) => {
        write!(f, "Array({},{})", ty, dims.iter().map(|dim| format!("{}", dim)).join(","))
      }
      Ty::Tuple(ref types) => {
        write!(f, "Tuple({})", types.iter().map(|dim| format!("{}", dim)).join(","))
      }
    }
  }
}

//
// Determine a result data type from two expression data types.
// #[allow(unused_variables)]
// pub fn result_data_ty(lhs_ty: &Ty, rhs_ty: &Ty) -> Ty {
// match *lhs_ty {
// Ty::Bool => {
// match *rhs_ty {
// Ty::Bool => rhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
//
// Ty::Int1 => {
// match *rhs_ty {
// Ty::Int1   |
// Ty::Int2   |
// Ty::Int4   |
// Ty::Int8   |
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Int2 => {
// match *rhs_ty {
// Ty::Int2   |
// Ty::Int4   |
// Ty::Int8   |
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1   => lhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Int4 => {
// match *rhs_ty {
// Ty::Int4   |
// Ty::Int8   |
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1 |
// Ty::Int2 => lhs_ty.clone(),
//
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Int8 => {
// match *rhs_ty {
// Ty::Int8   |
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1 |
// Ty::Int2 |
// Ty::Int4 => lhs_ty.clone(),
//
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Float4 => {
// match *rhs_ty {
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1 |
// Ty::Int2 |
// Ty::Int4 |
// Ty::Int8 => lhs_ty.clone(),
//
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Float8 => {
// match *rhs_ty {
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1   |
// Ty::Int2   |
// Ty::Int4   |
// Ty::Int8   |
// Ty::Float4 => lhs_ty.clone(),
//
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Numeric(ref p, ref s) => {
// panic!("Undefined operator")
// },
//
// Ty::Date => {
// panic!("Undefined Operator")
// },
//
// Ty::Time => {
// panic!("Undefined Operator")
// },
//
// Ty::Timez => {
// panic!("Undefined Operator")
// },
//
// Ty::Timestamp => {
// panic!("Undefined Operator")
// },
//
// Ty::Timestampz => {
// panic!("Undefined Operator")
// },
//
// Ty::Interval => {
// panic!("Undefined Operator")
// },
//
// Ty::Char(ref len) => {
// panic!("Undefined Operator")
// },
//
// Ty::Binary(ref len) => {
// panic!("Undefined Operator")
// },
//
// Ty::Clob => {
// match *rhs_ty {
// Ty::Clob => rhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Blob => {
// match *rhs_ty {
// Ty::Blob => rhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Array(ref ty) => {
// panic!("Undefined Operator")
// }
//
// Ty::Struct(ref tys) => {
// panic!("Undefined Operator")
// },
//
// Ty::Map(ref kty, ref vty) => {
// panic!("Undefined Operator")
// }
// }
// }
//

// pub fn bool_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<bool>()))
// })
// };
//
// Ty::new(BOOL_STR, true, true, handler)
// }
//
// pub fn i8_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<i8>()))
// })
// };
//
// Ty::new(I8_STR, true, true, handler)
// }
//
// pub fn i16_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<i16>()))
// })
// };
//
// Ty::new(I32_STR, true, true, handler)
// }
//
// pub fn i32_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<i32>()))
// })
// };
//
// Ty::new(I32_STR, true, true, handler)
// }
//
// pub fn i64_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<i64>()))
// })
// };
//
// Ty::new(I64_STR, true, true, handler)
// }
//
// pub fn f32_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<f32>()))
// })
// };
//
// Ty::new(F32_STR, true, true, handler)
// }
//
// pub fn f64_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<f64>()))
// })
// };
//
// Ty::new(F64_STR, true, true, handler)
// }
//<commit_msg>Add unit tests for 'Display for Ty'.<commit_after>//! Type represents a data type. Its implementation is pluggable.
//! So, Types are loaded from the packages.
//!

use std::fmt;
use std::mem;
use std::cmp::Ordering;
use std::rc::Rc;

use itertools::Itertools;

use err::Result;
use page::Chunk;

pub type TypeFactory = Rc<Fn(&str) -> Result<Ty>>;

pub mod name {
  pub static BOOL: &'static str = "bool";
  pub static U8: &'static str = "u8";
  pub static I8: &'static str = "i8";
  pub static I16: &'static str = "i16";
  pub static I32: &'static str = "i32";
  pub static I64: &'static str = "i64";
  pub static F32: &'static str = "f32";
  pub static F64: &'static str = "f64";
  pub static Array: &'static str = "Array";
  pub static Tuple: &'static str = "Tuple";
}

pub static BOOL: &'static Ty = &Ty::Bool;
pub static U8: &'static Ty = &Ty::U8;
pub static I8: &'static Ty = &Ty::I8;
pub static I16: &'static Ty = &Ty::I16;
pub static I32: &'static Ty = &Ty::I32;
pub static I64: &'static Ty = &Ty::I64;
pub static F32: &'static Ty = &Ty::F32;
pub static F64: &'static Ty = &Ty::F64;

/// Types
///
/// * Bool
/// * U8 : unsigned 8 bit integer
/// * I8 : signed 8 bit integer
/// * I16: signed 16 bit integer
/// * I32: signed 32 bit integer
/// * I64: signed 64 bit integer
/// * F32: single precision floating type
/// * F64: double precision floating type
/// * Array: multi-dimensional array of same elements
/// * Tuple: an ordered list of arbtrary type values
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug)]
pub enum Ty {
  Bool,
  U8,
  I8,
  I16,
  I32,
  I64,
  F32,
  F64,
  Array(Box<Ty>, Vec<usize>),
  Tuple(Vec<Ty>),
}

impl Ty {
  /// Get a base name
  pub fn base(&self) -> &str {
    match *self {
      Ty::Bool => name::BOOL,
      Ty::U8 => name::U8,
      Ty::I8 => name::I8,
      Ty::I16 => name::I16,
      Ty::I32 => name::I32,
      Ty::I64 => name::I64,
      Ty::F32 => name::F32,
      Ty::F64 => name::F64,
      Ty::Array(..) => panic!("unsupported type: vector"),
      Ty::Tuple(_) => panic!("unsupported type: tuple"),
    }
  }

  #[inline(always)]
  pub fn is_int(&self) -> bool {
    self.is_sint() || self.is_uint()
  }

  pub fn is_sint(&self) -> bool {
    match *self {
      Ty::Bool |
      Ty::I8 |
      Ty::I16 |
      Ty::I32 |
      Ty::I64 => true,
      _ => false,
    }
  }

  pub fn is_uint(&self) -> bool {
    *self == Ty::U8
  }

  pub fn is_float(&self) -> bool {
    *self == Ty::F32 || *self == Ty::F64
  }

  pub fn size_of(&self) -> usize {
    match *self {
      Ty::Bool => 1,
      Ty::U8 | Ty::I8 => 1,
      Ty::I16 => 2,
      Ty::I32 | Ty::F32 => 4,
      Ty::I64 | Ty::F64 => 8,
      Ty::Array(ref ty, ref dims) => dims.iter().fold(0, |acc, dim| acc + (ty.size_of() * dim)),
      Ty::Tuple(ref tys) => tys.iter().fold(0, |acc, ty| acc + ty.size_of()),
    }
  }

  pub fn is_variable(&self) -> bool {
    false
  }
}

pub fn u(size: u32) -> &'static Ty {
  match size {
    8 => U8,
    _ => panic!("unsupported integer type: i{}", size),
  }
}

pub fn i(size: u32) -> &'static Ty {
  match size {
    8 => I8,
    16 => I16,
    32 => I32,
    64 => I64,
    _ => panic!("unsupported integer type: i{}", size),
  }
}

pub fn f(size: u32) -> &'static Ty {
  match size {
    32 => F32,
    64 => F64,
    _ => panic!("unsupported integer type: f{}", size),
  }
}

/// Typed implementation
pub trait HasType {
  fn ty(&self) -> &Ty;
}

impl fmt::Display for Ty {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match *self {
      Ty::Bool => write!(f, "bool"),
      Ty::I8 => write!(f, "i8"),
      Ty::U8 => write!(f, "u8"),
      Ty::I16 => write!(f, "i16"),
      Ty::I32 => write!(f, "i32"),
      Ty::I64 => write!(f, "i64"),
      Ty::F32 => write!(f, "f32"),
      Ty::F64 => write!(f, "f64"),
      Ty::Array(ref ty, ref dims) => {
        write!(f, "Array({},{})", ty, dims.iter().map(|dim| format!("{}", dim)).join(","))
      }
      Ty::Tuple(ref types) => {
        write!(f, "({})", types.iter().map(|dim| format!("{}", dim)).join(","))
      }
    }
  }
}

//
// Determine a result data type from two expression data types.
// #[allow(unused_variables)]
// pub fn result_data_ty(lhs_ty: &Ty, rhs_ty: &Ty) -> Ty {
// match *lhs_ty {
// Ty::Bool => {
// match *rhs_ty {
// Ty::Bool => rhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
//
// Ty::Int1 => {
// match *rhs_ty {
// Ty::Int1   |
// Ty::Int2   |
// Ty::Int4   |
// Ty::Int8   |
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Int2 => {
// match *rhs_ty {
// Ty::Int2   |
// Ty::Int4   |
// Ty::Int8   |
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1   => lhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Int4 => {
// match *rhs_ty {
// Ty::Int4   |
// Ty::Int8   |
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1 |
// Ty::Int2 => lhs_ty.clone(),
//
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Int8 => {
// match *rhs_ty {
// Ty::Int8   |
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1 |
// Ty::Int2 |
// Ty::Int4 => lhs_ty.clone(),
//
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Float4 => {
// match *rhs_ty {
// Ty::Float4 |
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1 |
// Ty::Int2 |
// Ty::Int4 |
// Ty::Int8 => lhs_ty.clone(),
//
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Float8 => {
// match *rhs_ty {
// Ty::Float8 => rhs_ty.clone(),
//
// Ty::Int1   |
// Ty::Int2   |
// Ty::Int4   |
// Ty::Int8   |
// Ty::Float4 => lhs_ty.clone(),
//
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Numeric(ref p, ref s) => {
// panic!("Undefined operator")
// },
//
// Ty::Date => {
// panic!("Undefined Operator")
// },
//
// Ty::Time => {
// panic!("Undefined Operator")
// },
//
// Ty::Timez => {
// panic!("Undefined Operator")
// },
//
// Ty::Timestamp => {
// panic!("Undefined Operator")
// },
//
// Ty::Timestampz => {
// panic!("Undefined Operator")
// },
//
// Ty::Interval => {
// panic!("Undefined Operator")
// },
//
// Ty::Char(ref len) => {
// panic!("Undefined Operator")
// },
//
// Ty::Binary(ref len) => {
// panic!("Undefined Operator")
// },
//
// Ty::Clob => {
// match *rhs_ty {
// Ty::Clob => rhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Blob => {
// match *rhs_ty {
// Ty::Blob => rhs_ty.clone(),
// _ => panic!("Undefined Operator")
// }
// },
//
// Ty::Array(ref ty) => {
// panic!("Undefined Operator")
// }
//
// Ty::Struct(ref tys) => {
// panic!("Undefined Operator")
// },
//
// Ty::Map(ref kty, ref vty) => {
// panic!("Undefined Operator")
// }
// }
// }
//

// pub fn bool_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<bool>()))
// })
// };
//
// Ty::new(BOOL_STR, true, true, handler)
// }
//
// pub fn i8_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<i8>()))
// })
// };
//
// Ty::new(I8_STR, true, true, handler)
// }
//
// pub fn i16_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<i16>()))
// })
// };
//
// Ty::new(I32_STR, true, true, handler)
// }
//
// pub fn i32_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<i32>()))
// })
// };
//
// Ty::new(I32_STR, true, true, handler)
// }
//
// pub fn i64_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<i64>()))
// })
// };
//
// Ty::new(I64_STR, true, true, handler)
// }
//
// pub fn f32_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<f32>()))
// })
// };
//
// Ty::new(F32_STR, true, true, handler)
// }
//
// pub fn f64_ty() -> Ty {
// let handler = TypeHandler {
// create_minipage: Rc::new(|| -> Box<MiniPage> {
// Box::new(FMiniPage::new(mem::size_of::<f64>()))
// })
// };
//
// Ty::new(F64_STR, true, true, handler)
// }
//

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

  fn assert_display(ty: Ty, expected: &str) {
    assert_eq!(&format!("{}", ty), expected)
  }

  #[test]
  fn test_display_agg_types() {
    assert_display(Ty::Array(Box::new(Ty::F64), vec!(4,4)), "Array(f64,4,4)");
    assert_display(Ty::Tuple(vec!(Ty::F64, Ty::F64, Ty::I64)), "(f64,f64,i64)");
  }
}<|endoftext|>


<commit_before>use std::mem;
use std::collections::HashMap;

use super::lexer::{Lexer, LexError};
use super::token::{TokenSpan, Token, Lit};
use super::exec::*; // TODO: remove * import

pub struct Parser<'a> {
    lexer: Lexer<'a>,

    curr: Option<TokenSpan>,
    last: Option<TokenSpan>,
    peek: Option<TokenSpan>,
}

impl<'a> Parser<'a> {
    pub fn from_query(q: &'a str) -> Parser<'a> {
        let lex = Lexer::from_query(q);
        Parser {
            lexer: lex,
            curr: None,
            last: None,
            peek: None,
        }
    }

    pub fn parse(&mut self) -> Result<Query, ParserError> {
        // TODO: handle this with a better error message
        try!(self.bump());
        try!(self.bump());

        self.parse_commands()
    }

    fn bump(&mut self) -> Result<(), ParserError> {
        // do stuff. Mainly swap last = curr, curr = peek, then peek = next_real
        mem::swap(&mut self.last, &mut self.curr);
        mem::swap(&mut self.curr, &mut self.peek);
        self.peek = try!(self.lexer.next_real());
        Ok(())
    }

    // SQL Commands

    fn parse_commands(&mut self) -> Result<Query, ParserError> {
        let curr = self.curr.clone();

        // Parse first word that
        match curr.unwrap().token {
            Token::Word(val) => self.run_major_command(val),
            _ => Err(ParserError::FirstCmdNotWord),
        }
    }

    fn run_major_command(&mut self, cmd: String) -> Result<Query, ParserError> {
        match Keyword::from_str(&*cmd).unwrap() { // TODO: clean up unwrap
            Keyword::Select => self.parse_select(),
            Keyword::Insert => self.parse_insert(),

            _ => Err(ParserError::FirstCmdNotMajor),
        }
    }

    fn parse_select(&mut self) -> Result<Query, ParserError> {
        // TODO: impl parse_select

        Ok(Query::Table(TableStmt::Select(SelectStmt {
            cols: vec![Col { name: "id".to_owned() }],
            table: Table {
                name: "user_v1".to_owned(),
                alias: None,
            },
        })))
    }

    fn parse_insert(&mut self) -> Result<Query, ParserError> {
        // TODO: impl parse_insert
        try!(self.expect_keyword(Keyword::Into));

        //try!();

        try!(self.expect_token(Token::ParentOP));

        let cols = try!(self.expect_comma_dil_word());

        Ok(Query::Table(TableStmt::Insert(InsertStmt {
            table: Table {
                name: "user_v1".to_owned(),
                alias: None,
            },
            cols: HashMap::new(),
        })))
    }
}

// Helper function
impl<'a> Parser<'a> {
    fn expect_keyword(&mut self, exp: Keyword) -> Result<Keyword, ParserError> {
        // TODO: clean up unwrap but they should be safe for the moment

        try!(self.bump());
        let curr = {
            let token = &self.curr.clone().unwrap();

            match &token.token {
                &Token::Word(ref word) => word.clone(),
                t => return Err(ParserError::ExpectedKeyword(exp, format!("{:?}", t))),
            }
        };

        let actual = try!(Keyword::from_str(&curr));

        if actual == exp {
            Ok(actual)
        } else {
            Err(ParserError::ExpectedKeyword(exp, curr))
        }
    }

    fn expect_token(&mut self, exp: Token)  -> Result<Token, ParserError> {
        try!(self.bump());

        let token = self.curr.clone().unwrap();
        let actual = token.token.clone();

        if actual == exp {
            Ok(actual)
        } else {
            Err(ParserError::ExpectedToken(exp, format!("{:?}", actual)))
        }
    }

    // expect word case insensitive.
    fn expect_word(&mut self) -> Result<String, ParserError> {
        try!(self.bump());

        let token = match self.curr.clone() {
            Some(t) => t,
            None => return Err(ParserError::ExpectedTokenButGotNone),
        };
        let actual = token.token.clone();

        let word = match actual {
            Token::Word(ref word) => word.to_lowercase(), // always lowercase
            t => return Err(ParserError::ExpectedToken(Token::Word(String::new()), format!("{:?}", t))),
        };

        Ok(word)
    }

    fn expect_lit(&mut self) -> Result<Lit, ParserError> {
        try!(self.bump());

        let token = self.curr.clone().unwrap();
        let actual = token.token.clone();

        match actual {
            Token::Literal(lit) => Ok(lit),
            t => Err(ParserError::ExpectedToken(Token::Literal(Lit::String(String::new())), format!("{:?}", t))),
        }
    }

    fn expect_comma_dil_word(&mut self) -> Result<Vec<String>, ParserError> {
        let mut cols = Vec::new();

        loop {
            match self.expect_word() {
                Ok(ref word) => {
                    cols.push(word.to_owned());
                    match try!(self.peek_clone()) {
                        Token::Comma => try!(self.bump()),
                        Token::ParentCL => {
                            try!(self.bump());
                            break;
                        },
                        _ => (),
                    }
                },
                Err(ParserError::ExpectedToken(_, _)) => {
                    let curr = self.curr.clone().unwrap().token;

                    match curr {
                        Token::Comma => try!(self.bump()),
                        Token::ParentCL => {
                            try!(self.bump());
                            break;
                        },
                        token => return Err(ParserError::ExpectedToken(Token::Comma, format!("{:?}", token))),
                    }
                },
                Err(err) => return Err(err),
            }
        }

        Ok(cols)
    }

    fn peek_clone(&mut self) -> Result<Token, ParserError> {
        let peek = try!(Self::unwrap_tokenspan(self.peek.clone()));

        Ok(peek.token)
    }

    fn unwrap_tokenspan(t: Option<TokenSpan>) -> Result<TokenSpan, ParserError> {
        match t {
            Some(val) =>  Ok(val),
            None => Err(ParserError::ExpectedTokenButGotNone),
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum Keyword {
    // Major
    Select,
    Insert,

    // Minor
    From,
    Into,
}

impl Keyword {
    pub fn from_str(k: &str) -> Result<Keyword, ParserError> {
        let keyword = match &*k.to_lowercase() {
            "select" => Keyword::Select,
            "insert" => Keyword::Insert,

            "from" => Keyword::From,
            "into" => Keyword::Into,

            // Keyword not found
            keyword => return Err(ParserError::UnexpectedKeyword(keyword.to_owned())), // TODO: clean up panic
        };

        Ok(keyword)
    }
}

#[derive(Debug)]
pub enum ParserError {
    InvalidCommand,
    LexerError(LexError),

    FirstCmdNotWord,
    FirstCmdNotMajor,

    ExpectedKeyword(Keyword, String), // exp, actual
    ExpectedToken(Token, String), // exp, actual
    ExpectedTokenButGotNone,

    UnexpectedKeyword(String),
}

impl From<LexError> for ParserError {
    fn from(e: LexError) -> ParserError {
        ParserError::LexerError(e)
    }
}

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

    #[test]
    fn select() {
        let mut p = Parser::from_query("select");
        p.parse().unwrap();
    }

    #[test]
    fn insert() {
        let mut p = Parser::from_query("insert into (name, email)");
        let q = p.parse().unwrap();

    }

    #[test]
    #[should_panic]
    #[ignore]
    fn insert_panic() {
        Parser::from_query("insert into (asdf aslkdfhjahh dsfkjals)").parse().unwrap();
    }

    #[test]
    #[should_panic]
    fn first_non_major() {
        let err = Parser::from_query("alskdfj").parse();
        assert!(err.is_err());
    }
}
<commit_msg>cleaned up not panicing on wrong insert type<commit_after>use std::mem;
use std::collections::HashMap;

use super::lexer::{Lexer, LexError};
use super::token::{TokenSpan, Token, Lit};
use super::exec::*; // TODO: remove * import

pub struct Parser<'a> {
    lexer: Lexer<'a>,

    curr: Option<TokenSpan>,
    last: Option<TokenSpan>,
    peek: Option<TokenSpan>,
}

impl<'a> Parser<'a> {
    pub fn from_query(q: &'a str) -> Parser<'a> {
        let lex = Lexer::from_query(q);
        Parser {
            lexer: lex,
            curr: None,
            last: None,
            peek: None,
        }
    }

    pub fn parse(&mut self) -> Result<Query, ParserError> {
        // TODO: handle this with a better error message
        try!(self.bump());
        try!(self.bump());

        self.parse_commands()
    }

    fn bump(&mut self) -> Result<(), ParserError> {
        // do stuff. Mainly swap last = curr, curr = peek, then peek = next_real
        mem::swap(&mut self.last, &mut self.curr);
        mem::swap(&mut self.curr, &mut self.peek);
        self.peek = try!(self.lexer.next_real());
        Ok(())
    }

    // SQL Commands

    fn parse_commands(&mut self) -> Result<Query, ParserError> {
        let curr = self.curr.clone();

        // Parse first word that
        match curr.unwrap().token {
            Token::Word(val) => self.run_major_command(val),
            _ => Err(ParserError::FirstCmdNotWord),
        }
    }

    fn run_major_command(&mut self, cmd: String) -> Result<Query, ParserError> {
        match Keyword::from_str(&*cmd).unwrap() { // TODO: clean up unwrap
            Keyword::Select => self.parse_select(),
            Keyword::Insert => self.parse_insert(),

            _ => Err(ParserError::FirstCmdNotMajor),
        }
    }

    fn parse_select(&mut self) -> Result<Query, ParserError> {
        // TODO: impl parse_select

        Ok(Query::Table(TableStmt::Select(SelectStmt {
            cols: vec![Col { name: "id".to_owned() }],
            table: Table {
                name: "user_v1".to_owned(),
                alias: None,
            },
        })))
    }

    fn parse_insert(&mut self) -> Result<Query, ParserError> {
        // TODO: impl parse_insert
        try!(self.expect_keyword(Keyword::Into));

        //try!();

        try!(self.expect_token(Token::ParentOP));

        let cols = try!(self.expect_comma_dil_word());

        Ok(Query::Table(TableStmt::Insert(InsertStmt {
            table: Table {
                name: "user_v1".to_owned(),
                alias: None,
            },
            cols: HashMap::new(),
        })))
    }
}

// Helper function
impl<'a> Parser<'a> {
    fn expect_keyword(&mut self, exp: Keyword) -> Result<Keyword, ParserError> {
        // TODO: clean up unwrap but they should be safe for the moment

        try!(self.bump());
        let curr = {
            let token = &self.curr.clone().unwrap();

            match &token.token {
                &Token::Word(ref word) => word.clone(),
                t => return Err(ParserError::ExpectedKeyword(exp, format!("{:?}", t))),
            }
        };

        let actual = try!(Keyword::from_str(&curr));

        if actual == exp {
            Ok(actual)
        } else {
            Err(ParserError::ExpectedKeyword(exp, curr))
        }
    }

    fn expect_token(&mut self, exp: Token)  -> Result<Token, ParserError> {
        try!(self.bump());

        let token = self.curr.clone().unwrap();
        let actual = token.token.clone();

        if actual == exp {
            Ok(actual)
        } else {
            Err(ParserError::ExpectedToken(exp, format!("{:?}", actual)))
        }
    }

    // expect word case insensitive.
    fn expect_word(&mut self) -> Result<String, ParserError> {
        try!(self.bump());

        let token = match self.curr.clone() {
            Some(t) => t,
            None => return Err(ParserError::ExpectedTokenButGotNone),
        };
        let actual = token.token.clone();

        let word = match actual {
            Token::Word(ref word) => word.to_lowercase(), // always lowercase
            t => return Err(ParserError::ExpectedToken(Token::Word(String::new()), format!("{:?}", t))),
        };

        Ok(word)
    }

    fn expect_lit(&mut self) -> Result<Lit, ParserError> {
        try!(self.bump());

        let token = self.curr.clone().unwrap();
        let actual = token.token.clone();

        match actual {
            Token::Literal(lit) => Ok(lit),
            t => Err(ParserError::ExpectedToken(Token::Literal(Lit::String(String::new())), format!("{:?}", t))),
        }
    }

    fn expect_comma_dil_word(&mut self) -> Result<Vec<String>, ParserError> {
        let mut cols = Vec::new();

        loop {
            println!("{:?}", &self.curr);
            match self.expect_word() {
                Ok(ref word) => {
                    cols.push(word.to_owned());
                    match try!(self.peek_clone()) {
                        Token::Comma => try!(self.bump()),
                        Token::ParentCL => {
                            try!(self.bump());
                            break;
                        },
                        token => return Err(ParserError::ExpectedToken(Token::Comma, format!("{:?}", token))),
                    }
                },
                Err(ParserError::ExpectedToken(_, _)) => {
                    let curr = self.curr.clone().unwrap().token;

                    match curr {
                        Token::Comma => try!(self.bump()),
                        Token::ParentCL => {
                            try!(self.bump());
                            break;
                        },
                        token => return Err(ParserError::ExpectedToken(Token::Comma, format!("{:?}", token))),
                    }
                },
                Err(err) => return Err(err),
            }
        }

        Ok(cols)
    }

    fn peek_clone(&mut self) -> Result<Token, ParserError> {
        let peek = try!(Self::unwrap_tokenspan(self.peek.clone()));

        Ok(peek.token)
    }

    fn unwrap_tokenspan(t: Option<TokenSpan>) -> Result<TokenSpan, ParserError> {
        match t {
            Some(val) =>  Ok(val),
            None => Err(ParserError::ExpectedTokenButGotNone),
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum Keyword {
    // Major
    Select,
    Insert,

    // Minor
    From,
    Into,
}

impl Keyword {
    pub fn from_str(k: &str) -> Result<Keyword, ParserError> {
        let keyword = match &*k.to_lowercase() {
            "select" => Keyword::Select,
            "insert" => Keyword::Insert,

            "from" => Keyword::From,
            "into" => Keyword::Into,

            // Keyword not found
            keyword => return Err(ParserError::UnexpectedKeyword(keyword.to_owned())), // TODO: clean up panic
        };

        Ok(keyword)
    }
}

#[derive(Debug)]
pub enum ParserError {
    InvalidCommand,
    LexerError(LexError),

    FirstCmdNotWord,
    FirstCmdNotMajor,

    ExpectedKeyword(Keyword, String), // exp, actual
    ExpectedToken(Token, String), // exp, actual
    ExpectedTokenButGotNone,

    UnexpectedKeyword(String),
}

impl From<LexError> for ParserError {
    fn from(e: LexError) -> ParserError {
        ParserError::LexerError(e)
    }
}

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

    #[test]
    fn select() {
        let mut p = Parser::from_query("select");
        p.parse().unwrap();
    }

    #[test]
    fn insert() {
        let mut p = Parser::from_query("insert into (name, email)");
        let q = p.parse().unwrap();

    }

    #[test]
    #[should_panic]
    fn insert_panic() {
        Parser::from_query("insert into (asdf aslkdfhjahh dsfkjals)").parse().unwrap();
    }

    #[test]
    #[should_panic]
    fn first_non_major() {
        let err = Parser::from_query("alskdfj").parse();
        assert!(err.is_err());
    }
}
<|endoftext|>


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

//! # Parser Nodes
//!
//! Parser nodes represent the grammar that is defined
//! by the currently permissible set of commands and their
//! parameters.

use std::rc::Rc;

/// Minimum priority.
pub const PRIORITY_MINIMUM: i32 = -10000;
/// The default priority for a parameter.
pub const PRIORITY_PARAMETER: i32 = -10;
/// The default priority.
pub const PRIORITY_DEFAULT: i32 = 0;

/// A node in the tree of commands and their parameters
/// used by the `Parser`.
pub trait Node {
    /// The data describing this node.
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields;

    /// The text used to identify this node in help text.
    /// This is typically the node name, either in plain
    /// form or decorated for parameters.
    fn help_symbol(&self) -> String {
        // XXX:Make this return a &String.
        self.node_data().help_symbol.clone()
    }

    /// Help text describing this node.
    fn help_text(&self) -> &Option<String> {
        &self.node_data().help_text
    }

    /// Hidden nodes are still found for matching, but are
    /// hidden from completion.
    fn hidden(&self) -> bool {
        self.node_data().hidden
    }

    /// The name of this node.
    fn name(&self) -> &String {
        &self.node_data().name
    }

    /// This priority of this node during matching and completion.
    fn priority(&self) -> i32 {
        self.node_data().priority
    }

    /// Nodes that are children of this node. Used to
    /// by the `Parser` during `advance`, `complete`, etc.
    fn successors(&self) -> &Vec<Rc<Node>> {
        &self.node_data().successors
    }
}

impl PartialEq for Node {
    /// Nodes are equal based on pointer equality.
    fn eq(&self, other: &Self) -> bool {
        self as *const _ == other as *const _
    }
}

/// A parse tree node.
#[doc(hidden)]
pub struct NodeFields {
    /// The name of this node.
    name: String,
    /// The text used to identify this node in help text.
    /// This is typically the node name, either in plain
    /// form or decorated for parameters.
    help_symbol: String,
    /// Help text describing this node.
    help_text: Option<String>,
    /// Hidden nodes are not completed. This doesn't modify matching.
    hidden: bool,
    /// Match and complete priority.
    priority: i32,
    /// Possible successor nodes. Collected while building.
    successors: Vec<Rc<Node>>,
}

/// The root of a command tree.
///
/// ```
/// use commands::parser::nodes::RootNode;
///
/// let root = RootNode::new(vec![]);
/// ```
pub struct RootNode {
    node_fields: NodeFields,
}

impl RootNode {
    /// Create a new `RootNode`
    pub fn new(successors: Vec<Rc<Node>>) -> Rc<Self> {
        Rc::new(RootNode {
            node_fields: NodeFields {
                name: "__root__".to_string(),
                help_symbol: "".to_string(),
                help_text: None,
                hidden: false,
                priority: PRIORITY_DEFAULT,
                successors: successors,
            },
        })
    }
}

impl Node for RootNode {
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

/// A node representing a command.
pub struct CommandNode {
    node_fields: NodeFields,
    command_fields: CommandNodeFields,
}

struct CommandNodeFields {
    handler: Option<fn(&node: Node) -> ()>,
    parameters: Vec<Rc<ParameterNode>>,
}

impl CommandNode {
    /// Construct a new `CommandNode`.
    pub fn new(name: &str,
               help_text: Option<String>,
               hidden: bool,
               priority: i32,
               handler: Option<fn(&node: Node) -> ()>)
               -> Self {
        CommandNode {
            node_fields: NodeFields {
                successors: vec![],
                name: name.to_string(),
                priority: priority,
                help_symbol: name.to_string(),
                help_text: help_text,
                hidden: hidden,
            },
            command_fields: CommandNodeFields {
                handler: handler,
                parameters: vec![],
            },
        }
    }
}
impl Node for CommandNode {
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

impl CommandNode {
    /// The handler which is executed once this node has been accepted.
    pub fn handler(&self) -> Option<fn(&node: Node) -> ()> {
        self.command_fields.handler
    }

    /// Get the parameter nodes for this command.
    pub fn parameters(&self) -> &Vec<Rc<ParameterNode>> {
        &self.command_fields.parameters
    }
}

/// A wrapper node wraps another command.
///
/// This is used for the help command so that it can complete
/// normal commands.
///
/// The `successors` will be those of the wrapped node.
pub struct WrapperNode {
    node_fields: NodeFields,
    #[allow(dead_code)]
    command_fields: CommandNodeFields,
    root: Rc<Node>,
}

impl Node for WrapperNode {
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }

    fn successors(&self) -> &Vec<Rc<Node>> {
        self.root.successors()
    }
}

/// A repeatable node is an internal helper for representing
/// nodes that can be repeated, like some parameters.
pub trait RepeatableNode: Node {
    /// Internal data for a repeatable node.
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields;

    /// Whether or not this node can be repeated. A repeated
    /// node can be `accept`ed multiple times.
    fn repeatable(&self) -> bool {
        self.repeatable_data().repeatable
    }

    /// If present, this node will no longer be `acceptable`.
    fn repeat_marker(&self) -> &Option<Rc<Node>> {
        &self.repeatable_data().repeat_marker
    }
}

/// The data for a repeatable node.
#[doc(hidden)]
pub struct RepeatableNodeFields {
    repeatable: bool,
    repeat_marker: Option<Rc<Node>>,
}

/// A node that represented the name portion of a named
/// parameter.
pub struct ParameterNameNode {
    node_fields: NodeFields,
    repeatable_fields: RepeatableNodeFields,
    parameter: Rc<Node>,
}

impl Node for ParameterNameNode {
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }

    fn help_symbol(&self) -> String {
        self.node_fields.name.clone() + " " + self.parameter.help_symbol().as_str()
    }
}

impl RepeatableNode for ParameterNameNode {
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields {
        &self.repeatable_fields
    }
}

/// Parameter nodes.
pub trait ParameterNode: Node + RepeatableNode {
    /// Internal data for a parameter node.
    #[doc(hidden)]
    fn parameter_data(&self) -> &ParameterNodeFields;

    /// A `required` parameter must be supplied for the
    /// command line being parsed to be valid.
    fn required(&self) -> bool {
        self.parameter_data().required
    }
}

/// Data for parameter nodes.
#[doc(hidden)]
pub struct ParameterNodeFields {
    required: bool,
}

/// A flag parameter node.
///
/// When implemented, this will only have a value of
/// true when it is present.
pub struct FlagParameterNode {
    node_fields: NodeFields,
    repeatable_fields: RepeatableNodeFields,
    parameter_fields: ParameterNodeFields,
}

impl Node for FlagParameterNode {
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

impl RepeatableNode for FlagParameterNode {
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields {
        &self.repeatable_fields
    }
}

impl ParameterNode for FlagParameterNode {
    #[doc(hidden)]
    fn parameter_data(&self) -> &ParameterNodeFields {
        &self.parameter_fields
    }
}

impl FlagParameterNode {
    /// Construct a new `FlagParameterNode`.
    pub fn new(name: &str,
               help_text: Option<String>,
               hidden: bool,
               priority: i32,
               successors: Vec<Rc<Node>>,
               repeatable: bool,
               repeat_marker: Option<Rc<Node>>,
               required: bool)
               -> Self {
        let help_symbol = String::from("<") + name +
                          if repeatable {
            ">..."
        } else {
            ">"
        };
        FlagParameterNode {
            node_fields: NodeFields {
                name: name.to_string(),
                help_symbol: help_symbol,
                help_text: help_text,
                hidden: hidden,
                priority: priority,
                successors: successors,
            },
            repeatable_fields: RepeatableNodeFields {
                repeatable: repeatable,
                repeat_marker: repeat_marker,
            },
            parameter_fields: ParameterNodeFields { required: required },
        }
    }
}

/// A named parameter node.
pub struct NamedParameterNode {
    node_fields: NodeFields,
    repeatable_fields: RepeatableNodeFields,
    parameter_fields: ParameterNodeFields,
}

impl Node for NamedParameterNode {
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

impl RepeatableNode for NamedParameterNode {
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields {
        &self.repeatable_fields
    }
}

impl ParameterNode for NamedParameterNode {
    #[doc(hidden)]
    fn parameter_data(&self) -> &ParameterNodeFields {
        &self.parameter_fields
    }
}

impl NamedParameterNode {
    /// Construct a new `NamedParameterNode`.
    pub fn new(name: &str,
               help_text: Option<String>,
               hidden: bool,
               priority: i32,
               successors: Vec<Rc<Node>>,
               repeatable: bool,
               repeat_marker: Option<Rc<Node>>,
               required: bool)
               -> Self {
        NamedParameterNode {
            node_fields: NodeFields {
                name: name.to_string(),
                help_symbol: name.to_string(),
                help_text: help_text,
                hidden: hidden,
                priority: priority,
                successors: successors,
            },
            repeatable_fields: RepeatableNodeFields {
                repeatable: repeatable,
                repeat_marker: repeat_marker,
            },
            parameter_fields: ParameterNodeFields { required: required },
        }
    }
}

/// A simple parameter node. This is only present in a command
/// line as a value.
pub struct SimpleParameterNode {
    node_fields: NodeFields,
    repeatable_fields: RepeatableNodeFields,
    parameter_fields: ParameterNodeFields,
}

impl Node for SimpleParameterNode {
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

impl RepeatableNode for SimpleParameterNode {
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields {
        &self.repeatable_fields
    }
}

impl ParameterNode for SimpleParameterNode {
    #[doc(hidden)]
    fn parameter_data(&self) -> &ParameterNodeFields {
        &self.parameter_fields
    }
}

impl SimpleParameterNode {
    /// Construct a new `SimpleParameterNode`.
    pub fn new(name: &str,
               help_text: Option<String>,
               hidden: bool,
               priority: i32,
               successors: Vec<Rc<Node>>,
               repeatable: bool,
               repeat_marker: Option<Rc<Node>>,
               required: bool)
               -> Self {
        SimpleParameterNode {
            node_fields: NodeFields {
                name: name.to_string(),
                help_symbol: name.to_string(),
                help_text: help_text,
                hidden: hidden,
                priority: priority,
                successors: successors,
            },
            repeatable_fields: RepeatableNodeFields {
                repeatable: repeatable,
                repeat_marker: repeat_marker,
            },
            parameter_fields: ParameterNodeFields { required: required },
        }
    }
}
<commit_msg>CommandNode::new() takes successors, parameters.<commit_after>// 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.

//! # Parser Nodes
//!
//! Parser nodes represent the grammar that is defined
//! by the currently permissible set of commands and their
//! parameters.

use std::rc::Rc;

/// Minimum priority.
pub const PRIORITY_MINIMUM: i32 = -10000;
/// The default priority for a parameter.
pub const PRIORITY_PARAMETER: i32 = -10;
/// The default priority.
pub const PRIORITY_DEFAULT: i32 = 0;

/// A node in the tree of commands and their parameters
/// used by the `Parser`.
pub trait Node {
    /// The data describing this node.
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields;

    /// The text used to identify this node in help text.
    /// This is typically the node name, either in plain
    /// form or decorated for parameters.
    fn help_symbol(&self) -> String {
        // XXX:Make this return a &String.
        self.node_data().help_symbol.clone()
    }

    /// Help text describing this node.
    fn help_text(&self) -> &Option<String> {
        &self.node_data().help_text
    }

    /// Hidden nodes are still found for matching, but are
    /// hidden from completion.
    fn hidden(&self) -> bool {
        self.node_data().hidden
    }

    /// The name of this node.
    fn name(&self) -> &String {
        &self.node_data().name
    }

    /// This priority of this node during matching and completion.
    fn priority(&self) -> i32 {
        self.node_data().priority
    }

    /// Nodes that are children of this node. Used to
    /// by the `Parser` during `advance`, `complete`, etc.
    fn successors(&self) -> &Vec<Rc<Node>> {
        &self.node_data().successors
    }
}

impl PartialEq for Node {
    /// Nodes are equal based on pointer equality.
    fn eq(&self, other: &Self) -> bool {
        self as *const _ == other as *const _
    }
}

/// A parse tree node.
#[doc(hidden)]
pub struct NodeFields {
    /// The name of this node.
    name: String,
    /// The text used to identify this node in help text.
    /// This is typically the node name, either in plain
    /// form or decorated for parameters.
    help_symbol: String,
    /// Help text describing this node.
    help_text: Option<String>,
    /// Hidden nodes are not completed. This doesn't modify matching.
    hidden: bool,
    /// Match and complete priority.
    priority: i32,
    /// Possible successor nodes. Collected while building.
    successors: Vec<Rc<Node>>,
}

/// The root of a command tree.
///
/// ```
/// use commands::parser::nodes::RootNode;
///
/// let root = RootNode::new(vec![]);
/// ```
pub struct RootNode {
    node_fields: NodeFields,
}

impl RootNode {
    /// Create a new `RootNode`
    pub fn new(successors: Vec<Rc<Node>>) -> Rc<Self> {
        Rc::new(RootNode {
            node_fields: NodeFields {
                name: "__root__".to_string(),
                help_symbol: "".to_string(),
                help_text: None,
                hidden: false,
                priority: PRIORITY_DEFAULT,
                successors: successors,
            },
        })
    }
}

impl Node for RootNode {
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

/// A node representing a command.
pub struct CommandNode {
    node_fields: NodeFields,
    command_fields: CommandNodeFields,
}

struct CommandNodeFields {
    handler: Option<fn(&node: Node) -> ()>,
    parameters: Vec<Rc<ParameterNode>>,
}

impl CommandNode {
    /// Construct a new `CommandNode`.
    pub fn new(name: &str,
               help_text: Option<String>,
               hidden: bool,
               priority: i32,
               successors: Vec<Rc<Node>>,
               handler: Option<fn(&node: Node) -> ()>,
               parameters: Vec<Rc<ParameterNode>>)
               -> Self {
        CommandNode {
            node_fields: NodeFields {
                name: name.to_string(),
                help_symbol: name.to_string(),
                help_text: help_text,
                hidden: hidden,
                priority: priority,
                successors: successors,
            },
            command_fields: CommandNodeFields {
                handler: handler,
                parameters: parameters,
            },
        }
    }
}
impl Node for CommandNode {
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

impl CommandNode {
    /// The handler which is executed once this node has been accepted.
    pub fn handler(&self) -> Option<fn(&node: Node) -> ()> {
        self.command_fields.handler
    }

    /// Get the parameter nodes for this command.
    pub fn parameters(&self) -> &Vec<Rc<ParameterNode>> {
        &self.command_fields.parameters
    }
}

/// A wrapper node wraps another command.
///
/// This is used for the help command so that it can complete
/// normal commands.
///
/// The `successors` will be those of the wrapped node.
pub struct WrapperNode {
    node_fields: NodeFields,
    #[allow(dead_code)]
    command_fields: CommandNodeFields,
    root: Rc<Node>,
}

impl Node for WrapperNode {
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }

    fn successors(&self) -> &Vec<Rc<Node>> {
        self.root.successors()
    }
}

/// A repeatable node is an internal helper for representing
/// nodes that can be repeated, like some parameters.
pub trait RepeatableNode: Node {
    /// Internal data for a repeatable node.
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields;

    /// Whether or not this node can be repeated. A repeated
    /// node can be `accept`ed multiple times.
    fn repeatable(&self) -> bool {
        self.repeatable_data().repeatable
    }

    /// If present, this node will no longer be `acceptable`.
    fn repeat_marker(&self) -> &Option<Rc<Node>> {
        &self.repeatable_data().repeat_marker
    }
}

/// The data for a repeatable node.
#[doc(hidden)]
pub struct RepeatableNodeFields {
    repeatable: bool,
    repeat_marker: Option<Rc<Node>>,
}

/// A node that represented the name portion of a named
/// parameter.
pub struct ParameterNameNode {
    node_fields: NodeFields,
    repeatable_fields: RepeatableNodeFields,
    parameter: Rc<Node>,
}

impl Node for ParameterNameNode {
    #[doc(hidden)]
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }

    fn help_symbol(&self) -> String {
        self.node_fields.name.clone() + " " + self.parameter.help_symbol().as_str()
    }
}

impl RepeatableNode for ParameterNameNode {
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields {
        &self.repeatable_fields
    }
}

/// Parameter nodes.
pub trait ParameterNode: Node + RepeatableNode {
    /// Internal data for a parameter node.
    #[doc(hidden)]
    fn parameter_data(&self) -> &ParameterNodeFields;

    /// A `required` parameter must be supplied for the
    /// command line being parsed to be valid.
    fn required(&self) -> bool {
        self.parameter_data().required
    }
}

/// Data for parameter nodes.
#[doc(hidden)]
pub struct ParameterNodeFields {
    required: bool,
}

/// A flag parameter node.
///
/// When implemented, this will only have a value of
/// true when it is present.
pub struct FlagParameterNode {
    node_fields: NodeFields,
    repeatable_fields: RepeatableNodeFields,
    parameter_fields: ParameterNodeFields,
}

impl Node for FlagParameterNode {
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

impl RepeatableNode for FlagParameterNode {
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields {
        &self.repeatable_fields
    }
}

impl ParameterNode for FlagParameterNode {
    #[doc(hidden)]
    fn parameter_data(&self) -> &ParameterNodeFields {
        &self.parameter_fields
    }
}

impl FlagParameterNode {
    /// Construct a new `FlagParameterNode`.
    pub fn new(name: &str,
               help_text: Option<String>,
               hidden: bool,
               priority: i32,
               successors: Vec<Rc<Node>>,
               repeatable: bool,
               repeat_marker: Option<Rc<Node>>,
               required: bool)
               -> Self {
        let help_symbol = String::from("<") + name +
                          if repeatable {
            ">..."
        } else {
            ">"
        };
        FlagParameterNode {
            node_fields: NodeFields {
                name: name.to_string(),
                help_symbol: help_symbol,
                help_text: help_text,
                hidden: hidden,
                priority: priority,
                successors: successors,
            },
            repeatable_fields: RepeatableNodeFields {
                repeatable: repeatable,
                repeat_marker: repeat_marker,
            },
            parameter_fields: ParameterNodeFields { required: required },
        }
    }
}

/// A named parameter node.
pub struct NamedParameterNode {
    node_fields: NodeFields,
    repeatable_fields: RepeatableNodeFields,
    parameter_fields: ParameterNodeFields,
}

impl Node for NamedParameterNode {
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

impl RepeatableNode for NamedParameterNode {
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields {
        &self.repeatable_fields
    }
}

impl ParameterNode for NamedParameterNode {
    #[doc(hidden)]
    fn parameter_data(&self) -> &ParameterNodeFields {
        &self.parameter_fields
    }
}

impl NamedParameterNode {
    /// Construct a new `NamedParameterNode`.
    pub fn new(name: &str,
               help_text: Option<String>,
               hidden: bool,
               priority: i32,
               successors: Vec<Rc<Node>>,
               repeatable: bool,
               repeat_marker: Option<Rc<Node>>,
               required: bool)
               -> Self {
        NamedParameterNode {
            node_fields: NodeFields {
                name: name.to_string(),
                help_symbol: name.to_string(),
                help_text: help_text,
                hidden: hidden,
                priority: priority,
                successors: successors,
            },
            repeatable_fields: RepeatableNodeFields {
                repeatable: repeatable,
                repeat_marker: repeat_marker,
            },
            parameter_fields: ParameterNodeFields { required: required },
        }
    }
}

/// A simple parameter node. This is only present in a command
/// line as a value.
pub struct SimpleParameterNode {
    node_fields: NodeFields,
    repeatable_fields: RepeatableNodeFields,
    parameter_fields: ParameterNodeFields,
}

impl Node for SimpleParameterNode {
    fn node_data(&self) -> &NodeFields {
        &self.node_fields
    }
}

impl RepeatableNode for SimpleParameterNode {
    #[doc(hidden)]
    fn repeatable_data(&self) -> &RepeatableNodeFields {
        &self.repeatable_fields
    }
}

impl ParameterNode for SimpleParameterNode {
    #[doc(hidden)]
    fn parameter_data(&self) -> &ParameterNodeFields {
        &self.parameter_fields
    }
}

impl SimpleParameterNode {
    /// Construct a new `SimpleParameterNode`.
    pub fn new(name: &str,
               help_text: Option<String>,
               hidden: bool,
               priority: i32,
               successors: Vec<Rc<Node>>,
               repeatable: bool,
               repeat_marker: Option<Rc<Node>>,
               required: bool)
               -> Self {
        SimpleParameterNode {
            node_fields: NodeFields {
                name: name.to_string(),
                help_symbol: name.to_string(),
                help_text: help_text,
                hidden: hidden,
                priority: priority,
                successors: successors,
            },
            repeatable_fields: RepeatableNodeFields {
                repeatable: repeatable,
                repeat_marker: repeat_marker,
            },
            parameter_fields: ParameterNodeFields { required: required },
        }
    }
}
<|endoftext|>


<commit_before>pub mod detector;
pub mod platforms;
pub mod bsd;

use std::fmt::Debug;
use handler::Handler;
use handler::inline::Inline;
use provider;

// See https://stackoverflow.com/questions/30353462/how-to-clone-a-struct-storing-a-trait-object
pub trait Platform: Debug + PlatformClone {
    fn new() -> Self where Self: Sized;

    fn detect(&self, h: &Box<Handler>) -> Option<Box<Platform>> {
        if let Some(_) = h.downcast_ref::<Inline>() {
            h.detect_platform(&|| self.detect_inline())
        } else {
            None
        }
    }

    fn detect_inline(&self) -> Option<Box<Platform>>;

    fn get_provider(&self) -> Box<provider::Provider>;
}

pub trait PlatformClone {
    fn clone_box(&self) -> Box<Platform>;
}

impl<T> PlatformClone for T
    where T: 'static + Platform + Clone
{
    fn clone_box(&self) -> Box<Platform> {
        Box::new(self.clone())
    }
}

impl Clone for Box<Platform> {
    fn clone(&self) -> Box<Platform> {
        self.clone_box()
    }
}
<commit_msg>Remove unused function<commit_after>pub mod detector;
pub mod platforms;
pub mod bsd;

use std::fmt::Debug;
use provider;

// See https://stackoverflow.com/questions/30353462/how-to-clone-a-struct-storing-a-trait-object
pub trait Platform: Debug + PlatformClone {
    fn new() -> Self where Self: Sized;

    fn detect_inline(&self) -> Option<Box<Platform>>;

    fn get_provider(&self) -> Box<provider::Provider>;
}

pub trait PlatformClone {
    fn clone_box(&self) -> Box<Platform>;
}

impl<T> PlatformClone for T
    where T: 'static + Platform + Clone
{
    fn clone_box(&self) -> Box<Platform> {
        Box::new(self.clone())
    }
}

impl Clone for Box<Platform> {
    fn clone(&self) -> Box<Platform> {
        self.clone_box()
    }
}
<|endoftext|>


<commit_before>use data_type::DataType;
use storage::MemoryPage;
use std::mem::transmute;

mod packer;

/// Serializes and writes values to MemoryPage.
/// Always writes values in the architertural endian currently.
#[derive(Debug)]
pub struct SerializeStream<'a> {
    position: usize,
    page: &'a mut MemoryPage,
}

impl<'a> SerializeStream<'a> {
    /// Creates new stream.
    pub fn new(page: &'a mut MemoryPage, pos: usize) -> Self {
        SerializeStream {
            position: pos,
            page: page,
        }
    }

    fn check_available_space(&self, val: isize) -> Result<(), String> {
        let avail: isize = self.page.data().len() as isize - self.position as isize;

        if avail < val as isize {
            Err(format!("Not enough memory to serialize value: required={}, available={}",
                        val,
                        avail))
        } else {
            Ok(())
        }
    }

    /// Check if we have enough memory in page to write a static typed value.
    fn check_static_type_len(&self, field_type: DataType) -> Result<(), String> {
        let field_len: isize = field_type.static_len() as isize;

        match self.check_available_space(field_len) {
            Err(e) => return Err(format!("Unable to write {:?}: {:?}", field_type, e)),
            Ok(_) => ()
        }

        Ok(())
    }

    /// Check if we have enough memory in page to write a dynamic typed value.
    fn check_dynamic_type_len(&self, field_type: DataType, size: usize) -> Result<(), String> {
        let field_len: isize = field_type.static_len() as isize;

        match self.check_available_space(field_len + size as isize) {
            Err(e) => return Err(format!("Unable to write {:?}: {:?}", field_type, e)),
            Ok(_) => ()
        }

        Ok(())
    }

    /// Write INTEGER to stream.
    pub fn write_int(&mut self, val: i32) -> Result<(), String> {
        self.check_static_type_len(DataType::INTEGER)?;

        let mem = self.page.data_mut();

        mem[self.position] = val as u8;
        mem[self.position + 1] = (val >> 8) as u8;
        mem[self.position + 2] = (val >> 16) as u8;
        mem[self.position + 3] = (val >> 24) as u8;

        self.position += 4;

        Ok(())
    }

    /// Write SMALLINT to stream.
    pub fn write_smallint(&mut self, val: i16) -> Result<(), String> {
        self.check_static_type_len(DataType::SMALLINT)?;

        let mem = self.page.data_mut();

        mem[self.position] = val as u8;
        mem[self.position + 1] = (val >> 8) as u8;

        self.position += 2;

        Ok(())
    }

    /// Write BIGINT to stream.
    pub fn write_bigint(&mut self, val: i64) -> Result<(), String> {
        self.check_static_type_len(DataType::BIGINT)?;

        let mem = self.page.data_mut();

        mem[self.position] = val as u8;
        mem[self.position + 1] = (val >> 8) as u8;
        mem[self.position + 2] = (val >> 16) as u8;
        mem[self.position + 3] = (val >> 24) as u8;
        mem[self.position + 4] = (val >> 32) as u8;
        mem[self.position + 5] = (val >> 40) as u8;
        mem[self.position + 6] = (val >> 48) as u8;
        mem[self.position + 7] = (val >> 56) as u8;

        self.position += 8;

        Ok(())
    }

    /// Write BOOLEAN to stream.
    pub fn write_bool(&mut self, val: bool) -> Result<(), String> {
        self.check_static_type_len(DataType::BOOLEAN)?;

        let mem = self.page.data_mut();

        mem[self.position] = val as u8;

        self.position += 1;

        Ok(())
    }

    /// Write VARCHAR to stream.
    pub fn write_float(&mut self, val: f64) -> Result<(), String> {
        self.check_static_type_len(DataType::FLOAT)?;

        let transumuted = unsafe {
            transmute::<f64, i64>(val)
        };

        self.write_bigint(transumuted)
    }

    /// Write u32 to stream.
    fn write_u32(&mut self, val: u32) -> Result<(), String> {
        self.check_available_space(4)?;

        let mem = self.page.data_mut();

        mem[self.position] = val as u8;
        mem[self.position + 1] = (val >> 8) as u8;
        mem[self.position + 2] = (val >> 16) as u8;
        mem[self.position + 3] = (val >> 24) as u8;

        self.position += 4;

        Ok(())
    }

    /// Write VARCHAR to stream.
    pub fn write_varchar(&mut self, val: &str) -> Result<(), String> {
        self.check_dynamic_type_len(DataType::VARCHAR, val.len())?;

        self.write_u32(val.len() as u32)?;

        let mem = self.page.data_mut();

        for b in val.as_bytes() {
            mem[self.position] = *b as u8;
            self.position += 1;
        }

        Ok(())
    }

    /// Write VARBINARY to stream.
    pub fn write_varbinary(&mut self, val: &[u8]) -> Result<(), String> {
        self.check_dynamic_type_len(DataType::VARBINARY, val.len())?;

        self.write_u32(val.len() as u32)?;

        let mem = self.page.data_mut();

        for b in val {
            mem[self.position] = *b as u8;
            self.position += 1;
        }

        Ok(())
    }
}

/// Reads and deserializes values from MemoryPage.
/// Always reads values in the architertural endian currently.
#[derive(Debug)]
pub struct DeserializeStream<'a> {
    position: usize,
    page: &'a MemoryPage,
}

impl<'a> DeserializeStream<'a> {
    /// Creates new stream.
    pub fn new(page: &'a MemoryPage, pos: usize) -> Self {
        DeserializeStream {
            position: pos,
            page: page,
        }
    }

    /// Check if we have enough memory in page to read a value.
    fn check_space(&self, len: usize) -> Result<(), String> {
        let avail: isize = self.page.data().len() as isize - self.position as isize;

        if avail < len as isize {
            Err(format!("Not enough memory to serialize INTEGER value: required={}, available={}",
                        len,
                        avail))
        } else {
            Ok(())
        }
    }

    /// Read integer from stream.
    pub fn read_int(&mut self) -> Result<i32, String> {
        self.check_space(DataType::INTEGER.static_len())?;

        let mem = self.page.data();
        let p = self.position;

        let res: i32 = (mem[p] as i32 & 0xFFi32) | (mem[p + 1] as i32 & 0xFFi32) << 8 |
                       (mem[p + 2] as i32 & 0xFFi32) << 16 |
                       (mem[p + 3] as i32 & 0xFFi32) << 24;

        self.position += 4;

        Ok(res)
    }
}

#[test]
fn write_single_int() {
    let mut page = MemoryPage::new(4);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_int(42).expect("Should not fail");
    stream.write_int(999).unwrap_err();
}

#[test]
fn write_several_ints() {
    let mut page = MemoryPage::new(4 + 4 + 4 + 3);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_int(2093608745).expect("Should not fail");
    stream.write_int(0).expect("Should not fail");
    stream.write_int(-1294).expect("Should not fail");
    stream.write_int(0).unwrap_err();
}

#[test]
fn write_signle_smallint() {
    let mut page = MemoryPage::new(2);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_smallint(42).expect("Should not fail");
    stream.write_smallint(999).unwrap_err();
}

#[test]
fn write_several_smallints() {
    let mut page = MemoryPage::new(3 * 2 + 1);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_smallint(11).expect("Should not fail");
    stream.write_smallint(0).expect("Should not fail");
    stream.write_smallint(-1294).expect("Should not fail");
    stream.write_smallint(0).unwrap_err();
}

#[test]
fn write_signle_bigint() {
    let mut page = MemoryPage::new(8);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bigint(42).expect("Should not fail");
    stream.write_bigint(999).unwrap_err();
}

#[test]
fn write_several_bigints() {
    let mut page = MemoryPage::new(3 * 8 + 7);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bigint(11).expect("Should not fail");
    stream.write_bigint(0).expect("Should not fail");
    stream.write_bigint(-1294).expect("Should not fail");
    stream.write_bigint(0).unwrap_err();
}

#[test]
fn write_signle_bool() {
    let mut page = MemoryPage::new(1);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bool(true).expect("Should not fail");
    stream.write_bool(false).unwrap_err();
}

#[test]
fn write_several_bools() {
    let mut page = MemoryPage::new(3 * 1);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bool(true).expect("Should not fail");
    stream.write_bool(true).expect("Should not fail");
    stream.write_bool(true).expect("Should not fail");
    stream.write_bool(false).unwrap_err();
}

#[test]
fn write_signle_float() {
    let mut page = MemoryPage::new(8);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_float(42.05).expect("Should not fail");
    stream.write_float(999.05).unwrap_err();
}

#[test]
fn write_several_float() {
    let mut page = MemoryPage::new(3 * 8 + 7);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_float(11.05).expect("Should not fail");
    stream.write_float(0.05).expect("Should not fail");
    stream.write_float(-1294.05).expect("Should not fail");
    stream.write_float(0.05).unwrap_err();
}

#[test]
fn write_signle_string() {
    let test = "test";
    let test1 = "test";
    let mut page = MemoryPage::new(test.len() + 4);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_varchar(test).expect("Should not fail");
    stream.write_varchar(test1).unwrap_err();
}

#[test]
fn write_several_strings() {
    let test = "test";
    let test1 = "test1";
    let test2 = "test2";
    let mut page = MemoryPage::new(3 * 4 + test.len() + test1.len() + test2.len());
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_varchar(test).expect("Should not fail");
    stream.write_varchar(test1).expect("Should not fail");
    stream.write_varchar(test2).expect("Should not fail");
    stream.write_varchar("error").unwrap_err();
}

#[test]
fn write_signle_array() {
    let arr: [u8; 5] = [1, 2, 3, 4, 5];
    let mut page = MemoryPage::new(arr.len() + 4);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varbinary(&[1, 1]).unwrap_err();
}

#[test]
fn write_several_arrays() {
    let arr: [u8; 5] = [1, 2, 3, 4, 5];

    let mut page = MemoryPage::new(3 * 4 + arr.len() + arr.len() + arr.len());
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varbinary(&[2, 2]).unwrap_err();
}

#[test]
fn write_all_types() {
    let arr: [u8; 5] = [1, 2, 3, 4, 5];
    let test = "test";

    let mut page = MemoryPage::new(2 * 4 + arr.len() + test.len() +
                                   1 + 4 +
                                   2 + 8 +
                                   8);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bool(true).expect("Should not fail");
    stream.write_float(2.2).expect("Should not fail");
    stream.write_int(2).expect("Should not fail");
    stream.write_smallint(2).expect("Should not fail");
    stream.write_bigint(2).expect("Should not fail");
    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varchar(test).expect("Should not fail");
    stream.write_varbinary(&[2, 2]).unwrap_err();
}
#[test]
fn write_read_single_int() {
    let mut page = MemoryPage::new(4);
    {
        let mut ws = SerializeStream::new(&mut page, 0);
        ws.write_int(42).expect("Should not fail");
    }

    let mut rs = DeserializeStream::new(&mut page, 0);
    let val = rs.read_int().unwrap();

    assert_eq!(val, 42);
}

#[test]
fn write_read_several_ints() {
    let mut page = MemoryPage::new(4 + 4 + 4 + 3);
    {
        let mut ws = SerializeStream::new(&mut page, 0);

        ws.write_int(2093608745).expect("Should not fail");
        ws.write_int(0).expect("Should not fail");
        ws.write_int(-1294).expect("Should not fail");
    }

    let mut rs = DeserializeStream::new(&mut page, 0);
    assert_eq!(rs.read_int().unwrap(), 2093608745);
    assert_eq!(rs.read_int().unwrap(), 0);
    assert_eq!(rs.read_int().unwrap(), -1294);
}
<commit_msg>Rewrote serializer with packer functionality<commit_after>use data_type::DataType;
use storage::MemoryPage;

mod packer;

/// Serializes and writes values to MemoryPage.
/// Always writes values in the architertural endian currently.
#[derive(Debug)]
pub struct SerializeStream<'a> {
    position: usize,
    page: &'a mut MemoryPage,
}

impl<'a> SerializeStream<'a> {
    /// Creates new stream.
    pub fn new(page: &'a mut MemoryPage, pos: usize) -> Self {
        SerializeStream {
            position: pos,
            page: page,
        }
    }

    fn check_available_space(&self, val: isize) -> Result<(), String> {
        let avail: isize = self.page.data().len() as isize - self.position as isize;

        if avail < val as isize {
            Err(format!("Not enough memory to serialize value: required={}, available={}",
                        val,
                        avail))
        } else {
            Ok(())
        }
    }

    /// Check if we have enough memory in page to write a static typed value.
    fn check_static_type_len(&self, field_type: DataType) -> Result<(), String> {
        let field_len: isize = field_type.static_len() as isize;

        match self.check_available_space(field_len) {
            Err(e) => return Err(format!("Unable to write {:?}: {:?}", field_type, e)),
            Ok(_) => ()
        }

        Ok(())
    }

    /// Check if we have enough memory in page to write a dynamic typed value.
    fn check_dynamic_type_len(&self, field_type: DataType, size: usize) -> Result<(), String> {
        let field_len: isize = field_type.static_len() as isize;

        match self.check_available_space(field_len + size as isize) {
            Err(e) => return Err(format!("Unable to write {:?}: {:?}", field_type, e)),
            Ok(_) => ()
        }

        Ok(())
    }

    /// Write INTEGER to stream.
    pub fn write_int(&mut self, val: i32) -> Result<(), String> {
        self.check_static_type_len(DataType::INTEGER)?;

        let mem = self.page.data_mut();
        let len = mem.len();

        packer::pack_int(&mut mem[self.position..len], val);

        self.position += 4;

        Ok(())
    }

    /// Write SMALLINT to stream.
    pub fn write_smallint(&mut self, val: i16) -> Result<(), String> {
        self.check_static_type_len(DataType::SMALLINT)?;

        let mem = self.page.data_mut();
        let len = mem.len();

        packer::pack_smallint(&mut mem[self.position..len], val);

        self.position += 2;

        Ok(())
    }

    /// Write BIGINT to stream.
    pub fn write_bigint(&mut self, val: i64) -> Result<(), String> {
        self.check_static_type_len(DataType::BIGINT)?;

        let mem = self.page.data_mut();
        let len = mem.len();

        packer::pack_bigint(&mut mem[self.position..len], val);

        self.position += 8;

        Ok(())
    }

    /// Write BOOLEAN to stream.
    pub fn write_bool(&mut self, val: bool) -> Result<(), String> {
        self.check_static_type_len(DataType::BOOLEAN)?;

        let mem = self.page.data_mut();
        let len = mem.len();

        packer::pack_bool(&mut mem[self.position..len], val);

        self.position += 1;

        Ok(())
    }

    /// Write VARCHAR to stream.
    pub fn write_float(&mut self, val: f64) -> Result<(), String> {
        self.check_static_type_len(DataType::FLOAT)?;

        let mem = self.page.data_mut();
        let len = mem.len();

        packer::pack_float(&mut mem[self.position..len], val);

        self.position += 8;

        Ok(())
    }

    /// Write VARCHAR to stream.
    pub fn write_varchar(&mut self, val: &str) -> Result<(), String> {
        self.check_dynamic_type_len(DataType::VARCHAR, val.len())?;

        let mem = self.page.data_mut();
        let len = mem.len();

        packer::pack_string(&mut mem[self.position..len], val);

        self.position += val.len() + 4; // Here we skip 4 bytes for length

        Ok(())
    }

    /// Write VARBINARY to stream.
    pub fn write_varbinary(&mut self, val: &[u8]) -> Result<(), String> {
        self.check_dynamic_type_len(DataType::VARBINARY, val.len())?;

        let mem = self.page.data_mut();
        let len = mem.len();

        packer::pack_array(&mut mem[self.position..len], val);

        self.position += val.len() + 4; // Here we skip 4 bytes for length

        Ok(())
    }
}

/// Reads and deserializes values from MemoryPage.
/// Always reads values in the architertural endian currently.
#[derive(Debug)]
pub struct DeserializeStream<'a> {
    position: usize,
    page: &'a MemoryPage,
}

impl<'a> DeserializeStream<'a> {
    /// Creates new stream.
    pub fn new(page: &'a MemoryPage, pos: usize) -> Self {
        DeserializeStream {
            position: pos,
            page: page,
        }
    }

    /// Check if we have enough memory in page to read a value.
    fn check_space(&self, len: usize) -> Result<(), String> {
        let avail: isize = self.page.data().len() as isize - self.position as isize;

        if avail < len as isize {
            Err(format!("Not enough memory to serialize INTEGER value: required={}, available={}",
                        len,
                        avail))
        } else {
            Ok(())
        }
    }

    /// Read integer from stream.
    pub fn read_int(&mut self) -> Result<i32, String> {
        self.check_space(DataType::INTEGER.static_len())?;

        let mem = self.page.data();
        let p = self.position;

        let res: i32 = (mem[p] as i32 & 0xFFi32) | (mem[p + 1] as i32 & 0xFFi32) << 8 |
                       (mem[p + 2] as i32 & 0xFFi32) << 16 |
                       (mem[p + 3] as i32 & 0xFFi32) << 24;

        self.position += 4;

        Ok(res)
    }
}

#[test]
fn write_single_int() {
    let mut page = MemoryPage::new(4);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_int(42).expect("Should not fail");
    stream.write_int(999).unwrap_err();
}

#[test]
fn write_several_ints() {
    let mut page = MemoryPage::new(4 + 4 + 4 + 3);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_int(2093608745).expect("Should not fail");
    stream.write_int(0).expect("Should not fail");
    stream.write_int(-1294).expect("Should not fail");
    stream.write_int(0).unwrap_err();
}

#[test]
fn write_signle_smallint() {
    let mut page = MemoryPage::new(2);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_smallint(42).expect("Should not fail");
    stream.write_smallint(999).unwrap_err();
}

#[test]
fn write_several_smallints() {
    let mut page = MemoryPage::new(3 * 2 + 1);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_smallint(11).expect("Should not fail");
    stream.write_smallint(0).expect("Should not fail");
    stream.write_smallint(-1294).expect("Should not fail");
    stream.write_smallint(0).unwrap_err();
}

#[test]
fn write_single_bigint() {
    let mut page = MemoryPage::new(8);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bigint(42).expect("Should not fail");
    stream.write_bigint(999).unwrap_err();
}

#[test]
fn write_several_bigints() {
    let mut page = MemoryPage::new(3 * 8 + 7);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bigint(11).expect("Should not fail");
    stream.write_bigint(0).expect("Should not fail");
    stream.write_bigint(-1294).expect("Should not fail");
    stream.write_bigint(0).unwrap_err();
}

#[test]
fn write_single_bool() {
    let mut page = MemoryPage::new(1);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bool(true).expect("Should not fail");
    stream.write_bool(false).unwrap_err();
}

#[test]
fn write_several_bools() {
    let mut page = MemoryPage::new(3 * 1);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bool(true).expect("Should not fail");
    stream.write_bool(true).expect("Should not fail");
    stream.write_bool(true).expect("Should not fail");
    stream.write_bool(false).unwrap_err();
}

#[test]
fn write_single_float() {
    let mut page = MemoryPage::new(8);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_float(42.05).expect("Should not fail");
    stream.write_float(999.05).unwrap_err();
}

#[test]
fn write_several_float() {
    let mut page = MemoryPage::new(3 * 8 + 7);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_float(11.05).expect("Should not fail");
    stream.write_float(0.05).expect("Should not fail");
    stream.write_float(-1294.05).expect("Should not fail");
    stream.write_float(0.05).unwrap_err();
}

#[test]
fn write_single_string() {
    let test = "test";
    let test1 = "test";
    let mut page = MemoryPage::new(test.len() + 4);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_varchar(test).expect("Should not fail");
    stream.write_varchar(test1).unwrap_err();
}

#[test]
fn write_several_strings() {
    let test = "test";
    let test1 = "test1";
    let test2 = "test2";
    let mut page = MemoryPage::new(3 * 4 + test.len() + test1.len() + test2.len());
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_varchar(test).expect("Should not fail");
    stream.write_varchar(test1).expect("Should not fail");
    stream.write_varchar(test2).expect("Should not fail");
    stream.write_varchar("error").unwrap_err();
}

#[test]
fn write_signle_array() {
    let arr: [u8; 5] = [1, 2, 3, 4, 5];
    let mut page = MemoryPage::new(arr.len() + 4);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varbinary(&[1, 1]).unwrap_err();
}

#[test]
fn write_several_arrays() {
    let arr: [u8; 5] = [1, 2, 3, 4, 5];

    let mut page = MemoryPage::new(3 * 4 + arr.len() + arr.len() + arr.len());
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varbinary(&[2, 2]).unwrap_err();
}

#[test]
fn write_all_types() {
    let arr: [u8; 5] = [1, 2, 3, 4, 5];
    let test = "test";

    let mut page = MemoryPage::new(2 * 4 + arr.len() + test.len() +
                                   1 + 4 +
                                   2 + 8 +
                                   8);
    let mut stream = SerializeStream::new(&mut page, 0);

    stream.write_bool(true).expect("Should not fail");
    stream.write_float(2.2).expect("Should not fail");
    stream.write_int(2).expect("Should not fail");
    stream.write_smallint(2).expect("Should not fail");
    stream.write_bigint(2).expect("Should not fail");
    stream.write_varbinary(&arr).expect("Should not fail");
    stream.write_varchar(test).expect("Should not fail");
    stream.write_varbinary(&[2, 2]).unwrap_err();
}
#[test]
fn write_read_single_int() {
    let mut page = MemoryPage::new(4);
    {
        let mut ws = SerializeStream::new(&mut page, 0);
        ws.write_int(42).expect("Should not fail");
    }

    let mut rs = DeserializeStream::new(&mut page, 0);
    let val = rs.read_int().unwrap();

    assert_eq!(val, 42);
}

#[test]
fn write_read_several_ints() {
    let mut page = MemoryPage::new(4 + 4 + 4 + 3);
    {
        let mut ws = SerializeStream::new(&mut page, 0);

        ws.write_int(2093608745).expect("Should not fail");
        ws.write_int(0).expect("Should not fail");
        ws.write_int(-1294).expect("Should not fail");
    }

    let mut rs = DeserializeStream::new(&mut page, 0);
    assert_eq!(rs.read_int().unwrap(), 2093608745);
    assert_eq!(rs.read_int().unwrap(), 0);
    assert_eq!(rs.read_int().unwrap(), -1294);
}
<|endoftext|>


<commit_before>use hyper::server::{Request, Response};
use hyper::header::common::ContentLength;

pub fn serve(mut req: Request, mut res: Response)
{
    println!("{}", req.uri);
    let mut res = res.start().unwrap();
    res.write(b"Hello World!").unwrap();
    res.end().unwrap();
}
<commit_msg>Did some more work, this actually compiles and shows how pattern matching can be used to determine the method used & url requested.<commit_after>use hyper::server::{Request, Response};
use hyper::header::common::ContentLength;
use hyper::{Get, Post, uri, status};

pub fn serve(mut req: Request, mut res: Response)
{
    println!("{}", req.uri);
    match req.uri
    {
        // Match the request URL. If its an AbsolutePath, match it further.
        uri::AbsolutePath(ref path) => match(&req.method, path.as_slice())
        {
            (&Get, "/") =>
            {
               let out = b"You GET requested '/'";

               res.headers_mut().set(ContentLength(out.len()));
               let mut res = res.start().unwrap();
               res.write(out).unwrap();
               res.end().unwrap();
               return;
            },
            _ =>
            {
                *res.status_mut() = status::NotFound;
                res.start().and_then(|res| res.end());
                return;
            }
        },
        _ =>
        {
            return;
        }
    }
    let mut res = res.start().unwrap();
    res.write(b"Hello World!").unwrap();
    res.end().unwrap();
}
<|endoftext|>