<commit_before>extern crate fixedbitset;
extern crate rand;

pub mod dna_base;
pub mod base4;
pub mod graph;

use std::str::FromStr;
use std::ops::Deref;
use std::fmt::{self, Debug};
use fixedbitset::FixedBitSet;
use rand::{Rng, Rand};

/// Represents the bases used in the genome string.
/// For example the bases of the DNA are adenine (A),
/// thymine (T), guanine (G) and cytosine (C).
pub trait Base: Sized + PartialEq + Eq + Copy + Clone + Debug + Rand {
    /// Returns the "successor" base, wrapping around. Used
    /// to produce the gene product.
    fn succ(self) -> Self;

    fn from_char(c: char) -> Option<Self>;
}

// Locate ```substr``` in ```s```.
fn locate_substr<T: Eq>(s: &[T], substr: &[T]) -> Option<usize> {
    assert!(substr.len() > 0);

    if s.len() < substr.len() {
        return None;
    }

    for (i, window) in s.windows(substr.len()).enumerate() {
        if window == substr {
            return Some(i);
        }
    }

    return None;
}

// Count occurrence of ```substr``` in ```s```.
fn count_substr<T: Eq>(s: &[T], substr: &[T]) -> usize {
    assert!(substr.len() > 0);

    let mut cnt = 0;
    for window in s.windows(substr.len()) {
        if window == substr {
            cnt += 1;
        }
    }

    return cnt;
}

#[derive(Debug)]
pub struct Gene<'a, B: Base + 'a> {
    pub regulatory_region: &'a [B],
    pub gene: &'a [B],
}

impl<'a, B: Base + 'a> Gene<'a, B> {
    /// The gene product
    pub fn product(&self) -> BaseString<B> {
        BaseString { v: self.gene.iter().map(|b| b.succ()).collect() }
    }

    pub fn find_product_in_regulatory_region(&self, product: &[B]) -> bool {
        locate_substr(self.regulatory_region, product).is_some()
    }
    pub fn count_product_in_regulatory_region(&self, product: &[B]) -> usize {
        count_substr(self.regulatory_region, product)
    }
}

pub struct GeneIterator<'a, 'b, B: Base + 'a + 'b> {
    // Genes have fixed length
    length_of_gene: usize,
    sequence: &'a [B],
    promoter: &'b [B],
}

impl<'a, 'b, B: Base + 'a + 'b> Iterator for GeneIterator<'a, 'b, B> {
    type Item = Gene<'a, B>;

    fn next(&mut self) -> Option<Self::Item> {
        match locate_substr(self.sequence, self.promoter) {
            Some(pos) => {
                let gene_start = pos + self.promoter.len();
                let gene_end = gene_start + self.length_of_gene;

                // gene is not complete
                if gene_end > self.sequence.len() {
                    return None;
                }

                let gene = Gene {
                    regulatory_region: &self.sequence[..pos],
                    gene: &self.sequence[gene_start..gene_end],
                };
                self.sequence = &self.sequence[gene_end..];
                return Some(gene);
            }
            None => {
                return None;
            }
        }
    }
}

// A positive value enhances, a negative inhibits the expression of a gene.
#[derive(Debug)]
pub struct ProteinRegulator(i32);

impl ProteinRegulator {
    pub fn enhance() -> ProteinRegulator {
        ProteinRegulator(1)
    }

    pub fn inhibit() -> ProteinRegulator {
        ProteinRegulator(-1)
    }
}

pub struct BaseString<B: Base> {
    v: Vec<B>,
}

impl<B: Base> FromStr for BaseString<B> {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(BaseString { v: s.chars().filter_map(|c| B::from_char(c)).collect() })
    }
}

impl<B: Base> Deref for BaseString<B> {
    type Target = [B];

    fn deref(&self) -> &Self::Target {
        &self.v
    }
}

impl<B: Base> Debug for BaseString<B> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "["));
        for base in &self.v {
            try!(write!(f, "{:?}", base));
        }
        write!(f, "]")
    }
}

impl<B: Base> BaseString<B> {
    pub fn random<R: Rng>(rng: &mut R, n: usize) -> BaseString<B> {
        assert!(n > 0);
        BaseString { v: (0..n).map(|_| rng.gen()).collect() }
    }
}

/// A Genome is a string of Base
pub struct Genome<B: Base> {
    genome: BaseString<B>,
}

impl<B: Base> Genome<B> {
    pub fn random<R: Rng>(rng: &mut R, n: usize) -> Genome<B> {
        Genome { genome: BaseString::random(rng, n) }
    }
}

#[derive(Debug)]
struct Edge {
    src: usize,
    weight: ProteinRegulator,
}

#[derive(Debug)]
pub struct Node {
    incoming_edges: Vec<Edge>,
}

impl Node {
    fn new() -> Node {
        Node { incoming_edges: Vec::new() }
    }

    pub fn sum_edges(&self, network_state: &GeneNetworkState) -> i32 {
        let mut sum = 0;
        for edge in self.incoming_edges.iter() {
            let factor = if network_state.state.contains(edge.src) {
                1
            } else {
                0
            };
            sum += factor * edge.weight.0;
        }

        return sum;
    }
}

#[derive(Debug)]
pub struct GeneNetwork {
    nodes: Vec<Node>,
}

#[derive(Debug, Clone)]
pub struct GeneNetworkState {
    pub state: FixedBitSet,
}

impl GeneNetwork {
    fn new(num_nodes: usize) -> GeneNetwork {
        assert!(num_nodes > 0);
        GeneNetwork { nodes: (0..num_nodes).map(|_| Node::new()).collect() }
    }

    pub fn nodes(&self) -> &[Node] {
        &self.nodes
    }

    fn add_edge(&mut self, src: usize, dst: usize, weight: ProteinRegulator) {
        assert!(src < self.nodes.len());
        assert!(dst < self.nodes.len());
        self.nodes[dst].incoming_edges.push(Edge {
            src: src,
            weight: weight,
        });
    }

    pub fn new_state(&self) -> GeneNetworkState {
        GeneNetworkState { state: FixedBitSet::with_capacity(self.nodes.len()) }
    }
}

// Convert genome into sections, i.e. Split at the promoter.
impl<B: Base> Genome<B> {
    pub fn iter_genes<'a, 'b>(&'a self,
                              promoter: &'b [B],
                              length_of_gene: usize)
                              -> GeneIterator<'a, 'b, B> {
        GeneIterator {
            length_of_gene: length_of_gene,
            sequence: &self.genome,
            promoter: promoter,
        }
    }

    // Construct a dependency network between the genes
    pub fn construct_network<F>(&self,
                                promoter: &[B],
                                length_of_gene: usize,
                                protein_regulation: &F)
                                -> GeneNetwork
        where F: Fn(&[B]) -> ProteinRegulator
    {
        let genes: Vec<_> = self.iter_genes(promoter, length_of_gene).collect();
        let num_genes = genes.len();

        // each gene is a node in the boolean network
        let mut network = GeneNetwork::new(num_genes);

        for (src, gene) in genes.iter().enumerate() {
            let product = gene.product();
            // A gene product either enhances (> 0) or inyhibits (< 0) the expression of
            // another gene.
            let regulator = protein_regulation(&product);

            // determine which other genes ```gene``` regulates
            for (dst, gene2) in genes.iter().enumerate() {
                // XXX: Can a gene regulate itself?
                // if src != dst {
                let factor = gene2.count_product_in_regulatory_region(&product);
                if factor > 0 {
                    network.add_edge(src, dst, ProteinRegulator(regulator.0 * factor as i32));
                }
                // }
            }
        }

        return network;
    }
}

impl<B: Base> FromStr for Genome<B> {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        FromStr::from_str(s).map(|bs| Genome { genome: bs })
    }
}
<commit_msg>derive Clone<commit_after>extern crate fixedbitset;
extern crate rand;

pub mod dna_base;
pub mod base4;
pub mod graph;

use std::str::FromStr;
use std::ops::Deref;
use std::fmt::{self, Debug};
use fixedbitset::FixedBitSet;
use rand::{Rng, Rand};

/// Represents the bases used in the genome string.
/// For example the bases of the DNA are adenine (A),
/// thymine (T), guanine (G) and cytosine (C).
pub trait Base: Sized + PartialEq + Eq + Copy + Clone + Debug + Rand {
    /// Returns the "successor" base, wrapping around. Used
    /// to produce the gene product.
    fn succ(self) -> Self;

    fn from_char(c: char) -> Option<Self>;
}

// Locate ```substr``` in ```s```.
fn locate_substr<T: Eq>(s: &[T], substr: &[T]) -> Option<usize> {
    assert!(substr.len() > 0);

    if s.len() < substr.len() {
        return None;
    }

    for (i, window) in s.windows(substr.len()).enumerate() {
        if window == substr {
            return Some(i);
        }
    }

    return None;
}

// Count occurrence of ```substr``` in ```s```.
fn count_substr<T: Eq>(s: &[T], substr: &[T]) -> usize {
    assert!(substr.len() > 0);

    let mut cnt = 0;
    for window in s.windows(substr.len()) {
        if window == substr {
            cnt += 1;
        }
    }

    return cnt;
}

#[derive(Debug)]
pub struct Gene<'a, B: Base + 'a> {
    pub regulatory_region: &'a [B],
    pub gene: &'a [B],
}

impl<'a, B: Base + 'a> Gene<'a, B> {
    /// The gene product
    pub fn product(&self) -> BaseString<B> {
        BaseString { v: self.gene.iter().map(|b| b.succ()).collect() }
    }

    pub fn find_product_in_regulatory_region(&self, product: &[B]) -> bool {
        locate_substr(self.regulatory_region, product).is_some()
    }
    pub fn count_product_in_regulatory_region(&self, product: &[B]) -> usize {
        count_substr(self.regulatory_region, product)
    }
}

pub struct GeneIterator<'a, 'b, B: Base + 'a + 'b> {
    // Genes have fixed length
    length_of_gene: usize,
    sequence: &'a [B],
    promoter: &'b [B],
}

impl<'a, 'b, B: Base + 'a + 'b> Iterator for GeneIterator<'a, 'b, B> {
    type Item = Gene<'a, B>;

    fn next(&mut self) -> Option<Self::Item> {
        match locate_substr(self.sequence, self.promoter) {
            Some(pos) => {
                let gene_start = pos + self.promoter.len();
                let gene_end = gene_start + self.length_of_gene;

                // gene is not complete
                if gene_end > self.sequence.len() {
                    return None;
                }

                let gene = Gene {
                    regulatory_region: &self.sequence[..pos],
                    gene: &self.sequence[gene_start..gene_end],
                };
                self.sequence = &self.sequence[gene_end..];
                return Some(gene);
            }
            None => {
                return None;
            }
        }
    }
}

// A positive value enhances, a negative inhibits the expression of a gene.
#[derive(Debug)]
pub struct ProteinRegulator(i32);

impl ProteinRegulator {
    pub fn enhance() -> ProteinRegulator {
        ProteinRegulator(1)
    }

    pub fn inhibit() -> ProteinRegulator {
        ProteinRegulator(-1)
    }
}

