<commit_before>use wlroots_sys::{wlr_xcursor_manager, wlr_xcursor_manager_create, wlr_xcursor_manager_load, wlr_xcursor_manager_set_cursor_image};
use types::Cursor;
use std::ptr;
use utils::safe_as_cstring;

#[derive(Debug)]
pub struct XCursorManager {
    manager: *mut wlr_xcursor_manager
}

impl XCursorManager {
    pub fn create<T: Into<Option<String>>>(name: T, size: u32) -> Option<Self> {
        unsafe {
            let name_str = name.into().map(safe_as_cstring);
            let name_ptr = name_str.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut());
            let manager = wlr_xcursor_manager_create(name_ptr, size);
            if manager.is_null() {
                None
            } else {
                Some(XCursorManager { manager })
            }
        }
    }

    /// returns 0 if the scaled theme was successfully loaded and 1 otherwise
    pub fn load(&self, scale: f32) -> i32 {
        unsafe {
            wlr_xcursor_manager_load(self.manager, scale)
        }
    }

    pub fn set_cursor_image(&mut self, name: String, cursor: &Cursor) {
        let name_ptr = safe_as_cstring(name).as_ptr();
        unsafe {
            wlr_xcursor_manager_set_cursor_image(self.manager, name_ptr, cursor.as_ptr());
        }
    }
}
<commit_msg>implement drop for xcursor_manager<commit_after>use wlroots_sys::{wlr_xcursor_manager, wlr_xcursor_manager_create, wlr_xcursor_manager_load, wlr_xcursor_manager_set_cursor_image, wlr_xcursor_manager_destroy};
use types::Cursor;
use std::ptr;
use utils::safe_as_cstring;

#[derive(Debug)]
pub struct XCursorManager {
    manager: *mut wlr_xcursor_manager
}

impl XCursorManager {
    pub fn create<T: Into<Option<String>>>(name: T, size: u32) -> Option<Self> {
        unsafe {
            let name_str = name.into().map(safe_as_cstring);
            let name_ptr = name_str.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut());
            let manager = wlr_xcursor_manager_create(name_ptr, size);
            if manager.is_null() {
                None
            } else {
                Some(XCursorManager { manager })
            }
        }
    }

    /// returns 0 if the scaled theme was successfully loaded and 1 otherwise
    pub fn load(&self, scale: f32) -> i32 {
        unsafe {
            wlr_xcursor_manager_load(self.manager, scale)
        }
    }

    pub fn set_cursor_image(&mut self, name: String, cursor: &Cursor) {
        let name_ptr = safe_as_cstring(name).as_ptr();
        unsafe {
            wlr_xcursor_manager_set_cursor_image(self.manager, name_ptr, cursor.as_ptr());
        }
    }
}

impl Drop for XCursorManager {
    fn drop(&mut self) {
        unsafe { wlr_xcursor_manager_destroy(self.manager) }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.

#[cfg(test)]
mod test;

// warning: rust uses '!' as bitwise not operator
// blcic(!x) = tzmsk(x)+1 = product of the '2's of x's prime decomposition
pub fn blcic(x: u64) -> u64 {
    x.wrapping_add(1) & !x
} // 101111-> 10000
pub fn tzmsk(x: u64) -> u64 {
    x.wrapping_sub(1) & !x
} // 010000->  1111
pub fn bitsmear(mut smear: u64) -> u64 {
    smear |= smear >> 32;
    smear |= smear >> 16;
    smear |= smear >> 8;
    smear |= smear >> 4;
    smear |= smear >> 2;
    smear |= smear >> 1;
    smear
}

pub fn gcd_lcm(mut m: u64, mut n: u64) -> (u64, u64) {
    let p = m * n;
    while m != 0 {
        let o = m;
        m = n % m;
        n = o;
    }
    (n,
     if n == 0 {
        0
    } else {
        p / n
    })
}

pub fn multiplicative_inverse(mut a: u64, n: u64) -> Option<u64> {

    // println!("{:?} {:?}", a, n);

    if n == 0 {
        return Option::None;
    }
    a %= n;
    // println!(" ({:?} {:?})", a, n);
    if a == 0 {
        return Option::None;
    }

    let mut t: u64 = 0;
    let mut r: u64 = n;
    let mut nt: u64 = 1;
    let mut nr: u64 = a;

    while nr != 0 {
        // TODO: make sure q*nt never overflows
        let (ot, or) = (nt, nr);
        let q = r / nr;

        // TODO: make sure this doesn't overflow
        nt = (t + q * (n - nt)) % n;
        nr = r - q * nr;
        t = ot;
        r = or;
    }
    if r > 1 {
        return Option::None;
    }
    // println!("= {:?}", t);
    Option::Some(t)
}
<commit_msg>Added integer-overflow-checks<commit_after>// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.

#[cfg(test)]
mod test;

// warning: rust uses '!' as bitwise not operator
// blcic(!x) = tzmsk(x)+1 = product of the '2's of x's prime decomposition
pub fn blcic(x: u64) -> u64 {
    x.wrapping_add(1) & !x
} // 101111-> 10000
pub fn tzmsk(x: u64) -> u64 {
    x.wrapping_sub(1) & !x
} // 010000->  1111
pub fn bitsmear(mut smear: u64) -> u64 {
    smear |= smear >> 32;
    smear |= smear >> 16;
    smear |= smear >> 8;
    smear |= smear >> 4;
    smear |= smear >> 2;
    smear |= smear >> 1;
    smear
}

pub fn gcd_lcm(mut m: u64, mut n: u64) -> (u64, u64) {
    let p = m * n;
    while m != 0 {
        let o = m;
        m = n % m;
        n = o;
    }
    (n,
     if n == 0 {
        0
    } else {
        p / n
    })
}

pub fn multiplicative_inverse(mut a: u64, n: u64) -> Option<u64> {

    // println!("{:?} {:?}", a, n);

    if n == 0 {
        return Option::None;
    }
    a %= n;
    // println!(" ({:?} {:?})", a, n);
    if a == 0 {
        return Option::None;
    }

    let mut t: u64 = 0;
    let mut r: u64 = n;
    let mut nt: u64 = 1;
    let mut nr: u64 = a;

    while nr != 0 {

        let (ot, or) = (nt, nr);
        let q = match r.checked_div(nr) {
            Some(x) => x,
            None => return Option::None;
        };

        //nt = (t + q * (n - nt)) % n;

        nt = match (match t.checked_add(q) {
            Some(layer1) => {
                match layer1.checked_mul(match n.checked_sub(nt) {
                    Some(layer2) => layer2,
                    None => return Option::None
                }) {
                    Some(layer2) => layer2,
                    None => return Option::None
                }
            },
            None => return Option::None
        }).checked_rem(n) {
            Some(x) => x,
            None => return Option::None
        };

        // nr = r - q * nr;

        nr = match r.checked_sub(match q.checked_mul(nr) {
            Some(x) => x,
            None => return Option::None
        }) {
            Some(x) => x,
            None => return Option::None
        };
        t = ot;
        r = or;
    }
    if r > 1 {
        return Option::None;
    }
    // println!("= {:?}", t);
    Option::Some(t)
}
<|endoftext|>


<commit_before>//! Procedural macro implementing `#[derive(Enum)]`
//!
//! This is supposed to used with `enum-map` crate, which provides the
//! actual usage documentation.

#![recursion_limit = "128"]

extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
extern crate syn;

use std::iter;

use syn::spanned::Spanned;
use syn::{Data, DataEnum, DeriveInput, Fields, Ident, Variant};

fn generate_enum_code(name: Ident, data_enum: DataEnum) -> proc_macro2::TokenStream {
    let enum_count = data_enum.variants.len();
    let mut has_discriminants = false;

    for variant in &data_enum.variants {
        let Variant {
            fields,
            discriminant,
            ..
        } = variant;
        match fields {
            Fields::Unit => (),
            _ => {
                return syn::Error::new(
                    fields.span(),
                    "#[derive(Enum)] requires C style style enum",
                )
                .to_compile_error();
            }
        }

        if discriminant.is_some() {
            has_discriminants = true;
        }
    }

    let variants_names_a = data_enum.variants.iter().map(|variant| &variant.ident);
    let variants_names_b = data_enum.variants.iter().map(|variant| &variant.ident);
    let repeat_name_a = iter::repeat(&name);
    let repeat_name_b = repeat_name_a.clone();
    let counter = 0..enum_count;

    let to_usize = if enum_count == 0 || has_discriminants {
        let variants_names = data_enum.variants.iter().map(|variant| &variant.ident);
        let repeat_name = repeat_name_a.clone();
        let counter = counter.clone();

        quote! {
            match self {
                #(
                    #repeat_name::#variants_names => #counter,
                )*
            }
        }
    } else {
        quote! { self as usize }
    };

    quote! {
        #[automatically_derived]
        impl<V> ::enum_map::Enum<V> for #name {
            type Array = [V; #enum_count];
            const POSSIBLE_VALUES: usize = #enum_count;

            #[inline]
            fn slice(array: &Self::Array) -> &[V] {
                array
            }

            #[inline]
            fn slice_mut(array: &mut Self::Array) -> &mut [V] {
                array
            }

            #[inline]
            fn from_usize(value: usize) -> Self {
                match value {
                    #(
                        #counter => #repeat_name_a::#variants_names_a,
                    )*
                    _ => unreachable!()
                }
            }

            #[inline]
            fn to_usize(self) -> usize {
                #to_usize
            }

            #[inline]
            fn from_function<F: FnMut(Self) -> V>(mut _f: F) -> Self::Array {
                [#(
                    _f(#repeat_name_b::#variants_names_b),
                )*]
            }
        }
    }
}

