<commit_before>use internal::{IResult,Err};

#[cfg(not(feature = "core"))]
use std::collections::HashMap;

#[cfg(feature = "core")]
use std::prelude::v1::*;
use std::vec::Vec;
use std::string::ToString;

#[cfg(not(feature = "core"))]
pub trait HexDisplay {
  fn offset(&self, second:&[u8]) -> usize;

  /// Converts the value of `self` to a hex value, returning the owned
  /// string.
  fn to_hex(&self, chunk_size: usize) -> String;

  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String;
}

static CHARS: &'static[u8] = b"0123456789abcdef";

#[cfg(not(feature = "core"))]
impl HexDisplay for [u8] {
  fn offset(&self, second:&[u8]) -> usize {
    let fst = self.as_ptr();
    let snd = second.as_ptr();

    snd as usize - fst as usize
  }

  #[allow(unused_variables)]
  fn to_hex(&self, chunk_size: usize) -> String {
    self.to_hex_from(chunk_size, 0)
  }

  #[allow(unused_variables)]
  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
    let mut v = Vec::with_capacity(self.len() * 3);
    let mut i = from;
    for chunk in self.chunks(chunk_size) {
      let s = format!("{:08x}", i);
      for &ch in s.as_bytes().iter() {
        v.push(ch);
      }
      v.push('\t' as u8);

      i = i + chunk_size;

      for &byte in chunk {
        v.push(CHARS[(byte >> 4) as usize]);
        v.push(CHARS[(byte & 0xf) as usize]);
        v.push(' ' as u8);
      }
      if chunk_size > chunk.len() {
        for j in 0..(chunk_size - chunk.len()) {
          v.push(' ' as u8);
          v.push(' ' as u8);
          v.push(' ' as u8);
        }
      }
      v.push('\t' as u8);

      for &byte in chunk {
        if (byte >=32 && byte <= 126) || byte >= 128 {
          v.push(byte);
        } else {
          v.push('.' as u8);
        }
      }
      v.push('\n' as u8);
    }

    unsafe {
      String::from_utf8_unchecked(v)
    }
  }
}

/// Prints a message if the parser fails
///
/// The message prints the `Error` or `Incomplete`
/// and the parser's calling code
///
/// ```
/// # #[macro_use] extern crate nom;
/// # fn main() {
///    named!(f, dbg!( tag!( "abcd" ) ) );
///
///    let a = &b"efgh"[..];
///
///    // Will print the following message:
///    // Error(Position(0, [101, 102, 103, 104])) at l.5 by ' tag ! ( "abcd" ) '
///    f(a);
/// # }
/// ```
#[macro_export]
macro_rules! dbg (
  ($i: expr, $submac:ident!( $($args:tt)* )) => (
    {
      let l = line!();
      match $submac!($i, $($args)*) {
        $crate::IResult::Error(a) => {
          println!("Error({:?}) at l.{} by ' {} '", a, l, stringify!($submac!($($args)*)));
          $crate::IResult::Error(a)
        },
        $crate::IResult::Incomplete(a) => {
          println!("Incomplete({:?}) at {} by ' {} '", a, l, stringify!($submac!($($args)*)));
          $crate::IResult::Incomplete(a)
        },
        a => a
      }
    }
  );
);

/// Prints a message and the input if the parser fails
///
/// The message prints the `Error` or `Incomplete`
/// and the parser's calling code.
///
/// It also displays the input in hexdump format
///
/// ```
/// # #[macro_use] extern crate nom;
/// # fn main() {
///    named!(f, dbg_dmp!( tag!( "abcd" ) ) );
///
///    let a = &b"efghijkl"[..];
///
///    // Will print the following message:
///    // Error(Position(0, [101, 102, 103, 104, 105, 106, 107, 108])) at l.5 by ' tag ! ( "abcd" ) '
///    // 00000000        65 66 67 68 69 6a 6b 6c         efghijkl
///    f(a);
/// # }
#[macro_export]
macro_rules! dbg_dmp (
  ($i: expr, $submac:ident!( $($args:tt)* )) => (
    {
      use $crate::HexDisplay;
      let l = line!();
      match $submac!($i, $($args)*) {
        $crate::IResult::Error(a) => {
          println!("Error({:?}) at l.{} by ' {} '\n{}", a, l, stringify!($submac!($($args)*)), $i.to_hex(8));
          $crate::IResult::Error(a)
        },
        $crate::IResult::Incomplete(a) => {
          println!("Incomplete({:?}) at {} by ' {} '\n{}", a, l, stringify!($submac!($($args)*)), $i.to_hex(8));
          $crate::IResult::Incomplete(a)
        },
        a => a
      }
    }
  );
);

pub fn error_to_list(e:Err) -> Vec<u32> {
  let mut v:Vec<u32> = Vec::new();
  let mut err = e;
  loop {
    match err {
      Err::Code(i) | Err::Position(i,_)                  => {
        v.push(i);
        return v;
      },
      Err::Node(i, next) | Err::NodePosition(i, _, next) => {
        v.push(i);
        err = *next;
      }
    }
  }
}

pub fn compare_error_paths(e1:Err, e2:Err) -> bool {
  return error_to_list(e1) == error_to_list(e2)
}

#[cfg(not(feature = "core"))]
pub fn add_error_pattern<'a,'b,I,O>(h: &mut HashMap<Vec<u32>, &'b str>, res: IResult<'a,I,O>, message: &'b str) -> bool {
  if let IResult::Error(e) = res {
    h.insert(error_to_list(e), message);
    true
  } else {
    false
  }
}

pub fn slice_to_offsets(input: &[u8], s: &[u8]) -> (usize, usize) {
  let start = input.as_ptr();
  let off1  = s.as_ptr() as usize - start as usize;
  let off2  = off1 + s.len();
  return (off1, off2);
}

#[cfg(not(feature = "core"))]
pub fn prepare_errors<I,O>(input: &[u8], res: IResult<I,O>) -> Option<Vec<(u32, usize, usize)> > {
  if let IResult::Error(e) = res {
    let mut v:Vec<(u32, usize, usize)> = Vec::new();
    let mut err = e.clone();
    loop {
      match err {
        Err::Position(i,s)            => {
          let (o1, o2) = slice_to_offsets(input, s);
          v.push((i, o1, o2));
          //println!("v is: {:?}", v);
          break;
        },
        Err::NodePosition(i, s, next) => {
          let (o1, o2) = slice_to_offsets(input, s);
          v.push((i, o1, o2));
          err = *next;
        },
        Err::Node(_, next)            => {
          err = *next;
        },
        Err::Code(_)                  => {
          break;
        }
      }
    }
    v.sort_by(|a, b| a.1.cmp(&b.1));
    Some(v)
  } else {
    None
  }
}

#[cfg(not(feature = "core"))]
pub fn print_error<I,O>(input: &[u8], res: IResult<I,O>) {
  if let Some(v) = prepare_errors(input, res) {
    let colors = generate_colors(&v);
    println!("parser codes: {}",   print_codes(colors, HashMap::new()));
    println!("{}",   print_offsets(input, 0, &v));

  } else {
    println!("not an error");
  }
}

#[cfg(not(feature = "core"))]
pub fn generate_colors(v: &Vec<(u32, usize, usize)>) -> HashMap<u32, u8> {
  let mut h: HashMap<u32, u8> = HashMap::new();
  let mut color = 0;

  for &(c,_,_) in v.iter() {
    h.insert(c, color + 31);
    color = color + 1 % 7;
  }

  h
}

pub fn code_from_offset(v: &Vec<(u32, usize, usize)>, offset: usize) -> Option<u32> {
  let mut acc: Option<(u32, usize, usize)> = None;
  for &(c, s, e) in v.iter() {
    if s <= offset && offset <=e {
      if let Some((_, start, end)) = acc {
        if start <= s && e <= end {
          acc = Some((c, s, e));
        }
      } else {
        acc = Some((c, s, e));
      }
    }
  }
  if let Some((code, _, _)) = acc {
    return Some(code);
  } else {
    return None;
  }
}

pub fn reset_color(v: &mut Vec<u8>) {
  v.push(0x1B);
  v.push('[' as u8);
  v.push(0);
  v.push('m' as u8);
}

pub fn write_color(v: &mut Vec<u8>, color: u8) {
  v.push(0x1B);
  v.push('[' as u8);
  v.push(1);
  v.push(';' as u8);
  let s = color.to_string();
  let bytes = s.as_bytes();
  v.extend(bytes.iter().cloned());
  v.push('m' as u8);
}

#[cfg(not(feature = "core"))]
pub fn print_codes(colors: HashMap<u32, u8>, names: HashMap<u32, &str>) -> String {
  let mut v = Vec::new();
  for (code, &color) in &colors {
    if let Some(&s) = names.get(&code) {
      let bytes = s.as_bytes();
      write_color(&mut v, color);
      v.extend(bytes.iter().cloned());
    } else {
      let s = code.to_string();
      let bytes = s.as_bytes();
      write_color(&mut v, color);
      v.extend(bytes.iter().cloned());
    }
    reset_color(&mut v);
    v.push(' ' as u8);
  }
  reset_color(&mut v);

  unsafe {
    String::from_utf8_unchecked(v)
  }

}

#[cfg(not(feature = "core"))]
pub fn print_offsets(input: &[u8], from: usize, offsets: &Vec<(u32, usize, usize)>) -> String {
  let mut v = Vec::with_capacity(input.len() * 3);
  let mut i = from;
  let chunk_size = 8;
  let mut current_code:  Option<u32> = None;
  let mut current_code2: Option<u32> = None;

  let colors = generate_colors(&offsets);

  for chunk in input.chunks(chunk_size) {
    let s = format!("{:08x}", i);
    for &ch in s.as_bytes().iter() {
      v.push(ch);
    }
    v.push('\t' as u8);

    let mut k = i;
    let mut l = i;
    for &byte in chunk {
      if let Some(code) = code_from_offset(&offsets, k) {
        if let Some(current) = current_code {
          if current != code {
            reset_color(&mut v);
            current_code = Some(code);
            if let Some(&color) = colors.get(&code) {
              write_color(&mut v, color);
            }
          }
        } else {
          current_code = Some(code);
          if let Some(&color) = colors.get(&code) {
            write_color(&mut v, color);
          }
        }
      }
      v.push(CHARS[(byte >> 4) as usize]);
      v.push(CHARS[(byte & 0xf) as usize]);
      v.push(' ' as u8);
      k = k + 1;
    }

    reset_color(&mut v);

    if chunk_size > chunk.len() {
      for _ in 0..(chunk_size - chunk.len()) {
        v.push(' ' as u8);
        v.push(' ' as u8);
        v.push(' ' as u8);
      }
    }
    v.push('\t' as u8);

    for &byte in chunk {
      if let Some(code) = code_from_offset(&offsets, l) {
        if let Some(current) = current_code2 {
          if current != code {
            reset_color(&mut v);
            current_code2 = Some(code);
            if let Some(&color) = colors.get(&code) {
              write_color(&mut v, color);
            }
          }
        } else {
          current_code2 = Some(code);
          if let Some(&color) = colors.get(&code) {
            write_color(&mut v, color);
          }
        }
      }
      if (byte >=32 && byte <= 126) || byte >= 128 {
        v.push(byte);
      } else {
        v.push('.' as u8);
      }
      l = l + 1;
    }
    reset_color(&mut v);

    v.push('\n' as u8);
    i = i + chunk_size;
  }

  unsafe {
    String::from_utf8_unchecked(v)
  }

}