#[derive(Clone)]
pub struct BaseString<B: Base> {
    v: Vec<B>,
}

impl<B: Base> FromStr for BaseString<B> {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(BaseString { v: s.chars().filter_map(|c| B::from_char(c)).collect() })
    }
}

impl<B: Base> Deref for BaseString<B> {
    type Target = [B];

    fn deref(&self) -> &Self::Target {
        &self.v
    }
}

impl<B: Base> Debug for BaseString<B> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "["));
        for base in &self.v {
            try!(write!(f, "{:?}", base));
        }
        write!(f, "]")
    }
}

impl<B: Base> BaseString<B> {
    pub fn random<R: Rng>(rng: &mut R, n: usize) -> BaseString<B> {
        assert!(n > 0);
        BaseString { v: (0..n).map(|_| rng.gen()).collect() }
    }
}

/// A Genome is a string of Base
#[derive(Clone)]
pub struct Genome<B: Base> {
    genome: BaseString<B>,
}

impl<B: Base> Genome<B> {
    pub fn random<R: Rng>(rng: &mut R, n: usize) -> Genome<B> {
        Genome { genome: BaseString::random(rng, n) }
    }
}

#[derive(Debug)]
struct Edge {
    src: usize,
    weight: ProteinRegulator,
}

#[derive(Debug)]
pub struct Node {
    incoming_edges: Vec<Edge>,
}

impl Node {
    fn new() -> Node {
        Node { incoming_edges: Vec::new() }
    }

    pub fn sum_edges(&self, network_state: &GeneNetworkState) -> i32 {
        let mut sum = 0;
        for edge in self.incoming_edges.iter() {
            let factor = if network_state.state.contains(edge.src) {
                1
            } else {
                0
            };
            sum += factor * edge.weight.0;
        }

        return sum;
    }
}

#[derive(Debug)]
pub struct GeneNetwork {
    nodes: Vec<Node>,
}

#[derive(Debug, Clone)]
pub struct GeneNetworkState {
    pub state: FixedBitSet,
}

impl GeneNetwork {
    fn new(num_nodes: usize) -> GeneNetwork {
        assert!(num_nodes > 0);
        GeneNetwork { nodes: (0..num_nodes).map(|_| Node::new()).collect() }
    }

    pub fn nodes(&self) -> &[Node] {
        &self.nodes
    }

    fn add_edge(&mut self, src: usize, dst: usize, weight: ProteinRegulator) {
        assert!(src < self.nodes.len());
        assert!(dst < self.nodes.len());
        self.nodes[dst].incoming_edges.push(Edge {
            src: src,
            weight: weight,
        });
    }

    pub fn new_state(&self) -> GeneNetworkState {
        GeneNetworkState { state: FixedBitSet::with_capacity(self.nodes.len()) }
    }
}

// Convert genome into sections, i.e. Split at the promoter.
impl<B: Base> Genome<B> {
    pub fn iter_genes<'a, 'b>(&'a self,
                              promoter: &'b [B],
                              length_of_gene: usize)
                              -> GeneIterator<'a, 'b, B> {
        GeneIterator {
            length_of_gene: length_of_gene,
            sequence: &self.genome,
            promoter: promoter,
        }
    }

    // Construct a dependency network between the genes
    pub fn construct_network<F>(&self,
                                promoter: &[B],
                                length_of_gene: usize,
                                protein_regulation: &F)
                                -> GeneNetwork
        where F: Fn(&[B]) -> ProteinRegulator
    {
        let genes: Vec<_> = self.iter_genes(promoter, length_of_gene).collect();
        let num_genes = genes.len();

        // each gene is a node in the boolean network
        let mut network = GeneNetwork::new(num_genes);

        for (src, gene) in genes.iter().enumerate() {
            let product = gene.product();
            // A gene product either enhances (> 0) or inyhibits (< 0) the expression of
            // another gene.
            let regulator = protein_regulation(&product);

            // determine which other genes ```gene``` regulates
            for (dst, gene2) in genes.iter().enumerate() {
                // XXX: Can a gene regulate itself?
                // if src != dst {
                let factor = gene2.count_product_in_regulatory_region(&product);
                if factor > 0 {
                    network.add_edge(src, dst, ProteinRegulator(regulator.0 * factor as i32));
                }
                // }
            }
        }

        return network;
    }
}

impl<B: Base> FromStr for Genome<B> {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        FromStr::from_str(s).map(|bs| Genome { genome: bs })
    }
}
<|endoftext|>


<commit_before>//Until it's clear what the unstable things are replaced by
#![allow(unstable)]
#![allow(non_snake_case)]

#[macro_use] extern crate log;
extern crate "rustc-serialize" as rustc_serialize;
extern crate core;
extern crate hyper;
extern crate regex;

#[macro_use] pub mod macros;
mod common;
mod httpapi;
pub mod command;
pub mod error;
pub mod server;
pub mod response;

#[test]
fn it_works() {
}
<commit_msg>Make common public<commit_after>//Until it's clear what the unstable things are replaced by
#![allow(unstable)]
#![allow(non_snake_case)]

#[macro_use] extern crate log;
extern crate "rustc-serialize" as rustc_serialize;
extern crate core;
extern crate hyper;
extern crate regex;

#[macro_use] pub mod macros;
mod httpapi;
pub mod command;
pub mod common;
pub mod error;
pub mod server;
pub mod response;

#[test]
fn it_works() {
}
<|endoftext|>


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

#![crate_name="html5ever"]
#![crate_type="dylib"]

#![feature(macro_rules, phase, globs)]
#![deny(warnings)]
#![allow(unused_parens)]

// Don't implicitly pull in things from std::*
// This helps us make a C-friendly library.
#![no_std]

extern crate alloc;

#[phase(plugin, link)]
extern crate core;

#[cfg(not(for_c))]
#[phase(plugin, link)]
extern crate std;

#[cfg(for_c)]
extern crate libc;

#[phase(plugin, link)]
extern crate collections;

#[cfg(not(for_c))]
#[phase(plugin, link)]
extern crate log;

#[phase(plugin)]
extern crate phf_mac;

#[phase(plugin)]
extern crate string_cache_macros;
extern crate string_cache;

#[phase(plugin)]
extern crate html5ever_macros;

extern crate phf;

extern crate time;

pub use tokenizer::Attribute;
pub use driver::{one_input, ParseOpts, parse_to, parse};

#[cfg(not(for_c))]
pub use serialize::serialize;

mod macros;

mod util {
    #![macro_escape]

    pub mod str;
    pub mod smallcharset;
}

pub mod tokenizer;
pub mod tree_builder;

#[cfg(not(for_c))]
pub mod serialize;

/// Consumers of the parser API.
#[cfg(not(for_c))]
pub mod sink {
    pub mod common;
    pub mod rcdom;
    pub mod owned_dom;
}

pub mod driver;

#[cfg(for_c)]
pub mod for_c {
    pub mod common;
    pub mod tokenizer;
}

/// A fake `std` module so that `deriving` and other macros will work.
/// See rust-lang/rust#16803.
#[cfg(for_c)]
mod std {
    pub use core::{clone, cmp, default, fmt, option, str};
    pub use collections::hash;
}
<commit_msg>Use std even in for_c builds<commit_after>// Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![crate_name="html5ever"]
#![crate_type="dylib"]

#![feature(macro_rules, phase, globs)]
#![deny(warnings)]
#![allow(unused_parens)]

// Don't implicitly pull in things from std::*
// This helps us make a C-friendly library.
#![no_std]

extern crate alloc;

#[phase(plugin, link)]
extern crate core;

#[phase(plugin, link)]
extern crate std;

#[cfg(for_c)]
extern crate libc;

#[phase(plugin, link)]
extern crate collections;

#[cfg(not(for_c))]
#[phase(plugin, link)]
extern crate log;

#[phase(plugin)]
extern crate phf_mac;

#[phase(plugin)]
extern crate string_cache_macros;
extern crate string_cache;

#[phase(plugin)]
extern crate html5ever_macros;

extern crate phf;

extern crate time;

pub use tokenizer::Attribute;
pub use driver::{one_input, ParseOpts, parse_to, parse};

#[cfg(not(for_c))]
pub use serialize::serialize;

mod macros;

mod util {
    #![macro_escape]

    pub mod str;
    pub mod smallcharset;
}

pub mod tokenizer;
pub mod tree_builder;

#[cfg(not(for_c))]
pub mod serialize;

/// Consumers of the parser API.
#[cfg(not(for_c))]
pub mod sink {
    pub mod common;
    pub mod rcdom;
    pub mod owned_dom;
}

pub mod driver;

#[cfg(for_c)]
pub mod for_c {
    pub mod common;
    pub mod tokenizer;
}
<|endoftext|>


