<commit_before>/*!
A library for finding occurrences of many patterns at once. This library
provides multiple pattern search principally through an implementation of the
[Aho-Corasick algorithm](https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm),
which builds a fast finite state machine for executing searches in linear time.

Additionally, this library provides a number of configuration options for
building the automaton that permit controlling the space versus time trade
off. Other features include simple ASCII case insensitive matching, finding
overlapping matches, replacements, searching streams and even searching and
replacing text in streams.

Finally, unlike all other (known) Aho-Corasick implementations, this one
supports enabling
[leftmost-first](enum.MatchKind.html#variant.LeftmostFirst)
or
[leftmost-longest](enum.MatchKind.html#variant.LeftmostFirst)
match semantics, using a (seemingly) novel alternative construction algorithm.
For more details on what match semantics means, see the
[`MatchKind`](enum.MatchKind.html)
type.

# Overview

This section gives a brief overview of the primary types in this crate:

* [`AhoCorasick`](struct.AhoCorasick.html) is the primary type and represents
  an Aho-Corasick automaton. This is the type you use to execute searches.
* [`AhoCorasickBuilder`](struct.AhoCorasickBuilder.html) can be used to build
  an Aho-Corasick automaton, and supports configuring a number of options.
* [`Match`](struct.Match.html) represents a single match reported by an
  Aho-Corasick automaton. Each match has two pieces of information: the pattern
  that matched and the start and end byte offsets corresponding to the position
  in the haystack at which it matched.

# Example: basic searching

This example shows how to search for occurrences of multiple patterns
simultaneously. Each match includes the pattern that matched along with the
byte offsets of the match.

```
use aho_corasick::AhoCorasick;

let patterns = &["apple", "maple", "Snapple"];
let haystack = "Nobody likes maple in their apple flavored Snapple.";

let ac = AhoCorasick::new(patterns);
let mut matches = vec![];
for mat in ac.find_iter(haystack) {
    matches.push((mat.pattern(), mat.start(), mat.end()));
}
assert_eq!(matches, vec![
    (1, 13, 18),
    (0, 28, 33),
    (2, 43, 50),
]);
```

# Example: case insensitivity

This is like the previous example, but matches `Snapple` case insensitively
using `AhoCorasickBuilder`:

```
use aho_corasick::AhoCorasickBuilder;

let patterns = &["apple", "maple", "snapple"];
let haystack = "Nobody likes maple in their apple flavored Snapple.";

let ac = AhoCorasickBuilder::new()
    .ascii_case_insensitive(true)
    .build(patterns);
let mut matches = vec![];
for mat in ac.find_iter(haystack) {
    matches.push((mat.pattern(), mat.start(), mat.end()));
}
assert_eq!(matches, vec![
    (1, 13, 18),
    (0, 28, 33),
    (2, 43, 50),
]);
```

# Example: replacing matches in a stream

This example shows how to execute a search and replace on a stream without
loading the entire stream into memory first.

```
use aho_corasick::AhoCorasick;

# fn example() -> Result<(), ::std::io::Error> {
let patterns = &["fox", "brown", "quick"];
let replace_with = &["sloth", "grey", "slow"];

// In a real example, these might be `std::fs::File`s instead. All you need to
// do is supply a pair of `std::io::Read` and `std::io::Write` implementations.
let rdr = "The quick brown fox.";
let mut wtr = vec![];

let ac = AhoCorasick::new(patterns);
ac.stream_replace_all(rdr.as_bytes(), &mut wtr, replace_with)?;
assert_eq!(b"The slow grey sloth.".to_vec(), wtr);
# Ok(()) }; example().unwrap()
```

# Example: finding the leftmost first match

In the textbook description of Aho-Corasick, its formulation is typically
structured such that it reports all possible matches, even when they overlap
with another. In many cases, overlapping matches may not be desired, such as
the case of finding all successive non-overlapping matches like you might with
a standard regular expression.

Unfortunately the "obvious" way to modify the Aho-Corasick algorithm to do
this doesn't always work in the expected way, since it will report matches as
soon as they are seen. For example, consider matching the regex `Samwise|Sam`
against the text `Samwise`. Most regex engines (that are Perl-like, or
non-POSIX) will report `Samwise` as a match, but the standard Aho-Corasick
algorithm modified for reporting non-overlapping matches will report `Sam`.

A novel contribution of this library is the ability to change the match
semantics of Aho-Corasick (without additional search time overhead) such that
`Samwise` is reported instead. For example, here's the standard approach:

```
use aho_corasick::AhoCorasick;

let patterns = &["Samwise", "Sam"];
let haystack = "Samwise";

let ac = AhoCorasick::new(patterns);
let mat = ac.find(haystack).expect("should have a match");
assert_eq!("Sam", &haystack[mat.start()..mat.end()]);
```

And now here's the leftmost-first version, which matches how a Perl-like
regex will work:

```
use aho_corasick::{AhoCorasickBuilder, MatchKind};

let patterns = &["Samwise", "Sam"];
let haystack = "Samwise";

let ac = AhoCorasickBuilder::new()
    .match_kind(MatchKind::LeftmostFirst)
    .build(patterns);
let mat = ac.find(haystack).expect("should have a match");
assert_eq!("Samwise", &haystack[mat.start()..mat.end()]);
```

In addition to leftmost-first semantics, this library also supports
leftmost-longest semantics, which match the POSIX behavior of a regular
expression alternation. See
[`MatchKind`](enum.MatchKind.html)
for more details.

# Prefilters

While an Aho-Corasick automaton can perform admirably when compared to more
naive solutions, it is generally slower than more specialized algorithms that
are accelerated using vector instructions such as SIMD.

For that reason, this library will internally use a "prefilter" to attempt
to accelerate searches when possible. Currently, this library has fairly
limited implementation that only applies when there are 3 or fewer unique
starting bytes among all patterns in an automaton.

In the future, it is intended for this prefilter to grow more sophisticated
by pushing applicable optimizations from the
[`regex`](http://docs.rs/regex)
crate (and other places) down into this library.

While a prefilter is generally good to have on by default since it works well
in the common case, it can lead to less predictable or even sub-optimal
performance in some cases. For that reason, prefilters can be disabled via
[`AhoCorasickBuilder::prefilter`](struct.AhoCorasickBuilder.html#method.prefilter).
*/

#![deny(missing_docs)]

// We can never be truly no_std, but we could be alloc-only some day, so
// require the std feature for now.
#[cfg(not(feature = "std"))]
compile_error!("`std` feature is currently required to build this crate");

extern crate memchr;
#[cfg(test)]
#[macro_use]
extern crate doc_comment;

#[cfg(test)]
doctest!("../README.md");

pub use ahocorasick::{
    AhoCorasick, AhoCorasickBuilder, MatchKind,
    FindIter, FindOverlappingIter, StreamFindIter,
};
pub use error::{Error, ErrorKind};
pub use state_id::StateID;

mod ahocorasick;
mod automaton;
mod buffer;
mod dfa;
mod error;
mod classes;
mod prefilter;
mod nfa;
mod state_id;
#[cfg(test)]
mod tests;

/// A representation of a match reported by an Aho-Corasick automaton.
///
/// A match has two essential pieces of information: the identifier of the
/// pattern that matched, along with the start and end offsets of the match
/// in the haystack.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let ac = AhoCorasick::new(&[
///     "foo", "bar", "baz",
/// ]);
/// let mat = ac.find("xxx bar xxx").expect("should have a match");
/// assert_eq!(1, mat.pattern());
/// assert_eq!(4, mat.start());
/// assert_eq!(7, mat.end());
/// ```
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Match {
    /// The pattern id.
    pattern: usize,
    /// The length of this match, such that the starting position of the match
    /// is `end - len`.
    ///
    /// We use length here because, other than the pattern id, the only
    /// information about each pattern that the automaton stores is its length.
    /// So using the length here is just a bit more natural. But it isn't
    /// technically required.
    len: usize,
    /// The end offset of the match, exclusive.
    end: usize,
}

impl Match {
    /// Returns the identifier of the pattern that matched.
    ///
    /// The identifier of a pattern is derived from the position in which it
    /// was originally inserted into the corresponding automaton. The first
    /// pattern has identifier `0`, and each subsequent pattern is `1`, `2`
    /// and so on.
    #[inline]
    pub fn pattern(&self) -> usize {
        self.pattern
    }

    /// The starting position of the match.
    #[inline]
    pub fn start(&self) -> usize {
        self.end - self.len
    }

    /// The ending position of the match.
    #[inline]
    pub fn end(&self) -> usize {
        self.end
    }