pub trait AsBytes {
  fn as_bytes(&self) -> &[u8];
}

impl<'a> AsBytes for &'a str {
  #[inline(always)]
  fn as_bytes(&self) -> &[u8] {
    str::as_bytes(self)
  }
}

impl AsBytes for str {
  #[inline(always)]
  fn as_bytes(&self) -> &[u8] {
    str::as_bytes(self)
  }
}

impl<'a> AsBytes for &'a [u8] {
  #[inline(always)]
  fn as_bytes(&self) -> &[u8] {
    *self
  }
}

impl AsBytes for [u8] {
  #[inline(always)]
  fn as_bytes(&self) -> &[u8] {
    self
  }
}

pub enum ErrorCode {
  Tag,
  MapRes,
  MapOpt,
  Alt,
  IsNot,
  IsA,
  Filter,
  SeparatedList,
  SeparatedNonEmptyList,
  Many1,
  Count,
  TakeUntilAndConsume,
  TakeUntil,
  TakeUntilEitherAndConsume,
  TakeUntilEither,
  LengthValue,
  TagClosure,
  Alpha,
  Digit,
  AlphaNumeric,
  Space,
  MultiSpace,
  LengthValueFn,
  Eof,
  ExprOpt,
  ExprRes
}
<commit_msg>Add AsBytes implementation for fixed-length arrays<commit_after>use internal::{IResult,Err};

#[cfg(not(feature = "core"))]
use std::collections::HashMap;

#[cfg(feature = "core")]
use std::prelude::v1::*;
use std::vec::Vec;
use std::string::ToString;

#[cfg(not(feature = "core"))]
pub trait HexDisplay {
  fn offset(&self, second:&[u8]) -> usize;

  /// Converts the value of `self` to a hex value, returning the owned
  /// string.
  fn to_hex(&self, chunk_size: usize) -> String;

  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String;
}

static CHARS: &'static[u8] = b"0123456789abcdef";

#[cfg(not(feature = "core"))]
impl HexDisplay for [u8] {
  fn offset(&self, second:&[u8]) -> usize {
    let fst = self.as_ptr();
    let snd = second.as_ptr();

    snd as usize - fst as usize
  }

  #[allow(unused_variables)]
  fn to_hex(&self, chunk_size: usize) -> String {
    self.to_hex_from(chunk_size, 0)
  }

  #[allow(unused_variables)]
  fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
    let mut v = Vec::with_capacity(self.len() * 3);
    let mut i = from;
    for chunk in self.chunks(chunk_size) {
      let s = format!("{:08x}", i);
      for &ch in s.as_bytes().iter() {
        v.push(ch);
      }
      v.push('\t' as u8);

      i = i + chunk_size;

      for &byte in chunk {
        v.push(CHARS[(byte >> 4) as usize]);
        v.push(CHARS[(byte & 0xf) as usize]);
        v.push(' ' as u8);
      }
      if chunk_size > chunk.len() {
        for j in 0..(chunk_size - chunk.len()) {
          v.push(' ' as u8);
          v.push(' ' as u8);
          v.push(' ' as u8);
        }
      }
      v.push('\t' as u8);

      for &byte in chunk {
        if (byte >=32 && byte <= 126) || byte >= 128 {
          v.push(byte);
        } else {
          v.push('.' as u8);
        }
      }
      v.push('\n' as u8);
    }

    unsafe {
      String::from_utf8_unchecked(v)
    }
  }
}

/// Prints a message if the parser fails
///
/// The message prints the `Error` or `Incomplete`
/// and the parser's calling code
///
/// ```
/// # #[macro_use] extern crate nom;
/// # fn main() {
///    named!(f, dbg!( tag!( "abcd" ) ) );
///
///    let a = &b"efgh"[..];
///
///    // Will print the following message:
///    // Error(Position(0, [101, 102, 103, 104])) at l.5 by ' tag ! ( "abcd" ) '
///    f(a);
/// # }
/// ```
#[macro_export]
macro_rules! dbg (
  ($i: expr, $submac:ident!( $($args:tt)* )) => (
    {
      let l = line!();
      match $submac!($i, $($args)*) {
        $crate::IResult::Error(a) => {
          println!("Error({:?}) at l.{} by ' {} '", a, l, stringify!($submac!($($args)*)));
          $crate::IResult::Error(a)
        },
        $crate::IResult::Incomplete(a) => {
          println!("Incomplete({:?}) at {} by ' {} '", a, l, stringify!($submac!($($args)*)));
          $crate::IResult::Incomplete(a)
        },
        a => a
      }
    }
  );
);

/// Prints a message and the input if the parser fails
///
/// The message prints the `Error` or `Incomplete`
/// and the parser's calling code.
///
/// It also displays the input in hexdump format
///
/// ```
/// # #[macro_use] extern crate nom;
/// # fn main() {
///    named!(f, dbg_dmp!( tag!( "abcd" ) ) );
///
///    let a = &b"efghijkl"[..];
///
///    // Will print the following message:
///    // Error(Position(0, [101, 102, 103, 104, 105, 106, 107, 108])) at l.5 by ' tag ! ( "abcd" ) '
///    // 00000000        65 66 67 68 69 6a 6b 6c         efghijkl
///    f(a);
/// # }
#[macro_export]
macro_rules! dbg_dmp (
  ($i: expr, $submac:ident!( $($args:tt)* )) => (
    {
      use $crate::HexDisplay;
      let l = line!();
      match $submac!($i, $($args)*) {
        $crate::IResult::Error(a) => {
          println!("Error({:?}) at l.{} by ' {} '\n{}", a, l, stringify!($submac!($($args)*)), $i.to_hex(8));
          $crate::IResult::Error(a)
        },
        $crate::IResult::Incomplete(a) => {
          println!("Incomplete({:?}) at {} by ' {} '\n{}", a, l, stringify!($submac!($($args)*)), $i.to_hex(8));
          $crate::IResult::Incomplete(a)
        },
        a => a
      }
    }
  );
);

pub fn error_to_list(e:Err) -> Vec<u32> {
  let mut v:Vec<u32> = Vec::new();
  let mut err = e;
  loop {
    match err {
      Err::Code(i) | Err::Position(i,_)                  => {
        v.push(i);
        return v;
      },
      Err::Node(i, next) | Err::NodePosition(i, _, next) => {
        v.push(i);
        err = *next;
      }
    }
  }
}

pub fn compare_error_paths(e1:Err, e2:Err) -> bool {
  return error_to_list(e1) == error_to_list(e2)
}

#[cfg(not(feature = "core"))]
pub fn add_error_pattern<'a,'b,I,O>(h: &mut HashMap<Vec<u32>, &'b str>, res: IResult<'a,I,O>, message: &'b str) -> bool {
  if let IResult::Error(e) = res {
    h.insert(error_to_list(e), message);
    true
  } else {
    false
  }
}

pub fn slice_to_offsets(input: &[u8], s: &[u8]) -> (usize, usize) {
  let start = input.as_ptr();
  let off1  = s.as_ptr() as usize - start as usize;
  let off2  = off1 + s.len();
  return (off1, off2);
}

#[cfg(not(feature = "core"))]
pub fn prepare_errors<I,O>(input: &[u8], res: IResult<I,O>) -> Option<Vec<(u32, usize, usize)> > {
  if let IResult::Error(e) = res {
    let mut v:Vec<(u32, usize, usize)> = Vec::new();
    let mut err = e.clone();
    loop {
      match err {
        Err::Position(i,s)            => {
          let (o1, o2) = slice_to_offsets(input, s);
          v.push((i, o1, o2));
          //println!("v is: {:?}", v);
          break;
        },
        Err::NodePosition(i, s, next) => {
          let (o1, o2) = slice_to_offsets(input, s);
          v.push((i, o1, o2));
          err = *next;
        },
        Err::Node(_, next)            => {
          err = *next;
        },
        Err::Code(_)                  => {
          break;
        }
      }
    }
    v.sort_by(|a, b| a.1.cmp(&b.1));
    Some(v)
  } else {
    None
  }
}

#[cfg(not(feature = "core"))]
pub fn print_error<I,O>(input: &[u8], res: IResult<I,O>) {
  if let Some(v) = prepare_errors(input, res) {
    let colors = generate_colors(&v);
    println!("parser codes: {}",   print_codes(colors, HashMap::new()));
    println!("{}",   print_offsets(input, 0, &v));

  } else {
    println!("not an error");
  }
}

#[cfg(not(feature = "core"))]
pub fn generate_colors(v: &Vec<(u32, usize, usize)>) -> HashMap<u32, u8> {
  let mut h: HashMap<u32, u8> = HashMap::new();
  let mut color = 0;

  for &(c,_,_) in v.iter() {
    h.insert(c, color + 31);
    color = color + 1 % 7;
  }

  h
}

pub fn code_from_offset(v: &Vec<(u32, usize, usize)>, offset: usize) -> Option<u32> {
  let mut acc: Option<(u32, usize, usize)> = None;
  for &(c, s, e) in v.iter() {
    if s <= offset && offset <=e {
      if let Some((_, start, end)) = acc {
        if start <= s && e <= end {
          acc = Some((c, s, e));
        }
      } else {
        acc = Some((c, s, e));
      }
    }
  }
  if let Some((code, _, _)) = acc {
    return Some(code);
  } else {
    return None;
  }
}

pub fn reset_color(v: &mut Vec<u8>) {
  v.push(0x1B);
  v.push('[' as u8);
  v.push(0);
  v.push('m' as u8);
}

pub fn write_color(v: &mut Vec<u8>, color: u8) {
  v.push(0x1B);
  v.push('[' as u8);
  v.push(1);
  v.push(';' as u8);
  let s = color.to_string();
  let bytes = s.as_bytes();
  v.extend(bytes.iter().cloned());
  v.push('m' as u8);
}