<commit_before>/*
  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

extern crate chrono;
extern crate rusqlite;
#[macro_use]
extern crate try_opt;

pub mod catalog;
pub mod collections;
pub mod content;
pub mod folders;
pub mod fromdb;
pub mod images;
pub mod keywords;
pub mod keywordtree;
pub mod libraryfiles;
pub mod lrobject;

pub use catalog::{Catalog,CatalogVersion};
pub use collections::Collection;
pub use content::Content;
pub use folders::{Folder,Folders,RootFolder};
pub use images::Image;
pub use keywords::Keyword;
pub use keywordtree::KeywordTree;
pub use libraryfiles::LibraryFile;
pub use lrobject::{LrObject,LrId};
<commit_msg>limit the re-exports<commit_after>/*
  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

extern crate chrono;
extern crate rusqlite;
#[macro_use]
extern crate try_opt;

mod catalog;
mod collections;
mod content;
mod folders;
mod fromdb;
mod images;
mod keywords;
mod keywordtree;
mod libraryfiles;
mod lrobject;

pub use catalog::{Catalog,CatalogVersion};
pub use collections::Collection;
pub use content::Content;
pub use folders::{Folder,Folders,RootFolder};
pub use images::Image;
pub use keywords::Keyword;
pub use keywordtree::KeywordTree;
pub use libraryfiles::LibraryFile;
pub use lrobject::{LrObject,LrId};
<|endoftext|>


<commit_before>#[macro_use]
extern crate lazy_static;
extern crate libc;
extern crate nix;
#[macro_use]
extern crate serde;
extern crate serde_json;
extern crate toml;

mod applog;
mod buffer;
mod connection;
mod cstructs;
mod error;
mod message;
mod statics;
mod structs;

use buffer::Buffer;
use connection::Connection;
use cstructs::{Group, Passwd, Spwd};
use message::{ClientMessage as CMsg, DaemonMessage as DMsg, Ent, Gr, Pw, Sp};
use nix::errno::Errno;
use std::ffi::CStr;
use std::process;
use std::string::String;

#[allow(dead_code)]
enum NssStatus {
    TryAgain,
    Unavail,
    NotFound,
    Success,
}

impl From<NssStatus> for libc::c_int {
    fn from(status: NssStatus) -> libc::c_int {
        match status {
            NssStatus::TryAgain => -2,
            NssStatus::Unavail => -1,
            NssStatus::NotFound => 0,
            NssStatus::Success => 1,
        }
    }
}

fn string_from(cstrptr: *const libc::c_char) -> String {
    let cstr: &CStr = unsafe { CStr::from_ptr(cstrptr) };
    String::from(cstr.to_str().unwrap_or(""))
}

macro_rules! succeed {
    () => {{
        log::debug!("Success!");
        return libc::c_int::from(NssStatus::Success);
    }};
}

macro_rules! fail {
    ($err_no_p:ident, $err_no:expr, $return_val:expr) => {{
        *$err_no_p = $err_no as libc::c_int;
        log::debug!("Faill!");
        return libc::c_int::from($return_val);
    }};
}

macro_rules! try_unwrap {
    ($getter:expr) => {{
        match $getter {
            Ok(ret) => {
                log::debug!("Ok: {:?}", ret);
                ret
            }
            Err(e) => {
                log::debug!("failed (will retry): {:?}", e);
                return libc::c_int::from(NssStatus::TryAgain);
            }
        }
    }};
    ($getter:expr, $err_no_p:ident) => {{
        match $getter {
            Ok(ret) => ret,
            Err(e) => {
                log::debug!("failed (will retry): {:?}", e);
                *$err_no_p = Errno::EAGAIN as libc::c_int;
                return libc::c_int::from(NssStatus::TryAgain);
            }
        }
    }};
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getpwnam_r(cnameptr: *const libc::c_char, pwptr: *mut Passwd,
                                                 buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getpwnam_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Nam(string_from(cnameptr)))), errnop);
    if let DMsg::Pw { login,
                      uid,
                      gid,
                      home,
                      sh, } = msg
    {
        match { (*pwptr).pack_args(&mut buffer, &login, uid, gid, &home, &sh) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getpwuid_r(uid: libc::uid_t, pwptr: *mut Passwd, buf: *mut libc::c_char,
                                                 buflen: libc::size_t, errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getpwuid_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Uid(uid as u64))), errnop);
    if let DMsg::Pw { login,
                      uid,
                      gid,
                      home,
                      sh, } = msg
    {
        match { (*pwptr).pack_args(&mut buffer, &login, uid, gid, &home, &sh) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_setpwent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_setpwent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Ent(Ent::Set(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::TryAgain)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getpwent_r(pwptr: *mut Passwd, buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getpwent_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Ent(Ent::Get(process::id())))), errnop);
    if let DMsg::Pw { login,
                      uid,
                      gid,
                      home,
                      sh, } = msg
    {
        match { (*pwptr).pack_args(&mut buffer, &login, uid, gid, &home, &sh) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_endpwent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_endpwent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Ent(Ent::End(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::TryAgain)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getspnam_r(cnameptr: *const libc::c_char, spptr: *mut Spwd,
                                                 buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getspnam_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Sp(Sp::Nam(string_from(cnameptr)))), errnop);
    if let DMsg::Sp { login, pass } = msg {
        match { (*spptr).pack_args(&mut buffer, &login, &pass) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_setspent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_setspent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Sp(Sp::Ent(Ent::Set(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::Success)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getspent_r(spptr: *mut Spwd, buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getspent_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Sp(Sp::Ent(Ent::Get(process::id())))), errnop);
    if let DMsg::Sp { login, pass } = msg {
        match { (*spptr).pack_args(&mut buffer, &login, &pass) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_endspent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_endspent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Sp(Sp::Ent(Ent::End(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::TryAgain)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getgrgid_r(gid: libc::gid_t, grptr: *mut Group, buf: *mut libc::c_char,
                                                 buflen: libc::size_t, errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getgrgid_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Gid(gid as u64))), errnop);
    if let DMsg::Gr { sector } = msg {
        let members: Vec<&str> = sector.members.values().map(|m| m.login.as_str()).collect();
        match { (*grptr).pack_args(&mut buffer, &sector.get_group(), u64::from(gid), &members) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getgrnam_r(cnameptr: *const libc::c_char, grptr: *mut Group,
                                                 buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getgrnam_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Nam(string_from(cnameptr)))), errnop);
    if let DMsg::Gr { sector } = msg {
        let members: Vec<&str> = sector.members.values().map(|m| m.login.as_str()).collect();
        match { (*grptr).pack_args(&mut buffer, &sector.get_group(), sector.get_gid(), &members) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_setgrent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_setgrent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Ent(Ent::Set(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::Success)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getgrent_r(grptr: *mut Group, buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getgrent_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Ent(Ent::Get(process::id())))), errnop);
    if let DMsg::Gr { sector } = msg {
        let members: Vec<&str> = sector.members.values().map(|m| m.login.as_str()).collect();
        match { (*grptr).pack_args(&mut buffer, &sector.get_group(), sector.get_gid(), &members) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_endgrent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_endgrent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Ent(Ent::End(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::TryAgain)
}
<commit_msg>Remove an unused extern crate<commit_after>#[macro_use]
extern crate lazy_static;
extern crate libc;
extern crate nix;
#[macro_use]
extern crate serde;
extern crate serde_json;

mod applog;
mod buffer;
mod connection;
mod cstructs;
mod error;
mod message;
mod statics;
mod structs;

use buffer::Buffer;
use connection::Connection;
use cstructs::{Group, Passwd, Spwd};
use message::{ClientMessage as CMsg, DaemonMessage as DMsg, Ent, Gr, Pw, Sp};
use nix::errno::Errno;
use std::ffi::CStr;
use std::process;
use std::string::String;

#[allow(dead_code)]
enum NssStatus {
    TryAgain,
    Unavail,
    NotFound,
    Success,
}

impl From<NssStatus> for libc::c_int {
    fn from(status: NssStatus) -> libc::c_int {
        match status {
            NssStatus::TryAgain => -2,
            NssStatus::Unavail => -1,
            NssStatus::NotFound => 0,
            NssStatus::Success => 1,
        }
    }
}

fn string_from(cstrptr: *const libc::c_char) -> String {
    let cstr: &CStr = unsafe { CStr::from_ptr(cstrptr) };
    String::from(cstr.to_str().unwrap_or(""))
}

macro_rules! succeed {
    () => {{
        log::debug!("Success!");
        return libc::c_int::from(NssStatus::Success);
    }};
}

macro_rules! fail {
    ($err_no_p:ident, $err_no:expr, $return_val:expr) => {{
        *$err_no_p = $err_no as libc::c_int;
        log::debug!("Faill!");
        return libc::c_int::from($return_val);
    }};
}

macro_rules! try_unwrap {
    ($getter:expr) => {{
        match $getter {
            Ok(ret) => {
                log::debug!("Ok: {:?}", ret);
                ret
            }
            Err(e) => {
                log::debug!("failed (will retry): {:?}", e);
                return libc::c_int::from(NssStatus::TryAgain);
            }
        }
    }};
    ($getter:expr, $err_no_p:ident) => {{
        match $getter {
            Ok(ret) => ret,
            Err(e) => {
                log::debug!("failed (will retry): {:?}", e);
                *$err_no_p = Errno::EAGAIN as libc::c_int;
                return libc::c_int::from(NssStatus::TryAgain);
            }
        }
    }};
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getpwnam_r(cnameptr: *const libc::c_char, pwptr: *mut Passwd,
                                                 buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getpwnam_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Nam(string_from(cnameptr)))), errnop);
    if let DMsg::Pw { login,
                      uid,
                      gid,
                      home,
                      sh, } = msg
    {
        match { (*pwptr).pack_args(&mut buffer, &login, uid, gid, &home, &sh) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getpwuid_r(uid: libc::uid_t, pwptr: *mut Passwd, buf: *mut libc::c_char,
                                                 buflen: libc::size_t, errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getpwuid_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Uid(uid as u64))), errnop);
    if let DMsg::Pw { login,
                      uid,
                      gid,
                      home,
                      sh, } = msg
    {
        match { (*pwptr).pack_args(&mut buffer, &login, uid, gid, &home, &sh) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_setpwent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_setpwent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Ent(Ent::Set(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::TryAgain)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getpwent_r(pwptr: *mut Passwd, buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getpwent_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Ent(Ent::Get(process::id())))), errnop);
    if let DMsg::Pw { login,
                      uid,
                      gid,
                      home,
                      sh, } = msg
    {
        match { (*pwptr).pack_args(&mut buffer, &login, uid, gid, &home, &sh) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_endpwent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_endpwent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Pw(Pw::Ent(Ent::End(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::TryAgain)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getspnam_r(cnameptr: *const libc::c_char, spptr: *mut Spwd,
                                                 buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getspnam_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Sp(Sp::Nam(string_from(cnameptr)))), errnop);
    if let DMsg::Sp { login, pass } = msg {
        match { (*spptr).pack_args(&mut buffer, &login, &pass) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_setspent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_setspent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Sp(Sp::Ent(Ent::Set(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::Success)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getspent_r(spptr: *mut Spwd, buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getspent_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Sp(Sp::Ent(Ent::Get(process::id())))), errnop);
    if let DMsg::Sp { login, pass } = msg {
        match { (*spptr).pack_args(&mut buffer, &login, &pass) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_endspent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_endspent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Sp(Sp::Ent(Ent::End(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::TryAgain)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getgrgid_r(gid: libc::gid_t, grptr: *mut Group, buf: *mut libc::c_char,
                                                 buflen: libc::size_t, errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getgrgid_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Gid(gid as u64))), errnop);
    if let DMsg::Gr { sector } = msg {
        let members: Vec<&str> = sector.members.values().map(|m| m.login.as_str()).collect();
        match { (*grptr).pack_args(&mut buffer, &sector.get_group(), u64::from(gid), &members) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getgrnam_r(cnameptr: *const libc::c_char, grptr: *mut Group,
                                                 buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getgrnam_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Nam(string_from(cnameptr)))), errnop);
    if let DMsg::Gr { sector } = msg {
        let members: Vec<&str> = sector.members.values().map(|m| m.login.as_str()).collect();
        match { (*grptr).pack_args(&mut buffer, &sector.get_group(), sector.get_gid(), &members) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_setgrent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_setgrent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Ent(Ent::Set(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::Success)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_getgrent_r(grptr: *mut Group, buf: *mut libc::c_char, buflen: libc::size_t,
                                                 errnop: *mut libc::c_int)
                                                 -> libc::c_int {
    let mut buffer = Buffer::new(buf, buflen);
    let conn = try_unwrap!(Connection::new("_nss_sectora_getgrent_r"), errnop);
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Ent(Ent::Get(process::id())))), errnop);
    if let DMsg::Gr { sector } = msg {
        let members: Vec<&str> = sector.members.values().map(|m| m.login.as_str()).collect();
        match { (*grptr).pack_args(&mut buffer, &sector.get_group(), sector.get_gid(), &members) } {
            Ok(_) => succeed!(),
            Err(_) => fail!(errnop, Errno::ERANGE, NssStatus::TryAgain),
        }
    }
    fail!(errnop, Errno::ENOENT, NssStatus::NotFound)
}

#[no_mangle]
pub unsafe extern "C" fn _nss_sectora_endgrent() -> libc::c_int {
    let conn = try_unwrap!(Connection::new("_nss_sectora_endgrent"));
    let msg = try_unwrap!(conn.communicate(CMsg::Gr(Gr::Ent(Ent::End(process::id())))));
    if let DMsg::Success = msg {
        return libc::c_int::from(NssStatus::Success);
    }
    libc::c_int::from(NssStatus::TryAgain)
}
<|endoftext|>


<commit_before>// This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013-2015  Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#![crate_name = "grust"]
#![crate_type = "lib"]

#![allow(unstable_features)]

#![feature(alloc)]
#![feature(core)]
#![feature(unsafe_no_drop_flag)]

extern crate libc;
extern crate glib_2_0_sys as glib;
extern crate gobject_2_0_sys as gobject;

#[macro_use]
mod macros;

pub mod boxed;
pub mod enumeration;
pub mod error;
pub mod flags;
pub mod gstr;
pub mod gtype;
pub mod mainloop;
pub mod object;
pub mod quark;
pub mod refcount;
pub mod types;
pub mod util;
pub mod value;
pub mod wrap;
<commit_msg>Massacre of the unstable features<commit_after>// This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013-2015  Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#![crate_name = "grust"]
#![crate_type = "lib"]

extern crate libc;
extern crate glib_2_0_sys as glib;
extern crate gobject_2_0_sys as gobject;

#[macro_use]
mod macros;

pub mod boxed;
pub mod enumeration;
pub mod error;
pub mod flags;
pub mod gstr;
pub mod gtype;
pub mod mainloop;
pub mod object;
pub mod quark;
pub mod refcount;
pub mod types;
pub mod util;
pub mod value;
pub mod wrap;
<|endoftext|>


<commit_before>//! Sqlite support for the `r2d2` connection pool.
extern crate r2d2;
extern crate rusqlite;

use std::error::{self, Error as StdError};
use std::fmt;
use std::convert;

use rusqlite::{Connection, Error as RusqliteError, OpenFlags};

#[derive(Debug)]
pub enum Error {
    Connect(RusqliteError),
}

impl convert::From<RusqliteError> for Error {
    fn from(e: RusqliteError) -> Error {
        Error::Connect(e)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}: {}", self.description(), self.cause().unwrap())
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Connect(_) => "Error opening a connection",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::Connect(ref err) => Some(err as &error::Error),
        }
    }
}

enum ConnectionConfig {
    InMemory(OpenFlags),
    File(String, OpenFlags),
}

pub struct SqliteConnectionManager {
    config: ConnectionConfig,
}

impl SqliteConnectionManager {
    pub fn new(database: &str) -> Self {
        Self::new_with_flags(database, OpenFlags::default())
    }

    pub fn new_with_flags(database: &str, flags: OpenFlags) -> Self {
        SqliteConnectionManager { config: ConnectionConfig::File(database.to_string(), flags) }
    }

    pub fn new_in_memory() -> Self {
        Self::new_in_memory_with_flags(OpenFlags::default())
    }

    pub fn new_in_memory_with_flags(flags: OpenFlags) -> Self {
        SqliteConnectionManager { config: ConnectionConfig::InMemory(flags) }
    }
}

impl r2d2::ManageConnection for SqliteConnectionManager {
    type Connection = Connection;
    type Error = Error;

    fn connect(&self) -> Result<Connection, Error> {
        match self.config {
                ConnectionConfig::InMemory(flags) => Connection::open_in_memory_with_flags(flags),
                ConnectionConfig::File(ref path, flags) => Connection::open_with_flags(path, flags),
            }
            .map_err(Into::into)
    }

    fn is_valid(&self, conn: &mut Connection) -> Result<(), Error> {
        conn.execute_batch("").map_err(Into::into)
    }

    fn has_broken(&self, _: &mut Connection) -> bool {
        false
    }
}
<commit_msg>Update documentation<commit_after>//! # Sqlite support for the `r2d2` connection pool.
//!
//! Library crate: [r2d2-sqlite](https://crates.io/crates/r2d2-sqlite/)
//!
//! Integrated with: [r2d2](https://crates.io/crates/r2d2)
//! and [rusqlite](https://crates.io/crates/rusqlite)
//!
//! ## Example
//!
//! ```rust,no_run
//! extern crate r2d2;
//! extern crate r2d2_sqlite;
//! extern crate rusqlite;
//!
//! use std::thread;
//! use r2d2_sqlite::SqliteConnectionManager;
//!
//! fn main() {
//!     let config = r2d2::Config::default();
//!     let manager = SqliteConnectionManager::new_in_memory();
//!     let pool = r2d2::Pool::new(config, manager).unwrap();
//!
//!     for i in 0..10i32 {
//!         let pool = pool.clone();
//!         thread::spawn(move || {
//!             let conn = pool.get().unwrap();
//!             conn.execute("INSERT INTO foo (bar) VALUES ($1)", &[&i]).unwrap();
//!         });
//!     }
//! }
//! ```
extern crate r2d2;
extern crate rusqlite;

use std::error::{self, Error as StdError};
use std::fmt;
use std::convert;

use rusqlite::{Connection, Error as RusqliteError, OpenFlags};

/// A unified enum of errors returned by `rusqlite::Connection`
#[derive(Debug)]
pub enum Error {
    Connect(RusqliteError),
}

impl convert::From<RusqliteError> for Error {
    fn from(e: RusqliteError) -> Error {
        Error::Connect(e)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}: {}", self.description(), self.cause().unwrap())
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Connect(_) => "Error opening a connection",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::Connect(ref err) => Some(err as &error::Error),
        }
    }
}

enum ConnectionConfig {
    InMemory(OpenFlags),
    File(String, OpenFlags),
}

/// An `r2d2::ManageConnection` for `rusqlite::Connection`s.
pub struct SqliteConnectionManager {
    config: ConnectionConfig,
}

impl SqliteConnectionManager {
    /// Creates a new `SqliteConnectionManager` from file.
    ///
    /// See `rusqlite::Connection::open`
    pub fn new(database: &str) -> Self {
        Self::new_with_flags(database, OpenFlags::default())
    }

    /// Creates a new `SqliteConnectionManager` from file with open flags.
    ///
    /// See `rusqlite::Connection::open_with_flags`
    pub fn new_with_flags(database: &str, flags: OpenFlags) -> Self {
        SqliteConnectionManager { config: ConnectionConfig::File(database.to_string(), flags) }
    }

    /// Creates a new `SqliteConnectionManager` in memory.
    ///
    /// See `rusqlite::Connection::open_in_memory`
    pub fn new_in_memory() -> Self {
        Self::new_in_memory_with_flags(OpenFlags::default())
    }

    /// Creates a new `SqliteConnectionManager` in memory with open flags.
    ///
    /// See `rusqlite::Connection::open_in_memory_with_flags`
    pub fn new_in_memory_with_flags(flags: OpenFlags) -> Self {
        SqliteConnectionManager { config: ConnectionConfig::InMemory(flags) }
    }
}

impl r2d2::ManageConnection for SqliteConnectionManager {
    type Connection = Connection;
    type Error = Error;

    fn connect(&self) -> Result<Connection, Error> {
        match self.config {
                ConnectionConfig::InMemory(flags) => Connection::open_in_memory_with_flags(flags),
                ConnectionConfig::File(ref path, flags) => Connection::open_with_flags(path, flags),
            }
            .map_err(Into::into)
    }

    fn is_valid(&self, conn: &mut Connection) -> Result<(), Error> {
        conn.execute_batch("").map_err(Into::into)
    }

    fn has_broken(&self, _: &mut Connection) -> bool {
        false
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// This Source Code Form is subject to the
// terms of the Mozilla Public License, v.
// 2.0. If a copy of the MPL was not
// distributed with this file, You can
// obtain one at
// http://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible
// With Secondary Licenses", as defined by
// the Mozilla Public License, v. 2.0.

#![allow(dead_code)]

#[macro_use]
extern crate log;
extern crate fern;
extern crate time;
extern crate libc;
extern crate rand;
extern crate simple_stream;
extern crate num_cpus;
#[cfg(target_os = "linux")]
extern crate epoll;

pub mod client;
#[cfg(target_os = "linux")]
pub mod server;

/// Initializes all the global things
pub fn init() {
    let _ = fern::init_global_logger(fern::DispatchConfig {
        format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
            format!("[{}][{}] {}", time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(), level, msg)
        }),
        output: vec![fern::OutputConfig::stdout(), fern::OutputConfig::file("/var/log/hydrogen.log")],
        level: log::LogLevelFilter::Trace,
    }, log::LogLevelFilter::Trace);
    trace!("Logging test :)");
}
<commit_msg>Debugging<commit_after>// Copyright 2015 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// This Source Code Form is subject to the
// terms of the Mozilla Public License, v.
// 2.0. If a copy of the MPL was not
// distributed with this file, You can
// obtain one at
// http://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible
// With Secondary Licenses", as defined by
// the Mozilla Public License, v. 2.0.

#![allow(dead_code)]

#[macro_use]
extern crate log;
extern crate fern;
extern crate time;
extern crate libc;
extern crate rand;
extern crate simple_stream;
extern crate num_cpus;
#[cfg(target_os = "linux")]
extern crate epoll;

pub mod client;
#[cfg(target_os = "linux")]
pub mod server;

/// Initializes all the global things
pub fn init() {
    let _ = fern::init_global_logger(fern::DispatchConfig {
        format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
            format!("[{}][{}] {}", time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(), level, msg)
        }),
        output: vec![fern::OutputConfig::stdout(), fern::OutputConfig::file("/var/log/hydrogen.log")],
        level: log::LogLevelFilter::Trace,
    }, log::LogLevelFilter::Trace);
    trace!("Logger initialized :)");
}
<|endoftext|>


<commit_before>/*!

*/