    /// Returns true if and only if this match is empty. That is, when
    /// `start() == end()`.
    ///
    /// An empty match can only be returned when the empty string was among
    /// the patterns used to build the Aho-Corasick automaton.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    #[inline]
    fn increment(&self, by: usize) -> Match {
        Match {
            pattern: self.pattern,
            len: self.len,
            end: self.end + by,
        }
    }
}
<commit_msg>compat: allow bare trait objects<commit_after>/*!
A library for finding occurrences of many patterns at once. This library
provides multiple pattern search principally through an implementation of the
[Aho-Corasick algorithm](https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm),
which builds a fast finite state machine for executing searches in linear time.

Additionally, this library provides a number of configuration options for
building the automaton that permit controlling the space versus time trade
off. Other features include simple ASCII case insensitive matching, finding
overlapping matches, replacements, searching streams and even searching and
replacing text in streams.

Finally, unlike all other (known) Aho-Corasick implementations, this one
supports enabling
[leftmost-first](enum.MatchKind.html#variant.LeftmostFirst)
or
[leftmost-longest](enum.MatchKind.html#variant.LeftmostFirst)
match semantics, using a (seemingly) novel alternative construction algorithm.
For more details on what match semantics means, see the
[`MatchKind`](enum.MatchKind.html)
type.

# Overview

This section gives a brief overview of the primary types in this crate:

* [`AhoCorasick`](struct.AhoCorasick.html) is the primary type and represents
  an Aho-Corasick automaton. This is the type you use to execute searches.
* [`AhoCorasickBuilder`](struct.AhoCorasickBuilder.html) can be used to build
  an Aho-Corasick automaton, and supports configuring a number of options.
* [`Match`](struct.Match.html) represents a single match reported by an
  Aho-Corasick automaton. Each match has two pieces of information: the pattern
  that matched and the start and end byte offsets corresponding to the position
  in the haystack at which it matched.

# Example: basic searching

This example shows how to search for occurrences of multiple patterns
simultaneously. Each match includes the pattern that matched along with the
byte offsets of the match.

```
use aho_corasick::AhoCorasick;

let patterns = &["apple", "maple", "Snapple"];
let haystack = "Nobody likes maple in their apple flavored Snapple.";

let ac = AhoCorasick::new(patterns);
let mut matches = vec![];
for mat in ac.find_iter(haystack) {
    matches.push((mat.pattern(), mat.start(), mat.end()));
}
assert_eq!(matches, vec![
    (1, 13, 18),
    (0, 28, 33),
    (2, 43, 50),
]);
```

# Example: case insensitivity

This is like the previous example, but matches `Snapple` case insensitively
using `AhoCorasickBuilder`:

```
use aho_corasick::AhoCorasickBuilder;

let patterns = &["apple", "maple", "snapple"];
let haystack = "Nobody likes maple in their apple flavored Snapple.";

let ac = AhoCorasickBuilder::new()
    .ascii_case_insensitive(true)
    .build(patterns);
let mut matches = vec![];
for mat in ac.find_iter(haystack) {
    matches.push((mat.pattern(), mat.start(), mat.end()));
}
assert_eq!(matches, vec![
    (1, 13, 18),
    (0, 28, 33),
    (2, 43, 50),
]);
```

# Example: replacing matches in a stream

This example shows how to execute a search and replace on a stream without
loading the entire stream into memory first.

```
use aho_corasick::AhoCorasick;

# fn example() -> Result<(), ::std::io::Error> {
let patterns = &["fox", "brown", "quick"];
let replace_with = &["sloth", "grey", "slow"];

// In a real example, these might be `std::fs::File`s instead. All you need to
// do is supply a pair of `std::io::Read` and `std::io::Write` implementations.
let rdr = "The quick brown fox.";
let mut wtr = vec![];

let ac = AhoCorasick::new(patterns);
ac.stream_replace_all(rdr.as_bytes(), &mut wtr, replace_with)?;
assert_eq!(b"The slow grey sloth.".to_vec(), wtr);
# Ok(()) }; example().unwrap()
```

# Example: finding the leftmost first match

In the textbook description of Aho-Corasick, its formulation is typically
structured such that it reports all possible matches, even when they overlap
with another. In many cases, overlapping matches may not be desired, such as
the case of finding all successive non-overlapping matches like you might with
a standard regular expression.

Unfortunately the "obvious" way to modify the Aho-Corasick algorithm to do
this doesn't always work in the expected way, since it will report matches as
soon as they are seen. For example, consider matching the regex `Samwise|Sam`
against the text `Samwise`. Most regex engines (that are Perl-like, or
non-POSIX) will report `Samwise` as a match, but the standard Aho-Corasick
algorithm modified for reporting non-overlapping matches will report `Sam`.

A novel contribution of this library is the ability to change the match
semantics of Aho-Corasick (without additional search time overhead) such that
`Samwise` is reported instead. For example, here's the standard approach:

```
use aho_corasick::AhoCorasick;

let patterns = &["Samwise", "Sam"];
let haystack = "Samwise";

let ac = AhoCorasick::new(patterns);
let mat = ac.find(haystack).expect("should have a match");
assert_eq!("Sam", &haystack[mat.start()..mat.end()]);
```

And now here's the leftmost-first version, which matches how a Perl-like
regex will work:

```
use aho_corasick::{AhoCorasickBuilder, MatchKind};

let patterns = &["Samwise", "Sam"];
let haystack = "Samwise";

let ac = AhoCorasickBuilder::new()
    .match_kind(MatchKind::LeftmostFirst)
    .build(patterns);
let mat = ac.find(haystack).expect("should have a match");
assert_eq!("Samwise", &haystack[mat.start()..mat.end()]);
```

In addition to leftmost-first semantics, this library also supports
leftmost-longest semantics, which match the POSIX behavior of a regular
expression alternation. See
[`MatchKind`](enum.MatchKind.html)
for more details.

# Prefilters

While an Aho-Corasick automaton can perform admirably when compared to more
naive solutions, it is generally slower than more specialized algorithms that
are accelerated using vector instructions such as SIMD.

For that reason, this library will internally use a "prefilter" to attempt
to accelerate searches when possible. Currently, this library has fairly
limited implementation that only applies when there are 3 or fewer unique
starting bytes among all patterns in an automaton.

In the future, it is intended for this prefilter to grow more sophisticated
by pushing applicable optimizations from the
[`regex`](http://docs.rs/regex)
crate (and other places) down into this library.

While a prefilter is generally good to have on by default since it works well
in the common case, it can lead to less predictable or even sub-optimal
performance in some cases. For that reason, prefilters can be disabled via
[`AhoCorasickBuilder::prefilter`](struct.AhoCorasickBuilder.html#method.prefilter).
*/

#![deny(missing_docs)]
#![allow(bare_trait_objects)]

// We can never be truly no_std, but we could be alloc-only some day, so
// require the std feature for now.
#[cfg(not(feature = "std"))]
compile_error!("`std` feature is currently required to build this crate");

extern crate memchr;
#[cfg(test)]
#[macro_use]
extern crate doc_comment;

#[cfg(test)]
doctest!("../README.md");

pub use ahocorasick::{
    AhoCorasick, AhoCorasickBuilder, MatchKind,
    FindIter, FindOverlappingIter, StreamFindIter,
};
pub use error::{Error, ErrorKind};
pub use state_id::StateID;

mod ahocorasick;
mod automaton;
mod buffer;
mod dfa;
mod error;
mod classes;
mod prefilter;
mod nfa;
mod state_id;
#[cfg(test)]
mod tests;

/// A representation of a match reported by an Aho-Corasick automaton.
///
/// A match has two essential pieces of information: the identifier of the
/// pattern that matched, along with the start and end offsets of the match
/// in the haystack.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let ac = AhoCorasick::new(&[
///     "foo", "bar", "baz",
/// ]);
/// let mat = ac.find("xxx bar xxx").expect("should have a match");
/// assert_eq!(1, mat.pattern());
/// assert_eq!(4, mat.start());
/// assert_eq!(7, mat.end());
/// ```
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Match {
    /// The pattern id.
    pattern: usize,
    /// The length of this match, such that the starting position of the match
    /// is `end - len`.
    ///
    /// We use length here because, other than the pattern id, the only
    /// information about each pattern that the automaton stores is its length.
    /// So using the length here is just a bit more natural. But it isn't
    /// technically required.
    len: usize,
    /// The end offset of the match, exclusive.
    end: usize,
}

impl Match {
    /// Returns the identifier of the pattern that matched.
    ///
    /// The identifier of a pattern is derived from the position in which it
    /// was originally inserted into the corresponding automaton. The first
    /// pattern has identifier `0`, and each subsequent pattern is `1`, `2`
    /// and so on.
    #[inline]
    pub fn pattern(&self) -> usize {
        self.pattern
    }

    /// The starting position of the match.
    #[inline]
    pub fn start(&self) -> usize {
        self.end - self.len
    }

    /// The ending position of the match.
    #[inline]
    pub fn end(&self) -> usize {
        self.end
    }

    /// Returns true if and only if this match is empty. That is, when
    /// `start() == end()`.
    ///
    /// An empty match can only be returned when the empty string was among
    /// the patterns used to build the Aho-Corasick automaton.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    #[inline]
    fn increment(&self, by: usize) -> Match {
        Match {
            pattern: self.pattern,
            len: self.len,
            end: self.end + by,
        }
    }
}
<|endoftext|>


<commit_before>//! A small library which provides convenient, non-panicking error handling for small CLI scripts.
#![deny(missing_docs)]
#![deny(unused)]

use std::borrow::Cow;
use std::env;
use std::error::Error as StdError;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::io::{self, Write};
use std::path::Path;
use std::process;

/// A minimalist error type to use in CLI scripts: it wraps an arbitrary cause which implements
/// `std::error::Error` and a description for the `Display` implementation.
#[derive(Debug)]
pub struct Error {
    description: Option<Cow<'static, str>>,
    cause: Option<Box<StdError>>,
}

impl Error {
    /// Creates a new `Error` with a description and a cause.
    ///
    /// In most cases you'll want to use the convenient `DescribeErr` trait or the `ctry`
    /// and `ccheck` macros.
    ///
    /// With a `&'static str`:
    ///
    /// ```
    ///    # use clierr::Error;
    ///    # let some_error = Error::with_description("x");
    /// Error::new("oh no!", some_error);
    /// ```
    ///
    /// With a `String`:
    ///
    /// ```
    ///    # use clierr::Error;
    ///    # let some_error = Error::with_description("x");
    ///    # let filename = "file.txt";
    /// Error::new(format!("should not have tried to open '{}'!", filename), some_error);
    /// ```
    pub fn new<S, E>(description: S, cause: E) -> Error
        where S: Into<Cow<'static, str>>,
              E: StdError + 'static
    {
        Error {
            description: Some(description.into()),
            cause: Some(Box::new(cause)),
        }
    }

    /// Creates a new error with a descrption but no cause. Useful for validation specific
    /// errors where there's no underlying error (e.g. CLI timeout argument must be
    /// greater than zero).
    pub fn with_description<S: Into<Cow<'static, str>>>(description: S) -> Error {
        Error {
            description: Some(description.into()),
            cause: None,
        }
    }

    /// Creates a new error with a cause, but no description. The `Display` implementation
    /// forwards to that of `cause` in this case.
    ///
    /// In most cases you'll want to use the convenient `DescribeErr` trait or the `ctry`
    /// and `ccheck` macros instead.
    pub fn caused_by<E: StdError + 'static>(cause: E) -> Error {
        Error {
            description: None,
            cause: Some(Box::new(cause)),
        }
    }
}

/// A trait which enables adding a description to any `Result` by wrapping its error type in an
/// `Error`
///
/// An implementation is provided for `Result<S, E: std::errror::Error` and it's not really meant to
/// be implemented for anything else (unless you're using some kind of custom `Result` type).
pub trait DescribeErr: Sized {
    /// The result of describing the `Result`'s error.
    type Described;

    /// Wraps the error contained by `Self` in an `Error` with the given description.
    fn describe_err<D>(self, description: D) -> Self::Described where D: Into<Cow<'static, str>>;

    /// Same as `describe_err`, but defer the construction of the description until it's actually
    /// needed (i.e. only in the error case for a `Result`).
    fn describe_err_with<F, D>(self, with: F) -> Self::Described
        where F: FnOnce() -> D,
              D: Into<Cow<'static, str>>;
}

impl<S, E: StdError + 'static> DescribeErr for Result<S, E> {
    type Described = Result<S, Error>;

    fn describe_err<D: Into<Cow<'static, str>>>(self, description: D) -> Result<S, Error> {
        self.map_err(|cause| Error::new(description, cause))
    }

    fn describe_err_with<F, D>(self, with: F) -> Result<S, Error>
        where F: FnOnce() -> D,
              D: Into<Cow<'static, str>>
    {
        self.map_err(|cause| Error::new(with(), cause))
    }
}

impl Display for Error {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        if let Some(description) = self.description.as_ref() {
            write!(fmt, "{}", description).and_then(|_| {
                if let Some(cause) = self.cause() {
                    write!(fmt, "\n    caused by: {}", cause)
                } else {
                    Ok(())
                }
            })
        } else if let Some(cause) = self.cause() {
            write!(fmt, "{}", cause)
        } else {
            write!(fmt, "<unknown error>")
        }
    }
}

impl StdError for Error {
    fn description(&self) -> &str {
        if let Some(description) = self.description.as_ref() {
            description
        } else if let Some(cause) = self.cause() {
            cause.description()
        } else {
            ""
        }
    }