/// Procedural derive generating `enum_map::Enum` implementation.
///
/// # Examples
///
/// ```
/// # extern crate enum_map;
/// use enum_map::Enum;
///
/// #[derive(Enum)]
/// enum A {
///     B,
///     C,
///     D,
/// }
///
/// assert_eq!(Enum::<()>::to_usize(A::C), 1);
/// ```
#[proc_macro_derive(Enum)]
pub fn derive_enum_map(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();

    let result = match input.data {
        Data::Enum(data_enum) => generate_enum_code(input.ident, data_enum),
        _ => quote!(compile_error! {"#[derive(Enum)] is only defined for enums"}),
    };

    result.into()
}
<commit_msg>Remove "style" word duplication in error message<commit_after>//! Procedural macro implementing `#[derive(Enum)]`
//!
//! This is supposed to used with `enum-map` crate, which provides the
//! actual usage documentation.

#![recursion_limit = "128"]

extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
extern crate syn;

use std::iter;

use syn::spanned::Spanned;
use syn::{Data, DataEnum, DeriveInput, Fields, Ident, Variant};

fn generate_enum_code(name: Ident, data_enum: DataEnum) -> proc_macro2::TokenStream {
    let enum_count = data_enum.variants.len();
    let mut has_discriminants = false;

    for variant in &data_enum.variants {
        let Variant {
            fields,
            discriminant,
            ..
        } = variant;
        match fields {
            Fields::Unit => (),
            _ => {
                return syn::Error::new(fields.span(), "#[derive(Enum)] requires C style enum")
                    .to_compile_error();
            }
        }

        if discriminant.is_some() {
            has_discriminants = true;
        }
    }

    let variants_names_a = data_enum.variants.iter().map(|variant| &variant.ident);
    let variants_names_b = data_enum.variants.iter().map(|variant| &variant.ident);
    let repeat_name_a = iter::repeat(&name);
    let repeat_name_b = repeat_name_a.clone();
    let counter = 0..enum_count;

    let to_usize = if enum_count == 0 || has_discriminants {
        let variants_names = data_enum.variants.iter().map(|variant| &variant.ident);
        let repeat_name = repeat_name_a.clone();
        let counter = counter.clone();

        quote! {
            match self {
                #(
                    #repeat_name::#variants_names => #counter,
                )*
            }
        }
    } else {
        quote! { self as usize }
    };

    quote! {
        #[automatically_derived]
        impl<V> ::enum_map::Enum<V> for #name {
            type Array = [V; #enum_count];
            const POSSIBLE_VALUES: usize = #enum_count;

            #[inline]
            fn slice(array: &Self::Array) -> &[V] {
                array
            }

            #[inline]
            fn slice_mut(array: &mut Self::Array) -> &mut [V] {
                array
            }

            #[inline]
            fn from_usize(value: usize) -> Self {
                match value {
                    #(
                        #counter => #repeat_name_a::#variants_names_a,
                    )*
                    _ => unreachable!()
                }
            }

            #[inline]
            fn to_usize(self) -> usize {
                #to_usize
            }

            #[inline]
            fn from_function<F: FnMut(Self) -> V>(mut _f: F) -> Self::Array {
                [#(
                    _f(#repeat_name_b::#variants_names_b),
                )*]
            }
        }
    }
}

/// Procedural derive generating `enum_map::Enum` implementation.
///
/// # Examples
///
/// ```
/// # extern crate enum_map;
/// use enum_map::Enum;
///
/// #[derive(Enum)]
/// enum A {
///     B,
///     C,
///     D,
/// }
///
/// assert_eq!(Enum::<()>::to_usize(A::C), 1);
/// ```
#[proc_macro_derive(Enum)]
pub fn derive_enum_map(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();

    let result = match input.data {
        Data::Enum(data_enum) => generate_enum_code(input.ident, data_enum),
        _ => quote!(compile_error! {"#[derive(Enum)] is only defined for enums"}),
    };

    result.into()
}
<|endoftext|>


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

use crate::errors::{bail, Error};
use crate::runtime;
use std::io::BufReader;
use std::process;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};

pub(crate) struct ChildProcess {
    process: std::process::Child,
    stdout: std::io::Lines<BufReader<std::process::ChildStdout>>,
    // Only none while in drop.
    stdin: Option<std::process::ChildStdin>,
    command: Arc<Mutex<process::Command>>,
    stderr_sender: Arc<Mutex<mpsc::Sender<String>>>,
}

impl ChildProcess {
    pub(crate) fn new(
        mut command: std::process::Command,
        stderr_sender: mpsc::Sender<String>,
    ) -> Result<ChildProcess, Error> {
        // Avoid a fork bomb. We could call runtime_hook here but then all the work that we did up
        // to this point would be wasted. Also, it's possible that we could already have started
        // threads, which could get messy.
        if std::env::var(runtime::EVCXR_IS_RUNTIME_VAR).is_ok() {
            bail!("Our current binary doesn't call runtime_hook()");
        }
        command
            .env(runtime::EVCXR_IS_RUNTIME_VAR, "1")
            .env("RUST_BACKTRACE", "1")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped());
        ChildProcess::new_internal(
            Arc::new(Mutex::new(command)),
            Arc::new(Mutex::new(stderr_sender)),
        )
    }

    fn new_internal(
        command: Arc<Mutex<std::process::Command>>,
        stderr_sender: Arc<Mutex<mpsc::Sender<String>>>,
    ) -> Result<ChildProcess, Error> {
        let process = command.lock().unwrap().spawn();
        let mut process = match process {
            Ok(c) => c,
            Err(error) => bail!("Failed to run '{:?}': {:?}", command, error),
        };

        let stdout = std::io::BufRead::lines(BufReader::new(process.stdout.take().unwrap()));

        // Handle stderr by patching it through to a channel in our output struct.
        let mut child_stderr =
            std::io::BufRead::lines(BufReader::new(process.stderr.take().unwrap()));
        std::thread::spawn({
            let stderr_sender = Arc::clone(&stderr_sender);
            move || {
                let stderr_sender = stderr_sender.lock().unwrap();
                while let Some(Ok(line)) = child_stderr.next() {
                    // Ignore errors, since it just means that the user of the library has dropped the receive end.
                    let _ = stderr_sender.send(line);
                }
            }
        });

        let stdin = process.stdin.take();
        Ok(ChildProcess {
            process,
            stdout,
            stdin,
            command,
            stderr_sender,
        })
    }

    /// Terminates this process if it hasn't already, then restarts
    pub(crate) fn restart(&mut self) -> Result<ChildProcess, Error> {
        // If the process hasn't already terminated for some reason, kill it.
        if let Ok(None) = self.process.try_wait() {
            let _ = self.process.kill();
            let _ = self.process.wait();
        }
        ChildProcess::new_internal(Arc::clone(&self.command), Arc::clone(&self.stderr_sender))
    }

    pub(crate) fn send(&mut self, command: &str) -> Result<(), Error> {
        use std::io::Write;
        writeln!(self.stdin.as_mut().unwrap(), "{}", command)
            .map_err(|_| self.get_termination_error())?;
        self.stdin.as_mut().unwrap().flush()?;
        Ok(())
    }

    pub(crate) fn recv_line(&mut self) -> Result<String, Error> {
        Ok(self
            .stdout
            .next()
            .ok_or_else(|| self.get_termination_error())??)
    }

    fn get_termination_error(&mut self) -> Error {
        // Wait until the stderr handling thread has released its lock on stderr_sender, which it
        // will do when there's nothing more to read from stderr. We don't need to keep the lock,
        // just wait until we can aquire it, then drop it straight away.
        std::mem::drop(self.stderr_sender.lock().unwrap());
        let mut content = String::new();
        while let Some(Ok(line)) = self.stdout.next() {
            content.push_str(&line);
            content.push('\n');
        }
        Error::ChildProcessTerminated(match self.process.wait() {
            Ok(exit_status) => format!(
                "{}Child process terminated with status: {}",
                content, exit_status
            ),
            Err(wait_error) => format!("Child process didn't start: {}", wait_error),
        })
    }
}

impl Drop for ChildProcess {
    fn drop(&mut self) {
        // Drop child_stdin before we wait. Our child process uses stdin being
        // closed to know that it's time to terminate.
        self.stdin.take();
        // Wait for our child process to terminate. Otherwise we'll be left with
        // zombie processes.
        let _ = self.process.wait();
    }
}
<commit_msg>Custom error message when subprocess exits with signal 9 on mac<commit_after>// Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::errors::{bail, Error};
use crate::runtime;
use std::io::BufReader;
use std::process;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};

pub(crate) struct ChildProcess {
    process: std::process::Child,
    stdout: std::io::Lines<BufReader<std::process::ChildStdout>>,
    // Only none while in drop.
    stdin: Option<std::process::ChildStdin>,
    command: Arc<Mutex<process::Command>>,
    stderr_sender: Arc<Mutex<mpsc::Sender<String>>>,
}