#[cfg(not(feature = "core"))]
pub fn print_codes(colors: HashMap<u32, u8>, names: HashMap<u32, &str>) -> String {
  let mut v = Vec::new();
  for (code, &color) in &colors {
    if let Some(&s) = names.get(&code) {
      let bytes = s.as_bytes();
      write_color(&mut v, color);
      v.extend(bytes.iter().cloned());
    } else {
      let s = code.to_string();
      let bytes = s.as_bytes();
      write_color(&mut v, color);
      v.extend(bytes.iter().cloned());
    }
    reset_color(&mut v);
    v.push(' ' as u8);
  }
  reset_color(&mut v);

  unsafe {
    String::from_utf8_unchecked(v)
  }

}

#[cfg(not(feature = "core"))]
pub fn print_offsets(input: &[u8], from: usize, offsets: &Vec<(u32, usize, usize)>) -> String {
  let mut v = Vec::with_capacity(input.len() * 3);
  let mut i = from;
  let chunk_size = 8;
  let mut current_code:  Option<u32> = None;
  let mut current_code2: Option<u32> = None;

  let colors = generate_colors(&offsets);

  for chunk in input.chunks(chunk_size) {
    let s = format!("{:08x}", i);
    for &ch in s.as_bytes().iter() {
      v.push(ch);
    }
    v.push('\t' as u8);

    let mut k = i;
    let mut l = i;
    for &byte in chunk {
      if let Some(code) = code_from_offset(&offsets, k) {
        if let Some(current) = current_code {
          if current != code {
            reset_color(&mut v);
            current_code = Some(code);
            if let Some(&color) = colors.get(&code) {
              write_color(&mut v, color);
            }
          }
        } else {
          current_code = Some(code);
          if let Some(&color) = colors.get(&code) {
            write_color(&mut v, color);
          }
        }
      }
      v.push(CHARS[(byte >> 4) as usize]);
      v.push(CHARS[(byte & 0xf) as usize]);
      v.push(' ' as u8);
      k = k + 1;
    }

    reset_color(&mut v);

    if chunk_size > chunk.len() {
      for _ in 0..(chunk_size - chunk.len()) {
        v.push(' ' as u8);
        v.push(' ' as u8);
        v.push(' ' as u8);
      }
    }
    v.push('\t' as u8);

    for &byte in chunk {
      if let Some(code) = code_from_offset(&offsets, l) {
        if let Some(current) = current_code2 {
          if current != code {
            reset_color(&mut v);
            current_code2 = Some(code);
            if let Some(&color) = colors.get(&code) {
              write_color(&mut v, color);
            }
          }
        } else {
          current_code2 = Some(code);
          if let Some(&color) = colors.get(&code) {
            write_color(&mut v, color);
          }
        }
      }
      if (byte >=32 && byte <= 126) || byte >= 128 {
        v.push(byte);
      } else {
        v.push('.' as u8);
      }
      l = l + 1;
    }
    reset_color(&mut v);

    v.push('\n' as u8);
    i = i + chunk_size;
  }

  unsafe {
    String::from_utf8_unchecked(v)
  }

}

pub trait AsBytes {
  fn as_bytes(&self) -> &[u8];
}

impl<'a> AsBytes for &'a str {
  #[inline(always)]
  fn as_bytes(&self) -> &[u8] {
    str::as_bytes(self)
  }
}

impl AsBytes for str {
  #[inline(always)]
  fn as_bytes(&self) -> &[u8] {
    str::as_bytes(self)
  }
}

impl<'a> AsBytes for &'a [u8] {
  #[inline(always)]
  fn as_bytes(&self) -> &[u8] {
    *self
  }
}

impl AsBytes for [u8] {
  #[inline(always)]
  fn as_bytes(&self) -> &[u8] {
    self
  }
}

macro_rules! array_impls {
  ($($N:expr)+) => {
    $(
      impl<'a> AsBytes for &'a [u8; $N] {
        #[inline(always)]
        fn as_bytes(&self) -> &[u8] {
          *self
        }
      }

      impl AsBytes for [u8; $N] {
        #[inline(always)]
        fn as_bytes(&self) -> &[u8] {
          self
        }
      }
    )+
  };
}

array_impls! {
     0  1  2  3  4  5  6  7  8  9
    10 11 12 13 14 15 16 17 18 19
    20 21 22 23 24 25 26 27 28 29
    30 31 32
}

pub enum ErrorCode {
  Tag,
  MapRes,
  MapOpt,
  Alt,
  IsNot,
  IsA,
  Filter,
  SeparatedList,
  SeparatedNonEmptyList,
  Many1,
  Count,
  TakeUntilAndConsume,
  TakeUntil,
  TakeUntilEitherAndConsume,
  TakeUntilEither,
  LengthValue,
  TagClosure,
  Alpha,
  Digit,
  AlphaNumeric,
  Space,
  MultiSpace,
  LengthValueFn,
  Eof,
  ExprOpt,
  ExprRes
}
<|endoftext|>


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

/// Escape a filter literal.
///
/// Literal values appearing in an LDAP filter can contain any character,
/// but some characters (parentheses, asterisk, backslash, NUL) must be
/// escaped in the filter's string representation. This function does the
/// escaping.
///
/// The argument, `lit`, can be owned or borrowed. The function doesn't
/// allocate the return value unless there's need to escape the input.
pub fn ldap_escape<'a, S: Into<Cow<'a, str>>>(lit: S) -> Cow<'a, str> {
    #[inline]
    fn needs_escape(c: u8) -> bool {
        c == b'\\' || c == b'*' || c == b'(' || c == b')' || c == 0
    }

    #[inline]
    fn xdigit(c: u8) -> u8 {
        c + if c < 10 { b'0' } else { b'a' - 10 }
    }

    let lit = lit.into();
    let mut vec_push = false;
    let mut output = Vec::with_capacity(lit.len() + 12); // guess: 4 escaped chars
    for (i, &c) in lit.as_bytes().iter().enumerate() {
        if needs_escape(c) {
            if !vec_push {
                output.extend(lit[..i].as_bytes());
                vec_push = true;
            }
            output.push(b'\\');
            output.push(xdigit(c >> 4));
            output.push(xdigit(c & 0xF));
        } else if vec_push {
            output.push(c);
        }
    }
    if vec_push {
        Cow::Owned(unsafe { String::from_utf8_unchecked(output) })
    } else {
        lit.into()
    }
}
<commit_msg>Eliminate allocation for no-escape case<commit_after>use std::borrow::Cow;

/// Escape a filter literal.
///
/// Literal values appearing in an LDAP filter can contain any character,
/// but some characters (parentheses, asterisk, backslash, NUL) must be
/// escaped in the filter's string representation. This function does the
/// escaping.
///
/// The argument, `lit`, can be owned or borrowed. The function doesn't
/// allocate the return value unless there's need to escape the input.
pub fn ldap_escape<'a, S: Into<Cow<'a, str>>>(lit: S) -> Cow<'a, str> {
    #[inline]
    fn needs_escape(c: u8) -> bool {
        c == b'\\' || c == b'*' || c == b'(' || c == b')' || c == 0
    }

    #[inline]
    fn xdigit(c: u8) -> u8 {
        c + if c < 10 { b'0' } else { b'a' - 10 }
    }

    let lit = lit.into();
    let mut output = None;
    for (i, &c) in lit.as_bytes().iter().enumerate() {
        if needs_escape(c) {
            if output.is_none() {
                output = Some(Vec::with_capacity(lit.len() + 12)); // guess: up to 4 escaped chars
                output.as_mut().unwrap().extend(lit[..i].as_bytes());
            }
            let output = output.as_mut().unwrap();
            output.push(b'\\');
            output.push(xdigit(c >> 4));
            output.push(xdigit(c & 0xF));
        } else if let Some(ref mut output) = output {
            output.push(c);
        }
    }
    if let Some(output) = output {
        Cow::Owned(unsafe { String::from_utf8_unchecked(output) })
    } else {
        lit.into()
    }
}
<|endoftext|>


<commit_before>pub fn get_array() {}

#[cfg(test)]
mod tests {
    #[test]
    fn test_get_array() {
        assert!(true)
    }
}
<commit_msg>feat: add workaround method for Config::get_array()<commit_after>use config::{Config, Value};

/// Gets an array from a config file using a key, returning `None` if
/// the key wasn't present or couldn't be coerced into a `Vec<Value>`.
///
/// `Config::get_array()` in version `0.4.1` has a bug where it
/// consumes `self` instead of taking `self` by reference. This
/// function is a workaround for the time being. The bug has been
/// fixed but will not be available until the release of version `0.5`
/// of `config-rs`.
pub fn ref_get_array(key: &str, config: &Config) -> Option<Vec<Value>> {
    config.get(key).and_then(Value::into_array)
}

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

    #[test]
    // The real test is that this compiles successfully without giving
    // a warning about the config file being moved.
    fn test_ref_get_array() {
        let mut c: Config = Config::new();
        c.set("numbers", vec![1, 2, 3]).unwrap();
        c.set("boolean", true).unwrap();

        // Uncomment and the compiler should complain
        // assert_eq!(c.get_array("numbers"),
        //            Some(vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)]));
        // assert_eq!(c.get_array("boolean"), None); // Use of moved value: c

        assert_eq!(ref_get_array("numbers", &c),
                   Some(vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)]));
        assert_eq!(ref_get_array("boolean", &c), None);
    }
}
<|endoftext|>


<commit_before>use log::{LogRecord, LogLevel, LogLevelFilter, LogMetadata, set_logger, Log};

pub struct Builder {
    lvl: LogLevelFilter
}

impl Builder {
    pub fn new(lvl: LogLevelFilter) -> Self {
        Builder { lvl: lvl }
    }

    pub fn enable(&self) {
        set_logger(|max_log_level| {
            max_log_level.set(LogLevelFilter::Info);
            Box::new(Logger)
        }).unwrap();
    }
}

struct Logger;

impl Log for Logger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= LogLevel::Info
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            println!("{} - {}", record.level(), record.args());
        }
    }
}
<commit_msg>fixed logger so it uses set value for logging lvl<commit_after>use log::{LogRecord, LogLevel, LogLevelFilter, LogMetadata, set_logger, Log};

pub struct Builder {
    lvl: LogLevelFilter
}

impl Builder {
    pub fn new(lvl: LogLevelFilter) -> Self {
        Builder { lvl: lvl }
    }

    pub fn enable(&self) {
        set_logger(|max_log_level| {
            max_log_level.set(self.lvl);
            Box::new(Logger)
        }).unwrap();
    }
}

struct Logger;

impl Log for Logger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= LogLevel::Info
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            println!("{} - {}", record.level(), record.args());
        }
    }
}
<|endoftext|>


<commit_before>//!Some helpful macros.