    fn cause(&self) -> Option<&StdError> {
        self.cause.as_ref().map(|e| &**e)
    }
}

fn run_impl<E, F>(main: F) -> i32
    where F: FnOnce() -> Result<(), E>,
          E: Into<Box<StdError>>
{
    if let Err(error) = main() {
        let error = error.into();
        let argv0 = env::args().next();
        let program_name = argv0.as_ref()
                                .and_then(|s| Path::new(s).file_name())
                                .map(|os| os.to_string_lossy());
        let prefix = program_name.as_ref().map(|s| &**s).unwrap_or("<unknown>");

        let _ = writeln!(io::stderr(), "{}: {}", prefix, error).is_ok();
        1
    } else {
        0
    }
}

/// Runs a `Result`-returning function and exits the process with 0 if successful.
///
/// If `main` returns an error, it displays it (and all its causes recursively) to `stderr` and
/// exists the process with 1.
pub fn run_and_exit<E, F>(main: F) -> !
    where F: FnOnce() -> Result<(), E>,
          E: Into<Box<StdError>>
{
    process::exit(run_impl(main))
}

/// Like `try!`, but in the error case the error is wrapped in an `Error` with a given description
/// (which can be specified using `format_args!` syntax).
///
/// Example:
///
/// ```norust
///     ctry!(File::open(filename), "could not open output file {}", filename)
/// ```
///
/// Note: If you don't like macros, the `DescribeErr` trait already cuts on a lot of verbosity.
#[macro_export]
macro_rules! ctry {
    ($e:expr, $fmt:expr) => {{
        use $crate::DescribeErr;
        try!($e.describe_err_with(|| $fmt))
    }};
    ($e:expr, $fmt:expr, $($arg:tt)*) => {{
        use $crate::DescribeErr;
        try!($e.describe_err_with(|| format!($fmt, $($arg)*)))
    }}
}

/// Like `assert!` but instead of panicking it early-returns an `Error` with a given description
/// (which can be specified using `format_args!` syntax).
///
/// Example:
///
/// ```norust
///     ccheck!(value(key) == 42, "value of {} was not 42 ({})", key, value(key))
/// ```
///
/// Note: If you don't like macros, the `DescribeErr` trait already cuts on a lot of verbosity.
#[macro_export]
macro_rules! ccheck {
    ($e:expr, $fmt:expr) => {{
        use $crate::Error;
        if !($e) {
            return Err(Error::with_description($fmt).into());
        }
    }};
    ($e:expr, $fmt:expr, $($arg:tt)*) => {{
        use $crate::Error;
        if !($e) {
            return Err(Error::with_description(format!($fmt, $($arg)*)).into());
        }
    }}
}

#[cfg(test)]
mod test {
    use super::{Error, DescribeErr, run_impl};
    use std::error::Error as StdError;
    use std::cell::Cell;

    fn ok() -> Result<(), Error> {
        Ok(())
    }

    fn err() -> Result<(), Error> {
        Err(Error::with_description("test"))
    }

    fn err_box() -> Result<(), Box<StdError>> {
        Err(Box::new(Error::with_description("test")))
    }

    #[test]
    fn error() {
        let with_static = Error::new("test", Error::with_description("cause"));
        let with_owned = Error::new("test2".to_owned(),
                                    Error::caused_by(Error::with_description("cause2")));

        assert_eq!(&format!("{}", with_static), "test\n    caused by: cause");
        assert_eq!(&format!("{}", with_owned), "test2\n    caused by: cause2");
        assert_eq!(with_static.description(), "test");
        assert_eq!(with_owned.description(), "test2");

        assert_eq!(with_static.cause().map(|c| c.description()), Some("cause"));
        assert!(with_static.cause().unwrap().cause().is_none());

        assert_eq!(with_owned.cause().map(|c| c.description()), Some("cause2"));
        assert!(with_owned.cause().unwrap().cause().unwrap().cause().is_none());
        assert_eq!(with_owned.cause().map(|c| format!("{}", c)),
                   Some("cause2".to_owned()));
        assert_eq!(with_owned.cause().and_then(|c| c.cause()).map(|c| c.description()),
                   Some("cause2"));
    }

    #[test]
    fn describe_err() {
        let counter = Cell::new(0);
        let inc = || {
            counter.set(counter.get() + 1);
            "wrapper"
        };

        assert!(ok().describe_err("wrapper").is_ok());
        assert!(ok().describe_err_with(&inc).is_ok());
        assert_eq!(counter.get(), 0);

        let described = err().describe_err("wrapper");
        match described {
            Err(error) => {
                assert_eq!(error.description(), "wrapper");
                assert_eq!(error.cause().map(|c| c.description()), Some("test"));
            }
            Ok(()) => panic!("failed: {:?}", described),
        }

        let described = err().describe_err_with(&inc);
        assert_eq!(counter.get(), 1);
        match described {
            Err(error) => {
                assert_eq!(error.description(), "wrapper");
                assert_eq!(error.cause().map(|c| c.description()), Some("test"));
            }
            Ok(()) => panic!("failed: {:?}", described),
        }
    }

    #[test]
    fn ctry_ok() {
        fn foo() -> Result<u32, Error> {
            let _ = ctry!(ok(), "oh no!");
            Ok(42)
        }
        assert_eq!(foo().unwrap(), 42);
    }

    #[test]
    fn ctry_err() {
        fn foo() -> Result<u32, Error> {
            let _ = ctry!(err(), "help {}", "us");
            Ok(42)
        }
        match foo() {
            Err(e) => {
                assert_eq!(e.description(), "help us");
                assert_eq!(e.cause().unwrap().description(), "test");
            }
            Ok(x) => panic!("failed: {:?}", x),
        }
    }

    #[test]
    fn ccheck_ok() {
        fn foo() -> Result<u32, Error> {
            ccheck!(true, "oh no!");
            Ok(42)
        }
        assert_eq!(foo().unwrap(), 42);
    }

    #[test]
    fn ccheck_err() {
        fn foo() -> Result<u32, Error> {
            ccheck!(false, "help {}", "us");
            Ok(42)
        }
        match foo() {
            Err(e) => {
                assert_eq!(e.description(), "help us");
                assert!(e.cause().is_none());
            }
            Ok(x) => panic!("failed: {:?}", x),
        }
    }

    #[test]
    fn run_returns_zero_for_success() {
        assert_eq!(run_impl(ok), 0);
    }

    #[test]
    fn run_returns_one_for_error() {
        assert_eq!(run_impl(err), 1);
    }

    #[test]
    fn run_returns_one_for_error_box() {
        assert_eq!(run_impl(err_box), 1);
    }
}
<commit_msg>Fixed indentation in doc examples.<commit_after>//! A small library which provides convenient, non-panicking error handling for small CLI scripts.
#![deny(missing_docs)]
#![deny(unused)]

use std::borrow::Cow;
use std::env;
use std::error::Error as StdError;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::io::{self, Write};
use std::path::Path;
use std::process;

/// A minimalist error type to use in CLI scripts: it wraps an arbitrary cause which implements
/// `std::error::Error` and a description for the `Display` implementation.
#[derive(Debug)]
pub struct Error {
    description: Option<Cow<'static, str>>,
    cause: Option<Box<StdError>>,
}

impl Error {
    /// Creates a new `Error` with a description and a cause.
    ///
    /// In most cases you'll want to use the convenient `DescribeErr` trait or the `ctry`
    /// and `ccheck` macros.
    ///
    /// With a `&'static str`:
    ///
    /// ```
    /// # use clierr::Error;
    /// # let some_error = Error::with_description("x");
    /// Error::new("oh no!", some_error);
    /// ```
    ///
    /// With a `String`:
    ///
    /// ```
    /// # use clierr::Error;
    /// # let some_error = Error::with_description("x");
    /// # let filename = "file.txt";
    /// Error::new(format!("should not have tried to open '{}'!", filename), some_error);
    /// ```
    pub fn new<S, E>(description: S, cause: E) -> Error
        where S: Into<Cow<'static, str>>,
              E: StdError + 'static
    {
        Error {
            description: Some(description.into()),
            cause: Some(Box::new(cause)),
        }
    }

    /// Creates a new error with a descrption but no cause. Useful for validation specific
    /// errors where there's no underlying error (e.g. CLI timeout argument must be
    /// greater than zero).
    pub fn with_description<S: Into<Cow<'static, str>>>(description: S) -> Error {
        Error {
            description: Some(description.into()),
            cause: None,
        }
    }

    /// Creates a new error with a cause, but no description. The `Display` implementation
    /// forwards to that of `cause` in this case.
    ///
    /// In most cases you'll want to use the convenient `DescribeErr` trait or the `ctry`
    /// and `ccheck` macros instead.
    pub fn caused_by<E: StdError + 'static>(cause: E) -> Error {
        Error {
            description: None,
            cause: Some(Box::new(cause)),
        }
    }
}

/// A trait which enables adding a description to any `Result` by wrapping its error type in an
/// `Error`
///
/// An implementation is provided for `Result<S, E: std::errror::Error` and it's not really meant to
/// be implemented for anything else (unless you're using some kind of custom `Result` type).
pub trait DescribeErr: Sized {
    /// The result of describing the `Result`'s error.
    type Described;

    /// Wraps the error contained by `Self` in an `Error` with the given description.
    fn describe_err<D>(self, description: D) -> Self::Described where D: Into<Cow<'static, str>>;

    /// Same as `describe_err`, but defer the construction of the description until it's actually
    /// needed (i.e. only in the error case for a `Result`).
    fn describe_err_with<F, D>(self, with: F) -> Self::Described
        where F: FnOnce() -> D,
              D: Into<Cow<'static, str>>;
}

impl<S, E: StdError + 'static> DescribeErr for Result<S, E> {
    type Described = Result<S, Error>;

    fn describe_err<D: Into<Cow<'static, str>>>(self, description: D) -> Result<S, Error> {
        self.map_err(|cause| Error::new(description, cause))
    }

    fn describe_err_with<F, D>(self, with: F) -> Result<S, Error>
        where F: FnOnce() -> D,
              D: Into<Cow<'static, str>>
    {
        self.map_err(|cause| Error::new(with(), cause))
    }
}

impl Display for Error {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        if let Some(description) = self.description.as_ref() {
            write!(fmt, "{}", description).and_then(|_| {
                if let Some(cause) = self.cause() {
                    write!(fmt, "\n    caused by: {}", cause)
                } else {
                    Ok(())
                }
            })
        } else if let Some(cause) = self.cause() {
            write!(fmt, "{}", cause)
        } else {
            write!(fmt, "<unknown error>")
        }
    }
}

impl StdError for Error {
    fn description(&self) -> &str {
        if let Some(description) = self.description.as_ref() {
            description
        } else if let Some(cause) = self.cause() {
            cause.description()
        } else {
            ""
        }
    }

    fn cause(&self) -> Option<&StdError> {
        self.cause.as_ref().map(|e| &**e)
    }
}