impl ChildProcess {
    pub(crate) fn new(
        mut command: std::process::Command,
        stderr_sender: mpsc::Sender<String>,
    ) -> Result<ChildProcess, Error> {
        // Avoid a fork bomb. We could call runtime_hook here but then all the work that we did up
        // to this point would be wasted. Also, it's possible that we could already have started
        // threads, which could get messy.
        if std::env::var(runtime::EVCXR_IS_RUNTIME_VAR).is_ok() {
            bail!("Our current binary doesn't call runtime_hook()");
        }
        command
            .env(runtime::EVCXR_IS_RUNTIME_VAR, "1")
            .env("RUST_BACKTRACE", "1")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped());
        ChildProcess::new_internal(
            Arc::new(Mutex::new(command)),
            Arc::new(Mutex::new(stderr_sender)),
        )
    }

    fn new_internal(
        command: Arc<Mutex<std::process::Command>>,
        stderr_sender: Arc<Mutex<mpsc::Sender<String>>>,
    ) -> Result<ChildProcess, Error> {
        let process = command.lock().unwrap().spawn();
        let mut process = match process {
            Ok(c) => c,
            Err(error) => bail!("Failed to run '{:?}': {:?}", command, error),
        };

        let stdout = std::io::BufRead::lines(BufReader::new(process.stdout.take().unwrap()));

        // Handle stderr by patching it through to a channel in our output struct.
        let mut child_stderr =
            std::io::BufRead::lines(BufReader::new(process.stderr.take().unwrap()));
        std::thread::spawn({
            let stderr_sender = Arc::clone(&stderr_sender);
            move || {
                let stderr_sender = stderr_sender.lock().unwrap();
                while let Some(Ok(line)) = child_stderr.next() {
                    // Ignore errors, since it just means that the user of the library has dropped the receive end.
                    let _ = stderr_sender.send(line);
                }
            }
        });

        let stdin = process.stdin.take();
        Ok(ChildProcess {
            process,
            stdout,
            stdin,
            command,
            stderr_sender,
        })
    }

    /// Terminates this process if it hasn't already, then restarts
    pub(crate) fn restart(&mut self) -> Result<ChildProcess, Error> {
        // If the process hasn't already terminated for some reason, kill it.
        if let Ok(None) = self.process.try_wait() {
            let _ = self.process.kill();
            let _ = self.process.wait();
        }
        ChildProcess::new_internal(Arc::clone(&self.command), Arc::clone(&self.stderr_sender))
    }

    pub(crate) fn send(&mut self, command: &str) -> Result<(), Error> {
        use std::io::Write;
        writeln!(self.stdin.as_mut().unwrap(), "{}", command)
            .map_err(|_| self.get_termination_error())?;
        self.stdin.as_mut().unwrap().flush()?;
        Ok(())
    }

    pub(crate) fn recv_line(&mut self) -> Result<String, Error> {
        Ok(self
            .stdout
            .next()
            .ok_or_else(|| self.get_termination_error())??)
    }

    fn get_termination_error(&mut self) -> Error {
        // Wait until the stderr handling thread has released its lock on stderr_sender, which it
        // will do when there's nothing more to read from stderr. We don't need to keep the lock,
        // just wait until we can aquire it, then drop it straight away.
        std::mem::drop(self.stderr_sender.lock().unwrap());
        let mut content = String::new();
        while let Some(Ok(line)) = self.stdout.next() {
            content.push_str(&line);
            content.push('\n');
        }
        Error::ChildProcessTerminated(match self.process.wait() {
            Ok(exit_status) => {
                #[cfg(target_os = "macos")]
                {
                    use std::os::unix::process::ExitStatusExt;
                    if Some(9) == exit_status.signal() {
                        return Error::ChildProcessTerminated(
                            "Subprocess terminated with signal 9. This is known \
                            to happen when evcxr is installed via a Homebrew shell \
                            under emulation. Try installing rustup and evcxr without \
                            using Homebrew and see if that helps."
                                .to_owned(),
                        );
                    }
                }
                format!(
                    "{}Child process terminated with status: {}",
                    content, exit_status
                )
            }
            Err(wait_error) => format!("Child process didn't start: {}", wait_error),
        })
    }
}

impl Drop for ChildProcess {
    fn drop(&mut self) {
        // Drop child_stdin before we wait. Our child process uses stdin being
        // closed to know that it's time to terminate.
        self.stdin.take();
        // Wait for our child process to terminate. Otherwise we'll be left with
        // zombie processes.
        let _ = self.process.wait();
    }
}
<|endoftext|>


<commit_before>use std::collections::{BTreeMap, HashMap};

use search::term::Term;
use search::document::Document;

#[derive(Debug)]
pub struct MemoryIndexStore {
    docs: BTreeMap<u64, Document>,
    index: BTreeMap<Term, BTreeMap<String, BTreeMap<u64, Vec<u32>>>>,
    next_doc_num: u64,
    doc_id_map: HashMap<String, u64>,
}

impl MemoryIndexStore {
    pub fn new() -> MemoryIndexStore {
        MemoryIndexStore {
            docs: BTreeMap::new(),
            index: BTreeMap::new(),
            next_doc_num: 1,
            doc_id_map: HashMap::new(),
        }
    }

    pub fn get_document_by_id(&self, id: &str) -> Option<&Document> {
        match self.doc_id_map.get(id) {
            Some(doc_num) => self.docs.get(doc_num),
            None => None,
        }
    }

    pub fn contains_document_id(&self, id: &str) -> bool {
        self.doc_id_map.contains_key(id)
    }

    pub fn remove_document_by_id(&mut self, id: &str) -> bool {
        match self.doc_id_map.remove(id) {
            Some(doc_num) => {
                self.docs.remove(&doc_num);

                true
            }
            None => false
        }
    }

    pub fn insert_or_update_document(&mut self, doc: Document) {
        let doc_num = self.next_doc_num;
        self.next_doc_num += 1;

        // Put field contents in inverted index
        for (field_name, tokens) in doc.fields.iter() {
            let mut position: u32 = 1;

            for token in tokens.iter() {
                if !self.index.contains_key(&token.term) {
                    self.index.insert(token.term.clone(), BTreeMap::new());
                }

                let mut index_fields = self.index.get_mut(&token.term).unwrap();

                if !index_fields.contains_key(field_name) {
                    index_fields.insert(field_name.clone(), BTreeMap::new());
                }

                let mut index_docs = index_fields.get_mut(field_name).unwrap();
                if !index_docs.contains_key(&doc_num) {
                    index_docs.insert(doc_num, Vec::new());
                }

                let mut postings_list = index_docs.get_mut(&doc_num).unwrap();
                postings_list.push(token.position);
            }
        }

        self.doc_id_map.insert(doc.id.clone(), doc_num);
        self.docs.insert(doc_num, doc);
    }

    pub fn num_docs(&self) -> usize {
        self.docs.len()
    }

    pub fn iter_docs<'a>(&'a self) -> Box<Iterator<Item=&'a Document> + 'a> {
        Box::new(self.docs.values())
    }
}
<commit_msg>Added next_doc method to MemoryIndexStore<commit_after>use std::collections::{BTreeMap, HashMap};

use search::term::Term;
use search::document::Document;

#[derive(Debug)]
pub struct MemoryIndexStore {
    docs: BTreeMap<u64, Document>,
    index: BTreeMap<Term, BTreeMap<String, BTreeMap<u64, Vec<u32>>>>,
    next_doc_num: u64,
    doc_id_map: HashMap<String, u64>,
}

impl MemoryIndexStore {
    pub fn new() -> MemoryIndexStore {
        MemoryIndexStore {
            docs: BTreeMap::new(),
            index: BTreeMap::new(),
            next_doc_num: 1,
            doc_id_map: HashMap::new(),
        }
    }

    pub fn get_document_by_id(&self, id: &str) -> Option<&Document> {
        match self.doc_id_map.get(id) {
            Some(doc_num) => self.docs.get(doc_num),
            None => None,
        }
    }

    pub fn contains_document_id(&self, id: &str) -> bool {
        self.doc_id_map.contains_key(id)
    }

    pub fn remove_document_by_id(&mut self, id: &str) -> bool {
        match self.doc_id_map.remove(id) {
            Some(doc_num) => {
                self.docs.remove(&doc_num);

                true
            }
            None => false
        }
    }

    pub fn insert_or_update_document(&mut self, doc: Document) {
        let doc_num = self.next_doc_num;
        self.next_doc_num += 1;

        // Put field contents in inverted index
        for (field_name, tokens) in doc.fields.iter() {
            let mut position: u32 = 1;

            for token in tokens.iter() {
                if !self.index.contains_key(&token.term) {
                    self.index.insert(token.term.clone(), BTreeMap::new());
                }

                let mut index_fields = self.index.get_mut(&token.term).unwrap();

                if !index_fields.contains_key(field_name) {
                    index_fields.insert(field_name.clone(), BTreeMap::new());
                }

                let mut index_docs = index_fields.get_mut(field_name).unwrap();
                if !index_docs.contains_key(&doc_num) {
                    index_docs.insert(doc_num, Vec::new());
                }

                let mut postings_list = index_docs.get_mut(&doc_num).unwrap();
                postings_list.push(token.position);
            }
        }

        self.doc_id_map.insert(doc.id.clone(), doc_num);
        self.docs.insert(doc_num, doc);
    }