//! TypeDef is used to identify and compare types, as well as print their names.
//!
//! If you do not need readable type name, you should use `TypeId`. This
//! wrapper re-implements `TypeId`.
//!
//! To get a name of a type:
//!
//! ```
//! use typedef::{ TypeDef };
//!
//! assert_eq!(TypeDef::name_of::<i64>(), "i64");
//! ```
//!
//! Type can also serve as type identifier and name container:
//!
//! ```
//! use typedef::{ TypeDef };
//!
//! let typedef = TypeDef::of::<i64>();
//!
//! assert!(typedef.is::<i64>());
//! assert_eq!(typedef.get_str(), "i64");
//! ```
//!
//! More common usage would be in a generic method:
//!
//! ```
//! use std::fmt::{ Show };
//! use typedef::{ TypeDef };
//!
//! fn foo<T: 'static + Show>(value: T) -> String {
//!     format!(
//!         "the value of {:?} type is {:?}",
//!         TypeDef::of::<T>(),
//!         value
//!     )
//! }
//!
//! fn main() {
//!     assert_eq!(foo(15), "the value of i32 type is 15i32");
//! }
//! ```

use std::any::TypeId;
use std::intrinsics::get_tydesc;
use std::fmt;

/// Create a TypeDef structure to identify a type and to print its name.
///
/// ```
/// use typedef::{ TypeDef };
///
/// let typedef = TypeDef::of::<i64>();
///
/// assert!(typedef.is::<i64>());
/// assert!(typedef.get_str() == "i64");
/// ```
#[stable]
#[derive(Clone, Copy)]
pub struct TypeDef {
    type_id: TypeId,
    type_name: &'static str,
}