fn run_impl<E, F>(main: F) -> i32
    where F: FnOnce() -> Result<(), E>,
          E: Into<Box<StdError>>
{
    if let Err(error) = main() {
        let error = error.into();
        let argv0 = env::args().next();
        let program_name = argv0.as_ref()
                                .and_then(|s| Path::new(s).file_name())
                                .map(|os| os.to_string_lossy());
        let prefix = program_name.as_ref().map(|s| &**s).unwrap_or("<unknown>");

        let _ = writeln!(io::stderr(), "{}: {}", prefix, error).is_ok();
        1
    } else {
        0
    }
}

/// Runs a `Result`-returning function and exits the process with 0 if successful.
///
/// If `main` returns an error, it displays it (and all its causes recursively) to `stderr` and
/// exists the process with 1.
pub fn run_and_exit<E, F>(main: F) -> !
    where F: FnOnce() -> Result<(), E>,
          E: Into<Box<StdError>>
{
    process::exit(run_impl(main))
}

/// Like `try!`, but in the error case the error is wrapped in an `Error` with a given description
/// (which can be specified using `format_args!` syntax).
///
/// Example:
///
/// ```norust
/// ctry!(File::open(filename), "could not open output file {}", filename)
/// ```
///
/// Note: If you don't like macros, the `DescribeErr` trait already cuts on a lot of verbosity.
#[macro_export]
macro_rules! ctry {
    ($e:expr, $fmt:expr) => {{
        use $crate::DescribeErr;
        try!($e.describe_err_with(|| $fmt))
    }};
    ($e:expr, $fmt:expr, $($arg:tt)*) => {{
        use $crate::DescribeErr;
        try!($e.describe_err_with(|| format!($fmt, $($arg)*)))
    }}
}

/// Like `assert!` but instead of panicking it early-returns an `Error` with a given description
/// (which can be specified using `format_args!` syntax).
///
/// Example:
///
/// ```norust
/// ccheck!(value(key) == 42, "value of {} was not 42 ({})", key, value(key))
/// ```
///
/// Note: If you don't like macros, the `DescribeErr` trait already cuts on a lot of verbosity.
#[macro_export]
macro_rules! ccheck {
    ($e:expr, $fmt:expr) => {{
        use $crate::Error;
        if !($e) {
            return Err(Error::with_description($fmt).into());
        }
    }};
    ($e:expr, $fmt:expr, $($arg:tt)*) => {{
        use $crate::Error;
        if !($e) {
            return Err(Error::with_description(format!($fmt, $($arg)*)).into());
        }
    }}
}

#[cfg(test)]
mod test {
    use super::{Error, DescribeErr, run_impl};
    use std::error::Error as StdError;
    use std::cell::Cell;

    fn ok() -> Result<(), Error> {
        Ok(())
    }

    fn err() -> Result<(), Error> {
        Err(Error::with_description("test"))
    }

    fn err_box() -> Result<(), Box<StdError>> {
        Err(Box::new(Error::with_description("test")))
    }

    #[test]
    fn error() {
        let with_static = Error::new("test", Error::with_description("cause"));
        let with_owned = Error::new("test2".to_owned(),
                                    Error::caused_by(Error::with_description("cause2")));

        assert_eq!(&format!("{}", with_static), "test\n    caused by: cause");
        assert_eq!(&format!("{}", with_owned), "test2\n    caused by: cause2");
        assert_eq!(with_static.description(), "test");
        assert_eq!(with_owned.description(), "test2");

        assert_eq!(with_static.cause().map(|c| c.description()), Some("cause"));
        assert!(with_static.cause().unwrap().cause().is_none());

        assert_eq!(with_owned.cause().map(|c| c.description()), Some("cause2"));
        assert!(with_owned.cause().unwrap().cause().unwrap().cause().is_none());
        assert_eq!(with_owned.cause().map(|c| format!("{}", c)),
                   Some("cause2".to_owned()));
        assert_eq!(with_owned.cause().and_then(|c| c.cause()).map(|c| c.description()),
                   Some("cause2"));
    }

    #[test]
    fn describe_err() {
        let counter = Cell::new(0);
        let inc = || {
            counter.set(counter.get() + 1);
            "wrapper"
        };

        assert!(ok().describe_err("wrapper").is_ok());
        assert!(ok().describe_err_with(&inc).is_ok());
        assert_eq!(counter.get(), 0);

        let described = err().describe_err("wrapper");
        match described {
            Err(error) => {
                assert_eq!(error.description(), "wrapper");
                assert_eq!(error.cause().map(|c| c.description()), Some("test"));
            }
            Ok(()) => panic!("failed: {:?}", described),
        }

        let described = err().describe_err_with(&inc);
        assert_eq!(counter.get(), 1);
        match described {
            Err(error) => {
                assert_eq!(error.description(), "wrapper");
                assert_eq!(error.cause().map(|c| c.description()), Some("test"));
            }
            Ok(()) => panic!("failed: {:?}", described),
        }
    }

    #[test]
    fn ctry_ok() {
        fn foo() -> Result<u32, Error> {
            let _ = ctry!(ok(), "oh no!");
            Ok(42)
        }
        assert_eq!(foo().unwrap(), 42);
    }

    #[test]
    fn ctry_err() {
        fn foo() -> Result<u32, Error> {
            let _ = ctry!(err(), "help {}", "us");
            Ok(42)
        }
        match foo() {
            Err(e) => {
                assert_eq!(e.description(), "help us");
                assert_eq!(e.cause().unwrap().description(), "test");
            }
            Ok(x) => panic!("failed: {:?}", x),
        }
    }

    #[test]
    fn ccheck_ok() {
        fn foo() -> Result<u32, Error> {
            ccheck!(true, "oh no!");
            Ok(42)
        }
        assert_eq!(foo().unwrap(), 42);
    }

    #[test]
    fn ccheck_err() {
        fn foo() -> Result<u32, Error> {
            ccheck!(false, "help {}", "us");
            Ok(42)
        }
        match foo() {
            Err(e) => {
                assert_eq!(e.description(), "help us");
                assert!(e.cause().is_none());
            }
            Ok(x) => panic!("failed: {:?}", x),
        }
    }

    #[test]
    fn run_returns_zero_for_success() {
        assert_eq!(run_impl(ok), 0);
    }

    #[test]
    fn run_returns_one_for_error() {
        assert_eq!(run_impl(err), 1);
    }

    #[test]
    fn run_returns_one_for_error_box() {
        assert_eq!(run_impl(err_box), 1);
    }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate lazy_static;
extern crate regex;

use regex::Regex;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::fmt;
use std::result;

pub type Result<T> = result::Result<T, String>;

lazy_static! {
        pub static ref SUBS: Regex = Regex::new(r"(?x)
            (\d+)
            (\r\n)
            (\d{2}):(\d{2}):(\d{2}),(\d{3})
            \s-->\s
            (\d{2}):(\d{2}):(\d{2}),(\d{3})
            (\r\n)
            ([\S\s]*?)
            (\r\n){2}?").unwrap();
    }

fn read_file(path: &Path) -> Result<String> {
    let mut file = try!(File::open(&path).map_err(|e| e.to_string()));
    let mut content = String::new();
    try!(file.read_to_string(&mut content).map_err(|e| e.to_string()));
    Ok(content)
}

fn parse(content: String) -> Subtitles {
    let mut result: Vec<SubLine> = vec![];

    for cap in SUBS.captures_iter(&content) {
        let start_timestamp = [cap.at(3).unwrap().parse::<u32>().unwrap(),
                               cap.at(4).unwrap().parse::<u32>().unwrap(),
                               cap.at(5).unwrap().parse::<u32>().unwrap(),
                               cap.at(6).unwrap().parse::<u32>().unwrap()];
        let end_timestamp = [cap.at(7).unwrap().parse::<u32>().unwrap(),
                             cap.at(8).unwrap().parse::<u32>().unwrap(),
                             cap.at(9).unwrap().parse::<u32>().unwrap(),
                             cap.at(10).unwrap().parse::<u32>().unwrap()];

        let start = to_miliseconds(&start_timestamp);
        let end = to_miliseconds(&end_timestamp);

        let line = SubLine {
            index: cap.at(1).unwrap().parse::<u32>().unwrap(),
            start_timestamp: start_timestamp,
            end_timestamp: end_timestamp,
            text: cap.at(12).unwrap().to_string(),
            start: start,
            end: end,
        };
        result.push(line)
    }
    Subtitles { field: result }
}

fn to_miliseconds(timestamp: &[u32; 4]) -> u32 {
    let mut result: u32 = 0;
    result += timestamp[3];
    result += timestamp[2] * 1000;
    result += timestamp[1] * 1000 * 60;
    result += timestamp[0] * 1000 * 60 * 60;
    result
}

#[derive(Debug, Clone)]
pub struct SubLine {
    text: String,
    index: u32,
    start_timestamp: [u32; 4],
    end_timestamp: [u32; 4],
    start: u32,
    end: u32,
}

impl fmt::Display for SubLine {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "{}\n{:?} --> {:?} ({}>>{})\n{}",
               self.index,
               self.start_timestamp,
               self.end_timestamp,
               self.start,
               self.end,
               self.text)
    }
}

impl SubLine {
    fn get_start(&self) -> u32 {
        self.start
    }

    fn get_start_timestamp(&self) -> [u32; 4] {
        self.start_timestamp
    }

    fn get_end(&self) -> u32 {
        self.end
    }

    fn get_duration(&self) -> u32 {
        self.end - self.start
    }
}

#[derive(Debug)]
pub struct Subtitles {
    field: Vec<SubLine>,
}

impl fmt::Display for Subtitles {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "length: {}\n{}\n..........\n{}\n",
               self.get_length(),
               self.field.first().unwrap(),
               self.field.last().unwrap())
    }
}

impl Subtitles {
    fn at_index(&self, index: usize) -> Option<SubLine> {
        self.field.get(index - 1).map(|n| n.clone())
    }

    fn get_length(&self) -> usize {
        self.field.len()
    }

    fn by_timestamp(&self, timestamp: [u32; 4]) -> Option<SubLine> {
        let miliseconds = to_miliseconds(&timestamp);
        self.by_miliseconds(miliseconds)
    }

    fn by_miliseconds(&self, time: u32) -> Option<SubLine> {
        let mut min = 0;
        let mut max = self.field.len() - 1;
        let mut guess_index;

        while max >= min {
            guess_index = (max + min) / 2;
            let guess = &self.field[guess_index];

            if (guess.start <= time) && (time <= guess.end) {
                return Some(guess.clone());
            } else if time > guess.end {
                min = guess_index + 1;
            } else {
                max = guess_index - 1;
            }
        }
        None
    }
}