///The `insert_routes!` macro generates routes from the provided handlers and routing tree and
///adds them to the provided router. The router is then returned.
///
///This can be useful to lower the risk of typing errors, among other things.
///
///##Example 1
///
///```rust
///#[macro_use]
///extern crate rustful;
///use rustful::TreeRouter;
///# use rustful::{Handler, Context, Response};
///
///# struct DummyHandler;
///# impl Handler for DummyHandler {
///#     fn handle_request(&self, _: Context, _: Response){}
///# }
///# fn main() {
///# let about_us = DummyHandler;
///# let show_user = DummyHandler;
///# let show_product = DummyHandler;
///# let show_error = DummyHandler;
///# let show_welcome = DummyHandler;
///let router = insert_routes! {
///    TreeRouter::new() => {
///        "/" => Get: show_welcome,
///        "/about" => Get: about_us,
///        "/user/:user" => Get: show_user,
///        "/product/:name" => Get: show_product,
///        "/*" => Get: show_error
///    }
///};
///# }
///```
///
///##Example 2
///
///```rust
///#[macro_use]
///extern crate rustful;
///use rustful::TreeRouter;
///# use rustful::{Handler, Context, Response};
///
///# #[derive(Clone, Copy)]
///# struct DummyHandler;
///# impl Handler for DummyHandler {
///#     fn handle_request(&self, _: Context, _: Response){}
///# }
///# fn main() {
///# let show_home = DummyHandler;
///# let show_user = DummyHandler;
///# let save_user = DummyHandler;
///# let show_all_products = DummyHandler;
///# let send_all_product_data = DummyHandler;
///# let show_product = DummyHandler;
///# let edit_product = DummyHandler;
///# let send_product_data = DummyHandler;
///
///let mut router = TreeRouter::new();
///
///insert_routes! {
///    &mut router => {
///        Get: show_home,
///
///        "home" => Get: show_home,
///        "user/:username" => {
///            Get: show_user,
///            Post: save_user
///        },
///        "product" => {
///            Get: show_all_products,
///
///            "json" => Get: send_all_product_data,
///            ":id" => {
///                Get: show_product,
///                Post: edit_product,
///                Delete: edit_product,
///
///                "json" => Get: send_product_data
///            }
///        }
///    }
///};
///# }
///```
#[macro_export]
macro_rules! insert_routes {
    ($router:expr => {$($paths:tt)+}) => {
        {
            use $crate::Router;
            let mut router = $router;
            __rustful_insert_internal!(router, [], $($paths)+);
            router
        }
    }
}

//Internal stuff. Only meant to be used through `insert_routes!`.
#[doc(hidden)]
#[macro_export]
macro_rules! __rustful_insert_internal {
    ($router:ident, [$($steps:expr),*], $path:expr => {$($paths:tt)+}, $($next:tt)*) => {
        {
            __rustful_insert_internal!($router, [$($steps,)* $path], $($paths)*);
            __rustful_insert_internal!($router, [$($steps),*], $($next)*);
        }
    };
    ($router:ident, [$($steps:expr),*], $path:tt => {$($paths:tt)+}) => {
        {
            __rustful_insert_internal!($router, [$($steps,)* __rustful_to_expr!($path)], $($paths)*);
        }
    };
    ($router:ident, [$($steps:expr),*], $($method:tt)::+: $handler:expr, $($next:tt)*) => {
        {
            let method = {
                #[allow(unused_imports)]
                use $crate::Method::*;
                __rustful_to_path!($($method)::+)
            };
            let path = __rustful_route_expr!($($steps),*);
            $router.insert(method, path, $handler);
            __rustful_insert_internal!($router, [$($steps),*], $($next)*)
        }
    };
    ($router:ident, [$($steps:expr),*], $path:tt => $method:path: $handler:expr, $($next:tt)*) => {
        {
            let method = {
                #[allow(unused_imports)]
                use $crate::Method::*;
                $method
            };
            let path = __rustful_route_expr!($($steps,)* __rustful_to_expr!($path));
            $router.insert(method, path, $handler);
            __rustful_insert_internal!($router, [$($steps),*], $($next)*)
        }
    };
    ($router:ident, [$($steps:expr),*], $($method:tt)::+: $handler:expr) => {
        {
            let method = {
                #[allow(unused_imports)]
                use $crate::Method::*;
                __rustful_to_path!($($method)::+)
            };
            let path = __rustful_route_expr!($($steps),*);
            $router.insert(method, path, $handler);
        }
    };
    ($router:ident, [$($steps:expr),*], $path:tt => $method:path: $handler:expr) => {
        {
            let method = {
                #[allow(unused_imports)]
                use $crate::Method::*;
                $method
            };
            let path = __rustful_route_expr!($($steps,)* __rustful_to_expr!($path));
            $router.insert(method, path, $handler);
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __rustful_route_expr {
    () => ("");
    ($($path:expr),+) => (&[$($path),+][..]);
}

/**
A macro for making content types.

It takes a main type, a sub type and a parameter list. Instead of this:

```rust
use rustful::header::ContentType;
use rustful::mime::{Mime, TopLevel, SubLevel, Attr, Value};

ContentType(
    Mime (
        TopLevel::Text,
        SubLevel::Html,
        vec![(Attr::Charset, Value::Utf8)]
    )
);
```

it can be written like this:

```
#[macro_use]
extern crate rustful;
use rustful::header::ContentType;

# fn main() {
ContentType(content_type!(Text / Html; Charset = Utf8));
# }
```

The `Charset = Utf8` part defines the parameter list for the content type and
may contain more than one parameter, or be omitted. Here are some more
examples showing that and how strings can be used for more exotic values:

```
#[macro_use]
extern crate rustful;
use rustful::header::ContentType;

# fn main() {
ContentType(content_type!(Application / "octet-stream"; "type" = "image/gif"; "padding" = "4"));
# }
```

```
#[macro_use]
extern crate rustful;
use rustful::header::ContentType;

# fn main() {
ContentType(content_type!(Image / Png));
# }
```
**/
#[macro_export]
macro_rules! content_type {
    ($main_type:tt / $sub_type:tt) => ({
        use $crate::macros::MimeHelper;
        $crate::mime::Mime (
            {
                #[allow(unused_imports)]
                use $crate::mime::TopLevel::*;
                MimeHelper::from(__rustful_to_expr!($main_type)).convert()
            },
            {
                #[allow(unused_imports)]
                use $crate::mime::SubLevel::*;
                MimeHelper::from(__rustful_to_expr!($sub_type)).convert()
            },
            Vec::new()
        )
    });

    ($main_type:tt / $sub_type:tt; $($param:tt = $value:tt);+) => ({
        use $crate::macros::MimeHelper;
        $crate::mime::Mime (
            {
                #[allow(unused_imports)]
                use $crate::mime::TopLevel::*;
                MimeHelper::from(__rustful_to_expr!($main_type)).convert()
            },
            {
                #[allow(unused_imports)]
                use $crate::mime::SubLevel::*;
                MimeHelper::from(__rustful_to_expr!($sub_type)).convert()
            },
            vec![ $( ({
                #[allow(unused_imports)]
                use $crate::mime::Attr::*;
                MimeHelper::from(__rustful_to_expr!($param)).convert()
            }, {
                #[allow(unused_imports)]
                use $crate::mime::Value::*;
                MimeHelper::from(__rustful_to_expr!($value)).convert()
            })),+ ]
        )
    });
}

#[doc(hidden)]
#[macro_export]
macro_rules! __rustful_to_expr {
    ($e: expr) => ($e)
}

#[doc(hidden)]
#[macro_export]
macro_rules! __rustful_to_path {
    ($e: path) => ($e)
}

use std::str::FromStr;
use std::fmt::Debug;
use mime::{TopLevel, SubLevel, Attr, Value};

#[doc(hidden)]
pub enum MimeHelper<'a, T> {
    Str(&'a str),
    Target(T)
}

impl<'a, T: FromStr> MimeHelper<'a, T> where <T as FromStr>::Err: Debug {
    pub fn convert(self) -> T {
        match self {
            MimeHelper::Str(s) => s.parse().unwrap(),
            MimeHelper::Target(t) => t
        }
    }
}

impl<'a, T: FromStr> From<&'a str> for MimeHelper<'a, T> {
    fn from(s: &'a str) -> MimeHelper<'a, T> {
        MimeHelper::Str(s)
    }
}

impl<'a> From<TopLevel> for MimeHelper<'a, TopLevel> {
    fn from(t: TopLevel) -> MimeHelper<'a, TopLevel> {
        MimeHelper::Target(t)
    }
}

impl<'a> From<SubLevel> for MimeHelper<'a, SubLevel> {
    fn from(t: SubLevel) -> MimeHelper<'a, SubLevel> {
        MimeHelper::Target(t)
    }
}

impl<'a> From<Attr> for MimeHelper<'a, Attr> {
    fn from(t: Attr) -> MimeHelper<'a, Attr> {
        MimeHelper::Target(t)
    }
}

impl<'a> From<Value> for MimeHelper<'a, Value> {
    fn from(t: Value) -> MimeHelper<'a, Value> {
        MimeHelper::Target(t)
    }
}
<commit_msg>Allow trailing `,` in insert_routes! macro<commit_after>//!Some helpful macros.

///The `insert_routes!` macro generates routes from the provided handlers and routing tree and
///adds them to the provided router. The router is then returned.
///
///This can be useful to lower the risk of typing errors, among other things.
///
///##Example 1
///
///```rust
///#[macro_use]
///extern crate rustful;
///use rustful::TreeRouter;
///# use rustful::{Handler, Context, Response};
///
///# struct DummyHandler;
///# impl Handler for DummyHandler {
///#     fn handle_request(&self, _: Context, _: Response){}
///# }
///# fn main() {
///# let about_us = DummyHandler;
///# let show_user = DummyHandler;
///# let show_product = DummyHandler;
///# let show_error = DummyHandler;
///# let show_welcome = DummyHandler;
///let router = insert_routes! {
///    TreeRouter::new() => {
///        "/" => Get: show_welcome,
///        "/about" => Get: about_us,
///        "/user/:user" => Get: show_user,
///        "/product/:name" => Get: show_product,
///        "/*" => Get: show_error
///    }
///};
///# }
///```
///
///##Example 2
///
///```rust
///#[macro_use]
///extern crate rustful;
///use rustful::TreeRouter;
///# use rustful::{Handler, Context, Response};
///
///# #[derive(Clone, Copy)]
///# struct DummyHandler;
///# impl Handler for DummyHandler {
///#     fn handle_request(&self, _: Context, _: Response){}
///# }
///# fn main() {
///# let show_home = DummyHandler;
///# let show_user = DummyHandler;
///# let save_user = DummyHandler;
///# let show_all_products = DummyHandler;
///# let send_all_product_data = DummyHandler;
///# let show_product = DummyHandler;
///# let edit_product = DummyHandler;
///# let send_product_data = DummyHandler;
///
///let mut router = TreeRouter::new();
///
///insert_routes! {
///    &mut router => {
///        Get: show_home,
///
///        "home" => Get: show_home,
///        "user/:username" => {
///            Get: show_user,
///            Post: save_user
///        },
///        "product" => {
///            Get: show_all_products,
///
///            "json" => Get: send_all_product_data,
///            ":id" => {
///                Get: show_product,
///                Post: edit_product,
///                Delete: edit_product,
///
///                "json" => Get: send_product_data
///            }
///        }
///    }
///};
///# }
///```
#[macro_export]
macro_rules! insert_routes {
    ($router:expr => {$($paths:tt)+}) => {
        {
            use $crate::Router;
            let mut router = $router;
            __rustful_insert_internal!(router, [], $($paths)+);
            router
        }
    }
}