#[stable]
impl TypeDef {
    /// Create a TypeDef structure from a type parameter.
    ///
    /// ```
    /// use typedef::{ TypeDef };
    ///
    /// let typedef = TypeDef::of::<i64>();
    /// ```
    #[stable]
    pub fn of<T: 'static>() -> TypeDef {
        TypeDef {
            type_id: TypeId::of::<T>(),
            type_name: unsafe { (*get_tydesc::<T>()).name },
        }
    }

    /// Get `TypeId` for specified type directly.
    ///
    /// ```
    /// use std::any::{ TypeId };
    /// use typedef::{ TypeDef };
    ///
    /// assert!(TypeDef::id_of::<i64>() == TypeId::of::<i64>());
    /// ```
    #[stable]
    pub fn id_of<T: 'static>() -> TypeId {
        TypeId::of::<T>()
    }

    /// Get type name for specified type directly.
    ///
    /// ```
    /// use typedef::{ TypeDef };
    ///
    /// assert_eq!(TypeDef::name_of::<i64>(), "i64");
    /// ```
    #[stable]
    pub fn name_of<T: 'static>() -> &'static str {
        unsafe { (*get_tydesc::<T>()).name }
    }

    /// Check if typedef instance matches type.
    ///
    /// ```
    /// use typedef::{ TypeDef };
    ///
    /// let typedef = TypeDef::of::<i64>();
    ///
    /// assert!(typedef.is::<i64>());
    /// ```
    #[stable]
    pub fn is<T: 'static>(&self) -> bool {
        self.type_id == TypeId::of::<T>()
    }

    /// Get the static `&str` for typedef instance.
    ///
    /// ```
    /// use typedef::{ TypeDef };
    ///
    /// let typedef = TypeDef::of::<i64>();
    ///
    /// assert!(typedef.get_str() == "i64");
    /// ```
    #[stable]
    pub fn get_str(&self) -> &'static str {
        self.type_name
    }
}

#[stable]
impl PartialEq for TypeDef {
    #[stable]
    fn eq(&self, other: &TypeDef) -> bool {
        self.type_id == other.type_id
    }
}

#[stable]
impl fmt::Show for TypeDef {
    #[stable]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.type_name)
    }
}

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

    #[test]
    fn should_match_type() {
        assert!(TypeDef::of::<i16>().is::<i16>());
    }

    #[test]
    #[should_fail]
    fn should_not_match_incorrect_type() {
        assert!(TypeDef::of::<i16>().is::<i32>());
    }

    #[test]
    fn should_return_type_name() {
        assert_eq!(TypeDef::of::<i16>().get_str(), "i16");
        assert_eq!(TypeDef::of::<i64>().get_str(), "i64");
    }

    #[test]
    fn should_be_equal_to_another_typedef_of_the_same_type() {
        assert_eq!(TypeDef::of::<i16>(), TypeDef::of::<i16>());
    }

    #[test]
    fn should_not_be_equal_to_another_typedef_of_different_type() {
        assert!(TypeDef::of::<i16>() != TypeDef::of::<i32>());
    }
}
<commit_msg>Allow unstable.<commit_after>/*!

*/

#![allow(unstable)]

//! TypeDef is used to identify and compare types, as well as print their names.
//!
//! If you do not need readable type name, you should use `TypeId`. This
//! wrapper re-implements `TypeId`.
//!
//! To get a name of a type:
//!
//! ```
//! use typedef::{ TypeDef };
//!
//! assert_eq!(TypeDef::name_of::<i64>(), "i64");
//! ```
//!
//! Type can also serve as type identifier and name container:
//!
//! ```
//! use typedef::{ TypeDef };
//!
//! let typedef = TypeDef::of::<i64>();
//!
//! assert!(typedef.is::<i64>());
//! assert_eq!(typedef.get_str(), "i64");
//! ```
//!
//! More common usage would be in a generic method:
//!
//! ```
//! use std::fmt::{ Show };
//! use typedef::{ TypeDef };
//!
//! fn foo<T: 'static + Show>(value: T) -> String {
//!     format!(
//!         "the value of {:?} type is {:?}",
//!         TypeDef::of::<T>(),
//!         value
//!     )
//! }
//!
//! fn main() {
//!     assert_eq!(foo(15), "the value of i32 type is 15i32");
//! }
//! ```

use std::any::TypeId;
use std::intrinsics::get_tydesc;
use std::fmt;

/// Create a TypeDef structure to identify a type and to print its name.
///
/// ```
/// use typedef::{ TypeDef };
///
/// let typedef = TypeDef::of::<i64>();
///
/// assert!(typedef.is::<i64>());
/// assert!(typedef.get_str() == "i64");
/// ```
#[stable]
#[derive(Clone, Copy)]
pub struct TypeDef {
    type_id: TypeId,
    type_name: &'static str,
}

#[stable]
impl TypeDef {
    /// Create a TypeDef structure from a type parameter.
    ///
    /// ```
    /// use typedef::{ TypeDef };
    ///
    /// let typedef = TypeDef::of::<i64>();
    /// ```
    #[stable]
    pub fn of<T: 'static>() -> TypeDef {
        TypeDef {
            type_id: TypeId::of::<T>(),
            type_name: unsafe { (*get_tydesc::<T>()).name },
        }
    }

    /// Get `TypeId` for specified type directly.
    ///
    /// ```
    /// use std::any::{ TypeId };
    /// use typedef::{ TypeDef };
    ///
    /// assert!(TypeDef::id_of::<i64>() == TypeId::of::<i64>());
    /// ```
    #[stable]
    pub fn id_of<T: 'static>() -> TypeId {
        TypeId::of::<T>()
    }

    /// Get type name for specified type directly.
    ///
    /// ```
    /// use typedef::{ TypeDef };
    ///
    /// assert_eq!(TypeDef::name_of::<i64>(), "i64");
    /// ```
    #[stable]
    pub fn name_of<T: 'static>() -> &'static str {
        unsafe { (*get_tydesc::<T>()).name }
    }

    /// Check if typedef instance matches type.
    ///
    /// ```
    /// use typedef::{ TypeDef };
    ///
    /// let typedef = TypeDef::of::<i64>();
    ///
    /// assert!(typedef.is::<i64>());
    /// ```
    #[stable]
    pub fn is<T: 'static>(&self) -> bool {
        self.type_id == TypeId::of::<T>()
    }

    /// Get the static `&str` for typedef instance.
    ///
    /// ```
    /// use typedef::{ TypeDef };
    ///
    /// let typedef = TypeDef::of::<i64>();
    ///
    /// assert!(typedef.get_str() == "i64");
    /// ```
    #[stable]
    pub fn get_str(&self) -> &'static str {
        self.type_name
    }
}

#[stable]
impl PartialEq for TypeDef {
    #[stable]
    fn eq(&self, other: &TypeDef) -> bool {
        self.type_id == other.type_id
    }
}

#[stable]
impl fmt::Show for TypeDef {
    #[stable]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.type_name)
    }
}

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

    #[test]
    fn should_match_type() {
        assert!(TypeDef::of::<i16>().is::<i16>());
    }

    #[test]
    #[should_fail]
    fn should_not_match_incorrect_type() {
        assert!(TypeDef::of::<i16>().is::<i32>());
    }

    #[test]
    fn should_return_type_name() {
        assert_eq!(TypeDef::of::<i16>().get_str(), "i16");
        assert_eq!(TypeDef::of::<i64>().get_str(), "i64");
    }

    #[test]
    fn should_be_equal_to_another_typedef_of_the_same_type() {
        assert_eq!(TypeDef::of::<i16>(), TypeDef::of::<i16>());
    }

    #[test]
    fn should_not_be_equal_to_another_typedef_of_different_type() {
        assert!(TypeDef::of::<i16>() != TypeDef::of::<i32>());
    }
}
<|endoftext|>


<commit_before>extern crate cards;

use cards::card::{Card};

pub enum CardSlot {
    Empty,
    Card,
}

pub enum HandRankClass {
    HighCard,
    OnePair,
    TwoPair,
    ThreeOfAKind,
    Straight,
    Flush,
    FullHouse,
    FourOfAKind,
    StraightFlush,
}

pub struct HandCards(pub CardSlot, pub CardSlot);
pub struct CommunityCards(pub CardSlot, pub CardSlot, pub CardSlot, pub CardSlot, pub CardSlot);
//TODO: unwrap to go from cardSlot to card or panic?
<commit_msg>Futile attempts to borrow from something option-like<commit_after>extern crate cards;

use cards::card::{Card};

pub type CardSlot = Option<Card>;

/*
pub enum CardSlot { //TODO: this could be an option as well?
    Empty,
    Card, //TODO: this is not working as expected
}
*/

/*
impl CardSlot {
    pub fn expect_borrow(&self) -> &Card {
        match self {
            &CardSlot::Empty => panic!("You are trying to borrow a non-dealt card"),
            x @ &CardSlot::Card => x
        }
    }
}
*/

/*
pub fn expectCard<'a>(cs: CardSlot) -> &'a Card {
    match cs {
        None => panic!("You are trying to borrow a non-dealt card"),
        Some(ref x) => x
    }
}
*/

pub enum HandRankClass {
    HighCard,
    OnePair,
    TwoPair,
    ThreeOfAKind,
    Straight,
    Flush,
    FullHouse,
    FourOfAKind,
    StraightFlush,
}

pub struct HandCards(pub CardSlot, pub CardSlot);
pub struct CommunityCards(pub CardSlot, pub CardSlot, pub CardSlot, pub CardSlot, pub CardSlot);
//TODO: unwrap to go from cardSlot to card or panic?
<|endoftext|>


<commit_before>#[macro_use]
extern crate nom;
use std::ffi::CStr;
use std::os::raw::c_char;

use nom::{le_u64,le_u32,le_i32};
use nom::IResult;

// These are all integer_t, aka int
#[allow(non_camel_case_types)]
pub type cpu_type_t = i32;
#[allow(non_camel_case_types)]
pub type cpu_subtype_t = i32;
#[allow(non_camel_case_types)]
pub type vm_prot_t = i32;

#[derive(Debug)]
pub struct MachHeader {
    pub header: MachHeader_,
    pub segments: Vec<SegmentCommand>,
}

#[derive(Debug)]
pub struct MachHeader_ {
    pub magic: u32,
    pub cputype: cpu_type_t,
    pub cpusubtype: cpu_subtype_t,
    pub filetype: u32,
    pub ncmds: u32,
    pub sizeofcmds: u32,
    pub flags: u32,
    reserved :u32,
}

impl MachHeader {
    pub fn parse(bytes: &[u8]) -> Option<MachHeader> {
        if let IResult::Done(_rest, header) = mach_header(bytes) {
            let mut rest = _rest;
            let mut segments = vec![];
            for _ in 0.. header.ncmds {
                if let IResult::Done(_rest, cmd) = segment_command(rest) {
                    rest = _rest;
                    segments.push(cmd);
                } else {
                    return None
                }
            }

            Some(MachHeader {
                header: header,
                segments: segments,
            })
        } else {
            return None
        }
    }
}