pub fn prepare(path: &str) -> Result<Subtitles> {
    let sub_path = Path::new(path);
    let mut content = try!(read_file(&sub_path).map_err(|e| e.to_string()));

    let eof_empty_lines = Regex::new(r"\S\s*?\z").unwrap();
    let unify_newline_style = Regex::new(r"(?x)
            ([^\n(\r\n)]\r[^\n(\r\n)])|
            ([^\r(\r\n)]\n[^\r(\r\n)])")
        .unwrap();

    content = eof_empty_lines.replace_all(&content, "\r\n\r\n");
    content = unify_newline_style.replace_all(&content, "\r\n");

    if !SUBS.is_match(&content) {
        return Err("Bad srt file".to_string());
    }

    Ok(parse(content))
}

#[test]
fn it_works() {
    let path = "ex1";
    let subs = prepare(path).unwrap();

    println!("{}", subs.at_index(3).unwrap());
    println!("{}", subs.by_miliseconds(261072).unwrap());
    println!("{}", subs.by_timestamp([0, 4, 22, 500]).unwrap());
}<commit_msg>some basic edit functionlity<commit_after>#[macro_use] extern crate lazy_static;
extern crate regex;

use regex::Regex;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::fmt;
use std::result;

pub type Result<T> = result::Result<T, String>;

lazy_static! {
        pub static ref SUBS: Regex = Regex::new(r"(?x)
            (\d+)
            (\r\n)
            (\d{2}):(\d{2}):(\d{2}),(\d{3})
            \s-->\s
            (\d{2}):(\d{2}):(\d{2}),(\d{3})
            (\r\n)
            ([\S\s]*?)
            (\r\n){2}?").unwrap();
    }

fn read_file(path: &Path) -> Result<String> {
    let mut file = try!(File::open(&path).map_err(|e| e.to_string()));
    let mut content = String::new();
    try!(file.read_to_string(&mut content).map_err(|e| e.to_string()));
    Ok(content)
}

fn parse(content: String, path: &str) -> Subtitles {
    let mut result: Vec<SubLine> = vec![];

    for cap in SUBS.captures_iter(&content) {
        let start_timestamp = [cap.at(3).unwrap().parse::<u32>().unwrap(),
                               cap.at(4).unwrap().parse::<u32>().unwrap(),
                               cap.at(5).unwrap().parse::<u32>().unwrap(),
                               cap.at(6).unwrap().parse::<u32>().unwrap()];
        let end_timestamp = [cap.at(7).unwrap().parse::<u32>().unwrap(),
                             cap.at(8).unwrap().parse::<u32>().unwrap(),
                             cap.at(9).unwrap().parse::<u32>().unwrap(),
                             cap.at(10).unwrap().parse::<u32>().unwrap()];

        let start = to_miliseconds(&start_timestamp);
        let end = to_miliseconds(&end_timestamp);

        let line = SubLine {
            index: cap.at(1).unwrap().parse::<u32>().unwrap(),
            text: cap.at(12).unwrap().to_string(),
            start: start,
            end: end,
        };
        result.push(line)
    }
    Subtitles { field: result, path: path.to_string() }
}

fn to_miliseconds(timestamp: &[u32; 4]) -> u32 {
    let mut result: u32 = 0;
    result += timestamp[3];
    result += timestamp[2] * 1000;
    result += timestamp[1] * 1000 * 60;
    result += timestamp[0] * 1000 * 60 * 60;
    result
}

fn recover_timestamp(miliseconds: &u32) -> [u32;4] {
    let hours = miliseconds / 3600000;
    let minutes = (miliseconds - hours * 3600000) / 60000;
    let seconds = (miliseconds - (hours * 3600000 + minutes * 60000)) / 1000;
    let miliseconds = miliseconds - (hours * 3600000 + minutes * 60000 + seconds * 1000);
    [hours, minutes, seconds, miliseconds]
}

#[derive(Debug, Clone)]
pub struct SubLine {
    text: String,
    index: u32,
    start: u32,
    end: u32,
}

impl fmt::Display for SubLine {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "{}\n{:?} --> {:?} ({}>>{})\n{}",
               self.index,
               self.start,
               self.end,
               self.start,
               self.end,
               self.text)
    }
}

impl SubLine {
    pub fn get_start(&self) -> u32 {
        self.start
    }

    pub fn get_text(&self) -> String {
        self.text.clone()
    }

    pub fn get_start_timestamp(&self) -> [u32; 4] {
        recover_timestamp(&self.start)
    }

    pub fn get_end_timestamp(&self) -> [u32; 4] {
        recover_timestamp(&self.end)
    }

    pub fn get_index(&self) -> u32 {
        self.index
    }

    pub fn get_end(&self) -> u32 {
        self.end
    }

    pub fn get_duration(&self) -> u32 {
        self.end - self.start
    }

    pub fn shift(&mut self, offset: i32) -> Result<()> {
        if offset > 0 {
            self.start += offset as u32;
            self.end += offset as u32;
            Ok(())
        } else if offset < 0 {
            if (-offset as u32 >= self.start) || (-offset as u32 >= self.end) {
                return Err("start can't be negative".to_string())
            };
            self.start -= -offset as u32;
            self.end -= -offset as u32;
            Ok(())
        } else {
            Err("offset can't be 0".to_string())
        }
    }
}

#[derive(Debug)]
pub struct Subtitles {
    field: Vec<SubLine>,
    path: String,
}

impl fmt::Display for Subtitles {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "length: {}\n{}\n..........\n{}\n",
               self.get_length(),
               self.field.first().unwrap(),
               self.field.last().unwrap())
    }
}

impl IntoIterator for Subtitles {
    type Item = SubLine;
    type IntoIter = ::std::vec::IntoIter<SubLine>;
    fn into_iter(self) -> Self::IntoIter {
        self.field.into_iter()
    }
}

impl Subtitles {
    pub fn get_path(&self) -> String {
        self.path.clone()
    }

    pub fn by_index(&self, index: usize) -> Option<SubLine> {
        self.field.get(index - 1).map(|n| n.clone())
    }

    pub fn get_length(&self) -> usize {
        self.field.len()
    }

    pub fn by_timestamp(&self, timestamp: &[u32; 4]) -> Option<SubLine> {
        let miliseconds = to_miliseconds(&timestamp);
        self.by_miliseconds(miliseconds)
    }

    pub fn by_miliseconds(&self, time: u32) -> Option<SubLine> {
        // binary search
        let mut min = 0;
        let mut max = self.field.len() - 1;
        let mut guess_index;

        while max >= min {
            guess_index = (max + min) / 2;
            let guess = self.field.get(guess_index).unwrap();

            if (guess.start <= time) && (time <= guess.end) {
                return Some(guess.clone());
            } else if time > guess.end {
                min = guess_index + 1;
            } else {
                max = guess_index - 1;
            }
        }
        None
    }

    pub fn mut_by_miliseconds(&mut self, time: u32) -> Option<&mut SubLine> {
        // binary search
        let mut min = 0;
        let mut max = self.field.len() - 1;
        let mut guess_index;
        let mut result: usize = 0;
        let mut state = false;

        while max >= min {
            guess_index = (max + min) / 2;

            let guess = self.field.get(guess_index).unwrap();

            if (guess.start <= time) && (time <= guess.end) {
                result = guess_index;
                state = true;
                break;
            } else if time > guess.end {
                min = guess_index + 1;
            } else {
                max = guess_index - 1;
            }
        }

        if state {
            Some(&mut self.field[result])
        } else { None }
    }

    pub fn mut_by_timestamp(&mut self, timestamp: &[u32; 4]) -> Option<&mut SubLine> {
        let miliseconds = to_miliseconds(&timestamp);
        self.mut_by_miliseconds(miliseconds)
    }

    pub fn mut_by_index(&mut self, index: usize) -> Option<&mut SubLine>{
        self.field.get_mut(index - 1)
    }

    pub fn shift_all(&mut self, offset: i32) -> Result<()> {
        for line in &mut self.field {
            try!(line.shift(offset));
        }
        Ok(())
    }
}