    pub fn next_doc(&self, term: &Term, field_name: &str, previous_doc: Option<u64>) -> Option<(u64, usize)> {
        let fields = match self.index.get(term) {
            Some(fields) => fields,
            None => return None,
        };

        let docs = match fields.get(field_name) {
            Some(docs) => docs,
            None => return None,
        };

        match previous_doc {
            Some(previous_doc) => {
                // Find first doc after specified doc
                // TODO: Speed this up (see section 2.1.2 of the IR book)
                for (doc_id, postings) in docs.iter() {
                    if *doc_id > previous_doc {
                        return Some((*doc_id, postings.len()));
                    }
                }

                // Ran out of docs
                return None;
            }
            None => {
                // Previous doc not specified, return first doc
                match docs.iter().next() {
                    Some((doc_id, postings)) => Some((*doc_id, postings.len())),
                    None => None,
                }
            }
        }
    }

    pub fn num_docs(&self) -> usize {
        self.docs.len()
    }

    pub fn iter_docs<'a>(&'a self) -> Box<Iterator<Item=&'a Document> + 'a> {
        Box::new(self.docs.values())
    }
}
<|endoftext|>


<commit_before>use std::fs::File;

use rand;

use bot::{Bot, Node, RoomEvent};
use services::utils::reservoir_sample;

pub struct Timecube {
}

impl Timecube {
    pub fn new() -> Self {
        Self {
        }
    }
}

impl<'a> Node<'a> for Timecube {
    fn handle(&mut self, bot: &Bot, event: RoomEvent) {
        let revent = &event.raw_event;
        if revent.type_ == "m.room.message" &&
           revent.content["msgtype"] == "m.text" &&
           revent.sender != "@rustix:cclub.cs.wmich.edu" {

            let body = revent.content["body"].as_str().unwrap();

            if body.starts_with("timecube") {
                let rng = rand::thread_rng();

                match File::open("timecube.txt") {
                    Ok(d) => {
                        let line = reservoir_sample(d, rng);
                        bot.reply(&event, &line);
                    },
                    Err(e) => {
                        println!("{:?}", e);
                        bot.reply(&event, "Error: problem with timecube file!");
                    }
                };
            }
        }
    }
}
<commit_msg>Remove unecessary checks in timecube module<commit_after>use std::fs::File;

use rand;

use bot::{Bot, Node, RoomEvent};
use services::utils::reservoir_sample;

pub struct Timecube {
}

impl Timecube {
    pub fn new() -> Self {
        Self {
        }
    }
}

impl<'a> Node<'a> for Timecube {
    fn handle(&mut self, bot: &Bot, event: RoomEvent) {
        let revent = &event.raw_event;
        if revent.type_ == "m.room.message" &&
           revent.content["msgtype"] == "m.text" {

            let body = revent.content["body"].as_str().unwrap();

            if body.starts_with("timecube") {
                let rng = rand::thread_rng();

                match File::open("timecube.txt") {
                    Ok(d) => {
                        let line = reservoir_sample(d, rng);
                        bot.reply(&event, &line);
                    },
                    Err(e) => {
                        println!("{:?}", e);
                        bot.reply(&event, "Error: problem with timecube file!");
                    }
                };
            }
        }
    }
}
<|endoftext|>


<commit_before>//! SMTP client
//!
//! `SmtpConnection` allows manually sending SMTP commands.
//!
//! ```rust,no_run
//! # use std::error::Error;
//!
//! # #[cfg(feature = "smtp-transport")]
//! # fn main() -> Result<(), Box<dyn Error>> {
//! use lettre::transport::smtp::{SMTP_PORT, extension::ClientId, commands::*, client::SmtpConnection};
//!
//! let hello = ClientId::Domain("my_hostname".to_string());
//! let mut client = SmtpConnection::connect(&("localhost", SMTP_PORT), None, &hello, None)?;
//! client.command(
//!         Mail::new(Some("user@example.com".parse()?), vec![])
//!     )?;
//! client.command(
//!         Rcpt::new("user@example.org".parse()?, vec![])
//!       )?;
//! client.command(Data)?;
//! client.message("Test email".as_bytes())?;
//! client.command(Quit)?;
//! # Ok(())
//! # }
//! ```

#[cfg(feature = "serde")]
use std::fmt::Debug;

#[cfg(any(feature = "tokio1", feature = "async-std1"))]
pub(crate) use self::async_connection::AsyncSmtpConnection;
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
pub(crate) use self::async_net::AsyncNetworkStream;
use self::net::NetworkStream;
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
pub(super) use self::tls::InnerTlsParameters;
pub use self::{
    connection::SmtpConnection,
    tls::{Certificate, Tls, TlsParameters, TlsParametersBuilder},
};

#[cfg(any(feature = "tokio1", feature = "async-std1"))]
mod async_connection;
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
mod async_net;
mod connection;
mod net;
mod tls;

/// The codec used for transparency
#[derive(Default, Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct ClientCodec {
    escape_count: u8,
}

impl ClientCodec {
    /// Creates a new client codec
    pub fn new() -> Self {
        ClientCodec::default()
    }

    /// Adds transparency
    fn encode(&mut self, frame: &[u8], buf: &mut Vec<u8>) {
        match frame.len() {
            0 => {
                match self.escape_count {
                    0 => buf.extend_from_slice(b"\r\n.\r\n"),
                    1 => buf.extend_from_slice(b"\n.\r\n"),
                    2 => buf.extend_from_slice(b".\r\n"),
                    _ => unreachable!(),
                }
                self.escape_count = 0;
            }
            _ => {
                let mut start = 0;
                for (idx, byte) in frame.iter().enumerate() {
                    match self.escape_count {
                        0 => self.escape_count = if *byte == b'\r' { 1 } else { 0 },
                        1 => self.escape_count = if *byte == b'\n' { 2 } else { 0 },
                        2 => self.escape_count = if *byte == b'.' { 3 } else { 0 },
                        _ => unreachable!(),
                    }
                    if self.escape_count == 3 {
                        self.escape_count = 0;
                        buf.extend_from_slice(&frame[start..idx]);
                        buf.extend_from_slice(b".");
                        start = idx;
                    }
                }
                buf.extend_from_slice(&frame[start..]);
            }
        }
    }
}

/// Returns the string replacing all the CRLF with "\<CRLF\>"
/// Used for debug displays
#[cfg(feature = "tracing")]
pub(super) fn escape_crlf(string: &str) -> String {
    string.replace("\r\n", "<CRLF>")
}

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

    #[test]
    fn test_codec() {
        let mut codec = ClientCodec::new();
        let mut buf: Vec<u8> = vec![];

        codec.encode(b"test\r\n", &mut buf);
        codec.encode(b".\r\n", &mut buf);
        codec.encode(b"\r\ntest", &mut buf);
        codec.encode(b"te\r\n.\r\nst", &mut buf);
        codec.encode(b"test", &mut buf);
        codec.encode(b"test.", &mut buf);
        codec.encode(b"test\n", &mut buf);
        codec.encode(b".test\n", &mut buf);
        codec.encode(b"test", &mut buf);
        assert_eq!(
            String::from_utf8(buf).unwrap(),
            "test\r\n..\r\n\r\ntestte\r\n..\r\nsttesttest.test\n.test\ntest"
        );
    }

    #[test]
    #[cfg(feature = "log")]
    fn test_escape_crlf() {
        assert_eq!(escape_crlf("\r\n"), "<CRLF>");
        assert_eq!(escape_crlf("EHLO my_name\r\n"), "EHLO my_name<CRLF>");
        assert_eq!(
            escape_crlf("EHLO my_name\r\nSIZE 42\r\n"),
            "EHLO my_name<CRLF>SIZE 42<CRLF>"
        );
    }
}
<commit_msg>fix(transport-smtp): Fix transparency codec (#627)<commit_after>//! SMTP client
//!
//! `SmtpConnection` allows manually sending SMTP commands.
//!
//! ```rust,no_run
//! # use std::error::Error;
//!
//! # #[cfg(feature = "smtp-transport")]
//! # fn main() -> Result<(), Box<dyn Error>> {
//! use lettre::transport::smtp::{SMTP_PORT, extension::ClientId, commands::*, client::SmtpConnection};
//!
//! let hello = ClientId::Domain("my_hostname".to_string());
//! let mut client = SmtpConnection::connect(&("localhost", SMTP_PORT), None, &hello, None)?;
//! client.command(
//!         Mail::new(Some("user@example.com".parse()?), vec![])
//!     )?;
//! client.command(
//!         Rcpt::new("user@example.org".parse()?, vec![])
//!       )?;
//! client.command(Data)?;
//! client.message("Test email".as_bytes())?;
//! client.command(Quit)?;
//! # Ok(())
//! # }
//! ```

#[cfg(feature = "serde")]
use std::fmt::Debug;

#[cfg(any(feature = "tokio1", feature = "async-std1"))]
pub(crate) use self::async_connection::AsyncSmtpConnection;
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
pub(crate) use self::async_net::AsyncNetworkStream;
use self::net::NetworkStream;
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
pub(super) use self::tls::InnerTlsParameters;
pub use self::{
    connection::SmtpConnection,
    tls::{Certificate, Tls, TlsParameters, TlsParametersBuilder},
};

#[cfg(any(feature = "tokio1", feature = "async-std1"))]
mod async_connection;
#[cfg(any(feature = "tokio1", feature = "async-std1"))]
mod async_net;
mod connection;
mod net;
mod tls;

/// The codec used for transparency
#[derive(Default, Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct ClientCodec {
    escape_count: u8,
}