#[derive(Debug)]
pub struct SegmentCommand {
    pub cmd: u32,
    pub cmdsize: u32,
    pub segname: String,
    pub vmaddr: u32,
    pub vmsize: u32,
    pub fileoff: u32,
    pub filesize: u32,
    pub maxprot: vm_prot_t,
    pub initprot: vm_prot_t,
    pub nsects: u32,
    pub flags: u32,
}

named!(mach_header<&[u8], MachHeader_>,
       chain!(
           magic: le_u32 ~
           cputype: le_i32 ~
           cpusubtype: le_i32 ~
           filetype: le_u32 ~
           ncmds: le_u32 ~
           sizeofcmds: le_u32 ~
           flags: le_u32 ~
           reserved: le_u32,

           || {
               assert_eq!(0xfeedfacf, magic);
               MachHeader_ {
                   magic: magic,
                   cputype: cputype,
                   cpusubtype: cpusubtype,
                   filetype: filetype,
                   ncmds: ncmds,
                   sizeofcmds: sizeofcmds,
                   flags: flags,
                   reserved: reserved,
               }
           }
           )
       );

named!(segment_command<&[u8], SegmentCommand>,
       chain!(
           cmd: le_u32 ~
           cmdsize: le_u32 ~
           segname: take!(16) ~
           vmaddr: le_u32 ~
           vmsize: le_u32 ~
           fileoff: le_u32 ~
           filesize: le_u32 ~
           maxprot: le_i32 ~
           initprot: le_i32 ~
           nsects: le_u32 ~
           flags: le_u32 ,

           || {

               let slice = unsafe { CStr::from_ptr(segname.as_ptr() as *const c_char) };
               let name = std::str::from_utf8(slice.to_bytes()).unwrap().to_string();

               SegmentCommand {
                   cmd: cmd,
                   cmdsize: cmdsize,
                   segname: name,
                   vmaddr: vmaddr,
                   vmsize: vmsize,
                   fileoff: fileoff,
                   filesize: filesize,
                   maxprot: maxprot,
                   initprot: initprot,
                   nsects: nsects,
                   flags: flags,
               }
           }
        )
    );

<commit_msg>Quirks<commit_after>#[macro_use]
extern crate nom;
use std::ffi::CStr;
use std::os::raw::c_char;

use nom::{le_u64,le_u32,le_i32};
use nom::IResult;

// These are all integer_t, aka int
#[allow(non_camel_case_types)]
pub type cpu_type_t = i32;
#[allow(non_camel_case_types)]
pub type cpu_subtype_t = u32;
#[allow(non_camel_case_types)]
pub type vm_prot_t = i32;

#[derive(Debug)]
pub struct MachHeader {
    pub header: MachHeader_,
    pub segments: Vec<SegmentCommand>,
}

#[derive(Debug)]
pub struct MachHeader_ {
    pub magic: u32,
    pub cputype: cpu_type_t,
    pub cpusubtype: cpu_subtype_t,
    pub filetype: u32,
    pub ncmds: u32,
    pub sizeofcmds: u32,
    pub flags: u32,
    reserved :u32,
}

impl MachHeader {
    pub fn parse(bytes: &[u8]) -> Option<MachHeader> {
        if let IResult::Done(_rest, header) = mach_header(bytes) {
            let mut rest = _rest;
            let mut segments = vec![];
            for _ in 0.. header.ncmds {
                if let IResult::Done(_rest, cmd) = segment_command(rest) {
                    rest = _rest;
                    segments.push(cmd);
                } else {
                    return None
                }
            }

            Some(MachHeader {
                header: header,
                segments: segments,
            })
        } else {
            return None
        }
    }
}

#[derive(Debug)]
pub struct SegmentCommand {
    pub cmd: u32,
    pub cmdsize: u32,
    pub segname: String,
    pub vmaddr: u32,
    pub vmsize: u32,
    pub fileoff: u32,
    pub filesize: u32,
    pub maxprot: vm_prot_t,
    pub initprot: vm_prot_t,
    pub nsects: u32,
    pub flags: u32,
}

named!(mach_header<&[u8], MachHeader_>,
       chain!(
           magic: le_u32 ~
           cputype: le_i32 ~
           cpusubtype: le_u32 ~
           filetype: le_u32 ~
           ncmds: le_u32 ~
           sizeofcmds: le_u32 ~
           flags: le_u32 ~
           reserved: le_u32,

           || {
               assert_eq!(0xfeedfacf, magic);
               MachHeader_ {
                   magic: magic,
                   cputype: cputype,
                   // This value needs to be masked to match otool -h
                   cpusubtype: cpusubtype,
                   filetype: filetype,
                   ncmds: ncmds,
                   sizeofcmds: sizeofcmds,
                   flags: flags,
                   reserved: reserved,
               }
           }
           )
       );

named!(segment_command<&[u8], SegmentCommand>,
       chain!(
           cmd: le_u32 ~
           cmdsize: le_u32 ~
           segname: take!(16) ~
           vmaddr: le_u32 ~
           vmsize: le_u32 ~
           fileoff: le_u32 ~
           filesize: le_u32 ~
           maxprot: le_i32 ~
           initprot: le_i32 ~
           nsects: le_u32 ~
           flags: le_u32 ,

           || {

               let slice = unsafe { CStr::from_ptr(segname.as_ptr() as *const c_char) };
               let name = std::str::from_utf8(slice.to_bytes()).unwrap().to_string();

               SegmentCommand {
                   cmd: cmd,
                   cmdsize: cmdsize,
                   segname: name,
                   vmaddr: vmaddr,
                   vmsize: vmsize,
                   fileoff: fileoff,
                   filesize: filesize,
                   maxprot: maxprot,
                   initprot: initprot,
                   nsects: nsects,
                   flags: flags,
               }
           }
        )
    );

<|endoftext|>


<commit_before>#![feature(macro_rules)]
#![feature(default_type_params)]
extern crate arena;

use std::default::Default;
use arena::TypedArena;
use std::cell::Cell;
use std::hash::{Writer, Hash};
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::RingBuf;
use std::collections::BinaryHeap;
use std::iter::Map;
use std::collections::hash_map::{
    Keys,
    Occupied,
    Vacant,
};
use std::fmt;

pub use scored::MinScored;
pub use digraph::DiGraph;
pub use graph::Graph;
mod scored;
pub mod digraph;
pub mod graph;