pub fn prepare(path: &str) -> Result<Subtitles> {
    let sub_path = Path::new(path);
    let mut content = try!(read_file(&sub_path).map_err(|e| e.to_string()));

    let eof_empty_lines = Regex::new(r"\S\s*?\z").unwrap();
    let unify_newline_style = Regex::new(r"(?x)
            ([^\n(\r\n)]\r[^\n(\r\n)])|
            ([^\r(\r\n)]\n[^\r(\r\n)])")
        .unwrap();

    content = eof_empty_lines.replace_all(&content, "\r\n\r\n");
    content = unify_newline_style.replace_all(&content, "\r\n");

    if !SUBS.is_match(&content) {
        return Err("Bad srt file".to_string());
    }

    Ok(parse(content, path))
}

#[test]
fn it_works() {
    let path = "ex1";
    let mut subs = prepare(path).unwrap();

    let line = subs.by_index(3).unwrap();
    {
        let another_one = subs.by_miliseconds(261072).unwrap();
        let same_line = subs.by_timestamp(&[0, 4, 22, 500]).unwrap();
        assert_eq!(line.get_index(), same_line.get_index());
        assert_eq!(same_line.get_text(), another_one.get_text());
    }

    println!("{}\n{:?} --> {:?}\n{}\n",
             line.get_index(),
             line.get_start(),
             line.get_end(),
             line.get_text());
    println!("duration: {}", line.get_duration());

    {
        let mut mutline = subs.mut_by_miliseconds(261072).unwrap();
        mutline.shift(-1).unwrap();
    }

    {
        let newline = subs.by_index(3).unwrap();
        assert_eq!(newline.get_start(), line.get_start() - 1);
    }

    subs.shift_all(1).unwrap();

    {
        let newline = subs.by_index(3).unwrap();
        assert_eq!(newline.get_start(), line.get_start());
    }

}<|endoftext|>


<commit_before>#![feature(collections)]
#![no_std]

extern crate collections;

extern crate abs;
extern crate approx;
extern crate bounded;
extern crate to_degrees;
extern crate to_radians;
extern crate to_primitive;
extern crate from_primitive;
extern crate max;
extern crate min;
extern crate one;
extern crate pi;
extern crate round;
extern crate signum;
extern crate sqrt;
extern crate trig;
extern crate zero;

use collections::string::ToString;
use core::ops::*;

use abs::Abs;
use approx::Approx;
use bounded::Bounded;
use to_degrees::ToDegrees;
use to_radians::ToRadians;
use to_primitive::ToPrimitive;
use from_primitive::FromPrimitive;
use max::Max;
use min::Min;
use one::One;
use pi::Pi;
use round::Round;
use signum::Signum;
use sqrt::Sqrt;
use trig::Trig;
use zero::Zero;

pub trait Num:
    Copy + One + Zero + Sqrt
    + Min + Max + Signum
    + Abs
    + Approx
    + Bounded
    + ToDegrees
    + ToRadians
    + ToPrimitive
    + FromPrimitive
    + Trig
    + Pi
    + PartialEq
    + PartialOrd
    + Round
    + ToString

    + Add<Self, Output = Self>
    + Mul<Self, Output = Self>
    + Sub<Self, Output = Self>
    + Div<Self, Output = Self>
    + Rem<Self, Output = Self>

    + AddAssign<Self>
    + MulAssign<Self>
    + SubAssign<Self>
    + DivAssign<Self>
    + RemAssign<Self>

    + Neg<Output = Self> {}

impl<T> Num for T where T:
    Copy + One + Zero + Sqrt
    + Min + Max + Signum
    + Abs
    + Approx
    + Bounded
    + ToDegrees
    + ToRadians
    + ToPrimitive
    + FromPrimitive
    + Trig
    + Pi
    + PartialEq
    + PartialOrd
    + Round
    + ToString

    + Add<T, Output = T>
    + Mul<T, Output = T>
    + Sub<T, Output = T>
    + Div<T, Output = T>
    + Rem<T, Output = T>

    + AddAssign<T>
    + MulAssign<T>
    + SubAssign<T>
    + DivAssign<T>
    + RemAssign<T>

    + Neg<Output = T> {}
<commit_msg>updates<commit_after>#![feature(collections)]
#![no_std]

extern crate collections;

extern crate abs;
extern crate approx;
extern crate bounded;
extern crate to_degrees;
extern crate to_radians;
extern crate to_primitive;
extern crate from_primitive;
extern crate max;
extern crate min;
extern crate one;
extern crate pi;
extern crate round;
extern crate signum;
extern crate sqrt;
extern crate trig;
extern crate zero;

use collections::string::ToString;
use core::ops::*;

use abs::Abs;
use approx::Approx;
use bounded::Bounded;
use to_degrees::ToDegrees;
use to_radians::ToRadians;
use to_primitive::ToPrimitive;
use from_primitive::FromPrimitive;
use max::Max;
use min::Min;
use one::One;
use pi::Pi;
use round::Round;
use signum::Signum;
use sqrt::Sqrt;
use trig::Trig;
use zero::Zero;

pub trait Num:
    Copy + One + Zero + Sqrt
    + Min + Max + Signum
    + Abs
    + Approx
    + Bounded
    + ToDegrees
    + ToRadians
    + ToPrimitive
    + FromPrimitive
    + Trig
    + Pi
    + PartialEq
    + PartialOrd
    + Round
    + ToString

    + Add<Self, Output = Self>
    + Mul<Self, Output = Self>
    + Sub<Self, Output = Self>
    + Div<Self, Output = Self>
    + Rem<Self, Output = Self>

    + AddAssign<Self>
    + MulAssign<Self>
    + SubAssign<Self>
    + DivAssign<Self>
    + RemAssign<Self> {}

impl<T> Num for T where T:
    Copy + One + Zero + Sqrt
    + Min + Max + Signum
    + Abs
    + Approx
    + Bounded
    + ToDegrees
    + ToRadians
    + ToPrimitive
    + FromPrimitive
    + Trig
    + Pi
    + PartialEq
    + PartialOrd
    + Round
    + ToString

    + Add<T, Output = T>
    + Mul<T, Output = T>
    + Sub<T, Output = T>
    + Div<T, Output = T>
    + Rem<T, Output = T>

    + AddAssign<T>
    + MulAssign<T>
    + SubAssign<T>
    + DivAssign<T>
    + RemAssign<T> {}
<|endoftext|>


<commit_before>// Copyright 2016 oauth-client-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.

//! Performs topological sorting.

#![warn(bad_style, missing_docs,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results)]

use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry;
use std::hash::Hash;

struct Dependency<T> {
    num_prec: usize,
    succ: HashSet<T>,
}

impl<T: Hash + Eq> Dependency<T> {
    fn new() -> Dependency<T> {
        Dependency {
            num_prec: 0,
            succ: HashSet::new(),
        }
    }
}

/// Performs topological sorting.
pub struct TopologicalSort<T> {
    top: HashMap<T, Dependency<T>>,
}

impl<T: Hash + Eq + Clone> TopologicalSort<T> {
    /// Creates new empty `TopologicalSort`.
    ///
    /// ```rust
    /// # extern crate topological_sort;
    /// # fn main() {
    /// use topological_sort::TopologicalSort;
    /// let mut ts = TopologicalSort::new();
    /// ts.add_dependency("hello_world.o", "hello_world");
    /// ts.add_dependency("hello_world.c", "hello_world");
    /// ts.add_dependency("stdio.h", "hello_world.o");
    /// ts.add_dependency("glibc.so", "hello_world");
    /// assert_eq!(vec!["glibc.so", "hello_world.c", "stdio.h"],
    ///            { let mut v = ts.pop_all(); v.sort(); v });
    /// assert_eq!(vec!["hello_world.o"],
    ///            { let mut v = ts.pop_all(); v.sort(); v });
    /// assert_eq!(vec!["hello_world"],
    ///            { let mut v = ts.pop_all(); v.sort(); v });
    /// assert!(ts.pop_all().is_empty());
    /// # }
    /// ```
    #[inline]
    pub fn new() -> TopologicalSort<T> {
        TopologicalSort { top: HashMap::new() }
    }

    /// Returns the number of elements in the `TopologicalSort`.
    #[inline]
    pub fn len(&self) -> usize {
        self.top.len()
    }

    /// Returns true if the `TopologicalSort` contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.top.is_empty()
    }

    /// Registers the two elements' dependency.
    ///
    /// # Arguments
    ///
    /// * `prec` - The element appears before `succ`. `prec` is depended on by `succ`.
    /// * `succ` - The element appears after `prec`. `succ` depends on `prec`.
    pub fn add_dependency(&mut self, prec: T, succ: T) {
        match self.top.entry(prec) {
            Entry::Vacant(e) => {
                let mut dep = Dependency::new();
                dep.succ.insert(succ.clone());
                let _ = e.insert(dep);
            }
            Entry::Occupied(e) => {
                if !e.into_mut().succ.insert(succ.clone()) {
                    // Already registered
                    return;
                }
            }
        }

        match self.top.entry(succ) {
            Entry::Vacant(e) => {
                let mut dep = Dependency::new();
                dep.num_prec += 1;
                let _ = e.insert(dep);
            }
            Entry::Occupied(e) => {
                e.into_mut().num_prec += 1;
            }
        }
    }

    /// Removes the item that is not depended on by any other items and returns it, or `None` if there is no such item.
    ///
    /// If `pop` returns `None` and `len` is not 0, there is cyclic dependencies.
    pub fn pop(&mut self) -> Option<T> {
        self.top
            .iter()
            .filter(|&(_, v)| v.num_prec == 0)
            .next()
            .map(|(k, _)| k.clone())
            .map(|key| {
                let _ = self.remove(&key);
                key
            })
    }

    /// Removes all items that are not depended on by any other items and returns it, or empty vector if there are no such items.
    ///
    /// If `pop_all` returns an empty vector and `len` is not 0, there is cyclic dependencies.
    pub fn pop_all(&mut self) -> Vec<T> {
        let keys = self.top
                       .iter()
                       .filter(|&(_, v)| v.num_prec == 0)
                       .map(|(k, _)| k.clone())
                       .collect::<Vec<_>>();
        for k in keys.iter() {
            let _ = self.remove(k);
        }
        keys
    }

    fn remove(&mut self, prec: &T) -> Option<Dependency<T>> {
        let result = self.top.remove(prec);
        if let Some(ref p) = result {
            for s in p.succ.iter() {
                if let Some(y) = self.top.get_mut(s) {
                    y.num_prec -= 1;
                }
            }
        }
        result
    }
}

impl<T: Hash + Eq + Clone> Iterator for TopologicalSort<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        self.pop()
    }
}

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

    #[test]
    fn iter() {
        let mut ts = TopologicalSort::<i32>::new();
        ts.add_dependency(1, 2);
        ts.add_dependency(2, 3);
        ts.add_dependency(3, 4);
        assert_eq!(Some(1), ts.next());
        assert_eq!(Some(2), ts.next());
        assert_eq!(Some(3), ts.next());
        assert_eq!(Some(4), ts.next());
        assert_eq!(None, ts.next());
    }

    #[test]
    fn pop_all() {
        fn check(result: &[i32], ts: &mut TopologicalSort<i32>) {
            let l = ts.len();
            let mut v = ts.pop_all();
            v.sort();
            assert_eq!(result, &v[..]);
            assert_eq!(l - result.len(), ts.len());
        }

        let mut ts = TopologicalSort::new();
        ts.add_dependency(7, 11);
        assert_eq!(2, ts.len());
        ts.add_dependency(7, 8);
        assert_eq!(3, ts.len());
        ts.add_dependency(5, 11);
        assert_eq!(4, ts.len());
        ts.add_dependency(3, 8);
        assert_eq!(5, ts.len());
        ts.add_dependency(3, 10);
        assert_eq!(6, ts.len());
        ts.add_dependency(11, 2);
        assert_eq!(7, ts.len());
        ts.add_dependency(11, 9);
        assert_eq!(8, ts.len());
        ts.add_dependency(11, 10);
        assert_eq!(8, ts.len());
        ts.add_dependency(8, 9);
        assert_eq!(8, ts.len());

        check(&[3, 5, 7], &mut ts);
        check(&[8, 11], &mut ts);
        check(&[2, 9, 10], &mut ts);
        check(&[], &mut ts);
    }
}
<commit_msg>Implement FromIterator<T: PartialOrd>, closes #5<commit_after>// Copyright 2016 oauth-client-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.

//! Performs topological sorting.

#![warn(bad_style, missing_docs,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results)]

use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry;
use std::hash::Hash;
use std::iter::FromIterator;

struct Dependency<T> {
    num_prec: usize,
    succ: HashSet<T>,
}

impl<T: Hash + Eq> Dependency<T> {
    fn new() -> Dependency<T> {
        Dependency {
            num_prec: 0,
            succ: HashSet::new(),
        }
    }
}

/// Performs topological sorting.
pub struct TopologicalSort<T> {
    top: HashMap<T, Dependency<T>>,
}

impl<T: Hash + Eq + Clone> TopologicalSort<T> {
    /// Creates new empty `TopologicalSort`.
    ///
    /// ```rust
    /// # extern crate topological_sort;
    /// # fn main() {
    /// use topological_sort::TopologicalSort;
    /// let mut ts = TopologicalSort::new();
    /// ts.add_dependency("hello_world.o", "hello_world");
    /// ts.add_dependency("hello_world.c", "hello_world");
    /// ts.add_dependency("stdio.h", "hello_world.o");
    /// ts.add_dependency("glibc.so", "hello_world");
    /// assert_eq!(vec!["glibc.so", "hello_world.c", "stdio.h"],
    ///            { let mut v = ts.pop_all(); v.sort(); v });
    /// assert_eq!(vec!["hello_world.o"],
    ///            { let mut v = ts.pop_all(); v.sort(); v });
    /// assert_eq!(vec!["hello_world"],
    ///            { let mut v = ts.pop_all(); v.sort(); v });
    /// assert!(ts.pop_all().is_empty());
    /// # }
    /// ```
    #[inline]
    pub fn new() -> TopologicalSort<T> {
        TopologicalSort { top: HashMap::new() }
    }

    /// Returns the number of elements in the `TopologicalSort`.
    #[inline]
    pub fn len(&self) -> usize {
        self.top.len()
    }