//Internal stuff. Only meant to be used through `insert_routes!`.
#[doc(hidden)]
#[macro_export]
macro_rules! __rustful_insert_internal {
    ($router:ident, [$($steps:expr),*],$(,)*) => {{}};
    ($router:ident, [$($steps:expr),*], $path:expr => {$($paths:tt)+}, $($next:tt)*) => {
        {
            __rustful_insert_internal!($router, [$($steps,)* $path], $($paths)*);
            __rustful_insert_internal!($router, [$($steps),*], $($next)*);
        }
    };
    ($router:ident, [$($steps:expr),*], $path:tt => {$($paths:tt)+}) => {
        {
            __rustful_insert_internal!($router, [$($steps,)* __rustful_to_expr!($path)], $($paths)*);
        }
    };
    ($router:ident, [$($steps:expr),*], $($method:tt)::+: $handler:expr, $($next:tt)*) => {
        {
            let method = {
                #[allow(unused_imports)]
                use $crate::Method::*;
                __rustful_to_path!($($method)::+)
            };
            let path = __rustful_route_expr!($($steps),*);
            $router.insert(method, path, $handler);
            __rustful_insert_internal!($router, [$($steps),*], $($next)*)
        }
    };
    ($router:ident, [$($steps:expr),*], $path:tt => $method:path: $handler:expr, $($next:tt)*) => {
        {
            let method = {
                #[allow(unused_imports)]
                use $crate::Method::*;
                $method
            };
            let path = __rustful_route_expr!($($steps,)* __rustful_to_expr!($path));
            $router.insert(method, path, $handler);
            __rustful_insert_internal!($router, [$($steps),*], $($next)*)
        }
    };
    ($router:ident, [$($steps:expr),*], $($method:tt)::+: $handler:expr) => {
        {
            let method = {
                #[allow(unused_imports)]
                use $crate::Method::*;
                __rustful_to_path!($($method)::+)
            };
            let path = __rustful_route_expr!($($steps),*);
            $router.insert(method, path, $handler);
        }
    };
    ($router:ident, [$($steps:expr),*], $path:tt => $method:path: $handler:expr) => {
        {
            let method = {
                #[allow(unused_imports)]
                use $crate::Method::*;
                $method
            };
            let path = __rustful_route_expr!($($steps,)* __rustful_to_expr!($path));
            $router.insert(method, path, $handler);
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __rustful_route_expr {
    () => ("");
    ($($path:expr),+) => (&[$($path),+][..]);
}

/**
A macro for making content types.

It takes a main type, a sub type and a parameter list. Instead of this:

```rust
use rustful::header::ContentType;
use rustful::mime::{Mime, TopLevel, SubLevel, Attr, Value};

ContentType(
    Mime (
        TopLevel::Text,
        SubLevel::Html,
        vec![(Attr::Charset, Value::Utf8)]
    )
);
```

it can be written like this:

```
#[macro_use]
extern crate rustful;
use rustful::header::ContentType;

# fn main() {
ContentType(content_type!(Text / Html; Charset = Utf8));
# }
```

The `Charset = Utf8` part defines the parameter list for the content type and
may contain more than one parameter, or be omitted. Here are some more
examples showing that and how strings can be used for more exotic values:

```
#[macro_use]
extern crate rustful;
use rustful::header::ContentType;

# fn main() {
ContentType(content_type!(Application / "octet-stream"; "type" = "image/gif"; "padding" = "4"));
# }
```

```
#[macro_use]
extern crate rustful;
use rustful::header::ContentType;

# fn main() {
ContentType(content_type!(Image / Png));
# }
```
**/
#[macro_export]
macro_rules! content_type {
    ($main_type:tt / $sub_type:tt) => ({
        use $crate::macros::MimeHelper;
        $crate::mime::Mime (
            {
                #[allow(unused_imports)]
                use $crate::mime::TopLevel::*;
                MimeHelper::from(__rustful_to_expr!($main_type)).convert()
            },
            {
                #[allow(unused_imports)]
                use $crate::mime::SubLevel::*;
                MimeHelper::from(__rustful_to_expr!($sub_type)).convert()
            },
            Vec::new()
        )
    });

    ($main_type:tt / $sub_type:tt; $($param:tt = $value:tt);+) => ({
        use $crate::macros::MimeHelper;
        $crate::mime::Mime (
            {
                #[allow(unused_imports)]
                use $crate::mime::TopLevel::*;
                MimeHelper::from(__rustful_to_expr!($main_type)).convert()
            },
            {
                #[allow(unused_imports)]
                use $crate::mime::SubLevel::*;
                MimeHelper::from(__rustful_to_expr!($sub_type)).convert()
            },
            vec![ $( ({
                #[allow(unused_imports)]
                use $crate::mime::Attr::*;
                MimeHelper::from(__rustful_to_expr!($param)).convert()
            }, {
                #[allow(unused_imports)]
                use $crate::mime::Value::*;
                MimeHelper::from(__rustful_to_expr!($value)).convert()
            })),+ ]
        )
    });
}

#[doc(hidden)]
#[macro_export]
macro_rules! __rustful_to_expr {
    ($e: expr) => ($e)
}

#[doc(hidden)]
#[macro_export]
macro_rules! __rustful_to_path {
    ($e: path) => ($e)
}

use std::str::FromStr;
use std::fmt::Debug;
use mime::{TopLevel, SubLevel, Attr, Value};

#[doc(hidden)]
pub enum MimeHelper<'a, T> {
    Str(&'a str),
    Target(T)
}

impl<'a, T: FromStr> MimeHelper<'a, T> where <T as FromStr>::Err: Debug {
    pub fn convert(self) -> T {
        match self {
            MimeHelper::Str(s) => s.parse().unwrap(),
            MimeHelper::Target(t) => t
        }
    }
}

impl<'a, T: FromStr> From<&'a str> for MimeHelper<'a, T> {
    fn from(s: &'a str) -> MimeHelper<'a, T> {
        MimeHelper::Str(s)
    }
}

impl<'a> From<TopLevel> for MimeHelper<'a, TopLevel> {
    fn from(t: TopLevel) -> MimeHelper<'a, TopLevel> {
        MimeHelper::Target(t)
    }
}

impl<'a> From<SubLevel> for MimeHelper<'a, SubLevel> {
    fn from(t: SubLevel) -> MimeHelper<'a, SubLevel> {
        MimeHelper::Target(t)
    }
}

impl<'a> From<Attr> for MimeHelper<'a, Attr> {
    fn from(t: Attr) -> MimeHelper<'a, Attr> {
        MimeHelper::Target(t)
    }
}