/// A reference that is hashed and compared by its pointer value.
#[deriving(Clone)]
pub struct Ptr<'b, T: 'b>(pub &'b T);

impl<'b, T> Copy for Ptr<'b, T> {}

fn ptreq<T>(a: &T, b: &T) -> bool {
    a as *const _ == b as *const _
}

impl<'b, T> PartialEq for Ptr<'b, T>
{
    /// Ptr compares by pointer equality, i.e if they point to the same value
    fn eq(&self, other: &Ptr<'b, T>) -> bool {
        ptreq(self.0, other.0)
    }
}

impl<'b, T> PartialOrd for Ptr<'b, T>
{
    fn partial_cmp(&self, other: &Ptr<'b, T>) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'b, T> Ord for Ptr<'b, T>
{
    /// Ptr is ordered by pointer value, i.e. an arbitrary but stable and total order.
    fn cmp(&self, other: &Ptr<'b, T>) -> Ordering {
        let a = self.0 as *const _;
        let b = other.0 as *const _;
        a.cmp(&b)
    }
}

impl<'b, T> Deref<T> for Ptr<'b, T> {
    fn deref<'a>(&'a self) -> &'a T {
        self.0
    }
}

impl<'b, T> Eq for Ptr<'b, T> {}

impl<'b, T, S: Writer> Hash<S> for Ptr<'b, T>
{
    fn hash(&self, st: &mut S)
    {
        let ptr = (self.0) as *const _;
        ptr.hash(st)
    }
}

impl<'b, T: fmt::Show> fmt::Show for Ptr<'b, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

pub fn dijkstra<'a,
                Graph, N, K,
                F, Edges>(graph: &'a Graph, start: N, mut edges: F) -> Vec<(N, K)>
where
    N: Copy + Eq + Hash + fmt::Show,
    K: Default + Add<K, K> + Copy + PartialOrd + fmt::Show,
    F: FnMut(&'a Graph, N) -> Edges,
    Edges: Iterator<(N, K)>,
{
    let mut visited = HashSet::new();
    let mut scores = HashMap::new();
    let mut predecessor = HashMap::new();
    let mut visit_next = BinaryHeap::new();
    let zero_score: K = Default::default();
    scores.insert(start, zero_score);
    visit_next.push(MinScored(zero_score, start));
    loop {
        let MinScored(node_score, node) = match visit_next.pop() {
            None => break,
            Some(t) => t,
        };
        if visited.contains(&node) {
            continue
        }
        println!("Visiting {} with score={}", node, node_score);
        for (next, edge) in edges(graph, node) {
            if visited.contains(&next) {
                continue
            }
            let mut next_score = node_score + edge;
            match scores.entry(next) {
                Occupied(ent) => if next_score < *ent.get() {
                    *ent.into_mut() = next_score;
                    predecessor.insert(next, node);
                } else {
                    next_score = *ent.get();
                },
                Vacant(ent) => {
                    ent.set(next_score);
                    predecessor.insert(next, node);
                }
            }
            visit_next.push(MinScored(next_score, next));
        }
        visited.insert(node);
    }
    println!("{}", predecessor);
    scores.into_iter().collect()
}

#[deriving(Show)]
pub struct Node<T>(pub T);

pub struct NodeCell<T: Copy>(pub Cell<T>);

impl<T: Copy> Deref<Cell<T>> for NodeCell<T> {
    #[inline]
    fn deref(&self) -> &Cell<T> {
        &self.0
    }
}

impl<T: Copy + fmt::Show> fmt::Show for NodeCell<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Node({})", self.0.get())
    }
}
<commit_msg>Remove unused imports<commit_after>#![feature(macro_rules)]
#![feature(default_type_params)]
extern crate arena;

use std::default::Default;
use std::cell::Cell;
use std::hash::{Writer, Hash};
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::BinaryHeap;
use std::collections::hash_map::{
    Occupied,
    Vacant,
};
use std::fmt;

pub use scored::MinScored;
pub use digraph::DiGraph;
pub use graph::Graph;
mod scored;
pub mod digraph;
pub mod graph;

/// A reference that is hashed and compared by its pointer value.
#[deriving(Clone)]
pub struct Ptr<'b, T: 'b>(pub &'b T);

impl<'b, T> Copy for Ptr<'b, T> {}

fn ptreq<T>(a: &T, b: &T) -> bool {
    a as *const _ == b as *const _
}

impl<'b, T> PartialEq for Ptr<'b, T>
{
    /// Ptr compares by pointer equality, i.e if they point to the same value
    fn eq(&self, other: &Ptr<'b, T>) -> bool {
        ptreq(self.0, other.0)
    }
}

impl<'b, T> PartialOrd for Ptr<'b, T>
{
    fn partial_cmp(&self, other: &Ptr<'b, T>) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'b, T> Ord for Ptr<'b, T>
{
    /// Ptr is ordered by pointer value, i.e. an arbitrary but stable and total order.
    fn cmp(&self, other: &Ptr<'b, T>) -> Ordering {
        let a = self.0 as *const _;
        let b = other.0 as *const _;
        a.cmp(&b)
    }
}

impl<'b, T> Deref<T> for Ptr<'b, T> {
    fn deref<'a>(&'a self) -> &'a T {
        self.0
    }
}

impl<'b, T> Eq for Ptr<'b, T> {}

impl<'b, T, S: Writer> Hash<S> for Ptr<'b, T>
{
    fn hash(&self, st: &mut S)
    {
        let ptr = (self.0) as *const _;
        ptr.hash(st)
    }
}

impl<'b, T: fmt::Show> fmt::Show for Ptr<'b, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

pub fn dijkstra<'a,
                Graph, N, K,
                F, Edges>(graph: &'a Graph, start: N, mut edges: F) -> Vec<(N, K)>
where
    N: Copy + Eq + Hash + fmt::Show,
    K: Default + Add<K, K> + Copy + PartialOrd + fmt::Show,
    F: FnMut(&'a Graph, N) -> Edges,
    Edges: Iterator<(N, K)>,
{
    let mut visited = HashSet::new();
    let mut scores = HashMap::new();
    let mut predecessor = HashMap::new();
    let mut visit_next = BinaryHeap::new();
    let zero_score: K = Default::default();
    scores.insert(start, zero_score);
    visit_next.push(MinScored(zero_score, start));
    loop {
        let MinScored(node_score, node) = match visit_next.pop() {
            None => break,
            Some(t) => t,
        };
        if visited.contains(&node) {
            continue
        }
        println!("Visiting {} with score={}", node, node_score);
        for (next, edge) in edges(graph, node) {
            if visited.contains(&next) {
                continue
            }
            let mut next_score = node_score + edge;
            match scores.entry(next) {
                Occupied(ent) => if next_score < *ent.get() {
                    *ent.into_mut() = next_score;
                    predecessor.insert(next, node);
                } else {
                    next_score = *ent.get();
                },
                Vacant(ent) => {
                    ent.set(next_score);
                    predecessor.insert(next, node);
                }
            }
            visit_next.push(MinScored(next_score, next));
        }
        visited.insert(node);
    }
    println!("{}", predecessor);
    scores.into_iter().collect()
}

#[deriving(Show)]
pub struct Node<T>(pub T);

pub struct NodeCell<T: Copy>(pub Cell<T>);

impl<T: Copy> Deref<Cell<T>> for NodeCell<T> {
    #[inline]
    fn deref(&self) -> &Cell<T> {
        &self.0
    }
}

impl<T: Copy + fmt::Show> fmt::Show for NodeCell<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Node({})", self.0.get())
    }
}
<|endoftext|>


<commit_before>#![crate_type = "lib"]
#![feature(ip_addr)]
#[allow(dead_code)]

use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

// A network
#[derive(Debug)]
pub enum IpNetwork {
    V4(Ipv4Network),
    V6(Ipv6Network),
}

pub struct Ipv4Network {
    addr: Ipv4Addr,
    prefix: u8,
}

pub struct Ipv6Network {
    addr: Ipv6Addr,
    prefix: u8,
}

impl Ipv4Network {
    pub fn new(addr: Ipv4Addr, prefix: u8) -> Ipv4Network {
        Ipv4Network { addr: addr, prefix: prefix }
    }

    pub fn ip(&self) -> &Ipv4Addr {
        &(self.addr)
    }

    pub fn prefix(&self) -> u8 {
        self.prefix
    }

    pub fn mask_int(&self) -> u32 {
        let prefix = self.prefix;
        !(0xffffffff >> prefix)
    }

    pub fn mask(&self) -> (Ipv4Addr, u32) {
        let prefix = self.prefix;
        let mask = !(0xffffffff >> prefix);
        return (Ipv4Addr::from(mask), mask);
    }

    pub fn network(&self) -> (Ipv4Addr, u32) {
        return (self.addr, u32::from(self.addr));
    }

    pub fn contains(&self, ip: Ipv4Addr) -> bool {
        let (_, net) = self.network();
        return ((u32::from(ip) & net) == net)
    }
}

impl Ipv6Network {
    pub fn new(addr: Ipv6Addr, prefix: u8) -> Ipv6Network {
        Ipv6Network { addr: addr, prefix: prefix }
    }

    pub fn ip(&self) -> &Ipv6Addr {
        &(self.addr)
    }

    pub fn prefix(&self) -> u8 {
        self.prefix
    }
}

impl IpNetwork {
    pub fn new(ip: IpAddr, prefix: u8) -> IpNetwork {
        match ip {
            IpAddr::V4(a) => IpNetwork::V4(Ipv4Network::new(a, prefix)),
            IpAddr::V6(a) => IpNetwork::V6(Ipv6Network::new(a, prefix)),
        }
    }

    pub fn ip(&self) -> IpAddr {
        match *self {
            IpNetwork::V4(ref a) => IpAddr::V4(*a.ip()),
            IpNetwork::V6(ref a) => IpAddr::V6(*a.ip()),
        }
    }

    pub fn prefix(&self) -> u8 {
        match *self {
            IpNetwork::V4(ref a) => a.prefix(),
            IpNetwork::V6(ref a) => a.prefix(),
        }
    }
}

impl fmt::Debug for Ipv4Network {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}/{}", self.ip(), self.prefix())
    }
}

impl fmt::Debug for Ipv6Network {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}/{}", self.ip(), self.prefix())
    }
}

#[cfg(test)]
mod test {
    use std::net::{Ipv4Addr, Ipv6Addr};
    use super::*;

    #[test]
    fn create_v4() {
        let cidr = Ipv4Network::new(Ipv4Addr::new(77, 88, 21, 11), 24);
        assert_eq!(cidr.prefix(), 24);
    }

    #[test]
    fn create_v6() {
        let cidr = Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 24);
        assert_eq!(cidr.prefix(), 24);
    }

    #[test]
    fn mask_v4() {
        let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 29);
        let (ip, int) = cidr.mask();
        assert_eq!(ip, Ipv4Addr::new(255, 255, 255, 248));
        assert_eq!(int, 4294967288);
    }

    #[test]
    fn network_v4() {
        let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 25);
        let (ip, int) = cidr.network();
        assert_eq!(ip, Ipv4Addr::new(74, 125, 227, 0));
        assert_eq!(int, 1249764096);
    }

    #[test]
    fn contains_v4() {
        let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 25);
        let ip = Ipv4Addr::new(74,125,227,4);
        assert!(cidr.contains(ip));
    }
}
<commit_msg>Remove the unnecessary parentheses<commit_after>#![crate_type = "lib"]
#![feature(ip_addr)]
#[allow(dead_code)]

use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

// A network
#[derive(Debug)]
pub enum IpNetwork {
    V4(Ipv4Network),
    V6(Ipv6Network),
}

pub struct Ipv4Network {
    addr: Ipv4Addr,
    prefix: u8,
}

pub struct Ipv6Network {
    addr: Ipv6Addr,
    prefix: u8,
}

impl Ipv4Network {
    pub fn new(addr: Ipv4Addr, prefix: u8) -> Ipv4Network {
        Ipv4Network { addr: addr, prefix: prefix }
    }

    pub fn ip(&self) -> &Ipv4Addr {
        &(self.addr)
    }

    pub fn prefix(&self) -> u8 {
        self.prefix
    }

    pub fn mask_int(&self) -> u32 {
        let prefix = self.prefix;
        !(0xffffffff >> prefix)
    }

    pub fn mask(&self) -> (Ipv4Addr, u32) {
        let prefix = self.prefix;
        let mask = !(0xffffffff >> prefix);
        return (Ipv4Addr::from(mask), mask);
    }

    pub fn network(&self) -> (Ipv4Addr, u32) {
        return (self.addr, u32::from(self.addr));
    }

    pub fn contains(&self, ip: Ipv4Addr) -> bool {
        let (_, net) = self.network();
        return (u32::from(ip) & net) == net
    }
}

impl Ipv6Network {
    pub fn new(addr: Ipv6Addr, prefix: u8) -> Ipv6Network {
        Ipv6Network { addr: addr, prefix: prefix }
    }

    pub fn ip(&self) -> &Ipv6Addr {
        &(self.addr)
    }

    pub fn prefix(&self) -> u8 {
        self.prefix
    }
}

impl IpNetwork {
    pub fn new(ip: IpAddr, prefix: u8) -> IpNetwork {
        match ip {
            IpAddr::V4(a) => IpNetwork::V4(Ipv4Network::new(a, prefix)),
            IpAddr::V6(a) => IpNetwork::V6(Ipv6Network::new(a, prefix)),
        }
    }

    pub fn ip(&self) -> IpAddr {
        match *self {
            IpNetwork::V4(ref a) => IpAddr::V4(*a.ip()),
            IpNetwork::V6(ref a) => IpAddr::V6(*a.ip()),
        }
    }

    pub fn prefix(&self) -> u8 {
        match *self {
            IpNetwork::V4(ref a) => a.prefix(),
            IpNetwork::V6(ref a) => a.prefix(),
        }
    }
}

impl fmt::Debug for Ipv4Network {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}/{}", self.ip(), self.prefix())
    }
}

impl fmt::Debug for Ipv6Network {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}/{}", self.ip(), self.prefix())
    }
}

#[cfg(test)]
mod test {
    use std::net::{Ipv4Addr, Ipv6Addr};
    use super::*;

    #[test]
    fn create_v4() {
        let cidr = Ipv4Network::new(Ipv4Addr::new(77, 88, 21, 11), 24);
        assert_eq!(cidr.prefix(), 24);
    }

    #[test]
    fn create_v6() {
        let cidr = Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 24);
        assert_eq!(cidr.prefix(), 24);
    }

    #[test]
    fn mask_v4() {
        let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 29);
        let (ip, int) = cidr.mask();
        assert_eq!(ip, Ipv4Addr::new(255, 255, 255, 248));
        assert_eq!(int, 4294967288);
    }

    #[test]
    fn network_v4() {
        let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 25);
        let (ip, int) = cidr.network();
        assert_eq!(ip, Ipv4Addr::new(74, 125, 227, 0));
        assert_eq!(int, 1249764096);
    }

    #[test]
    fn contains_v4() {
        let cidr = Ipv4Network::new(Ipv4Addr::new(74, 125, 227, 0), 25);
        let ip = Ipv4Addr::new(74,125,227,4);
        assert!(cidr.contains(ip));
    }
}
<|endoftext|>