    /// Returns true if the `TopologicalSort` contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.top.is_empty()
    }

    /// Registers the two elements' dependency.
    ///
    /// # Arguments
    ///
    /// * `prec` - The element appears before `succ`. `prec` is depended on by `succ`.
    /// * `succ` - The element appears after `prec`. `succ` depends on `prec`.
    pub fn add_dependency(&mut self, prec: T, succ: T) {
        match self.top.entry(prec) {
            Entry::Vacant(e) => {
                let mut dep = Dependency::new();
                dep.succ.insert(succ.clone());
                let _ = e.insert(dep);
            }
            Entry::Occupied(e) => {
                if !e.into_mut().succ.insert(succ.clone()) {
                    // Already registered
                    return;
                }
            }
        }

        match self.top.entry(succ) {
            Entry::Vacant(e) => {
                let mut dep = Dependency::new();
                dep.num_prec += 1;
                let _ = e.insert(dep);
            }
            Entry::Occupied(e) => {
                e.into_mut().num_prec += 1;
            }
        }
    }

    /// Inserts an element, without adding any dependencies from or to it.
    ///
    /// If the `TopologicalSort` did not have this element present, `true` is returned.
    ///
    /// If the `TopologicalSort` already had this element present, `false` is returned.
    pub fn insert(&mut self, elt: T) -> bool {
        match self.top.entry(elt) {
            Entry::Vacant(e) => {
                let dep = Dependency::new();
                let _ = e.insert(dep);
                true
            }
            Entry::Occupied(_) => {
                false
            }
        }
    }

    /// Removes the item that is not depended on by any other items and returns it, or `None` if there is no such item.
    ///
    /// If `pop` returns `None` and `len` is not 0, there is cyclic dependencies.
    pub fn pop(&mut self) -> Option<T> {
        self.top
            .iter()
            .filter(|&(_, v)| v.num_prec == 0)
            .next()
            .map(|(k, _)| k.clone())
            .map(|key| {
                let _ = self.remove(&key);
                key
            })
    }

    /// Removes all items that are not depended on by any other items and returns it, or empty vector if there are no such items.
    ///
    /// If `pop_all` returns an empty vector and `len` is not 0, there is cyclic dependencies.
    pub fn pop_all(&mut self) -> Vec<T> {
        let keys = self.top
                       .iter()
                       .filter(|&(_, v)| v.num_prec == 0)
                       .map(|(k, _)| k.clone())
                       .collect::<Vec<_>>();
        for k in keys.iter() {
            let _ = self.remove(k);
        }
        keys
    }

    fn remove(&mut self, prec: &T) -> Option<Dependency<T>> {
        let result = self.top.remove(prec);
        if let Some(ref p) = result {
            for s in p.succ.iter() {
                if let Some(y) = self.top.get_mut(s) {
                    y.num_prec -= 1;
                }
            }
        }
        result
    }
}

impl<T: PartialOrd + Eq + Hash + Clone> FromIterator<T> for TopologicalSort<T> {
    fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> TopologicalSort<T> {
        let mut top = TopologicalSort::new();
        let mut seen = Vec::<T>::default();
        for item in iter {
            top.insert(item.clone());
            for seen_item in seen.iter().cloned() {
                match seen_item.partial_cmp(&item) {
                    Some(Ordering::Less) => { top.add_dependency(seen_item, item.clone()); }
                    Some(Ordering::Greater) => { top.add_dependency(item.clone(), seen_item); }
                    _ => ()
                }
            }
            seen.push(item);
        }
        top
    }
}

impl<T: Hash + Eq + Clone> Iterator for TopologicalSort<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        self.pop()
    }
}

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

    #[test]
    fn iter() {
        let mut ts = TopologicalSort::<i32>::new();
        ts.add_dependency(1, 2);
        ts.add_dependency(2, 3);
        ts.add_dependency(3, 4);
        assert_eq!(Some(1), ts.next());
        assert_eq!(Some(2), ts.next());
        assert_eq!(Some(3), ts.next());
        assert_eq!(Some(4), ts.next());
        assert_eq!(None, ts.next());
    }

    #[test]
    fn pop_all() {
        fn check(result: &[i32], ts: &mut TopologicalSort<i32>) {
            let l = ts.len();
            let mut v = ts.pop_all();
            v.sort();
            assert_eq!(result, &v[..]);
            assert_eq!(l - result.len(), ts.len());
        }

        let mut ts = TopologicalSort::new();
        ts.add_dependency(7, 11);
        assert_eq!(2, ts.len());
        ts.add_dependency(7, 8);
        assert_eq!(3, ts.len());
        ts.add_dependency(5, 11);
        assert_eq!(4, ts.len());
        ts.add_dependency(3, 8);
        assert_eq!(5, ts.len());
        ts.add_dependency(3, 10);
        assert_eq!(6, ts.len());
        ts.add_dependency(11, 2);
        assert_eq!(7, ts.len());
        ts.add_dependency(11, 9);
        assert_eq!(8, ts.len());
        ts.add_dependency(11, 10);
        assert_eq!(8, ts.len());
        ts.add_dependency(8, 9);
        assert_eq!(8, ts.len());

        check(&[3, 5, 7], &mut ts);
        check(&[8, 11], &mut ts);
        check(&[2, 9, 10], &mut ts);
        check(&[], &mut ts);
    }
}
<|endoftext|>


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

//! Rust wrapper for RocksDB.
//!
//! # Examples
//!
//! ```
//!  use rocksdb::DB;
//!  // NB: db is automatically closed at end of lifetime
//!  let db = DB::open_default("path/for/rocksdb/storage").unwrap();
//!  db.put(b"my key", b"my value");
//!  match db.get(b"my key") {
//!     Ok(Some(value)) => println!("retrieved value {}", value.to_utf8().unwrap()),
//!     Ok(None) => println!("value not found"),
//!     Err(e) => println!("operational problem encountered: {}", e),
//!  }
//!  db.delete(b"my key").unwrap();
//! ```
//!

extern crate libc;
extern crate librocksdb_sys as ffi;

#[macro_use]
mod ffi_util;

pub mod backup;
mod comparator;
pub mod merge_operator;
pub mod compaction_filter;
mod db;
mod db_options;

pub use db::{DBCompactionStyle, DBCompressionType, DBIterator, DBRawIterator, DBRecoveryMode, DBVector,
             ReadOptions, Direction, IteratorMode, Snapshot, WriteBatch, new_bloom_filter};

pub use merge_operator::MergeOperands;
pub use compaction_filter::Decision as CompactionDecision;
use std::collections::BTreeMap;
use std::error;
use std::fmt;
use std::path::PathBuf;

/// A RocksDB database.
///
/// See crate level documentation for a simple usage example.
pub struct DB {
    inner: *mut ffi::rocksdb_t,
    cfs: BTreeMap<String, ColumnFamily>,
    path: PathBuf,
}

/// A simple wrapper round a string, used for errors reported from
/// ffi calls.
#[derive(Debug, Clone, PartialEq)]
pub struct Error {
    message: String,
}

impl Error {
    fn new(message: String) -> Error {
        Error { message: message }
    }

    pub fn to_string(self) -> String {
        self.into()
    }
}

impl AsRef<str> for Error {
    fn as_ref(&self) -> &str {
        &self.message
    }
}

impl From<Error> for String {
    fn from(e: Error) -> String {
        e.message
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.message.fmt(formatter)
    }
}

/// For configuring block-based file storage.
pub struct BlockBasedOptions {
    inner: *mut ffi::rocksdb_block_based_table_options_t,
}

/// Database-wide options around performance and behavior.
///
/// Please read [the official tuning guide](https://github.com/facebook/rocksdb/wiki/RocksDB-Tuning-Guide), and most importantly, measure performance under realistic workloads with realistic hardware.
///
/// # Examples
///
/// ```
/// use rocksdb::{Options, DB};
/// use rocksdb::DBCompactionStyle;
///
/// fn badly_tuned_for_somebody_elses_disk() -> DB {
///    let path = "path/for/rocksdb/storageX";
///    let mut opts = Options::default();
///    opts.create_if_missing(true);
///    opts.set_max_open_files(10000);
///    opts.set_use_fsync(false);
///    opts.set_bytes_per_sync(8388608);
///    opts.set_disable_data_sync(false);
///    opts.optimize_for_point_lookup(1024);
///    opts.set_table_cache_num_shard_bits(6);
///    opts.set_max_write_buffer_number(32);
///    opts.set_write_buffer_size(536870912);
///    opts.set_target_file_size_base(1073741824);
///    opts.set_min_write_buffer_number_to_merge(4);
///    opts.set_level_zero_stop_writes_trigger(2000);
///    opts.set_level_zero_slowdown_writes_trigger(0);
///    opts.set_compaction_style(DBCompactionStyle::Universal);
///    opts.set_max_background_compactions(4);
///    opts.set_max_background_flushes(4);
///    opts.set_disable_auto_compactions(true);
///
///    DB::open(&opts, path).unwrap()
/// }
/// ```
pub struct Options {
    inner: *mut ffi::rocksdb_options_t,
}

/// Optionally disable WAL or sync for this write.
///
/// # Examples
///
/// Making an unsafe write of a batch:
///
/// ```
/// use rocksdb::{DB, WriteBatch, WriteOptions};
///
/// let db = DB::open_default("path/for/rocksdb/storageY").unwrap();
///
/// let mut batch = WriteBatch::default();
/// batch.put(b"my key", b"my value");
/// batch.put(b"key2", b"value2");
/// batch.put(b"key3", b"value3");
///
/// let mut write_options = WriteOptions::default();
/// write_options.set_sync(false);
/// write_options.disable_wal(true);
///
/// db.write_opt(batch, &write_options);
/// ```
pub struct WriteOptions {
    inner: *mut ffi::rocksdb_writeoptions_t,
}

/// An opaque type used to represent a column family. Returned from some functions, and used
/// in others
#[derive(Copy, Clone)]
pub struct ColumnFamily {
    inner: *mut ffi::rocksdb_column_family_handle_t,
}
<commit_msg>ensure doctests are not elided by linker<commit_after>// Copyright 2014 Tyler Neely
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

//! Rust wrapper for RocksDB.
//!
//! # Examples
//!
//! ```
//!  use rocksdb::DB;
//!  // NB: db is automatically closed at end of lifetime
//!  let db = DB::open_default("path/for/rocksdb/storage").unwrap();
//!  db.put(b"my key", b"my value");
//!  match db.get(b"my key") {
//!     Ok(Some(value)) => println!("retrieved value {}", value.to_utf8().unwrap()),
//!     Ok(None) => println!("value not found"),
//!     Err(e) => println!("operational problem encountered: {}", e),
//!  }
//!  db.delete(b"my key").unwrap();
//! ```
//!

extern crate libc;
extern crate librocksdb_sys as ffi;

#[macro_use]
mod ffi_util;

pub mod backup;
mod comparator;
pub mod merge_operator;
pub mod compaction_filter;
mod db;
mod db_options;

pub use db::{DBCompactionStyle, DBCompressionType, DBIterator, DBRawIterator, DBRecoveryMode, DBVector,
             ReadOptions, Direction, IteratorMode, Snapshot, WriteBatch, new_bloom_filter};