impl ClientCodec {
    /// Creates a new client codec
    pub fn new() -> Self {
        ClientCodec::default()
    }

    /// Adds transparency
    fn encode(&mut self, frame: &[u8], buf: &mut Vec<u8>) {
        match frame.len() {
            0 => {
                match self.escape_count {
                    0 => buf.extend_from_slice(b"\r\n.\r\n"),
                    1 => buf.extend_from_slice(b"\n.\r\n"),
                    2 => buf.extend_from_slice(b".\r\n"),
                    _ => unreachable!(),
                }
                self.escape_count = 0;
            }
            _ => {
                let mut start = 0;
                for (idx, byte) in frame.iter().enumerate() {
                    match self.escape_count {
                        0 => self.escape_count = if *byte == b'\r' { 1 } else { 0 },
                        1 => self.escape_count = if *byte == b'\n' { 2 } else { 0 },
                        2 => {
                            self.escape_count = if *byte == b'.' {
                                3
                            } else if *byte == b'\r' {
                                1
                            } else {
                                0
                            }
                        }
                        _ => unreachable!(),
                    }
                    if self.escape_count == 3 {
                        self.escape_count = 0;
                        buf.extend_from_slice(&frame[start..idx]);
                        buf.extend_from_slice(b".");
                        start = idx;
                    }
                }
                buf.extend_from_slice(&frame[start..]);
            }
        }
    }
}

/// Returns the string replacing all the CRLF with "\<CRLF\>"
/// Used for debug displays
#[cfg(feature = "tracing")]
pub(super) fn escape_crlf(string: &str) -> String {
    string.replace("\r\n", "<CRLF>")
}

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

    #[test]
    fn test_codec() {
        let mut codec = ClientCodec::new();
        let mut buf: Vec<u8> = vec![];

        codec.encode(b"test\r\n", &mut buf);
        codec.encode(b"test\r\n\r\n", &mut buf);
        codec.encode(b".\r\n", &mut buf);
        codec.encode(b"\r\ntest", &mut buf);
        codec.encode(b"te\r\n.\r\nst", &mut buf);
        codec.encode(b"test", &mut buf);
        codec.encode(b"test.", &mut buf);
        codec.encode(b"test\n", &mut buf);
        codec.encode(b".test\n", &mut buf);
        codec.encode(b"test", &mut buf);
        assert_eq!(
            String::from_utf8(buf).unwrap(),
            "test\r\ntest\r\n\r\n..\r\n\r\ntestte\r\n..\r\nsttesttest.test\n.test\ntest"
        );
    }

    #[test]
    #[cfg(feature = "log")]
    fn test_escape_crlf() {
        assert_eq!(escape_crlf("\r\n"), "<CRLF>");
        assert_eq!(escape_crlf("EHLO my_name\r\n"), "EHLO my_name<CRLF>");
        assert_eq!(
            escape_crlf("EHLO my_name\r\nSIZE 42\r\n"),
            "EHLO my_name<CRLF>SIZE 42<CRLF>"
        );
    }
}
<|endoftext|>


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

use std::rc::Rc;

use std::sync::atomic::{
    AtomicUsize,
    Ordering,
};

#[derive(Clone)]
pub struct RcCounter {
    c: Rc<AtomicUsize>,
}

/// A simple shared counter.
impl RcCounter {
    pub fn with_initial(value: usize) -> Self {
        RcCounter { c: Rc::new(AtomicUsize::new(value)) }
    }

    pub fn new() -> Self {
        RcCounter { c: Rc::new(AtomicUsize::new(0)) }
    }

    /// Return the next value in the sequence.
    ///
    /// ```
    /// use mentat_core::counter::RcCounter;
    ///
    /// let c = RcCounter::with_initial(3);
    /// assert_eq!(c.next(), 3);
    /// assert_eq!(c.next(), 4);
    /// let d = c.clone();
    /// assert_eq!(d.next(), 5);
    /// assert_eq!(c.next(), 6);
    /// ```
    pub fn next(&self) -> usize {
        self.c.fetch_add(1, Ordering::SeqCst)
    }
}

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

    #[test]
    fn test_rc_counter() {
        let c = RcCounter::new();
        assert_eq!(c.next(), 0);
        assert_eq!(c.next(), 1);

        let d = c.clone();
        assert_eq!(d.next(), 2);
        assert_eq!(c.next(), 3);
    }
}
<commit_msg>Use Cell instead of AtomicUsize in RcCounter. (#646) r=rnewman<commit_after>// Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

use std::cell::Cell;
use std::rc::Rc;

#[derive(Clone)]
pub struct RcCounter {
    c: Rc<Cell<usize>>,
}

/// A simple shared counter.
impl RcCounter {
    pub fn with_initial(value: usize) -> Self {
        RcCounter { c: Rc::new(Cell::new(value)) }
    }

    pub fn new() -> Self {
        RcCounter { c: Rc::new(Cell::new(0)) }
    }

    /// Return the next value in the sequence.
    ///
    /// ```
    /// use mentat_core::counter::RcCounter;
    ///
    /// let c = RcCounter::with_initial(3);
    /// assert_eq!(c.next(), 3);
    /// assert_eq!(c.next(), 4);
    /// let d = c.clone();
    /// assert_eq!(d.next(), 5);
    /// assert_eq!(c.next(), 6);
    /// ```
    pub fn next(&self) -> usize {
        let current = self.c.get();
        self.c.replace(current + 1)
    }
}

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

    #[test]
    fn test_rc_counter() {
        let c = RcCounter::new();
        assert_eq!(c.next(), 0);
        assert_eq!(c.next(), 1);

        let d = c.clone();
        assert_eq!(d.next(), 2);
        assert_eq!(c.next(), 3);
    }
}
<|endoftext|>


<commit_before>#![macro_escape]

#[macro_export]
macro_rules! object_struct(
	($name:ident) => (
		object_struct!($name,)

		impl<S: ::std::hash::Writer> ::std::hash::Hash<S> for $name {
			fn hash(&self, state: &mut S) {
				use foundation::INSObject;
				self.hash_code().hash(state);
			}
		}
	);
	($name:ident<$($t:ident),+>) => (
		object_struct!($name, $($t),+)

		impl<$($t),+, S: ::std::hash::Writer> ::std::hash::Hash<S> for $name<$($t),+> {
			fn hash(&self, state: &mut S) {
				use foundation::INSObject;
				self.hash_code().hash(state);
			}
		}
	);
	($name:ident, $($t:ident),*) => (
		pub struct $name<$($t),*> {
			ptr: ::id::Id,
		}

		impl<$($t),*> ::runtime::Messageable for $name<$($t),*> {
			unsafe fn as_ptr(&self) -> *::runtime::Object {
				use runtime::Messageable;
				self.ptr.as_ptr()
			}
		}

		impl<$($t),*> ::id::FromId for $name<$($t),*> {
			unsafe fn from_id(id: ::id::Id) -> $name<$($t),*> {
				$name { ptr: id }
			}
		}

		impl<$($t),*> ::foundation::INSObject for $name<$($t),*> {
			fn class_name() -> ::id::ClassName<$name<$($t),*>> {
				::id::ClassName::from_str(stringify!($name))
			}
		}

		impl<$($t),*> ::std::clone::Clone for $name<$($t),*> {
			fn clone(&self) -> $name<$($t),*> {
				unsafe {
					::id::FromId::from_id(self.ptr.clone())
				}
			}
		}

		impl<$($t),*> ::std::cmp::PartialEq for $name<$($t),*> {
			fn eq(&self, other: &$name<$($t),*>) -> bool {
				use foundation::INSObject;
				self.is_equal(other)
			}
		}

		impl<$($t),*> ::std::cmp::Eq for $name<$($t),*> { }

		impl<$($t),*> ::std::fmt::Show for $name<$($t),*> {
			fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
				use foundation::{INSObject, INSString};
				self.description().as_str().fmt(f)
			}
		}
	);
)
<commit_msg>Simplified object_struct macro.<commit_after>#![macro_escape]