<commit_before>//! # Kdtree-Rust
//!
//! K-dimensional tree for Rust (sliding midpoint rule implemenation)
//!
//! ## Usage
//!
//! ```
//! use kdtree::Kdtree;
//! use kdtree::distance::euclidean;
//! use kdtree::distance::squared_euclidean;
//! use kdtree::KdtreePointTrait;
//!
//!
//! // This can by any object or point with its associated metadata
//! #[derive(Copy, Clone, PartialEq)]
//! pub struct Point3WithId {
//!     dims: [f64; 3],
//!     pub id: i32,
//! }
//!
//!
//! impl KdtreePointTrait for Point3WithId {
//!     #[inline]
//!     fn dims(&self) -> &[f64] {
//!         return &self.dims;
//!     }
//! }
//!
//! let a = Point3WithId { dims: [0.0, 0.0, 0.0], id: 0};
//! let b = Point3WithId { dims: [1.0, 0.0, 0.0], id: 1};
//! let c = Point3WithId { dims: [1.0, 1.0, 0.0], id: 2};
//! let d = Point3WithId { dims: [1.0, 1.0, 1.0], id: 3};
//! let mut pts = vec![a,b,c,d];
//! let tree = Kdtree::new(&mut pts);
//!
//! assert_eq!(tree.nearest_search(&a).id, a.id);
//!
//! assert_eq!(tree.within(&a, 0.001, &euclidean).len(), 1);
//! assert_eq!(tree.within(&a, 1.001, &euclidean).len(), 2);
//! assert_eq!(tree.within(&a, 1.415, &euclidean).len(), 3);
//! assert_eq!(tree.within(&a, 2.0, &euclidean).len(), 4);
//! assert_eq!(tree.within(&a, 4.0, &squared_euclidean).len(), 4);
//! ```
//!
//!
//! ## Notes
//!
//! This kdtree implementation uses a trait interface, useful for things like ECS and game engines.
//! Agents need to implement KdtreePointTrait to be used in the kdtree.
//!
//! ## Performance
//!
//! The sliding midpoint method is extremely fast.
//! Using (nanoflann)[https://github.com/jlblancoc/nanoflann] as the baseline,
//! Kdtree-rust comes in as the fastest for both constructing trees,
//! and querying them. On a 2.9 GHz i7, we get 19ms to construct a 100k node tree
//! and 318.74ns to query it.
//!
//! It should be noted that kdtrees are meant for a construct-once and query-often access patterns.
//! This might library might be fast enough for your use case,
//! but real-time nearest-neighbors is still a hard problem to solve.
//!
//!

#[cfg(test)]
#[macro_use]
extern crate quickcheck;

#[cfg(test)]
extern crate rand;

mod bounds;
pub mod distance;
mod kdtree;
mod partition;
pub mod test_common;

pub use kdtree::Kdtree;
pub use kdtree::KdtreePointTrait;
pub use test_common::{Point1WithId, Point2WithId, Point3WithId};
<commit_msg> more ocmments<commit_after>//! # Kdtree-Rust
//!
//! K-dimensional tree for Rust (sliding midpoint rule implemenation)
//! Handles only 2D and 3D at the moment.
//!
//! ## Usage
//!
//! ```
//! use kdtree::Kdtree;
//! use kdtree::distance::euclidean;
//! use kdtree::distance::squared_euclidean;
//! use kdtree::KdtreePointTrait;
//!
//!
//! // This can by any object or point with its associated metadata
//! #[derive(Copy, Clone, PartialEq)]
//! pub struct Point3WithId {
//!     dims: [f64; 3],
//!     pub id: i32,
//! }
//!
//!
//! impl KdtreePointTrait for Point3WithId {
//!     #[inline]
//!     fn dims(&self) -> &[f64] {
//!         return &self.dims;
//!     }
//! }
//!
//! let a = Point3WithId { dims: [0.0, 0.0, 0.0], id: 0};
//! let b = Point3WithId { dims: [1.0, 0.0, 0.0], id: 1};
//! let c = Point3WithId { dims: [1.0, 1.0, 0.0], id: 2};
//! let d = Point3WithId { dims: [1.0, 1.0, 1.0], id: 3};
//! let mut pts = vec![a,b,c,d];
//! let tree = Kdtree::new(&mut pts);
//!
//! assert_eq!(tree.nearest_search(&a).id, a.id);
//!
//! assert_eq!(tree.within(&a, 0.001, &euclidean).len(), 1);
//! assert_eq!(tree.within(&a, 1.001, &euclidean).len(), 2);
//! assert_eq!(tree.within(&a, 1.415, &euclidean).len(), 3);
//! assert_eq!(tree.within(&a, 2.0, &euclidean).len(), 4);
//! // basically equivalent as line above, but much less costly as no sqrt.
//! assert_eq!(tree.within(&a, 4.0, &squared_euclidean).len(), 4);
//! ```
//!
//!
//! ## Notes
//!
//! This kdtree implementation uses a trait interface, useful for things like ECS and game engines.
//! Agents need to implement KdtreePointTrait to be used in the kdtree.
//!
//! ## Performance
//!
//! The sliding midpoint method is extremely fast.
//! Using (nanoflann)[https://github.com/jlblancoc/nanoflann] as the baseline,
//! Kdtree-rust comes in as the fastest for both constructing trees,
//! and querying them. On a 2.9 GHz i7, we get 19ms to construct a 100k node tree
//! and 318.74ns to query it.
//!
//! It should be noted that kdtrees are meant for a construct-once and query-often access patterns.
//! This might library might be fast enough for your use case,
//! but real-time nearest-neighbors is still a hard problem to solve.
//!
//!

#[cfg(test)]
#[macro_use]
extern crate quickcheck;

#[cfg(test)]
extern crate rand;

mod bounds;
pub mod distance;
mod kdtree;
mod partition;
pub mod test_common;

pub use kdtree::Kdtree;
pub use kdtree::KdtreePointTrait;
pub use test_common::{Point1WithId, Point2WithId, Point3WithId};
<|endoftext|>


<commit_before>//! This crate provides native rust implementations of
//! Image encoders and decoders and basic image manipulation
//! functions.

#![crate_name = "image"]
#![crate_type = "rlib"]

#![warn(missing_docs)]
#![warn(unused_qualifications)]
#![deny(missing_copy_implementations)]
#![feature(core)]
#![feature(collections)]
#![feature(io)]
#![feature(std_misc)]
#![feature(rustc_private)]
#![feature(step_by)]
#![feature(convert)]
#![feature(slice_patterns)]
#![cfg_attr(test, feature(test))]

extern crate byteorder;
extern crate flate;
extern crate num;
#[cfg(test)] extern crate test;

pub use color::ColorType as ColorType;
pub use traits::Primitive;

pub use color::ColorType:: {
    Gray,
    RGB,
    Palette,
    GrayA,
    RGBA,
};
pub use color:: {
    Luma,
    LumaA,
    Rgb,
    Rgba,
};

pub use buffer::Pixel;

pub use image::ImageDecoder as ImageDecoder;
pub use image::ImageError as ImageError;
pub use image::ImageResult as ImageResult;
pub use image::ImageFormat as ImageFormat;
pub use imageops::FilterType as FilterType;

pub use imageops:: {
    Triangle,
    Nearest,
    CatmullRom,
    Gaussian,
    Lanczos3
};

pub use image::ImageFormat:: {
    PNG,
    JPEG,
    GIF,
    WEBP,
    PPM
};

// Image Types
pub use image::SubImage as SubImage;
pub use dynimage::DynamicImage as DynamicImage;
pub use buffer::{
    ImageBuffer,
    RgbImage,
    RgbaImage,
    GrayImage,
    GrayAlphaImage
};

// Traits
pub use image::GenericImage as GenericImage;

// Iterators
pub use image::Pixels as Pixels;
pub use image::MutPixels as MutPixels;

/// Opening and loading images
pub use dynimage:: {
    open,
    load,
    load_from_memory,
    load_from_memory_with_format,
    save_buffer,
};
pub use dynimage::DynamicImage:: {
    ImageRgb8,
    ImageRgba8,
    ImageLuma8,
    ImageLumaA8,
};

pub use animation:: {
    Frame, Frames
};

// Math utils
pub mod math;

// Image Processing Functions
pub mod imageops;

// Image Codecs
#[cfg(feature = "webp")]
pub mod webp;
#[cfg(feature = "ppm")]
pub mod ppm;
#[cfg(feature = "png")]
pub mod png;
#[cfg(feature = "jpeg")]
pub mod jpeg;
#[cfg(feature = "gif")]
pub mod gif;
#[cfg(feature = "tiff")]
pub mod tiff;
#[cfg(feature = "tga")]
pub mod tga;

mod image;
mod utils;
mod dynimage;
mod color;
mod buffer;
mod traits;
mod animation;
<commit_msg>Resolve warnings about unused features<commit_after>//! This crate provides native rust implementations of
//! Image encoders and decoders and basic image manipulation
//! functions.

#![crate_name = "image"]
#![crate_type = "rlib"]

#![warn(missing_docs)]
#![warn(unused_qualifications)]
#![deny(missing_copy_implementations)]
#![feature(core)]
#![feature(collections)]
#![feature(std_misc)]
#![feature(rustc_private)]
#![feature(step_by)]
#![feature(slice_patterns)]
#![cfg_attr(test, feature(test))]

extern crate byteorder;
extern crate flate;
extern crate num;
#[cfg(test)] extern crate test;

pub use color::ColorType as ColorType;
pub use traits::Primitive;

pub use color::ColorType:: {
    Gray,
    RGB,
    Palette,
    GrayA,
    RGBA,
};
pub use color:: {
    Luma,
    LumaA,
    Rgb,
    Rgba,
};

pub use buffer::Pixel;

pub use image::ImageDecoder as ImageDecoder;
pub use image::ImageError as ImageError;
pub use image::ImageResult as ImageResult;
pub use image::ImageFormat as ImageFormat;
pub use imageops::FilterType as FilterType;

pub use imageops:: {
    Triangle,
    Nearest,
    CatmullRom,
    Gaussian,
    Lanczos3
};

pub use image::ImageFormat:: {
    PNG,
    JPEG,
    GIF,
    WEBP,
    PPM
};

// Image Types
pub use image::SubImage as SubImage;
pub use dynimage::DynamicImage as DynamicImage;
pub use buffer::{
    ImageBuffer,
    RgbImage,
    RgbaImage,
    GrayImage,
    GrayAlphaImage
};

// Traits
pub use image::GenericImage as GenericImage;

// Iterators
pub use image::Pixels as Pixels;
pub use image::MutPixels as MutPixels;

/// Opening and loading images
pub use dynimage:: {
    open,
    load,
    load_from_memory,
    load_from_memory_with_format,
    save_buffer,
};
pub use dynimage::DynamicImage:: {
    ImageRgb8,
    ImageRgba8,
    ImageLuma8,
    ImageLumaA8,
};

pub use animation:: {
    Frame, Frames
};

// Math utils
pub mod math;

// Image Processing Functions
pub mod imageops;

// Image Codecs
#[cfg(feature = "webp")]
pub mod webp;
#[cfg(feature = "ppm")]
pub mod ppm;
#[cfg(feature = "png")]
pub mod png;
#[cfg(feature = "jpeg")]
pub mod jpeg;
#[cfg(feature = "gif")]
pub mod gif;
#[cfg(feature = "tiff")]
pub mod tiff;
#[cfg(feature = "tga")]
pub mod tga;

mod image;
mod utils;
mod dynimage;
mod color;
mod buffer;
mod traits;
mod animation;
<|endoftext|>