impl<'a> From<Value> for MimeHelper<'a, Value> {
    fn from(t: Value) -> MimeHelper<'a, Value> {
        MimeHelper::Target(t)
    }
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::{read_dir, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::thread;
use std::time;
use thread_priority::{set_current_thread_priority, ThreadPriority};

// This is the number of characters taken from timestamp to create new metrics file. E.g.
// from "2022-05-30_17.06.03", 13 means "2022-05-30.metrics".
const DEFAULT_METRICS_FILE_PRECISION: u8 = 10;

pub fn process_metrics(metrics_dir: PathBuf, metrics_precision: Option<u8>, log_dir: PathBuf) {
    thread::spawn(move || {
        set_current_thread_priority(ThreadPriority::Min).unwrap();
        let metrics_precision = metrics_precision.unwrap_or(DEFAULT_METRICS_FILE_PRECISION);
        let sleep_duration = time::Duration::from_millis(10000);

        // Read in the last file checked
        let metrics_state_file_path = metrics_dir.join(".state");

        loop {
            log::debug!(
                "Attempting metrics collection to {}",
                metrics_dir.to_str().unwrap()
            );

            let metrics_state_file: Option<File> = OpenOptions::new()
                .read(true)
                .open(&metrics_state_file_path)
                .map_or(None, |file| Some(file));
            let state: (String, usize) = if let Some(metrics_state_file) = metrics_state_file {
                let mut state_reader = BufReader::new(metrics_state_file);
                let mut state = String::new();
                state_reader.read_line(&mut state).unwrap();
                let split = state.split(" ");
                let state_split: Vec<&str> = split.collect();
                let state_path = state_split[0].to_string();
                let state_count_str = trim_newline(state_split[1]);
                (state_path, state_count_str.parse::<usize>().unwrap())
            } else {
                ("".to_string(), 0)
            };
            let mut paths = read_dir(log_dir.to_str().unwrap())
                .unwrap()
                .map(|res| res.map(|e| e.path()))
                .filter(|path| {
                    if let Ok(path) = path {
                        return path.is_file()
                            && path.extension() == Some(OsStr::new("log"))
                            && path.to_str().unwrap().to_string() >= state.0;
                    }
                    false
                })
                .collect::<Result<Vec<_>, std::io::Error>>()
                .unwrap();
            paths.sort();

            for path in paths {
                let stem: String = path
                    .file_stem()
                    .unwrap()
                    .to_os_string()
                    .into_string()
                    .unwrap();
                if stem.len() <= metrics_precision.into() {
                    log::warn!(
                        "Log file {} has too low precision, needs at least {}",
                        path.to_str().unwrap(),
                        metrics_precision + 1
                    );
                    continue;
                }

                let start_line_index: usize = if path.to_str().unwrap() == state.0 {
                    state.1 + 1
                } else {
                    0
                };
                let mut log_map: HashMap<String, usize> = HashMap::new();

                let log_file = File::open(&path).unwrap();
                let log_reader = BufReader::new(log_file);
                let mut last_processed_index: usize = 0;
                for (i, line) in log_reader.lines().enumerate() {
                    let line = line.unwrap();
                    if i >= start_line_index {
                        let split = line.split(" ");
                        let log: Vec<&str> = split.collect();
                        let key = format!("{} {}", log[1], trim_newline(log[2]));
                        if log.len() < 3 {
                            // If the line is shorter, it might be that it is being written ATM
                            log::warn!("Malformed log line: {}", &line);
                        } else if log_map.contains_key(&key) {
                            let new_count: usize = log_map.get(&key).unwrap() + 1;
                            log_map.insert(key, new_count);
                        } else {
                            log_map.insert(key, 1);
                        }
                        last_processed_index = i;
                    }
                }

                if !log_map.is_empty() {
                    log::debug!(
                        "Found (partially) unprocessed log file {}",
                        path.to_str().unwrap(),
                    );
                    let metrics_file_name: String =
                        stem[0..metrics_precision.into()].to_string() + ".metrics";
                    let metrics_file_tmp_name: String = format!("{}.tmp", &metrics_file_name);
                    let metrics_file_path = metrics_dir.join(&metrics_file_name);
                    let metrics_file_tmp_path = metrics_dir.join(metrics_file_tmp_name);
                    let metrics_file: Option<File> = OpenOptions::new()
                        .read(true)
                        .open(&metrics_file_path)
                        .map_or(None, |file| Some(file));

                    let mut metrics_file_tmp: File = OpenOptions::new()
                        .create(true)
                        .append(true)
                        .open(&metrics_file_tmp_path)
                        .unwrap();

                    // Read in existing and append to them
                    if let Some(metrics_reader) =
                        metrics_file.as_ref().map(|file| BufReader::new(file))
                    {
                        for line in metrics_reader.lines() {
                            let line = line.unwrap();
                            let split = line.split(" ");
                            let metric: Vec<&str> = split.collect();
                            if metric.len() < 3 {
                                log::warn!(
                                    "Malformed metric line: '{}' in file {}",
                                    &line,
                                    &metrics_file_name
                                );
                                continue;
                            }
                            let key = format!("{} {}", metric[0], metric[1]);
                            let existing_count_str = trim_newline(metric[2]);
                            let existing_count = existing_count_str.parse::<usize>().unwrap();

                            if let Some(additional_count) = log_map.get(&key) {
                                let new_line =
                                    format!("{} {}\n", key, existing_count + additional_count);
                                metrics_file_tmp.write_all(new_line.as_bytes()).unwrap();
                                log_map.remove(&key);
                            } else {
                                metrics_file_tmp
                                    .write_all((line + "\n").as_bytes())
                                    .unwrap();
                            }
                        }
                    }

                    // Write out new lines
                    for (key, count) in log_map {
                        let new_line = format!("{} {}\n", key, count);
                        metrics_file_tmp.write_all(new_line.as_bytes()).unwrap();
                    }

                    // Finally delete old metrics file, rename tmp, and change state
                    if metrics_file.is_some() {
                        std::fs::remove_file(&metrics_file_path).unwrap();
                    };
                    std::fs::rename(metrics_file_tmp_path, metrics_file_path).unwrap();
                    let mut metrics_state_file = std::fs::OpenOptions::new()
                        .create(true)
                        .write(true)
                        .truncate(true)
                        .open(&metrics_state_file_path)
                        .unwrap();
                    metrics_state_file
                        .write_all(
                            format!("{} {}\n", &path.to_str().unwrap(), last_processed_index)
                                .as_bytes(),
                        )
                        .unwrap();
                }

                // TODO: Lue jotenkin näin se sisältö HashMappiin, lue sitten rivi kerrallaan
                // sisään edellinen metrics-tiedosto, ja samalla kun looppaa, vaihda arvot,
                // poista avain hashmapistä, ja lopuksi lisää pohjalle kaikki loput arvot, ja
                // vaihda .state arvo oikeaan.
                //
                // let mut reader = BufReader::new(metrics_state_file);
                // let mut previous_path = String::new();
                // reader.read_line(&mut previous_path).unwrap();
            }

            thread::sleep(sleep_duration);
        }
    });
}

fn trim_newline(s: &str) -> String {
    if s.ends_with('\n') {
        s[0..s.len() - 1].to_string()
    } else {
        s.to_string()
    }
}
<commit_msg>Default metrics refresh duration is 10 seconds<commit_after>use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::{read_dir, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::thread;
use std::time;
use thread_priority::{set_current_thread_priority, ThreadPriority};

// This is the number of characters taken from timestamp to create new metrics file. E.g.
// from "2022-05-30_17.06.03", 13 means "2022-05-30.metrics".
const DEFAULT_METRICS_FILE_PRECISION: u8 = 10;

// The default time to sleep when trying to refresh metrics
const DEFAULT_METRICS_INTERVAL_SECONDS: u64 = 10;

pub fn process_metrics(metrics_dir: PathBuf, metrics_precision: Option<u8>, log_dir: PathBuf) {
    thread::spawn(move || {
        set_current_thread_priority(ThreadPriority::Min).unwrap();
        let metrics_precision = metrics_precision.unwrap_or(DEFAULT_METRICS_FILE_PRECISION);
        let sleep_duration = time::Duration::from_secs(DEFAULT_METRICS_INTERVAL_SECONDS);

        // Read in the last file checked
        let metrics_state_file_path = metrics_dir.join(".state");

        loop {
            log::debug!(
                "Attempting metrics collection to {}",
                metrics_dir.to_str().unwrap()
            );

            let metrics_state_file: Option<File> = OpenOptions::new()
                .read(true)
                .open(&metrics_state_file_path)
                .map_or(None, |file| Some(file));
            let state: (String, usize) = if let Some(metrics_state_file) = metrics_state_file {
                let mut state_reader = BufReader::new(metrics_state_file);
                let mut state = String::new();
                state_reader.read_line(&mut state).unwrap();
                let split = state.split(" ");
                let state_split: Vec<&str> = split.collect();
                let state_path = state_split[0].to_string();
                let state_count_str = trim_newline(state_split[1]);
                (state_path, state_count_str.parse::<usize>().unwrap())
            } else {
                ("".to_string(), 0)
            };
            let mut paths = read_dir(log_dir.to_str().unwrap())
                .unwrap()
                .map(|res| res.map(|e| e.path()))
                .filter(|path| {
                    if let Ok(path) = path {
                        return path.is_file()
                            && path.extension() == Some(OsStr::new("log"))
                            && path.to_str().unwrap().to_string() >= state.0;
                    }
                    false
                })
                .collect::<Result<Vec<_>, std::io::Error>>()
                .unwrap();
            paths.sort();

            for path in paths {
                let stem: String = path
                    .file_stem()
                    .unwrap()
                    .to_os_string()
                    .into_string()
                    .unwrap();
                if stem.len() <= metrics_precision.into() {
                    log::warn!(
                        "Log file {} has too low precision, needs at least {}",
                        path.to_str().unwrap(),
                        metrics_precision + 1
                    );
                    continue;
                }

                let start_line_index: usize = if path.to_str().unwrap() == state.0 {
                    state.1 + 1
                } else {
                    0
                };
                let mut log_map: HashMap<String, usize> = HashMap::new();

                let log_file = File::open(&path).unwrap();
                let log_reader = BufReader::new(log_file);
                let mut last_processed_index: usize = 0;
                for (i, line) in log_reader.lines().enumerate() {
                    let line = line.unwrap();
                    if i >= start_line_index {
                        let split = line.split(" ");
                        let log: Vec<&str> = split.collect();
                        let key = format!("{} {}", log[1], trim_newline(log[2]));
                        if log.len() < 3 {
                            // If the line is shorter, it might be that it is being written ATM
                            log::warn!("Malformed log line: {}", &line);
                        } else if log_map.contains_key(&key) {
                            let new_count: usize = log_map.get(&key).unwrap() + 1;
                            log_map.insert(key, new_count);
                        } else {
                            log_map.insert(key, 1);
                        }
                        last_processed_index = i;
                    }
                }

                if !log_map.is_empty() {
                    log::debug!(
                        "Found (partially) unprocessed log file {}",
                        path.to_str().unwrap(),
                    );
                    let metrics_file_name: String =
                        stem[0..metrics_precision.into()].to_string() + ".metrics";
                    let metrics_file_tmp_name: String = format!("{}.tmp", &metrics_file_name);
                    let metrics_file_path = metrics_dir.join(&metrics_file_name);
                    let metrics_file_tmp_path = metrics_dir.join(metrics_file_tmp_name);
                    let metrics_file: Option<File> = OpenOptions::new()
                        .read(true)
                        .open(&metrics_file_path)
                        .map_or(None, |file| Some(file));

                    let mut metrics_file_tmp: File = OpenOptions::new()
                        .create(true)
                        .append(true)
                        .open(&metrics_file_tmp_path)
                        .unwrap();

                    // Read in existing and append to them
                    if let Some(metrics_reader) =
                        metrics_file.as_ref().map(|file| BufReader::new(file))
                    {
                        for line in metrics_reader.lines() {
                            let line = line.unwrap();
                            let split = line.split(" ");
                            let metric: Vec<&str> = split.collect();
                            if metric.len() < 3 {
                                log::warn!(
                                    "Malformed metric line: '{}' in file {}",
                                    &line,
                                    &metrics_file_name
                                );
                                continue;
                            }
                            let key = format!("{} {}", metric[0], metric[1]);
                            let existing_count_str = trim_newline(metric[2]);
                            let existing_count = existing_count_str.parse::<usize>().unwrap();

                            if let Some(additional_count) = log_map.get(&key) {
                                let new_line =
                                    format!("{} {}\n", key, existing_count + additional_count);
                                metrics_file_tmp.write_all(new_line.as_bytes()).unwrap();
                                log_map.remove(&key);
                            } else {
                                metrics_file_tmp
                                    .write_all((line + "\n").as_bytes())
                                    .unwrap();
                            }
                        }
                    }

                    // Write out new lines
                    for (key, count) in log_map {
                        let new_line = format!("{} {}\n", key, count);
                        metrics_file_tmp.write_all(new_line.as_bytes()).unwrap();
                    }

                    // Finally delete old metrics file, rename tmp, and change state
                    if metrics_file.is_some() {
                        std::fs::remove_file(&metrics_file_path).unwrap();
                    };
                    std::fs::rename(metrics_file_tmp_path, metrics_file_path).unwrap();
                    let mut metrics_state_file = std::fs::OpenOptions::new()
                        .create(true)
                        .write(true)
                        .truncate(true)
                        .open(&metrics_state_file_path)
                        .unwrap();
                    metrics_state_file
                        .write_all(
                            format!("{} {}\n", &path.to_str().unwrap(), last_processed_index)
                                .as_bytes(),
                        )
                        .unwrap();
                }

                // TODO: Lue jotenkin näin se sisältö HashMappiin, lue sitten rivi kerrallaan
                // sisään edellinen metrics-tiedosto, ja samalla kun looppaa, vaihda arvot,
                // poista avain hashmapistä, ja lopuksi lisää pohjalle kaikki loput arvot, ja
                // vaihda .state arvo oikeaan.
                //
                // let mut reader = BufReader::new(metrics_state_file);
                // let mut previous_path = String::new();
                // reader.read_line(&mut previous_path).unwrap();
            }

            thread::sleep(sleep_duration);
        }
    });
}

fn trim_newline(s: &str) -> String {
    if s.ends_with('\n') {
        s[0..s.len() - 1].to_string()
    } else {
        s.to_string()
    }
}
<|endoftext|>


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

// Test harness that can run as a Tock application. Note that the application
// itself should be a library crate, as the Rust test harness includes main().
// Relies on internal details of rustc, so this may break during toolchain
// updates.

#![feature(asm)]
#![no_std]

mod assertions;
mod compiler_required;

pub use self::assertions::*;
pub use self::compiler_required::*;

libtock_core::stack_size!{2048}
<commit_msg>Remove unused "feature(asm)" from test_harness.<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Test harness that can run as a Tock application. Note that the application
// itself should be a library crate, as the Rust test harness includes main().
// Relies on internal details of rustc, so this may break during toolchain
// updates.

#![no_std]

mod assertions;
mod compiler_required;

pub use self::assertions::*;
pub use self::compiler_required::*;

libtock_core::stack_size!{2048}
<|endoftext|>


<commit_before>use std::cmp::Ordering;
use std::os::unix::fs::MetadataExt;

use getopts;
use glob;
use natord;

use fs::File;
use options::misfire::Misfire;

/// The **file filter** processes a vector of files before outputting them,
/// filtering and sorting the files depending on the user’s command-line
/// flags.
#[derive(Default, PartialEq, Debug, Clone)]
pub struct FileFilter {

    /// Whether directories should be listed first, and other types of file
    /// second. Some users prefer it like this.
    pub list_dirs_first: bool,

    /// The metadata field to sort by.
    pub sort_field: SortField,

    /// Whether to reverse the sorting order. This would sort the largest
    /// files first, or files starting with Z, or the most-recently-changed
    /// ones, depending on the sort field.
    pub reverse: bool,

    /// Whether to include invisible “dot” files when listing a directory.
    ///
    /// Files starting with a single “.” are used to determine “system” or
    /// “configuration” files that should not be displayed in a regular
    /// directory listing.
    ///
    /// This came about more or less by a complete historical accident,
    /// when the original `ls` tried to hide `.` and `..`:
    /// https://plus.google.com/+RobPikeTheHuman/posts/R58WgWwN9jp
    ///
    ///   When one typed ls, however, these files appeared, so either Ken or
    ///   Dennis added a simple test to the program. It was in assembler then,
    ///   but the code in question was equivalent to something like this:
    ///      if (name[0] == '.') continue;
    ///   This statement was a little shorter than what it should have been,
    ///   which is:
    ///      if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) continue;
    ///   but hey, it was easy.
    ///
    ///   Two things resulted.
    ///
    ///   First, a bad precedent was set. A lot of other lazy programmers
    ///   introduced bugs by making the same simplification. Actual files
    ///   beginning with periods are often skipped when they should be counted.
    ///
    ///   Second, and much worse, the idea of a "hidden" or "dot" file was
    ///   created. As a consequence, more lazy programmers started dropping
    ///   files into everyone's home directory. I don't have all that much
    ///   stuff installed on the machine I'm using to type this, but my home
    ///   directory has about a hundred dot files and I don't even know what
    ///   most of them are or whether they're still needed. Every file name
    ///   evaluation that goes through my home directory is slowed down by
    ///   this accumulated sludge.
    show_invisibles: bool,

    /// Glob patterns to ignore. Any file name that matches *any* of these
    /// patterns won't be displayed in the list.
    ignore_patterns: IgnorePatterns,
}

impl FileFilter {

    /// Determines the set of file filter options to use, based on the user’s
    /// command-line arguments.
    pub fn deduce(matches: &getopts::Matches) -> Result<FileFilter, Misfire> {
        Ok(FileFilter {
            list_dirs_first: matches.opt_present("group-directories-first"),
            reverse:         matches.opt_present("reverse"),
            sort_field:      SortField::deduce(matches)?,
            show_invisibles: matches.opt_present("all"),
            ignore_patterns: IgnorePatterns::deduce(matches)?,
        })
    }

    /// Remove every file in the given vector that does *not* pass the
    /// filter predicate for files found inside a directory.
    pub fn filter_child_files(&self, files: &mut Vec<File>) {
        if !self.show_invisibles {
            files.retain(|f| !f.is_dotfile());
        }

        files.retain(|f| !self.ignore_patterns.is_ignored(f));
    }

    /// Remove every file in the given vector that does *not* pass the
    /// filter predicate for file names specified on the command-line.
    ///
    /// The rules are different for these types of files than the other
    /// type because the ignore rules can be used with globbing. For
    /// example, running "exa -I='*.tmp' .vimrc" shouldn't filter out the
    /// dotfile, because it's been directly specified. But running
    /// "exa -I='*.ogg' music/*" should filter out the ogg files obtained
    /// from the glob, even though the globbing is done by the shell!
    pub fn filter_argument_files(&self, files: &mut Vec<File>) {
        files.retain(|f| !self.ignore_patterns.is_ignored(f));
    }

    /// Sort the files in the given vector based on the sort field option.
    pub fn sort_files<'a, F>(&self, files: &mut Vec<F>)
    where F: AsRef<File<'a>> {

        files.sort_by(|a, b| self.compare_files(a.as_ref(), b.as_ref()));

        if self.reverse {
            files.reverse();
        }

        if self.list_dirs_first {
            // This relies on the fact that `sort_by` is stable.
            files.sort_by(|a, b| b.as_ref().is_directory().cmp(&a.as_ref().is_directory()));
        }
    }

    /// Compares two files to determine the order they should be listed in,
    /// depending on the search field.
    pub fn compare_files(&self, a: &File, b: &File) -> Ordering {
        use self::SortCase::{Sensitive, Insensitive};

        match self.sort_field {
            SortField::Unsorted  => Ordering::Equal,

            SortField::Name(Sensitive)    => natord::compare(&a.name, &b.name),
            SortField::Name(Insensitive)  => natord::compare_ignore_case(&a.name, &b.name),

            SortField::Size          => a.metadata.len().cmp(&b.metadata.len()),
            SortField::FileInode     => a.metadata.ino().cmp(&b.metadata.ino()),
            SortField::ModifiedDate  => a.metadata.mtime().cmp(&b.metadata.mtime()),
            SortField::AccessedDate  => a.metadata.atime().cmp(&b.metadata.atime()),
            SortField::CreatedDate   => a.metadata.ctime().cmp(&b.metadata.ctime()),

            SortField::Extension(Sensitive) => match a.ext.cmp(&b.ext) {
                Ordering::Equal  => natord::compare(&*a.name, &*b.name),
                order            => order,
            },

            SortField::Extension(Insensitive) => match a.ext.cmp(&b.ext) {
                Ordering::Equal  => natord::compare_ignore_case(&*a.name, &*b.name),
                order            => order,
            },
        }
    }
}

/// User-supplied field to sort by.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum SortField {

    /// Don't apply any sorting. This is usually used as an optimisation in
    /// scripts, where the order doesn't matter.
    Unsorted,

    /// The file name. This is the default sorting.
    Name(SortCase),

    /// The file's extension, with extensionless files being listed first.
    Extension(SortCase),

    /// The file's size.
    Size,

    /// The file's inode. This is sometimes analogous to the order in which
    /// the files were created on the hard drive.
    FileInode,

    /// The time at which this file was modified (the `mtime`).
    ///
    /// As this is stored as a Unix timestamp, rather than a local time
    /// instance, the time zone does not matter and will only be used to
    /// display the timestamps, not compare them.
    ModifiedDate,

    /// The time at this file was accessed (the `atime`).
    ///
    /// Oddly enough, this field rarely holds the *actual* accessed time.
    /// Recording a read time means writing to the file each time it’s read
    /// slows the whole operation down, so many systems will only update the
    /// timestamp in certain circumstances. This has become common enough that
    /// it’s now expected behaviour for the `atime` field.
    /// http://unix.stackexchange.com/a/8842
    AccessedDate,

    /// The time at which this file was changed or created (the `ctime`).
    ///
    /// Contrary to the name, this field is used to mark the time when a
    /// file's metadata changed -- its permissions, owners, or link count.
    ///
    /// In original Unix, this was, however, meant as creation time.
    /// https://www.bell-labs.com/usr/dmr/www/cacm.html
    CreatedDate,
}