#[macro_export]
macro_rules! object_struct(
	($name:ident<$($t:ident),+>) => (
		object_struct!($name, $($t),+)
	);
	($name:ident $(,$t:ident)*) => (
		pub struct $name<$($t),*> {
			ptr: ::id::Id,
		}

		impl<$($t),*> ::runtime::Messageable for $name<$($t),*> {
			unsafe fn as_ptr(&self) -> *::runtime::Object {
				use runtime::Messageable;
				self.ptr.as_ptr()
			}
		}

		impl<$($t),*> ::id::FromId for $name<$($t),*> {
			unsafe fn from_id(id: ::id::Id) -> $name<$($t),*> {
				$name { ptr: id }
			}
		}

		impl<$($t),*> ::foundation::INSObject for $name<$($t),*> {
			fn class_name() -> ::id::ClassName<$name<$($t),*>> {
				::id::ClassName::from_str(stringify!($name))
			}
		}

		impl<$($t),*> ::std::clone::Clone for $name<$($t),*> {
			fn clone(&self) -> $name<$($t),*> {
				unsafe {
					::id::FromId::from_id(self.ptr.clone())
				}
			}
		}

		impl<$($t),*> ::std::cmp::PartialEq for $name<$($t),*> {
			fn eq(&self, other: &$name<$($t),*>) -> bool {
				use foundation::INSObject;
				self.is_equal(other)
			}
		}

		impl<$($t),*> ::std::cmp::Eq for $name<$($t),*> { }

		impl<$($t,)* S: ::std::hash::Writer> ::std::hash::Hash<S> for $name<$($t),*> {
			fn hash(&self, state: &mut S) {
				use foundation::INSObject;
				self.hash_code().hash(state);
			}
		}

		impl<$($t),*> ::std::fmt::Show for $name<$($t),*> {
			fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
				use foundation::{INSObject, INSString};
				self.description().as_str().fmt(f)
			}
		}
	);
)
<|endoftext|>


<commit_before><commit_msg>use powi instead of unnecessary powf<commit_after><|endoftext|>


<commit_before><commit_msg>Fix examples in ForkTable Rustdoc<commit_after><|endoftext|>


<commit_before>use atbash_cipher as cipher;

#[test]
fn test_encode_yes() {
    assert_eq!("bvh", cipher::encode("yes"));
}

#[test]
#[ignore]
fn test_encode_no() {
    assert_eq!("ml", cipher::encode("no"));
}

#[test]
#[ignore]
fn test_encode_omg() {
    assert_eq!("lnt", cipher::encode("OMG"));
}

#[test]
#[ignore]
fn test_encode_spaces() {
    assert_eq!("lnt", cipher::encode("O M G"));
}

#[test]
#[ignore]
fn test_encode_mindblowingly() {
    assert_eq!("nrmwy oldrm tob", cipher::encode("mindblowingly"));
}

#[test]
#[ignore]
fn test_encode_numbers() {
    assert_eq!(
        "gvhgr mt123 gvhgr mt",
        cipher::encode("Testing,1 2 3, testing.")
    );
}

#[test]
#[ignore]
fn test_encode_deep_thought() {
    assert_eq!("gifgs rhurx grlm", cipher::encode("Truth is fiction."));
}

#[test]
#[ignore]
fn test_encode_all_the_letters() {
    assert_eq!(
        "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt",
        cipher::encode("The quick brown fox jumps over the lazy dog.")
    );
}

#[test]
#[ignore]
fn test_encode_ignores_non_ascii() {
    assert_eq!("mlmzh xrrrt mlivw", cipher::encode("non ascii éignored"));
}

#[test]
#[ignore]
fn test_decode_exercism() {
    assert_eq!("exercism", cipher::decode("vcvix rhn"));
}

#[test]
#[ignore]
fn test_decode_a_sentence() {
    assert_eq!(
        "anobstacleisoftenasteppingstone",
        cipher::decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v")
    );
}

#[test]
#[ignore]
fn test_decode_numbers() {
    assert_eq!("testing123testing", cipher::decode("gvhgr mt123 gvhgr mt"));
}