pub use merge_operator::MergeOperands;
pub use compaction_filter::Decision as CompactionDecision;
use std::collections::BTreeMap;
use std::error;
use std::fmt;
use std::path::PathBuf;

/// A RocksDB database.
///
/// See crate level documentation for a simple usage example.
pub struct DB {
    inner: *mut ffi::rocksdb_t,
    cfs: BTreeMap<String, ColumnFamily>,
    path: PathBuf,
}

/// A simple wrapper round a string, used for errors reported from
/// ffi calls.
#[derive(Debug, Clone, PartialEq)]
pub struct Error {
    message: String,
}

impl Error {
    fn new(message: String) -> Error {
        Error { message: message }
    }

    pub fn to_string(self) -> String {
        self.into()
    }
}

impl AsRef<str> for Error {
    fn as_ref(&self) -> &str {
        &self.message
    }
}

impl From<Error> for String {
    fn from(e: Error) -> String {
        e.message
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.message.fmt(formatter)
    }
}

/// For configuring block-based file storage.
pub struct BlockBasedOptions {
    inner: *mut ffi::rocksdb_block_based_table_options_t,
}

/// Database-wide options around performance and behavior.
///
/// Please read [the official tuning guide](https://github.com/facebook/rocksdb/wiki/RocksDB-Tuning-Guide), and most importantly, measure performance under realistic workloads with realistic hardware.
///
/// # Examples
///
/// ```
/// use rocksdb::{Options, DB};
/// use rocksdb::DBCompactionStyle;
///
/// let mut opts = Options::default();
/// opts.create_if_missing(true);
/// opts.set_max_open_files(10000);
/// opts.set_use_fsync(false);
/// opts.set_bytes_per_sync(8388608);
/// opts.set_disable_data_sync(false);
/// opts.optimize_for_point_lookup(1024);
/// opts.set_table_cache_num_shard_bits(6);
/// opts.set_max_write_buffer_number(32);
/// opts.set_write_buffer_size(536870912);
/// opts.set_target_file_size_base(1073741824);
/// opts.set_min_write_buffer_number_to_merge(4);
/// opts.set_level_zero_stop_writes_trigger(2000);
/// opts.set_level_zero_slowdown_writes_trigger(0);
/// opts.set_compaction_style(DBCompactionStyle::Universal);
/// opts.set_max_background_compactions(4);
/// opts.set_max_background_flushes(4);
/// opts.set_disable_auto_compactions(true);
/// ```
pub struct Options {
    inner: *mut ffi::rocksdb_options_t,
}

/// Optionally disable WAL or sync for this write.
///
/// # Examples
///
/// Making an unsafe write of a batch:
///
/// ```
/// use rocksdb::{DB, WriteBatch, WriteOptions};
///
/// let db = DB::open_default("path/for/rocksdb/storageY").unwrap();
///
/// let mut batch = WriteBatch::default();
/// batch.put(b"my key", b"my value");
/// batch.put(b"key2", b"value2");
/// batch.put(b"key3", b"value3");
///
/// let mut write_options = WriteOptions::default();
/// write_options.set_sync(false);
/// write_options.disable_wal(true);
///
/// db.write_opt(batch, &write_options);
/// ```
pub struct WriteOptions {
    inner: *mut ffi::rocksdb_writeoptions_t,
}

/// An opaque type used to represent a column family. Returned from some functions, and used
/// in others
#[derive(Copy, Clone)]
pub struct ColumnFamily {
    inner: *mut ffi::rocksdb_column_family_handle_t,
}
<|endoftext|>


<commit_before>extern crate capnp;

mod json_shred;
mod key_builder;
mod stems;
mod index;

// include capnp code generated by `build.rs`
mod records_capnp {
    include!(concat!(env!("OUT_DIR"), "/records_capnp.rs"));
}

#[test]
fn it_works() {
}

<commit_msg>Remove junk<commit_after>extern crate capnp;

mod json_shred;
mod key_builder;
mod stems;
mod index;

// include capnp code generated by `build.rs`
mod records_capnp {
    include!(concat!(env!("OUT_DIR"), "/records_capnp.rs"));
}
<|endoftext|>


<commit_before>//! A helper trait to initialize a data structure with custom code.
//!
//! This crate is meant to aid in initializing fixed arrays using something other than a `Default`
//! implementation. For example, if you wanted to create an array of Vecs, you could create one
//! with `Default` that made all the Vecs empty:
//!
//! ```rust
//! let my_array = <[Vec<u32>; 3]>::default();
//! assert_eq!(my_array, [[], [], []]);
//! ```
//!
//! But if you wanted to start the arrays with some state, you either need to start with the empty
//! arrays and fill from there, or drop into unsafe code to write in a partially-initialized array.
//!
//! ```rust
//! let mut my_array = <[Vec<usize>; 3]>::default();
//!
//! for (idx, arr) in my_array.iter_mut().enumerate() {
//!     for i in 0..(idx+1) {
//!         arr.push(i);
//!     }
//! }
//!
//! assert_eq!(my_array, [vec![0], vec![0, 1], vec![0, 1, 2]]);
//! ```
//!
//! With `InitWith`, the same array could be initialized like this:
//!
//! ```rust
//! use init_with::InitWith;
//!
//! let my_array = {
//!     let mut seed = Vec::new();
//!     let mut next_val = 0;
//!
//!     <[Vec<u32>; 3]>::init_with(|| {
//!         seed.push(next_val);
//!         next_val += 1;
//!         seed.clone()
//!     })
//! };
//!
//! assert_eq!(my_array, [vec![0], vec![0, 1], vec![0, 1, 2]]);
//! ```
//!
//! This crate is built with `#![no_std]` and only uses libcore for its code, so it can be used
//! from other `no_std` crates.

#![no_std]

/// A trait that allows you to create an instance of a type by using a given function to generate
/// each element.
pub trait InitWith<T> {
    /// Create a new instance of this type using the given function to fill elements.
    ///
    /// # Examples
    ///
    /// Prefilling an array with a Vec, with no unsafe code\*:
    ///
    /// ```rust
    /// use init_with::InitWith;
    ///
    /// let src = vec![1, 2, 3];
    /// let dest: [i32; 3] = {
    ///     let mut idx = 0;
    ///
    ///     //*okay, there's unsafe code in here, but you didn't have to write it
    ///     <[i32; 3]>::init_with(|| {
    ///         let val = src[idx];
    ///         idx += 1;
    ///         val
    ///     })
    /// };
    ///
    /// assert_eq!(src, dest);
    /// ```
    fn init_with<F>(init: F) -> Self
        where F: FnMut() -> T,
              Self: Sized;
}

macro_rules! array_init {
    {$n:expr, $init:ident, $($stack:ident,)+} => {
        impl<T> InitWith<T> for [T; $n] {
            fn init_with<F>(mut $init: F) -> Self
                where F: FnMut() -> T
            {
                [$init(), $($stack()),+]
            }
        }
        array_init!{($n - 1), $($stack,)+}
    };
    {$n:expr, $init:ident,} => {
        impl<T> InitWith<T> for [T; $n] {
            fn init_with<F>(mut $init: F) -> Self
                where F: FnMut() -> T
            {
                [$init()]
            }
        }
        array_init!{($n - 1)}
    };
    {$n:expr} => {
        impl<T> InitWith<T> for [T; $n] {
            fn init_with<F>(_init: F) -> Self
                where F: FnMut() -> T
            {
                []
            }
        }
    };
}

array_init!{32, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init,}

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

    #[test]
    fn expected() {
        let val = <[i32; 3]>::init_with(|| 4);
        assert_eq!(val, [4, 4, 4]);
    }
}
<commit_msg>oh hey, there's not even unsafe code inside the crate any more<commit_after>//! A helper trait to initialize a data structure with custom code.
//!
//! This crate is meant to aid in initializing fixed arrays using something other than a `Default`
//! implementation. For example, if you wanted to create an array of Vecs, you could create one
//! with `Default` that made all the Vecs empty:
//!
//! ```rust
//! let my_array = <[Vec<u32>; 3]>::default();
//! assert_eq!(my_array, [[], [], []]);
//! ```
//!
//! But if you wanted to start the arrays with some state, you either need to start with the empty
//! arrays and fill from there, or drop into unsafe code to write in a partially-initialized array.
//!
//! ```rust
//! let mut my_array = <[Vec<usize>; 3]>::default();
//!
//! for (idx, arr) in my_array.iter_mut().enumerate() {
//!     for i in 0..(idx+1) {
//!         arr.push(i);
//!     }
//! }
//!
//! assert_eq!(my_array, [vec![0], vec![0, 1], vec![0, 1, 2]]);
//! ```
//!
//! With `InitWith`, the same array could be initialized like this:
//!
//! ```rust
//! use init_with::InitWith;
//!
//! let my_array = {
//!     let mut seed = Vec::new();
//!     let mut next_val = 0;
//!
//!     <[Vec<u32>; 3]>::init_with(|| {
//!         seed.push(next_val);
//!         next_val += 1;
//!         seed.clone()
//!     })
//! };
//!
//! assert_eq!(my_array, [vec![0], vec![0, 1], vec![0, 1, 2]]);
//! ```
//!
//! This crate is built with `#![no_std]` and only uses libcore for its code, so it can be used
//! from other `no_std` crates.

#![no_std]

/// A trait that allows you to create an instance of a type by using a given function to generate
/// each element.
pub trait InitWith<T> {
    /// Create a new instance of this type using the given function to fill elements.
    ///
    /// # Examples
    ///
    /// Prefilling an array with a Vec, with no unsafe code:
    ///
    /// ```rust
    /// use init_with::InitWith;
    ///
    /// let src = vec![1, 2, 3];
    /// let dest: [i32; 3] = {
    ///     let mut idx = 0;
    ///
    ///     <[i32; 3]>::init_with(|| {
    ///         let val = src[idx];
    ///         idx += 1;
    ///         val
    ///     })
    /// };
    ///
    /// assert_eq!(src, dest);
    /// ```
    fn init_with<F>(init: F) -> Self
        where F: FnMut() -> T,
              Self: Sized;
}

macro_rules! array_init {
    {$n:expr, $init:ident, $($stack:ident,)+} => {
        impl<T> InitWith<T> for [T; $n] {
            fn init_with<F>(mut $init: F) -> Self
                where F: FnMut() -> T
            {
                [$init(), $($stack()),+]
            }
        }
        array_init!{($n - 1), $($stack,)+}
    };
    {$n:expr, $init:ident,} => {
        impl<T> InitWith<T> for [T; $n] {
            fn init_with<F>(mut $init: F) -> Self
                where F: FnMut() -> T
            {
                [$init()]
            }
        }
        array_init!{($n - 1)}
    };
    {$n:expr} => {
        impl<T> InitWith<T> for [T; $n] {
            fn init_with<F>(_init: F) -> Self
                where F: FnMut() -> T
            {
                []
            }
        }
    };
}

array_init!{32, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init, init,}

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

    #[test]
    fn expected() {
        let val = <[i32; 3]>::init_with(|| 4);
        assert_eq!(val, [4, 4, 4]);
    }
}
<|endoftext|>