/// Whether a field should be sorted case-sensitively or case-insensitively.
///
/// This determines which of the `natord` functions to use.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum SortCase {

    /// Sort files case-sensitively with uppercase first, with ‘A’ coming
    /// before ‘a’.
    Sensitive,

    /// Sort files case-insensitively, with ‘A’ being equal to ‘a’.
    Insensitive,
}

impl Default for SortField {
    fn default() -> SortField {
        SortField::Name(SortCase::Sensitive)
    }
}

impl SortField {

    /// Determine the sort field to use, based on the presence of a “sort”
    /// argument. This will return `Err` if the option is there, but does not
    /// correspond to a valid field.
    fn deduce(matches: &getopts::Matches) -> Result<SortField, Misfire> {

        const SORTS: &[&str] = &[ "name", "Name", "size", "extension",
                                  "Extension", "modified", "accessed",
                                  "created", "inode", "none" ];

        if let Some(word) = matches.opt_str("sort") {
            match &*word {
                "name" | "filename"   => Ok(SortField::Name(SortCase::Sensitive)),
                "Name" | "Filename"   => Ok(SortField::Name(SortCase::Insensitive)),
                "size" | "filesize"   => Ok(SortField::Size),
                "ext"  | "extension"  => Ok(SortField::Extension(SortCase::Sensitive)),
                "Ext"  | "Extension"  => Ok(SortField::Extension(SortCase::Insensitive)),
                "mod"  | "modified"   => Ok(SortField::ModifiedDate),
                "acc"  | "accessed"   => Ok(SortField::AccessedDate),
                "cr"   | "created"    => Ok(SortField::CreatedDate),
                "none"                => Ok(SortField::Unsorted),
                "inode"               => Ok(SortField::FileInode),
                field                 => Err(Misfire::bad_argument("sort", field, SORTS))
            }
        }
        else {
            Ok(SortField::default())
        }
    }
}

#[derive(PartialEq, Default, Debug, Clone)]
struct IgnorePatterns {
    patterns: Vec<glob::Pattern>,
}

impl IgnorePatterns {
    /// Determines the set of file filter options to use, based on the user’s
    /// command-line arguments.
    pub fn deduce(matches: &getopts::Matches) -> Result<IgnorePatterns, Misfire> {
        let patterns = match matches.opt_str("ignore-glob") {
            None => Ok(Vec::new()),
            Some(is) => is.split('|').map(|a| glob::Pattern::new(a)).collect(),
        };

        Ok(IgnorePatterns {
            patterns: patterns?,
        })
    }