#[test]
#[ignore]
fn test_decode_all_the_letters() {
    assert_eq!(
        "thequickbrownfoxjumpsoverthelazydog",
        cipher::decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt")
    );
}
<commit_msg>atbash-cipher change test order to assert_eq!(actual, expected) (#902)<commit_after>use atbash_cipher as cipher;

#[test]
fn test_encode_yes() {
    assert_eq!(cipher::encode("yes"), "bvh");
}

#[test]
#[ignore]
fn test_encode_no() {
    assert_eq!(cipher::encode("no"), "ml");
}

#[test]
#[ignore]
fn test_encode_omg() {
    assert_eq!(cipher::encode("OMG"), "lnt");
}

#[test]
#[ignore]
fn test_encode_spaces() {
    assert_eq!(cipher::encode("O M G"), "lnt");
}

#[test]
#[ignore]
fn test_encode_mindblowingly() {
    assert_eq!(cipher::encode("mindblowingly"), "nrmwy oldrm tob");
}

#[test]
#[ignore]
fn test_encode_numbers() {
    assert_eq!(
        cipher::encode("Testing,1 2 3, testing."),
        "gvhgr mt123 gvhgr mt"
    );
}

#[test]
#[ignore]
fn test_encode_deep_thought() {
    assert_eq!(cipher::encode("Truth is fiction."), "gifgs rhurx grlm");
}

#[test]
#[ignore]
fn test_encode_all_the_letters() {
    assert_eq!(
        cipher::encode("The quick brown fox jumps over the lazy dog."),
        "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt"
    );
}

#[test]
#[ignore]
fn test_encode_ignores_non_ascii() {
    assert_eq!(cipher::encode("non ascii éignored"), "mlmzh xrrrt mlivw");
}

#[test]
#[ignore]
fn test_decode_exercism() {
    assert_eq!(cipher::decode("vcvix rhn"), "exercism");
}

#[test]
#[ignore]
fn test_decode_a_sentence() {
    assert_eq!(
        cipher::decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v"),
        "anobstacleisoftenasteppingstone"
    );
}

#[test]
#[ignore]
fn test_decode_numbers() {
    assert_eq!(cipher::decode("gvhgr mt123 gvhgr mt"), "testing123testing");
}

#[test]
#[ignore]
fn test_decode_all_the_letters() {
    assert_eq!(
        cipher::decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt"),
        "thequickbrownfoxjumpsoverthelazydog"
    );
}
<|endoftext|>


<commit_before>// Copyright 2014-2016 Johannes Köster, Taylor Cramer.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! The Burrows-Wheeler-Transform and related data structures.
//! The implementation is based on the lecture notes
//! "Algorithmen auf Sequenzen", Kopczynski, Marschall, Martin and Rahmann, 2008 - 2015.

use std::iter::repeat;

use utils::prescan;
use alphabets::Alphabet;
use data_structures::suffix_array::RawSuffixArray;
use std::ops::Deref;

pub type BWT = Vec<u8>;
pub type BWTSlice = [u8];
pub type Less = Vec<usize>;
pub type BWTFind = Vec<usize>;

pub trait DerefBWT: Deref<Target = BWT> {}
impl<T: Deref<Target = BWT>> DerefBWT for T {}

pub trait DerefOcc: Deref<Target = Occ> {}
impl<T: Deref<Target = Occ>> DerefOcc for T {}

pub trait DerefLess: Deref<Target = Less> {}
impl<T: Deref<Target = Less>> DerefLess for T {}

/// Calculate Burrows-Wheeler-Transform of the given text of length n.
/// Complexity: O(n).
///
/// # Arguments
///
/// * `text` - the text ended by sentinel symbol (being lexicographically smallest)
/// * `pos` - the suffix array for the text
///
/// # Example
///
/// ```
/// use bio::data_structures::suffix_array::suffix_array;
/// use bio::data_structures::bwt::bwt;
/// let text = b"GCCTTAACATTATTACGCCTA$";
/// let pos = suffix_array(text);
/// let bwt = bwt(text, &pos);
/// assert_eq!(bwt, b"ATTATTCAGGACCC$CTTTCAA");
/// ```
pub fn bwt(text: &[u8], pos: &RawSuffixArray) -> BWT {
    assert!(text.len() == pos.len());
    let n = text.len();
    let mut bwt: BWT = repeat(0).take(n).collect();
    for r in 0..n {
        let p = pos[r];
        bwt[r] = if p > 0 {
            text[p - 1]
        } else {
            text[n - 1]
        };
    }

    bwt
}

/// Calculate the inverse of a BWT of length n, which is the original text.
/// Complexity: O(n).
///
/// # Arguments
///
/// * `bwt` - the BWT
pub fn invert_bwt(bwt: &BWTSlice) -> Vec<u8> {
    let alphabet = Alphabet::new(bwt);
    let n = bwt.len();
    let bwtfind = bwtfind(bwt, &alphabet);
    let mut inverse = Vec::with_capacity(n);

    let mut r = bwtfind[0];
    for _ in 0..n {
        r = bwtfind[r];
        inverse.push(bwt[r]);
    }

    inverse
}

/// An occurence array implementation.
#[cfg_attr(feature = "serde_macros", derive(Serialize, Deserialize))]
pub struct Occ {
    occ: Vec<Vec<usize>>,
    k: usize,
}

impl Occ {
    /// Calculate occ array with sampling from BWT of length n.
    /// Time complexity: O(n).
    /// Space complexity: O(n / k * A) with A being the alphabet size.
    /// Alphabet size is determined on the fly from the BWT.
    /// For large texts, it is therefore advisable to transform
    /// the text before calculating the BWT (see alphabets::rank_transform).
    ///
    /// # Arguments
    ///
    /// * `bwt` - the BWT
    /// * `k` - the sampling rate: every k-th entry will be stored
    pub fn new(bwt: &BWTSlice, k: usize, alphabet: &Alphabet) -> Self {
        let n = bwt.len();
        let m = alphabet.max_symbol().expect("Expecting non-empty alphabet.") as usize + 1;
        let mut occ = Vec::with_capacity(n / k);
        let mut curr_occ: Vec<usize> = repeat(0).take(m).collect();
        for (i, &c) in bwt.iter().enumerate() {
            curr_occ[c as usize] += 1;
            if i % k == 0 {
                occ.push(curr_occ.clone());
            }
        }

        Occ { occ: occ, k: k }
    }

    /// Get occurrence count of symbol a in BWT[..r+1].
    /// Complexity: O(k).
    pub fn get(&self, bwt: &BWTSlice, r: usize, a: u8) -> usize {
        // self.k is our sampling rate, so find our last sampled checkpoint
        let i = r / self.k;
        let checkpoint = self.occ[i][a as usize];

        // find the portion of the BWT past the checkpoint which we need to count
        let start = (i * self.k) + 1;
        let end = r + 1;

        // count all the matching bytes b/t the closest checkpoint and our desired lookup
        let mut count = 0;
        for &x in &bwt[start..end] {
            if x == a {
                count += 1;
            }
        }

        // return the sampled checkpoint for this character + the manual count we just did
        checkpoint + count
    }
}

/// Calculate the less array for a given BWT. Complexity O(n).
pub fn less(bwt: &BWTSlice, alphabet: &Alphabet) -> Less {
    let m = alphabet.max_symbol().expect("Expecting non-empty alphabet.") as usize + 2;
    let mut less: Less = repeat(0)
                             .take(m)
                             .collect();
    for &c in bwt.iter() {
        less[c as usize] += 1;
    }
    // calculate +-prescan
    prescan(&mut less[..], 0, |a, b| a + b);

    less
}

/// Calculate the bwtfind array needed for inverting the BWT. Complexity O(n).
pub fn bwtfind(bwt: &BWTSlice, alphabet: &Alphabet) -> BWTFind {
    let n = bwt.len();
    let mut less = less(bwt, alphabet);

    let mut bwtfind: BWTFind = repeat(0).take(n).collect();
    for (r, &c) in bwt.iter().enumerate() {
        bwtfind[less[c as usize]] = r;
        less[c as usize] += 1;
    }

    bwtfind
}

#[cfg(test)]
mod tests {
    use super::{bwtfind, bwt, invert_bwt, Occ};
    use data_structures::suffix_array::suffix_array;
    use alphabets::Alphabet;

    #[test]
    fn test_bwtfind() {
        let text = b"cabca$";
        let alphabet = Alphabet::new(b"abc$");
        let pos = suffix_array(text);
        let bwt = bwt(text, &pos);
        let bwtfind = bwtfind(&bwt, &alphabet);
        assert_eq!(bwtfind, vec![5, 0, 3, 4, 1, 2]);
    }

    #[test]
    fn test_invert_bwt() {
        let text = b"cabca$";
        let pos = suffix_array(text);
        let bwt = bwt(text, &pos);
        let inverse = invert_bwt(&bwt);
        assert_eq!(inverse, text);
    }

    #[test]
    fn test_occ() {
        let bwt = vec![1u8, 3u8, 3u8, 1u8, 2u8, 0u8];
        let alphabet = Alphabet::new(&[0u8, 1u8, 2u8, 3u8]);
        let occ = Occ::new(&bwt, 3, &alphabet);
        assert_eq!(occ.occ, [[0, 1, 0, 0], [0, 2, 0, 2]]);
        assert_eq!(occ.get(&bwt, 4, 2u8), 1);
        assert_eq!(occ.get(&bwt, 4, 3u8), 2);
    }

    #[test]
    #[cfg(feature = "nightly")]
    fn test_serde() {
        use serde::{Serialize, Deserialize};
        fn impls_serde_traits<S: Serialize + Deserialize>() {}

        impls_serde_traits::<Occ>();
    }
}
<commit_msg>Switch Occ::k and Occ::get's count accumulator to u32.<commit_after>// Copyright 2014-2016 Johannes Köster, Taylor Cramer.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! The Burrows-Wheeler-Transform and related data structures.
//! The implementation is based on the lecture notes
//! "Algorithmen auf Sequenzen", Kopczynski, Marschall, Martin and Rahmann, 2008 - 2015.

use std::iter::repeat;

use utils::prescan;
use alphabets::Alphabet;
use data_structures::suffix_array::RawSuffixArray;
use std::ops::Deref;

pub type BWT = Vec<u8>;
pub type BWTSlice = [u8];
pub type Less = Vec<usize>;
pub type BWTFind = Vec<usize>;

pub trait DerefBWT: Deref<Target = BWT> {}
impl<T: Deref<Target = BWT>> DerefBWT for T {}

pub trait DerefOcc: Deref<Target = Occ> {}
impl<T: Deref<Target = Occ>> DerefOcc for T {}

pub trait DerefLess: Deref<Target = Less> {}
impl<T: Deref<Target = Less>> DerefLess for T {}

/// Calculate Burrows-Wheeler-Transform of the given text of length n.
/// Complexity: O(n).
///
/// # Arguments
///
/// * `text` - the text ended by sentinel symbol (being lexicographically smallest)
/// * `pos` - the suffix array for the text
///
/// # Example
///
/// ```
/// use bio::data_structures::suffix_array::suffix_array;
/// use bio::data_structures::bwt::bwt;
/// let text = b"GCCTTAACATTATTACGCCTA$";
/// let pos = suffix_array(text);
/// let bwt = bwt(text, &pos);
/// assert_eq!(bwt, b"ATTATTCAGGACCC$CTTTCAA");
/// ```
pub fn bwt(text: &[u8], pos: &RawSuffixArray) -> BWT {
    assert!(text.len() == pos.len());
    let n = text.len();
    let mut bwt: BWT = repeat(0).take(n).collect();
    for r in 0..n {
        let p = pos[r];
        bwt[r] = if p > 0 {
            text[p - 1]
        } else {
            text[n - 1]
        };
    }

    bwt
}

/// Calculate the inverse of a BWT of length n, which is the original text.
/// Complexity: O(n).
///
/// # Arguments
///
/// * `bwt` - the BWT
pub fn invert_bwt(bwt: &BWTSlice) -> Vec<u8> {
    let alphabet = Alphabet::new(bwt);
    let n = bwt.len();
    let bwtfind = bwtfind(bwt, &alphabet);
    let mut inverse = Vec::with_capacity(n);

    let mut r = bwtfind[0];
    for _ in 0..n {
        r = bwtfind[r];
        inverse.push(bwt[r]);
    }

    inverse
}

/// An occurence array implementation.
#[cfg_attr(feature = "serde_macros", derive(Serialize, Deserialize))]
pub struct Occ {
    occ: Vec<Vec<usize>>,
    k: u32,
}

impl Occ {
    /// Calculate occ array with sampling from BWT of length n.
    /// Time complexity: O(n).
    /// Space complexity: O(n / k * A) with A being the alphabet size.
    /// Alphabet size is determined on the fly from the BWT.
    /// For large texts, it is therefore advisable to transform
    /// the text before calculating the BWT (see alphabets::rank_transform).
    ///
    /// # Arguments
    ///
    /// * `bwt` - the BWT
    /// * `k` - the sampling rate: every k-th entry will be stored
    pub fn new(bwt: &BWTSlice, k: u32, alphabet: &Alphabet) -> Self {
        let n = bwt.len();
        let m = alphabet.max_symbol().expect("Expecting non-empty alphabet.") as usize + 1;
        let mut occ = Vec::with_capacity(n / k as usize);
        let mut curr_occ: Vec<usize> = repeat(0).take(m).collect();
        for (i, &c) in bwt.iter().enumerate() {
            curr_occ[c as usize] += 1;
            if i % k as usize == 0 {
                occ.push(curr_occ.clone());
            }
        }

        Occ { occ: occ, k: k }
    }

    /// Get occurrence count of symbol a in BWT[..r+1].
    /// Complexity: O(k).
    pub fn get(&self, bwt: &BWTSlice, r: usize, a: u8) -> usize {
        // NOTE:
        //
        // Retrieving byte match counts in this function is critical to the performance of FM Index.
        //
        // The below manual count code is roughly equivalent to:
        // ```
        // let count = bwt[(i * self.k) + 1..r + 1].iter().filter(|&&c| c == a).count();
        // self.occ[i][a as usize] + count
        // ```
        //
        // But there are a couple of reasons to do this manually:
        // 1) As of 2016, versions of rustc/LLVM vectorize this manual loop more reliably
        //    than the iterator adapter version.
        // 2) Manually accumulating the byte match count in a single chunk can allows
        //    us to use a `u32` for that count, which has faster arithmetic on common arches.
        //    This does necessitate storing `k` as a u32.
        //
        // See the conversation in these issues for some of the history here:
        //
        // https://github.com/rust-bio/rust-bio/pull/74
        // https://github.com/rust-bio/rust-bio/pull/76

        // self.k is our sampling rate, so find our last sampled checkpoint
        let i = r / self.k as usize;
        let checkpoint = self.occ[i][a as usize];

        // find the portion of the BWT past the checkpoint which we need to count
        let start = (i * self.k as usize) + 1;
        let end = r + 1;

        // count all the matching bytes b/t the closest checkpoint and our desired lookup
        let mut count: u32 = 0;
        for &x in &bwt[start..end] {
            if x == a {
                count += 1;
            }
        }

        // return the sampled checkpoint for this character + the manual count we just did
        checkpoint + (count as usize)
    }
}

/// Calculate the less array for a given BWT. Complexity O(n).
pub fn less(bwt: &BWTSlice, alphabet: &Alphabet) -> Less {
    let m = alphabet.max_symbol().expect("Expecting non-empty alphabet.") as usize + 2;
    let mut less: Less = repeat(0)
                             .take(m)
                             .collect();
    for &c in bwt.iter() {
        less[c as usize] += 1;
    }
    // calculate +-prescan
    prescan(&mut less[..], 0, |a, b| a + b);

    less
}

/// Calculate the bwtfind array needed for inverting the BWT. Complexity O(n).
pub fn bwtfind(bwt: &BWTSlice, alphabet: &Alphabet) -> BWTFind {
    let n = bwt.len();
    let mut less = less(bwt, alphabet);

    let mut bwtfind: BWTFind = repeat(0).take(n).collect();
    for (r, &c) in bwt.iter().enumerate() {
        bwtfind[less[c as usize]] = r;
        less[c as usize] += 1;
    }

    bwtfind
}

#[cfg(test)]
mod tests {
    use super::{bwtfind, bwt, invert_bwt, Occ};
    use data_structures::suffix_array::suffix_array;
    use alphabets::Alphabet;

    #[test]
    fn test_bwtfind() {
        let text = b"cabca$";
        let alphabet = Alphabet::new(b"abc$");
        let pos = suffix_array(text);
        let bwt = bwt(text, &pos);
        let bwtfind = bwtfind(&bwt, &alphabet);
        assert_eq!(bwtfind, vec![5, 0, 3, 4, 1, 2]);
    }

    #[test]
    fn test_invert_bwt() {
        let text = b"cabca$";
        let pos = suffix_array(text);
        let bwt = bwt(text, &pos);
        let inverse = invert_bwt(&bwt);
        assert_eq!(inverse, text);
    }

    #[test]
    fn test_occ() {
        let bwt = vec![1u8, 3u8, 3u8, 1u8, 2u8, 0u8];
        let alphabet = Alphabet::new(&[0u8, 1u8, 2u8, 3u8]);
        let occ = Occ::new(&bwt, 3, &alphabet);
        assert_eq!(occ.occ, [[0, 1, 0, 0], [0, 2, 0, 2]]);
        assert_eq!(occ.get(&bwt, 4, 2u8), 1);
        assert_eq!(occ.get(&bwt, 4, 3u8), 2);
    }

    #[test]
    #[cfg(feature = "nightly")]
    fn test_serde() {
        use serde::{Serialize, Deserialize};
        fn impls_serde_traits<S: Serialize + Deserialize>() {}

        impls_serde_traits::<Occ>();
    }
}
<|endoftext|>


<commit_before>extern crate rand;

#[macro_use]
extern crate common;

use common::err::{Void, void_ok};
use common::plugin::{Plugin, PluginManager};

mod arithm_funcs;
mod math_funcs;

const PACKAGE_NAME: &'static str = "default";

pub struct DefaultPackage;

impl Plugin for DefaultPackage
{
  fn name(&self) -> &str { PACKAGE_NAME }

  fn load(&self, mgr: &mut PluginManager) -> Void
  {
  	try!(arithm_funcs::register_funcs(mgr));
  	try!(math_funcs::register_funcs(mgr));

		void_ok
  }
}<commit_msg>Disable some functions.<commit_after>extern crate rand;

#[macro_use]
extern crate common;

use common::err::{Void, void_ok};
use common::plugin::{Plugin, PluginManager};

//mod arithm_funcs;
//mod math_funcs;

const PACKAGE_NAME: &'static str = "default";

pub struct DefaultPackage;

impl Plugin for DefaultPackage
{
  fn name(&self) -> &str { PACKAGE_NAME }

  fn load(&self, mgr: &mut PluginManager) -> Void
  {
  	//try!(arithm_funcs::register_funcs(mgr));
  	//try!(math_funcs::register_funcs(mgr));

		void_ok
  }
}<|endoftext|>


<commit_before><commit_msg>Refactored metadata.rs (#687)<commit_after><|endoftext|>


<commit_before><commit_msg>Test i64 and u64 types serealization/deserialization<commit_after><|endoftext|>


<commit_before><commit_msg>Implement Eq and Hash for ObjectIdentitifer (#149)<commit_after><|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/.

use std::path::Path;
use std::path::PathBuf;

use devicemapper::DM;
use uuid::Uuid;

use engine::Engine;
use engine::EngineError;
use engine::EngineResult;
use engine::ErrorEnum;
use engine::Pool;
use engine::Redundancy;
use engine::RenameAction;

use super::pool::StratPool;

use super::super::engine::{HasName, HasUuid, PoolUuid};
use super::super::structures::Table;

#[derive(Debug, PartialEq, Eq)]
pub enum DevOwnership {
    Ours(Uuid),
    Unowned,
    Theirs,
}

#[derive(Debug)]
pub struct StratEngine {
    pools: Table<StratPool>,
}

impl StratEngine {
    pub fn new() -> StratEngine {
        StratEngine { pools: Table::new() }
    }
}

impl Engine for StratEngine {
    fn configure_simulator(&mut self, _denominator: u32) -> EngineResult<()> {
        Ok(()) // we're not the simulator and not configurable, so just say ok
    }

    fn create_pool(&mut self,
                   name: &str,
                   blockdev_paths: &[&Path],
                   redundancy: Option<u16>,
                   force: bool)
                   -> EngineResult<(PoolUuid, Vec<PathBuf>)> {

        let redundancy = calculate_redundancy!(redundancy);

        if self.pools.contains_name(name) {
            return Err(EngineError::Engine(ErrorEnum::AlreadyExists, name.into()));
        }

        let dm = try!(DM::new());
        let pool = try!(StratPool::initialize(name, &dm, blockdev_paths, redundancy, force));
        let bdev_paths = pool.block_devs.iter().map(|p| p.1.devnode.clone()).collect();

        let uuid = pool.uuid().clone();
        self.pools.insert(pool);
        Ok((uuid, bdev_paths))
    }

    /// Destroy a pool, if the pool does not exist, return Ok.
    fn destroy_pool(&mut self, uuid: &PoolUuid) -> EngineResult<bool> {
        destroy_pool!{self; uuid}
    }

    fn rename_pool(&mut self, uuid: &PoolUuid, new_name: &str) -> EngineResult<RenameAction> {
        rename_pool!{self; uuid; new_name}
    }

    fn get_pool(&mut self, uuid: &PoolUuid) -> Option<&mut Pool> {
        get_pool!(self; uuid)
    }

    fn check(&mut self) -> () {
        for pool in self.pools.iter_mut() {
            pool.check();
        }
    }
}
<commit_msg>Get rid of header comment in implementation<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/.

use std::path::Path;
use std::path::PathBuf;

use devicemapper::DM;
use uuid::Uuid;

use engine::Engine;
use engine::EngineError;
use engine::EngineResult;
use engine::ErrorEnum;
use engine::Pool;
use engine::Redundancy;
use engine::RenameAction;

use super::pool::StratPool;

use super::super::engine::{HasName, HasUuid, PoolUuid};
use super::super::structures::Table;

#[derive(Debug, PartialEq, Eq)]
pub enum DevOwnership {
    Ours(Uuid),
    Unowned,
    Theirs,
}

#[derive(Debug)]
pub struct StratEngine {
    pools: Table<StratPool>,
}

impl StratEngine {
    pub fn new() -> StratEngine {
        StratEngine { pools: Table::new() }
    }
}

impl Engine for StratEngine {
    fn configure_simulator(&mut self, _denominator: u32) -> EngineResult<()> {
        Ok(()) // we're not the simulator and not configurable, so just say ok
    }

    fn create_pool(&mut self,
                   name: &str,
                   blockdev_paths: &[&Path],
                   redundancy: Option<u16>,
                   force: bool)
                   -> EngineResult<(PoolUuid, Vec<PathBuf>)> {

        let redundancy = calculate_redundancy!(redundancy);

        if self.pools.contains_name(name) {
            return Err(EngineError::Engine(ErrorEnum::AlreadyExists, name.into()));
        }

        let dm = try!(DM::new());
        let pool = try!(StratPool::initialize(name, &dm, blockdev_paths, redundancy, force));
        let bdev_paths = pool.block_devs.iter().map(|p| p.1.devnode.clone()).collect();

        let uuid = pool.uuid().clone();
        self.pools.insert(pool);
        Ok((uuid, bdev_paths))
    }

    fn destroy_pool(&mut self, uuid: &PoolUuid) -> EngineResult<bool> {
        destroy_pool!{self; uuid}
    }

    fn rename_pool(&mut self, uuid: &PoolUuid, new_name: &str) -> EngineResult<RenameAction> {
        rename_pool!{self; uuid; new_name}
    }

    fn get_pool(&mut self, uuid: &PoolUuid) -> Option<&mut Pool> {
        get_pool!(self; uuid)
    }

    fn check(&mut self) -> () {
        for pool in self.pools.iter_mut() {
            pool.check();
        }
    }
}
<|endoftext|>