    fn is_ignored(&self, file: &File) -> bool {
        self.patterns.iter().any(|p| p.matches(&file.name))
    }
}
<commit_msg>Move the show-invisibles flag into a struct<commit_after>use std::cmp::Ordering;
use std::os::unix::fs::MetadataExt;

use getopts;
use glob;
use natord;

use fs::File;
use options::misfire::Misfire;

/// The **file filter** processes a vector of files before outputting them,
/// filtering and sorting the files depending on the user’s command-line
/// flags.
#[derive(Default, PartialEq, Debug, Clone)]
pub struct FileFilter {

    /// Whether directories should be listed first, and other types of file
    /// second. Some users prefer it like this.
    pub list_dirs_first: bool,

    /// The metadata field to sort by.
    pub sort_field: SortField,

    /// Whether to reverse the sorting order. This would sort the largest
    /// files first, or files starting with Z, or the most-recently-changed
    /// ones, depending on the sort field.
    pub reverse: bool,

    /// Whether to include invisible “dot” files when listing a directory.
    ///
    /// Files starting with a single “.” are used to determine “system” or
    /// “configuration” files that should not be displayed in a regular
    /// directory listing.
    ///
    /// This came about more or less by a complete historical accident,
    /// when the original `ls` tried to hide `.` and `..`:
    /// https://plus.google.com/+RobPikeTheHuman/posts/R58WgWwN9jp
    ///
    ///   When one typed ls, however, these files appeared, so either Ken or
    ///   Dennis added a simple test to the program. It was in assembler then,
    ///   but the code in question was equivalent to something like this:
    ///      if (name[0] == '.') continue;
    ///   This statement was a little shorter than what it should have been,
    ///   which is:
    ///      if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) continue;
    ///   but hey, it was easy.
    ///
    ///   Two things resulted.
    ///
    ///   First, a bad precedent was set. A lot of other lazy programmers
    ///   introduced bugs by making the same simplification. Actual files
    ///   beginning with periods are often skipped when they should be counted.
    ///
    ///   Second, and much worse, the idea of a "hidden" or "dot" file was
    ///   created. As a consequence, more lazy programmers started dropping
    ///   files into everyone's home directory. I don't have all that much
    ///   stuff installed on the machine I'm using to type this, but my home
    ///   directory has about a hundred dot files and I don't even know what
    ///   most of them are or whether they're still needed. Every file name
    ///   evaluation that goes through my home directory is slowed down by
    ///   this accumulated sludge.
    dot_filter: DotFilter,

    /// Glob patterns to ignore. Any file name that matches *any* of these
    /// patterns won't be displayed in the list.
    ignore_patterns: IgnorePatterns,
}

impl FileFilter {

    /// Determines the set of file filter options to use, based on the user’s
    /// command-line arguments.
    pub fn deduce(matches: &getopts::Matches) -> Result<FileFilter, Misfire> {
        Ok(FileFilter {
            list_dirs_first: matches.opt_present("group-directories-first"),
            reverse:         matches.opt_present("reverse"),
            sort_field:      SortField::deduce(matches)?,
            dot_filter:      DotFilter::deduce(matches),
            ignore_patterns: IgnorePatterns::deduce(matches)?,
        })
    }

    /// Remove every file in the given vector that does *not* pass the
    /// filter predicate for files found inside a directory.
    pub fn filter_child_files(&self, files: &mut Vec<File>) {
        match self.dot_filter {
            DotFilter::JustFiles => files.retain(|f| !f.is_dotfile()),
            DotFilter::ShowDotfiles => {/* keep all elements */},
        }

        files.retain(|f| !self.ignore_patterns.is_ignored(f));
    }

    /// Remove every file in the given vector that does *not* pass the
    /// filter predicate for file names specified on the command-line.
    ///
    /// The rules are different for these types of files than the other
    /// type because the ignore rules can be used with globbing. For
    /// example, running "exa -I='*.tmp' .vimrc" shouldn't filter out the
    /// dotfile, because it's been directly specified. But running
    /// "exa -I='*.ogg' music/*" should filter out the ogg files obtained
    /// from the glob, even though the globbing is done by the shell!
    pub fn filter_argument_files(&self, files: &mut Vec<File>) {
        files.retain(|f| !self.ignore_patterns.is_ignored(f));
    }

    /// Sort the files in the given vector based on the sort field option.
    pub fn sort_files<'a, F>(&self, files: &mut Vec<F>)
    where F: AsRef<File<'a>> {

        files.sort_by(|a, b| self.compare_files(a.as_ref(), b.as_ref()));

        if self.reverse {
            files.reverse();
        }

        if self.list_dirs_first {
            // This relies on the fact that `sort_by` is stable.
            files.sort_by(|a, b| b.as_ref().is_directory().cmp(&a.as_ref().is_directory()));
        }
    }

    /// Compares two files to determine the order they should be listed in,
    /// depending on the search field.
    pub fn compare_files(&self, a: &File, b: &File) -> Ordering {
        use self::SortCase::{Sensitive, Insensitive};

        match self.sort_field {
            SortField::Unsorted  => Ordering::Equal,

            SortField::Name(Sensitive)    => natord::compare(&a.name, &b.name),
            SortField::Name(Insensitive)  => natord::compare_ignore_case(&a.name, &b.name),

            SortField::Size          => a.metadata.len().cmp(&b.metadata.len()),
            SortField::FileInode     => a.metadata.ino().cmp(&b.metadata.ino()),
            SortField::ModifiedDate  => a.metadata.mtime().cmp(&b.metadata.mtime()),
            SortField::AccessedDate  => a.metadata.atime().cmp(&b.metadata.atime()),
            SortField::CreatedDate   => a.metadata.ctime().cmp(&b.metadata.ctime()),

            SortField::Extension(Sensitive) => match a.ext.cmp(&b.ext) {
                Ordering::Equal  => natord::compare(&*a.name, &*b.name),
                order            => order,
            },

            SortField::Extension(Insensitive) => match a.ext.cmp(&b.ext) {
                Ordering::Equal  => natord::compare_ignore_case(&*a.name, &*b.name),
                order            => order,
            },
        }
    }
}

/// User-supplied field to sort by.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum SortField {

    /// Don't apply any sorting. This is usually used as an optimisation in
    /// scripts, where the order doesn't matter.
    Unsorted,

    /// The file name. This is the default sorting.
    Name(SortCase),

    /// The file's extension, with extensionless files being listed first.
    Extension(SortCase),

    /// The file's size.
    Size,

    /// The file's inode. This is sometimes analogous to the order in which
    /// the files were created on the hard drive.
    FileInode,

    /// The time at which this file was modified (the `mtime`).
    ///
    /// As this is stored as a Unix timestamp, rather than a local time
    /// instance, the time zone does not matter and will only be used to
    /// display the timestamps, not compare them.
    ModifiedDate,

    /// The time at this file was accessed (the `atime`).
    ///
    /// Oddly enough, this field rarely holds the *actual* accessed time.
    /// Recording a read time means writing to the file each time it’s read
    /// slows the whole operation down, so many systems will only update the
    /// timestamp in certain circumstances. This has become common enough that
    /// it’s now expected behaviour for the `atime` field.
    /// http://unix.stackexchange.com/a/8842
    AccessedDate,

    /// The time at which this file was changed or created (the `ctime`).
    ///
    /// Contrary to the name, this field is used to mark the time when a
    /// file's metadata changed -- its permissions, owners, or link count.
    ///
    /// In original Unix, this was, however, meant as creation time.
    /// https://www.bell-labs.com/usr/dmr/www/cacm.html
    CreatedDate,
}

/// Whether a field should be sorted case-sensitively or case-insensitively.
///
/// This determines which of the `natord` functions to use.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum SortCase {

    /// Sort files case-sensitively with uppercase first, with ‘A’ coming
    /// before ‘a’.
    Sensitive,

    /// Sort files case-insensitively, with ‘A’ being equal to ‘a’.
    Insensitive,
}

impl Default for SortField {
    fn default() -> SortField {
        SortField::Name(SortCase::Sensitive)
    }
}

impl SortField {

    /// Determine the sort field to use, based on the presence of a “sort”
    /// argument. This will return `Err` if the option is there, but does not
    /// correspond to a valid field.
    fn deduce(matches: &getopts::Matches) -> Result<SortField, Misfire> {

        const SORTS: &[&str] = &[ "name", "Name", "size", "extension",
                                  "Extension", "modified", "accessed",
                                  "created", "inode", "none" ];

        if let Some(word) = matches.opt_str("sort") {
            match &*word {
                "name" | "filename"   => Ok(SortField::Name(SortCase::Sensitive)),
                "Name" | "Filename"   => Ok(SortField::Name(SortCase::Insensitive)),
                "size" | "filesize"   => Ok(SortField::Size),
                "ext"  | "extension"  => Ok(SortField::Extension(SortCase::Sensitive)),
                "Ext"  | "Extension"  => Ok(SortField::Extension(SortCase::Insensitive)),
                "mod"  | "modified"   => Ok(SortField::ModifiedDate),
                "acc"  | "accessed"   => Ok(SortField::AccessedDate),
                "cr"   | "created"    => Ok(SortField::CreatedDate),
                "none"                => Ok(SortField::Unsorted),
                "inode"               => Ok(SortField::FileInode),
                field                 => Err(Misfire::bad_argument("sort", field, SORTS))
            }
        }
        else {
            Ok(SortField::default())
        }
    }
}

#[derive(PartialEq, Debug, Copy, Clone)]
enum DotFilter {

    /// Show files and dotfiles, but hide `.` and `..`.
    ShowDotfiles,

    /// Just show files, hiding anything beginning with a dot.
    JustFiles,
}

impl Default for DotFilter {
    fn default() -> DotFilter {
        DotFilter::JustFiles
    }
}

impl DotFilter {
    pub fn deduce(matches: &getopts::Matches) -> DotFilter {
        if matches.opt_present("all") { DotFilter::ShowDotfiles }
                                 else { DotFilter::JustFiles }
    }
}

#[derive(PartialEq, Default, Debug, Clone)]
struct IgnorePatterns {
    patterns: Vec<glob::Pattern>,
}

impl IgnorePatterns {
    /// Determines the set of file filter options to use, based on the user’s
    /// command-line arguments.
    pub fn deduce(matches: &getopts::Matches) -> Result<IgnorePatterns, Misfire> {
        let patterns = match matches.opt_str("ignore-glob") {
            None => Ok(Vec::new()),
            Some(is) => is.split('|').map(|a| glob::Pattern::new(a)).collect(),
        };

        Ok(IgnorePatterns {
            patterns: patterns?,
        })
    }

    fn is_ignored(&self, file: &File) -> bool {
        self.patterns.iter().any(|p| p.matches(&file.name))
    }
}
<|endoftext|>