<commit_before>#![crate_name = "locale"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![feature(core, env, path, io, std_misc)]

use std::old_io::fs::PathExtensions;
use std::old_io::{IoResult, File, BufferedReader};
use std::env::var_string;
use std::num::{Int, Float};
use std::fmt::Display;

enum LocaleType {
    Numeric, Time,
}

impl LocaleType {
    fn file_name(&self) -> &'static str {
        match *self {
            LocaleType::Numeric => "LC_NUMERIC",
            LocaleType::Time    => "LC_TIME",
        }
    }
}

#[derive(Debug, Clone)]
pub struct Numeric {
    decimal_sep: String,
    thousands_sep: String,
}

fn find_locale_path(locale_type: LocaleType) -> Option<Path> {
    if let Ok(numeric_path) = var_string("LC_ALL") {
        let path = Path::new(numeric_path);
        if path.exists() {
            return Some(path);
        }
    }

    if let Ok(numeric_path) = var_string(locale_type.file_name()) {
        let path = Path::new(numeric_path);
        if path.exists() {
            return Some(path);
        }
    }

    if let Ok(lang) = var_string("LANG") {
        let path = Path::new("/usr/share/locale").join(Path::new(lang)).join(Path::new(locale_type.file_name()));
        if path.exists() {
            return Some(path);
        }
    }

    None
}

impl Numeric {
    pub fn load_user_locale() -> IoResult<Numeric> {
        let path = find_locale_path(LocaleType::Numeric);

        if let Some(path) = path {
            let mut file = BufferedReader::new(File::open(&path));
            let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();

            Ok(Numeric {
                decimal_sep: lines[0].trim().to_string(),
                thousands_sep: lines[1].trim().to_string(),
            })
        }
        else {
            return Ok(Numeric::default());
        }
    }

    pub fn default() -> Numeric {
        Numeric::new(".", " ")
    }

    pub fn new(decimal_sep: &str, thousands_sep: &str) -> Numeric {
        Numeric {
            decimal_sep: decimal_sep.to_string(),
            thousands_sep: thousands_sep.to_string(),
        }
    }

    pub fn format_int<I: Int + Display>(&self, input: I) -> String {
        let s = input.to_string();
        let mut buf = String::new();

        for (i, c) in s.chars().enumerate() {
            buf.push(c);
            if (s.len() - i - 1) % 3 == 0 && i != s.len() - 1 {
                buf.push_str(&self.thousands_sep[]);
            }
        }

        buf
    }

    pub fn format_float<F: Float>(&self, input: F, decimal_places: usize) -> String {
        use std::num::strconv;
        strconv::float_to_str_common(input, 10, false, strconv::SignFormat::SignNone, strconv::SignificantDigits::DigExact(decimal_places), strconv::ExponentFormat::ExpNone, false).0.replace(".", self.decimal_sep.as_slice())
    }
}

// ---- time stuff ---

#[derive(Debug, Clone)]
pub struct Time {
    month_names: Vec<String>,
    long_month_names: Vec<String>,
    day_names: Vec<String>,
    long_day_names: Vec<String>,
}

impl Time {
    pub fn load_user_locale() -> IoResult<Time> {
        let path = find_locale_path(LocaleType::Time);

        if let Some(path) = path {
            let mut file = BufferedReader::new(File::open(&path));
            let mut iter = file.lines().map(|x| x.unwrap().trim().to_string());

            let month_names      = iter.by_ref().take(12).collect();
            let long_month_names = iter.by_ref().take(12).collect();
            let day_names        = iter.by_ref().take(7).collect();
            let long_day_names   = iter.by_ref().take(7).collect();

            Ok(Time {
                month_names:      month_names,
                long_month_names: long_month_names,
                day_names:        day_names,
                long_day_names:   long_day_names,
            })
        }
        else {
            return Ok(Time::default());
        }
    }

    pub fn default() -> Time {
        Time {
            month_names: vec![],
            long_month_names: vec![],
            day_names: vec![],
            long_day_names: vec![],
        }
    }

    pub fn long_month_name(&self, months_from_january: usize) -> String {
        self.month_names[months_from_january].clone()
    }

    pub fn short_month_name(&self, months_from_january: usize) -> String {
        self.month_names[months_from_january].clone()
    }

    pub fn long_day_name(&self, days_from_sunday: usize) -> String {
        self.day_names[days_from_sunday].clone()
    }

    pub fn short_day_name(&self, days_from_sunday: usize) -> String {
        self.day_names[days_from_sunday].clone()
    }

}

// ---- tests ----

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

    #[test]
    fn thousands_separator() {
        let numeric_options = Numeric::new("/", "=");
        assert_eq!("1=234=567".to_string(), numeric_options.format_int(1234567))
    }

    #[test]
    fn thousands_separator_2() {
        let numeric_options = Numeric::new("/", "=");
        assert_eq!("123=456".to_string(), numeric_options.format_int(123456))
    }

    #[test]
    fn thousands_separator_3() {
        let numeric_options = Numeric::new("/", "=");
        assert_eq!("12=345=678".to_string(), numeric_options.format_int(12345678))
    }
}
<commit_msg>Complete English month and day names<commit_after>#![crate_name = "locale"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![feature(core, env, path, io, std_misc)]

use std::old_io::fs::PathExtensions;
use std::old_io::{IoResult, File, BufferedReader};
use std::env::var_string;
use std::num::{Int, Float};
use std::fmt::Display;

/// The directory inside which locale files are found.
///
/// For example, the set of Korean files will be in
/// `/usr/share/locale/ko`.
static LOCALE_DIR: &'static str = "/usr/share/locale";

#[derive(Debug, Clone)]
enum LocaleType {
    Numeric, Time,
}

fn find_locale_path(locale_type: LocaleType) -> Option<Path> {
    if let Ok(numeric_path) = var_string("LC_ALL") {
        let path = Path::new(numeric_path);
        if path.exists() {
            return Some(path);
        }
    }

    let file_name = match locale_type {
        LocaleType::Numeric => "LC_NUMERIC",
        LocaleType::Time    => "LC_TIME",
    };

    if let Ok(numeric_path) = var_string(file_name) {
        let path = Path::new(numeric_path);
        if path.exists() {
            return Some(path);
        }
    }

    if let Ok(lang) = var_string("LANG") {
        let path = Path::new(LOCALE_DIR).join(Path::new(lang)).join(Path::new(file_name));

        if path.exists() {
            return Some(path);
        }
    }

    None
}

#[derive(Debug, Clone)]
pub struct Numeric {
    pub decimal_sep: String,
    pub thousands_sep: String,
}

impl Numeric {
    pub fn load_user_locale() -> IoResult<Numeric> {
        let path = find_locale_path(LocaleType::Numeric);

        if let Some(path) = path {
            let mut file = BufferedReader::new(File::open(&path));
            let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();

            Ok(Numeric {
                decimal_sep: lines[0].trim().to_string(),
                thousands_sep: lines[1].trim().to_string(),
            })
        }
        else {
            return Ok(Numeric::english());
        }
    }

    pub fn english() -> Numeric {
        Numeric::new(".", ",")
    }

    pub fn new(decimal_sep: &str, thousands_sep: &str) -> Numeric {
        Numeric {
            decimal_sep: decimal_sep.to_string(),
            thousands_sep: thousands_sep.to_string(),
        }
    }

    pub fn format_int<I: Int + Display>(&self, input: I) -> String {
        let s = input.to_string();
        let mut buf = String::new();

        for (i, c) in s.chars().enumerate() {
            buf.push(c);
            if (s.len() - i - 1) % 3 == 0 && i != s.len() - 1 {
                buf.push_str(&self.thousands_sep[]);
            }
        }

        buf
    }

    pub fn format_float<F: Float>(&self, input: F, decimal_places: usize) -> String {
        use std::num::strconv;
        strconv::float_to_str_common(input, 10, false, strconv::SignFormat::SignNone, strconv::SignificantDigits::DigExact(decimal_places), strconv::ExponentFormat::ExpNone, false).0.replace(".", self.decimal_sep.as_slice())
    }
}

// ---- time stuff ---

#[derive(Debug, Clone)]
pub struct Time {
    month_names: Vec<String>,
    long_month_names: Vec<String>,
    day_names: Vec<String>,
    long_day_names: Vec<String>,
}

impl Time {
    pub fn load_user_locale() -> IoResult<Time> {
        let path = find_locale_path(LocaleType::Time);

        if let Some(path) = path {
            let mut file = BufferedReader::new(File::open(&path));
            let mut iter = file.lines().map(|x| x.unwrap().trim().to_string());

            let month_names      = iter.by_ref().take(12).collect();
            let long_month_names = iter.by_ref().take(12).collect();
            let day_names        = iter.by_ref().take(7).collect();
            let long_day_names   = iter.by_ref().take(7).collect();

            Ok(Time {
                month_names:      month_names,
                long_month_names: long_month_names,
                day_names:        day_names,
                long_day_names:   long_day_names,
            })
        }
        else {
            return Ok(Time::english());
        }
    }

    pub fn english() -> Time {
        Time {
            month_names: vec![
                "Jan".to_string(),  "Feb".to_string(),  "Mar".to_string(),
                "Apr".to_string(),  "May".to_string(),  "Jun".to_string(),
                "Jul".to_string(),  "Aug".to_string(),  "Sep".to_string(),
                "Oct".to_string(),  "Nov".to_string(),  "Dec".to_string(),
            ],
            long_month_names: vec![
                "January".to_string(),    "February".to_string(),
                "March".to_string(),      "April".to_string(),
                "May".to_string(),        "June".to_string(),
                "July".to_string(),       "August".to_string(),
                "September".to_string(),  "October".to_string(),
                "November".to_string(),   "December".to_string(),
            ],
            day_names: vec![
                "Sun".to_string(),
                "Mon".to_string(),  "Tue".to_string(),  "Wed".to_string(),
                "Thu".to_string(),  "Fri".to_string(),  "Sat".to_string(),
            ],
            long_day_names: vec![
                "Sunday".to_string(),
                "Monday".to_string(),    "Tuesday".to_string(),  "Wednesday".to_string(),
                "Thursday".to_string(),  "Friday".to_string(),   "Saturday".to_string(),
            ],
        }
    }

    pub fn long_month_name(&self, months_from_january: usize) -> String {
        self.long_month_names[months_from_january].clone()
    }

    pub fn short_month_name(&self, months_from_january: usize) -> String {
        self.month_names[months_from_january].clone()
    }

    pub fn long_day_name(&self, days_from_sunday: usize) -> String {
        self.day_names[days_from_sunday].clone()
    }

    pub fn short_day_name(&self, days_from_sunday: usize) -> String {
        self.day_names[days_from_sunday].clone()
    }

}

// ---- tests ----

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

    #[test]
    fn thousands_separator() {
        let numeric_options = Numeric::new("/", "=");
        assert_eq!("1=234=567".to_string(), numeric_options.format_int(1234567))
    }

    #[test]
    fn thousands_separator_2() {
        let numeric_options = Numeric::new("/", "=");
        assert_eq!("123=456".to_string(), numeric_options.format_int(123456))
    }

    #[test]
    fn thousands_separator_3() {
        let numeric_options = Numeric::new("/", "=");
        assert_eq!("12=345=678".to_string(), numeric_options.format_int(12345678))
    }
}
<|endoftext|>


<commit_before>// Copyright 2016 Amanieu d'Antras
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! This library provides implementations of `Mutex`, `RwLock`, `Condvar` and
//! `Once` that are smaller, faster and more flexible than those in the Rust
//! standard library. It also exposes a low-level API for creating your own
//! efficient synchronization primitives.
//!
//! # Features
//!
//! The primitives provided by this library have several advantages over those
//! in the Rust standard library:
//!
//! 1. `Mutex`, `Condvar` and `Once` only require 1 byte of storage space, and
//!    `RwLock` only requires 1 word of storage space. On the other hand the
//!    standard library primitives require a dynamically allocated `Box` to hold
//!    OS-specific synchronization primitives. The small size of `Mutex` in
//!    particular encourages the use of fine-grained locks to increase
//!    parallelism.
//! 2. Since they consist of just a single atomic variable, have constant
//!    initializers and don't need destructors, these primitives can be used as
//!     `static` global variables. The standard library primitives require
//!    dynamic initialization and thus need to be lazily initialized with
//!    `lazy_static!`.
//! 3. Uncontended lock acquisition and release is done through fast inline
//!    paths which only require a single atomic operation.
//! 4. Microcontention (a contended lock with a short critical section) is
//!    efficiently handled by spinning a few times while trying to acquire a
//!    lock.
//! 5. The locks are adaptive and will suspend a thread after a few failed spin
//!    attempts. This makes the locks suitable for both long and short critical
//!    sections.
//!
//! # The parking lot
//!
//! To keep these primitives small, all thread queuing and suspending
//! functionality is offloaded to the *parking lot*. The idea behind this is
//! based on the Webkit [`WTF::ParkingLot`]
//! (https://webkit.org/blog/6161/locking-in-webkit/) class, which essentially
//! consists of a hash table mapping of lock addresses to queues of parked
//! (sleeping) threads. The Webkit parking lot was itself inspired by Linux
//! [futexes](http://man7.org/linux/man-pages/man2/futex.2.html), but it is more
//! powerful since it allows invoking callbacks while holding a queue lock.
//!
//! *Parking* refers to suspending the thread while simultaneously enqueuing it
//! on a queue keyed by some address. *Unparking* refers to dequeuing a thread
//! from a queue keyed by some address and resuming it. The parking lot API
//! consists of just 4 functions:
//!
//! ```rust,ignore
//! unsafe fn park(key: usize,
//!                validate: &mut FnMut() -> bool,
//!                before_sleep: &mut FnMut(),
//!                timed_out: &mut FnMut(usize, UnparkResult),
//!                timeout: Option<Instant>)
//!                -> bool
//! ```
//!
//! This function performs the following steps:
//!
//! 1. Lock the queue associated with `key`.
//! 2. Call `validate`, if it returns `false`, unlock the queue and return.
//! 3. Add the current thread to the queue.
//! 4. Unlock the queue.
//! 5. Call `before_sleep`.
//! 6. Sleep until we are unparked or `timeout` is reached.
//! 7. If the park timed out, call `timed_out`.
//! 8. Return `true` if we were unparked by another thread, `false` otherwise.
//!
//! ```rust,ignore
//! unsafe fn unpark_one(key: usize,
//!                      callback: &mut FnMut(UnparkResult))
//!                      -> UnparkResult
//! ```
//!
//! This function will unpark a single thread from the queue associated with
//! `key`. The `callback` function is invoked while holding the queue lock but
//! before the thread is unparked. The `UnparkResult` indicates whether the
//! queue was empty and, if not, whether there are still threads remaining in
//! the queue.
//!
//! ```rust,ignore
//! unsafe fn unpark_all(key: usize) -> usize
//! ```
//!
//! This function will unpark all threads in the queue associated with `key`. It
//! returns the number of threads that were unparked.
//!
//! ```rust,ignore
//! unsafe fn unpark_requeue(key_from: usize,
//!                          key_to: usize,
//!                          validate: &mut FnMut() -> RequeueOp,
//!                          callback: &mut FnMut(RequeueOp, usize))
//!                          -> usize
//! ```
//!
//! This function will remove all threads from the queue associated with
//! `key_from`, optionally unpark the first one and move the rest to the queue
//! associated with `key_to`. The `validate` function is invoked while holding
//! both queue locks and can choose whether to abort the operation and whether
//! to unpark one thread from the queue. The `callback` function is then called
//! with the result of `validate` and the number of threads that were in the
//! original queue.
//!
//! # Building custom synchronization primitives
//!
//! Building custom synchronization primitives is very simple since
//! `parking_lot` takes care of all the hard parts for you. The most commmon
//! case for a custom primitive would be to integrate a `Mutex` inside another
//! data type. Since a mutex only requires 2 bits, it can share space with other
//! data. For example, one could create an `ArcMutex` type that combines the
//! atomic reference count and the two mutex bits in the same atomic word.

#![warn(missing_docs)]
#![cfg_attr(feature = "nightly", feature(extended_compare_and_swap))]
#![cfg_attr(feature = "nightly", feature(const_fn))]
#![cfg_attr(feature = "nightly", feature(integer_atomics))]

extern crate smallvec;

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

#[cfg(all(feature = "nightly", target_os = "linux"))]
extern crate libc;

#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;

// Spin limit from JikesRVM & Webkit experiments
const SPIN_LIMIT: usize = 40;

#[cfg(all(feature = "nightly", target_os = "linux"))]
#[path = "thread_parker/linux.rs"]
mod thread_parker;
#[cfg(windows)]
#[path = "thread_parker/windows.rs"]
mod thread_parker;
#[cfg(not(any(windows, all(feature = "nightly", target_os = "linux"))))]
#[path = "thread_parker/generic.rs"]
mod thread_parker;

#[cfg(not(feature = "nightly"))]
mod stable;
mod word_lock;
mod parking_lot;
mod raw_mutex;
mod raw_rwlock;
mod condvar;
mod mutex;
mod rwlock;
mod once;

pub use once::{Once, ONCE_INIT, OnceState};
pub use parking_lot::{UnparkResult, RequeueOp, park, unpark_one, unpark_all, unpark_requeue};
pub use mutex::{Mutex, MutexGuard};
pub use condvar::{Condvar, WaitTimeoutResult};
pub use rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
<commit_msg>Increase the spin limit<commit_after>// Copyright 2016 Amanieu d'Antras
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! This library provides implementations of `Mutex`, `RwLock`, `Condvar` and
//! `Once` that are smaller, faster and more flexible than those in the Rust
//! standard library. It also exposes a low-level API for creating your own
//! efficient synchronization primitives.
//!
//! # Features
//!
//! The primitives provided by this library have several advantages over those
//! in the Rust standard library:
//!
//! 1. `Mutex`, `Condvar` and `Once` only require 1 byte of storage space, and
//!    `RwLock` only requires 1 word of storage space. On the other hand the
//!    standard library primitives require a dynamically allocated `Box` to hold
//!    OS-specific synchronization primitives. The small size of `Mutex` in
//!    particular encourages the use of fine-grained locks to increase
//!    parallelism.
//! 2. Since they consist of just a single atomic variable, have constant
//!    initializers and don't need destructors, these primitives can be used as
//!     `static` global variables. The standard library primitives require
//!    dynamic initialization and thus need to be lazily initialized with
//!    `lazy_static!`.
//! 3. Uncontended lock acquisition and release is done through fast inline
//!    paths which only require a single atomic operation.
//! 4. Microcontention (a contended lock with a short critical section) is
//!    efficiently handled by spinning a few times while trying to acquire a
//!    lock.
//! 5. The locks are adaptive and will suspend a thread after a few failed spin
//!    attempts. This makes the locks suitable for both long and short critical
//!    sections.
//!
//! # The parking lot
//!
//! To keep these primitives small, all thread queuing and suspending
//! functionality is offloaded to the *parking lot*. The idea behind this is
//! based on the Webkit [`WTF::ParkingLot`]
//! (https://webkit.org/blog/6161/locking-in-webkit/) class, which essentially
//! consists of a hash table mapping of lock addresses to queues of parked
//! (sleeping) threads. The Webkit parking lot was itself inspired by Linux
//! [futexes](http://man7.org/linux/man-pages/man2/futex.2.html), but it is more
//! powerful since it allows invoking callbacks while holding a queue lock.
//!
//! *Parking* refers to suspending the thread while simultaneously enqueuing it
//! on a queue keyed by some address. *Unparking* refers to dequeuing a thread
//! from a queue keyed by some address and resuming it. The parking lot API
//! consists of just 4 functions:
//!
//! ```rust,ignore
//! unsafe fn park(key: usize,
//!                validate: &mut FnMut() -> bool,
//!                before_sleep: &mut FnMut(),
//!                timed_out: &mut FnMut(usize, UnparkResult),
//!                timeout: Option<Instant>)
//!                -> bool
//! ```
//!
//! This function performs the following steps:
//!
//! 1. Lock the queue associated with `key`.
//! 2. Call `validate`, if it returns `false`, unlock the queue and return.
//! 3. Add the current thread to the queue.
//! 4. Unlock the queue.
//! 5. Call `before_sleep`.
//! 6. Sleep until we are unparked or `timeout` is reached.
//! 7. If the park timed out, call `timed_out`.
//! 8. Return `true` if we were unparked by another thread, `false` otherwise.
//!
//! ```rust,ignore
//! unsafe fn unpark_one(key: usize,
//!                      callback: &mut FnMut(UnparkResult))
//!                      -> UnparkResult
//! ```
//!
//! This function will unpark a single thread from the queue associated with
//! `key`. The `callback` function is invoked while holding the queue lock but
//! before the thread is unparked. The `UnparkResult` indicates whether the
//! queue was empty and, if not, whether there are still threads remaining in
//! the queue.
//!
//! ```rust,ignore
//! unsafe fn unpark_all(key: usize) -> usize
//! ```
//!
//! This function will unpark all threads in the queue associated with `key`. It
//! returns the number of threads that were unparked.
//!
//! ```rust,ignore
//! unsafe fn unpark_requeue(key_from: usize,
//!                          key_to: usize,
//!                          validate: &mut FnMut() -> RequeueOp,
//!                          callback: &mut FnMut(RequeueOp, usize))
//!                          -> usize
//! ```
//!
//! This function will remove all threads from the queue associated with
//! `key_from`, optionally unpark the first one and move the rest to the queue
//! associated with `key_to`. The `validate` function is invoked while holding
//! both queue locks and can choose whether to abort the operation and whether
//! to unpark one thread from the queue. The `callback` function is then called
//! with the result of `validate` and the number of threads that were in the
//! original queue.
//!
//! # Building custom synchronization primitives
//!
//! Building custom synchronization primitives is very simple since
//! `parking_lot` takes care of all the hard parts for you. The most commmon
//! case for a custom primitive would be to integrate a `Mutex` inside another
//! data type. Since a mutex only requires 2 bits, it can share space with other
//! data. For example, one could create an `ArcMutex` type that combines the
//! atomic reference count and the two mutex bits in the same atomic word.

#![warn(missing_docs)]
#![cfg_attr(feature = "nightly", feature(extended_compare_and_swap))]
#![cfg_attr(feature = "nightly", feature(const_fn))]
#![cfg_attr(feature = "nightly", feature(integer_atomics))]

extern crate smallvec;

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

#[cfg(all(feature = "nightly", target_os = "linux"))]
extern crate libc;

#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;

// Spin limit, determined experimentally
const SPIN_LIMIT: usize = 60;

#[cfg(all(feature = "nightly", target_os = "linux"))]
#[path = "thread_parker/linux.rs"]
mod thread_parker;
#[cfg(windows)]
#[path = "thread_parker/windows.rs"]
mod thread_parker;
#[cfg(not(any(windows, all(feature = "nightly", target_os = "linux"))))]
#[path = "thread_parker/generic.rs"]
mod thread_parker;

#[cfg(not(feature = "nightly"))]
mod stable;
mod word_lock;
mod parking_lot;
mod raw_mutex;
mod raw_rwlock;
mod condvar;
mod mutex;
mod rwlock;
mod once;

pub use once::{Once, ONCE_INIT, OnceState};
pub use parking_lot::{UnparkResult, RequeueOp, park, unpark_one, unpark_all, unpark_requeue};
pub use mutex::{Mutex, MutexGuard};
pub use condvar::{Condvar, WaitTimeoutResult};
pub use rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
<|endoftext|>


<commit_before>//! Rust-Rocks
//!
//! The RocksDB API in Rustic Style.
//!
//! # Examples
//!
//! ```no_run
//! use rocks::rocksdb::*;
//! // RAII DB instance
//! let db = DB::open(&Options::default(), "./data").unwrap();
//! assert!(db.put(&WriteOptions::default(), b"my key", b"my value").is_ok());
//! match db.get(&ReadOptions::default(), b"my key") {
//!     Ok(ref value) => println!("retrieved value {}", String::from_utf8_lossy(value)),
//!     Err(e) => println!("operational problem encountered: {}", e),
//! }
//! let _ = db.delete(&WriteOptions::default(), b"my key").unwrap();
//! ```
// #![cfg_attr(feature = "dev", feature(plugin))]
// #![cfg_attr(feature = "dev", plugin(clippy))]
// #![cfg_attr(not(feature = "dev"), allow(unknown_lints))]
// #![allow(not_unsafe_ptr_arg_deref, wrong_self_convention, doc_markdown)]
#![allow(unused_variables, dead_code)]

pub use error::Status;

/// The result type returned by RocksDB, wraps Status
pub type Result<T> = std::result::Result<T, Status>;

pub mod advanced_options;
pub mod cache;
pub mod compaction_filter;
pub mod compaction_job_stats;
pub mod comparator;
pub mod convenience;
pub mod db;
pub mod db_dump_tool;
pub mod debug;
pub mod env;
pub mod error;
pub mod filter_policy;
pub mod flush_block_policy;
pub mod iostats_context;
pub mod iterator;
pub mod listener;
pub mod merge_operator;
pub mod metadata;
pub mod options;
pub mod perf_context;
pub mod perf_level;
pub mod persistent_cache;
pub mod rate_limiter;
pub mod slice;
pub mod slice_transform;
pub mod snapshot;
pub mod sst_file_manager;
pub mod sst_file_writer;
pub mod statistics;
pub mod table;
pub mod table_properties;
pub mod thread_status;
pub mod transaction_log;
pub mod types;
pub mod universal_compaction;
pub mod wal_filter;
pub mod write_batch;
pub mod write_buffer_manager;

// the prelude
pub mod prelude;

// #[deprecated(since = "0.1.5", note = "Please use the `prelude` module instead")]
pub mod rocksdb {
    pub use crate::prelude::*;
}

// for raw pointer infomation hiding
mod to_raw;
<commit_msg>docs(rocks): refine default sample code<commit_after>//! Rust-Rocks
//!
//! The RocksDB API in Rustic Style.
//!
//! # Examples
//!
//! ```no_run
//! use rocks::rocksdb::*;
//!
//! let opt = Options::default().map_db_options(|db_opt| db_opt.create_if_missing(true));
//! let db = DB::open(opt, "./data").unwrap();
//!
//! assert!(db.put(WriteOptions::default_instance(), b"hello", b"world").is_ok());
//!
//! match db.get(ReadOptions::default_instance(), b"hello") {
//!     Ok(ref value) => println!("hello: {:?}", value),
//!     Err(e) => eprintln!("error: {}", e),
//! }
//! let _ = db.delete(WriteOptions::default_instance(), b"hello").unwrap();
//! ```
// #![cfg_attr(feature = "dev", feature(plugin))]
// #![cfg_attr(feature = "dev", plugin(clippy))]
// #![cfg_attr(not(feature = "dev"), allow(unknown_lints))]
// #![allow(not_unsafe_ptr_arg_deref, wrong_self_convention, doc_markdown)]
#![allow(unused_variables, dead_code)]

pub use error::Status;

/// The result type returned by RocksDB, wraps Status
pub type Result<T> = std::result::Result<T, Status>;

pub mod advanced_options;
pub mod cache;
pub mod compaction_filter;
pub mod compaction_job_stats;
pub mod comparator;
pub mod convenience;
pub mod db;
pub mod db_dump_tool;
pub mod debug;
pub mod env;
pub mod error;
pub mod filter_policy;
pub mod flush_block_policy;
pub mod iostats_context;
pub mod iterator;
pub mod listener;
pub mod merge_operator;
pub mod metadata;
pub mod options;
pub mod perf_context;
pub mod perf_level;
pub mod persistent_cache;
pub mod rate_limiter;
pub mod slice;
pub mod slice_transform;
pub mod snapshot;
pub mod sst_file_manager;
pub mod sst_file_writer;
pub mod statistics;
pub mod table;
pub mod table_properties;
pub mod thread_status;
pub mod transaction_log;
pub mod types;
pub mod universal_compaction;
pub mod wal_filter;
pub mod write_batch;
pub mod write_buffer_manager;

// the prelude
pub mod prelude;

// #[deprecated(since = "0.1.5", note = "Please use the `prelude` module instead")]
pub mod rocksdb {
    pub use crate::prelude::*;
}

// for raw pointer infomation hiding
mod to_raw;
<|endoftext|>


<commit_before>#![feature(macro_rules)]

extern crate "simple-logging" as logging;

use std::cell;
use std::sync;
use std::io::stdio;
use logging::Logger;
use logging::Level;
use logging::IntoLogger;
use logging::LoggerOutput;

thread_local!(static DEFAULT_LOGGER: cell::RefCell<sync::Arc<Box<Logger + Sync + Send>>> = cell::RefCell::new(sync::Arc::new(LoggerOutput::Stdout.into_logger().unwrap())))

pub fn init_thread_logger(logger: sync::Arc<Box<Logger + Sync + Send>>) {
    DEFAULT_LOGGER.with(move |log| {
        *log.borrow_mut() = logger;
    });
}

pub fn log(level: &Level, msg: &str) {
    DEFAULT_LOGGER.with(|logger| {
        match logger.borrow().log(level, msg) {
            Ok(()) => (),
            // TODO: Should we store stderr_raw here, or does it not matter, since this is really totally backup.
            Err(e) => match write!(&mut stdio::stderr_raw(), "Error logging {{level: {}, msg: {}}}: {}", level, msg, e) {
                Ok(()) => (),
                Err(e2) => panic!(format!("Backup logging failed after regular logging failed. Original log: {{level: {}, msg: {}}}\nLogging error: {}\nBackup logging error: {}", level, msg, e, e2)),
            }
        };
    });
}

#[macro_export]
macro_rules! log(
    ($level:expr, $($arg:tt)*) => (
        ::logging_macros::log($level, format!($($arg)*).as_slice())
    )
)

#[macro_export]
macro_rules! debug(
    ($($arg:tt)*) => (
        log!(&::logging::Level::Debug, $($arg)*)
    )
)

#[macro_export]
macro_rules! info(
    ($($arg:tt)*) => (
        log!(&::logging::Level::Info, $($arg)*)
    )
)

#[macro_export]
macro_rules! warning(
    ($($arg:tt)*) => (
        log!(&::logging::Level::Warning, $($arg)*)
    )
)

#[macro_export]
macro_rules! severe(
    ($($arg:tt)*) => (
        log!(&::logging::Level::Severe, $($arg)*)
    )
)

#[macro_export]
macro_rules! log_error(
    ($result:expr, $($arg:tt)*) => (
        match $result {
            Ok(_) => (),
            Err(e) => severe!(format!($($arg)*, e=e)),
        }
    )
)

#[macro_export]
macro_rules! log_error_then(
    ($result:expr, $after:expr, $($arg:tt)*) => (
        match $result {
            Ok(_) => (),
            Err(e) => {
                severe!($($arg)*, e=e);
                $after;
            },
        }
    )
)
<commit_msg>Update for latest rustc<commit_after>#![feature(macro_rules)]

extern crate "simple-logging" as logging;

use std::cell;
use std::sync;
use std::io::stdio;
use logging::Logger;
use logging::Level;
use logging::IntoLogger;
use logging::LoggerOutput;

thread_local!(static DEFAULT_LOGGER: cell::RefCell<sync::Arc<Box<Logger + Sync + Send>>> = cell::RefCell::new(sync::Arc::new(LoggerOutput::Stdout.into_logger().unwrap())));

pub fn init_thread_logger(logger: sync::Arc<Box<Logger + Sync + Send>>) {
    DEFAULT_LOGGER.with(move |log| {
        *log.borrow_mut() = logger;
    });
}

pub fn log(level: &Level, msg: &str) {
    DEFAULT_LOGGER.with(|logger| {
        match logger.borrow().log(level, msg) {
            Ok(()) => (),
            // TODO: Should we store stderr_raw here, or does it not matter, since this is really totally backup.
            Err(e) => match write!(&mut stdio::stderr_raw(), "Error logging {{level: {}, msg: {}}}: {}", level, msg, e) {
                Ok(()) => (),
                Err(e2) => panic!(format!("Backup logging failed after regular logging failed. Original log: {{level: {}, msg: {}}}\nLogging error: {}\nBackup logging error: {}", level, msg, e, e2)),
            }
        };
    });
}

#[macro_export]
macro_rules! log(
    ($level:expr, $($arg:tt)*) => (
        ::logging_macros::log($level, format!($($arg)*).as_slice())
    )
);

#[macro_export]
macro_rules! debug(
    ($($arg:tt)*) => (
        log!(&::logging::Level::Debug, $($arg)*)
    )
);

#[macro_export]
macro_rules! info(
    ($($arg:tt)*) => (
        log!(&::logging::Level::Info, $($arg)*)
    )
);

#[macro_export]
macro_rules! warning(
    ($($arg:tt)*) => (
        log!(&::logging::Level::Warning, $($arg)*)
    )
);

#[macro_export]
macro_rules! severe(
    ($($arg:tt)*) => (
        log!(&::logging::Level::Severe, $($arg)*)
    )
);

#[macro_export]
macro_rules! log_error(
    ($result:expr, $($arg:tt)*) => (
        match $result {
            Ok(_) => (),
            Err(e) => severe!(format!($($arg)*, e=e)),
        }
    )
);

#[macro_export]
macro_rules! log_error_then(
    ($result:expr, $after:expr, $($arg:tt)*) => (
        match $result {
            Ok(_) => (),
            Err(e) => {
                severe!($($arg)*, e=e);
                $after;
            },
        }
    )
);
<|endoftext|>


<commit_before>/*!
Miscellaneous utilities grab-bag.

 */

#![crate_name="calx"]
#![feature(core, collections, std_misc)]
#![feature(plugin, custom_attribute)]
#![plugin(regex_macros)]

extern crate collections;
extern crate rustc_serialize;
extern crate time;
extern crate rand;
extern crate regex;
extern crate image;
extern crate glutin;
#[macro_use]
extern crate glium;

use std::env;
use std::path::{Path, PathBuf};
use std::num::Wrapping;

pub use rgb::{Rgb, Rgba};
pub use geom::{V2, V3, Rect, RectIter};
pub use img::{color_key};
pub use atlas::{AtlasBuilder, Atlas, AtlasItem};
pub use dijkstra::{DijkstraNode, Dijkstra};
pub use encode_rng::{EncodeRng};

mod atlas;
mod dijkstra;
mod geom;
mod encode_rng;
mod img;
mod primitive;
mod rgb;

pub mod backend;
pub mod color;
pub mod text;
pub mod timing;
pub mod vorud;

/// Things that describe a color.
pub trait ToColor {
    fn to_rgba(&self) -> [f32; 4];
}

/// Things that can be made from a color.
pub trait FromColor: Sized {
    fn from_rgba(rgba: [f32; 4]) -> Self;

    fn from_color<C: ToColor>(color: &C) -> Self {
        FromColor::from_rgba(color.to_rgba())
    }
}

pub trait Color: ToColor + FromColor {}

/// Clamp a value to range.
pub fn clamp<C: PartialOrd+Copy>(mn: C, mx: C, x: C) -> C {
    if x < mn { mn }
    else if x > mx { mx }
    else { x }
}

/// Deterministic noise.
pub fn noise(n: i32) -> f32 {
    let n = Wrapping(n);
    let n = (n << 13) ^ n;
    let m = (n * (n * n * Wrapping(15731) + Wrapping(789221)) + Wrapping(1376312589))
        & Wrapping(0x7fffffff);
    let Wrapping(m) = m;
    1.0 - m as f32 / 1073741824.0
}

/// Rectangle anchoring points.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Anchor {
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
    Top,
    Left,
    Right,
    Bottom,
    Center
}

/// Return the application data directory path for the current platform.
#[cfg(target_os = "macos")]
pub fn app_data_path(app_name: &str) -> PathBuf {
    Path::new(
        format!("{}/Library/Application Support/{}",
                env::var("HOME").unwrap(), app_name))
    .to_path_buf()
}

#[cfg(target_os = "windows")]
pub fn app_data_path(_app_name: &str) -> PathBuf {
    use std::os;

    // Unless the Windows app was installed with an actual installer instead
    // of just being a portable .exe file, it shouldn't go around creating
    // strange directories but just use the local directory instead.

    // Path::new(
    // format!("{}\\{}", env::var("APPDATA").unwrap(), app_name))
    // .to_path_buf();

    match os::self_exe_path() {
        Some(p) => p.to_path_buf(),
        // If couldn't get self exe path, just use the local relative path and
        // hope for the best.
        _ => Path::new(".").to_path_buf()
    }
}

#[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
pub fn app_data_path(app_name: &str) -> PathBuf {
    Path::new(
        &format!("{}/.config/{}", env::var("HOME").unwrap(), app_name))
    .to_path_buf()
}

#[cfg(test)]
mod test {
    #[test]
    fn test_noise() {
        use super::noise;

        for i in 0i32..100 {
            assert!(noise(i) >= -1.0 && noise(i) <= 1.0);
        }
    }
}
<commit_msg>Update Windows path determination<commit_after>/*!
Miscellaneous utilities grab-bag.

 */

#![crate_name="calx"]
#![feature(core, collections, std_misc)]
#![feature(plugin, custom_attribute)]
#![plugin(regex_macros)]

extern crate collections;
extern crate rustc_serialize;
extern crate time;
extern crate rand;
extern crate regex;
extern crate image;
extern crate glutin;
#[macro_use]
extern crate glium;

use std::env;
use std::path::{Path, PathBuf};
use std::num::Wrapping;

pub use rgb::{Rgb, Rgba};
pub use geom::{V2, V3, Rect, RectIter};
pub use img::{color_key};
pub use atlas::{AtlasBuilder, Atlas, AtlasItem};
pub use dijkstra::{DijkstraNode, Dijkstra};
pub use encode_rng::{EncodeRng};

mod atlas;
mod dijkstra;
mod geom;
mod encode_rng;
mod img;
mod primitive;
mod rgb;

pub mod backend;
pub mod color;
pub mod text;
pub mod timing;
pub mod vorud;

/// Things that describe a color.
pub trait ToColor {
    fn to_rgba(&self) -> [f32; 4];
}

/// Things that can be made from a color.
pub trait FromColor: Sized {
    fn from_rgba(rgba: [f32; 4]) -> Self;

    fn from_color<C: ToColor>(color: &C) -> Self {
        FromColor::from_rgba(color.to_rgba())
    }
}

pub trait Color: ToColor + FromColor {}

/// Clamp a value to range.
pub fn clamp<C: PartialOrd+Copy>(mn: C, mx: C, x: C) -> C {
    if x < mn { mn }
    else if x > mx { mx }
    else { x }
}

/// Deterministic noise.
pub fn noise(n: i32) -> f32 {
    let n = Wrapping(n);
    let n = (n << 13) ^ n;
    let m = (n * (n * n * Wrapping(15731) + Wrapping(789221)) + Wrapping(1376312589))
        & Wrapping(0x7fffffff);
    let Wrapping(m) = m;
    1.0 - m as f32 / 1073741824.0
}

/// Rectangle anchoring points.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Anchor {
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
    Top,
    Left,
    Right,
    Bottom,
    Center
}

/// Return the application data directory path for the current platform.
#[cfg(target_os = "macos")]
pub fn app_data_path(app_name: &str) -> PathBuf {
    Path::new(
        format!("{}/Library/Application Support/{}",
                env::var("HOME").unwrap(), app_name))
    .to_path_buf()
}

#[cfg(target_os = "windows")]
pub fn app_data_path(_app_name: &str) -> PathBuf {
    use std::env;

    // Unless the Windows app was installed with an actual installer instead
    // of just being a portable .exe file, it shouldn't go around creating
    // strange directories but just use the local directory instead.

    // Path::new(
    // format!("{}\\{}", env::var("APPDATA").unwrap(), app_name))
    // .to_path_buf();

    match env::current_exe() {
        Ok(mut p) => { p.pop(); p }
        // If couldn't get self exe path, just use the local relative path and
        // hope for the best.
        _ => Path::new(".").to_path_buf()
    }
}

#[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
pub fn app_data_path(app_name: &str) -> PathBuf {
    Path::new(
        &format!("{}/.config/{}", env::var("HOME").unwrap(), app_name))
    .to_path_buf()
}

#[cfg(test)]
mod test {
    #[test]
    fn test_noise() {
        use super::noise;

        for i in 0i32..100 {
            assert!(noise(i) >= -1.0 && noise(i) <= 1.0);
        }
    }
}
<|endoftext|>


<commit_before>#[clippy::author]
#[cfg(any(target_arch = "x86"))]
pub struct Foo {
    x: u32,
}

fn main() {}
<commit_msg>remove needless my_lint ui test<commit_after><|endoftext|>


<commit_before>//! # boxcars (also written boxca-rs)
//!
//! boxcars is an example of a [Rocket League](http://www.rocketleaguegame.com/) replay parser
//! written in Rust using [nom](https://github.com/Geal/nom) for parsing and
//! [serde](https://github.com/serde-rs/serde) for serialization. Emphasis on example, as this
//! library in no way competes with the other feature complete parsers such as
//! [Octane](https://github.com/tfausak/octane) and
//! [RocketLeagueReplayParser](https://github.com/jjbott/RocketLeagueReplayParser). Rather, let
//! boxcars be a good example of Rust code using nom, and serde as extensive examples are hard to
//! come by. While lacking feature completeness and user friendly error message -- [among other
//! issues](https://github.com/nickbabcock/boxcars/issues), tests and documentation strive to be
//! thorough.
//!
//! ```
//! # let filename = "assets/rumble.replay";
//! let mut f = File::open(filename).unwrap();
//! let mut buffer = vec![];
//! f.read_to_end(&mut buffer).unwrap();
//! let b = boxcars::parse(&buffer);
//!
//! match b {
//!     IResult::Done(_, val) => {
//!         let serialized = serde_json::to_string(&val).unwrap();
//!         println!("{}", serialized);
//!     }
//!     _ => {
//!         println!("Oh no we failed to parse");
//!     }
//! }
//! ```

#![feature(plugin, custom_derive)]
#![plugin(serde_macros)]

#[macro_use]
extern crate nom;
extern crate serde;

#[cfg(test)] extern crate serde_json;

pub use self::models::*;
pub use self::parsing::*;
mod models;
mod parsing;

<commit_msg>Fix up rustdoc examples<commit_after>//! # boxcars (also written boxca-rs)
//!
//! boxcars is an example of a [Rocket League](http://www.rocketleaguegame.com/) replay parser
//! written in Rust using [nom](https://github.com/Geal/nom) for parsing and
//! [serde](https://github.com/serde-rs/serde) for serialization. Emphasis on example, as this
//! library in no way competes with the other feature complete parsers such as
//! [Octane](https://github.com/tfausak/octane) and
//! [RocketLeagueReplayParser](https://github.com/jjbott/RocketLeagueReplayParser). Rather, let
//! boxcars be a good example of Rust code using nom, and serde as extensive examples are hard to
//! come by. While lacking feature completeness and user friendly error message -- [among other
//! issues](https://github.com/nickbabcock/boxcars/issues), tests and documentation strive to be
//! thorough.
//!
//! ```
//! extern crate boxcars;
//! extern crate nom;
//! extern crate serde_json;
//!
//! use std::fs::File;
//! use std::io::Read;
//!
//! # let filename = "assets/rumble.replay";
//! let mut f = File::open(filename).unwrap();
//! let mut buffer = vec![];
//! f.read_to_end(&mut buffer).unwrap();
//! let b = boxcars::parse(&buffer);
//!
//! match b {
//!     nom::IResult::Done(_, val) => {
//!         let serialized = serde_json::to_string(&val).unwrap();
//!         println!("{}", serialized);
//!     }
//!     _ => {
//!         println!("Oh no we failed to parse");
//!     }
//! }
//! ```

#![feature(plugin, custom_derive)]
#![plugin(serde_macros)]

#[macro_use]
extern crate nom;
extern crate serde;

#[cfg(test)] extern crate serde_json;

pub use self::models::*;
pub use self::parsing::*;
mod models;
mod parsing;

<|endoftext|>


<commit_before>extern crate x11;
extern crate libc;

use std::ptr;
use std::process::Command;
use std::boxed::Box;

use x11::xlib;
use super::WindowManager;
use super::Workspaces;
use super::container;
use super::layout::{self, LayoutDirection, MoveDirection};
use super::super::libx::{self, Context};

#[derive(Hash, Eq, PartialEq, Debug)]
pub struct KeyBind {
    pub key: xlib::KeySym,
    pub mask: u32,
}

impl KeyBind {
    pub fn build(mod_key: u32, tokens: &[&str]) -> KeyBind {
        let mut mask = 0;
        let mut sym = 0;
        for key in tokens {
            match *key {
                "$mod" => mask = mask | mod_key,
                "Shift" => mask = mask | xlib::ShiftMask,
                "Ctrl" => mask = mask | xlib::ControlMask,
                "Mod1" => mask = mask | xlib::Mod1Mask,
                "Mod2" => mask = mask | xlib::Mod2Mask,
                "Mod3" => mask = mask | xlib::Mod3Mask,
                "Mod4" => mask = mask | xlib::Mod4Mask,
                "Mod5" => mask = mask | xlib::Mod5Mask,
                _ => {
                    sym = libx::string_to_keysym(key);
                }
            }
        }

        KeyBind {
            mask: mask,
            key: sym
        }
    }
}

pub trait Handler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context);
}

pub struct ExecHandler {
    pub cmd: Command
}

pub struct LayoutHandler {
    layout_type: layout::Type,
}

pub struct FullscreenHandler;
/// switch to another workspace
pub struct WorkspaceHandler {
    pub key: char,
}

/// move window to target workspace
pub struct WindowToWorkspaceHandler {
    pub key: char,
}

pub struct WindowFocusHandler {
    pub direction: MoveDirection,
}

pub struct WindowCloseHandler;
pub struct SplitHandler;

pub enum Resize {
    Shrink,
    Grow,
}

pub struct WindowResizeHandler {
    pub direction: LayoutDirection,
    pub resize: Resize
}

impl Handler for WindowResizeHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        let focused = workspaces.get_focus();
        if focused.is_some() {
            let c = focused.unwrap();
            let parent = c.get_parent();
            if parent.is_some() {
                let p = parent.unwrap();
                let index = p.contain(c.raw_id()).unwrap();
                if p.direction == self.direction {
                    let step:f32 = match self.resize {
                        Resize::Shrink => {
                            -0.05
                        }
                        Resize::Grow => {
                            0.05
                        }
                    };

                    if index > 0 && index < (p.size() - 1) {
                        p.resize_children(index, index-1, step);
                        p.resize_children(index, index+1, step);
                    }
                    else if index > 0 {
                        p.resize_children(index, index-1, step*2.0);
                    }
                    else if index < (p.size() - 1) {
                        p.resize_children(index, index+1, step*2.0);
                    }
                    p.update_layout();
                }

            }
        }
    }
}

impl Handler for SplitHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        workspaces.current().print_tree(0);
        match workspaces.get_focus() {
            Some(c) => {
                c.split();
            }
            None => {}
        }
        println!("after");
        workspaces.current().print_tree(0);
    }
}

impl Handler for WindowCloseHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("handle window close");
        let (window, _) = libx::get_input_focus(context);
        libx::kill_window(context, window);
        // xlib::XWithdrawWindow(context, window, screen_num);
        // xlib::XDestroyWindow(context, window);
        println!("try kill window {}", window);

    }
}
impl Handler for WindowFocusHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("change focus in current workspace");
        // let res = workspaces.get_focus(context);

        // match res {
        //     Some(container) => {
        //         println!("window {}", container.id);
        //         container.unfocus();

        //         let current = workspaces.current();
        //         match current.contain(container.id) {
        //             Some(i) => {
        //                 let next = current.next_client(container.id);
        //                 next.unwrap().focus();
        //             }
        //             None => {}
        //         }
        //     }
        //     None => {}
        // }
        let current = workspaces.current();
        current.switch_client();
    }
}

impl Handler for WindowToWorkspaceHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        let id = match workspaces.get_focus() {
            Some(container) => {
                container.raw_id()
            }
            None => { return }
        };
        let from = workspaces.current_name();
        let to = self.key;
        workspaces.move_window(id, from, to);
    }
}

impl Handler for FullscreenHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("fullscreen toggle");
        let focused = workspaces.get_focus();
        match focused {
            Some(c) => {
                c.mode_toggle();
            }
            None => {}
        }
    }
}
impl Handler for WorkspaceHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("handle workspace form {}", workspaces.current_name());
        if !workspaces.contain(self.key) {
            workspaces.create(self.key);
        }
        workspaces.switch_workspace(self.key, context);
        println!("to {}", workspaces.current_name());
    }
}

impl Handler for ExecHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("handle exec");
        self.cmd.spawn();
    }
}

impl Handler for LayoutHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("handle layout");
        let t = self.layout_type.clone();
        let focused = workspaces.get_focus();
        match focused {
            Some(container) => {
                let c = if container.get_parent().is_some() {
                    container.get_parent().unwrap()
                }
                else {
                    container
                };
                c.change_layout(t);
                c.update_layout();
            }
            None => {}
        }
    }
}

impl LayoutHandler {
    pub fn new(layout: layout::Type) -> LayoutHandler{
        LayoutHandler {
            layout_type: layout
        }
    }
}

impl ExecHandler {
    pub fn new(tokens: &[&str]) -> ExecHandler {
        let (name, args) = tokens.split_at(1);
        let mut cmd = Command::new(name[0]);
        cmd.args(args);

        let handler = ExecHandler {
            cmd: cmd,
        };
        handler
    }
}
<commit_msg>focus handler<commit_after>extern crate x11;
extern crate libc;

use std::ptr;
use std::process::Command;
use std::boxed::Box;

use x11::xlib;
use super::WindowManager;
use super::Workspaces;
use super::container;
use super::layout::{self, LayoutDirection, MoveDirection};
use super::super::libx::{self, Context};

#[derive(Hash, Eq, PartialEq, Debug)]
pub struct KeyBind {
    pub key: xlib::KeySym,
    pub mask: u32,
}

impl KeyBind {
    pub fn build(mod_key: u32, tokens: &[&str]) -> KeyBind {
        let mut mask = 0;
        let mut sym = 0;
        for key in tokens {
            match *key {
                "$mod" => mask = mask | mod_key,
                "Shift" => mask = mask | xlib::ShiftMask,
                "Ctrl" => mask = mask | xlib::ControlMask,
                "Mod1" => mask = mask | xlib::Mod1Mask,
                "Mod2" => mask = mask | xlib::Mod2Mask,
                "Mod3" => mask = mask | xlib::Mod3Mask,
                "Mod4" => mask = mask | xlib::Mod4Mask,
                "Mod5" => mask = mask | xlib::Mod5Mask,
                _ => {
                    sym = libx::string_to_keysym(key);
                }
            }
        }

        KeyBind {
            mask: mask,
            key: sym
        }
    }
}

pub trait Handler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context);
}

pub struct ExecHandler {
    pub cmd: Command
}

pub struct LayoutHandler {
    layout_type: layout::Type,
}

pub struct FullscreenHandler;
/// switch to another workspace
pub struct WorkspaceHandler {
    pub key: char,
}

/// move window to target workspace
pub struct WindowToWorkspaceHandler {
    pub key: char,
}

pub struct WindowFocusHandler {
    pub direction: MoveDirection,
}

pub struct WindowCloseHandler;
pub struct SplitHandler;

pub enum Resize {
    Shrink,
    Grow,
}

pub struct WindowResizeHandler {
    pub direction: LayoutDirection,
    pub resize: Resize
}

impl Handler for WindowResizeHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        let focused = workspaces.get_focus();
        if focused.is_some() {
            let c = focused.unwrap();
            let parent = c.get_parent();
            if parent.is_some() {
                let p = parent.unwrap();
                let index = p.contain(c.raw_id()).unwrap();
                if p.direction == self.direction {
                    let step:f32 = match self.resize {
                        Resize::Shrink => {
                            -0.05
                        }
                        Resize::Grow => {
                            0.05
                        }
                    };

                    if index > 0 && index < (p.size() - 1) {
                        p.resize_children(index, index-1, step);
                        p.resize_children(index, index+1, step);
                    }
                    else if index > 0 {
                        p.resize_children(index, index-1, step*2.0);
                    }
                    else if index < (p.size() - 1) {
                        p.resize_children(index, index+1, step*2.0);
                    }
                    p.update_layout();
                }

            }
        }
    }
}

impl Handler for SplitHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        workspaces.current().print_tree(0);
        match workspaces.get_focus() {
            Some(c) => {
                c.split();
            }
            None => {}
        }
        println!("after");
        workspaces.current().print_tree(0);
    }
}

impl Handler for WindowCloseHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("handle window close");
        let (window, _) = libx::get_input_focus(context);
        libx::kill_window(context, window);
        // xlib::XWithdrawWindow(context, window, screen_num);
        // xlib::XDestroyWindow(context, window);
        println!("try kill window {}", window);

    }
}
impl Handler for WindowFocusHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("change focus in current workspace");
        let focused = workspaces.get_focus();
        match focused {
            Some(c) => {
                match c.get_parent() {
                    Some(p) => {
                        let index = p.contain(c.raw_id()).unwrap();
                        let size = p.size();
                        match p.direction {
                            LayoutDirection::Vertical => {
                                let next = match self.direction {
                                    MoveDirection::Up => {
                                        (index-1) % size
                                    }
                                    MoveDirection::Down => {
                                        (index+1) % size
                                    }
                                    _ => { return }
                                };
                                c.unfocus();
                                let next_c = p.get_child(next).unwrap().focus();
                            }
                            LayoutDirection::Horizontal => {
                                let next = match self.direction {
                                    MoveDirection::Left => {
                                        (index-1) % size
                                    }
                                    MoveDirection::Right => {
                                        (index+1) % size
                                    }
                                    _ => { return }
                                };
                                c.unfocus();
                                let next_c = p.get_child(next).unwrap().focus();
                            }
                        }
                    }
                    None => {}
                }
            }
            None => {}
        }
    }
}

impl Handler for WindowToWorkspaceHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        let id = match workspaces.get_focus() {
            Some(container) => {
                container.raw_id()
            }
            None => { return }
        };
        let from = workspaces.current_name();
        let to = self.key;
        workspaces.move_window(id, from, to);
    }
}

impl Handler for FullscreenHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("fullscreen toggle");
        let focused = workspaces.get_focus();
        match focused {
            Some(c) => {
                c.mode_toggle();
            }
            None => {}
        }
    }
}
impl Handler for WorkspaceHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("handle workspace form {}", workspaces.current_name());
        if !workspaces.contain(self.key) {
            workspaces.create(self.key);
        }
        workspaces.switch_workspace(self.key, context);
        println!("to {}", workspaces.current_name());
    }
}

impl Handler for ExecHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("handle exec");
        self.cmd.spawn();
    }
}

impl Handler for LayoutHandler {
    fn handle(&mut self, workspaces: &mut Workspaces, context: Context) {
        debug!("handle layout");
        let t = self.layout_type.clone();
        let focused = workspaces.get_focus();
        match focused {
            Some(container) => {
                let c = if container.get_parent().is_some() {
                    container.get_parent().unwrap()
                }
                else {
                    container
                };
                c.change_layout(t);
                c.update_layout();
            }
            None => {}
        }
    }
}

impl LayoutHandler {
    pub fn new(layout: layout::Type) -> LayoutHandler{
        LayoutHandler {
            layout_type: layout
        }
    }
}

impl ExecHandler {
    pub fn new(tokens: &[&str]) -> ExecHandler {
        let (name, args) = tokens.split_at(1);
        let mut cmd = Command::new(name[0]);
        cmd.args(args);

        let handler = ExecHandler {
            cmd: cmd,
        };
        handler
    }
}
<|endoftext|>


<commit_before>use term::*;
use term::Term::*;
use term::Error::*;
use booleans::*;
use reduction::*;

// PAIR := λxyf.f x y
pub fn pair() -> Term { abs(abs(abs(Var(1).app(Var(3)).app(Var(2))))) }

// FIRST := λp.p TRUE
pub fn first() -> Term { abs(Var(1).app(tru())) }

// SECOND := λp.p FALSE
pub fn second() -> Term { abs(Var(1).app(fls())) }

// NIL := λx.TRUE
pub fn nil() -> Term { abs(tru()) }

// NULL := λp.p (λxy.FALSE)
pub fn null() -> Term { abs(Var(1).app(abs(abs(fls())))) }

// CONS := λht.PAIR FALSE (PAIR h t)
pub fn cons() -> Term { abs(abs(pair().app(fls()).app(pair().app(Var(2)).app(Var(1))))) }

// HEAD := λz.FIRST (SECOND z)
pub fn head() -> Term { abs(first().app(second().app(Var(1)))) }

// TAIL := λz.SECOND (SECOND z)
pub fn tail() -> Term { abs(second().app(second().app(Var(1)))) }

impl Term {
	pub fn is_pair(&self) -> bool {
		self.fst_ref().is_ok() && self.snd_ref().is_ok()
	}

	pub fn unpair(self) -> Result<(Term, Term), Error> {
		if let Abs(_) = self {
			if let Ok((wrapped_a, b)) = self.unabs().and_then(|t| t.unapp()) {
				Ok((try!(wrapped_a.rhs()), b))
			} else {
				Err(NotAPair)
			}
		} else {
			if let Ok((wrapped_a, b)) = self.unapp() {
				Ok((try!(wrapped_a.rhs()), b))
			} else {
				Err(NotAPair)
			}
		}
	}

	pub fn unpair_ref(&self) -> Result<(&Term, &Term), Error> {
		if let Abs(_) = *self {
			if let Ok((wrapped_a, b)) = self.unabs_ref().and_then(|t| t.unapp_ref()) {
				Ok((try!(wrapped_a.rhs_ref()), b))
			} else {
				Err(NotAPair)
			}
		} else {
			if let Ok((wrapped_a, b)) = self.unapp_ref() {
				Ok((try!(wrapped_a.rhs_ref()), b))
			} else {
				Err(NotAPair)
			}
		}
	}

	pub fn unpair_ref_mut(&mut self) -> Result<(&mut Term, &mut Term), Error> {
		if let Abs(_) = *self {
			if let Ok((wrapped_a, b)) = self.unabs_ref_mut().and_then(|t| t.unapp_ref_mut()) {
				Ok((try!(wrapped_a.rhs_ref_mut()), b))
			} else {
				Err(NotAPair)
			}
		} else {
			if let Ok((wrapped_a, b)) = self.unapp_ref_mut() {
				Ok((try!(wrapped_a.rhs_ref_mut()), b))
			} else {
				Err(NotAPair)
			}
		}
	}

	pub fn fst(self) -> Result<Term, Error> {
		Ok(try!(self.unpair()).0)
	}

	pub fn fst_ref(&self) -> Result<&Term, Error> {
		Ok(try!(self.unpair_ref()).0)
	}

	pub fn fst_ref_mut(&mut self) -> Result<&mut Term, Error> {
		Ok(try!(self.unpair_ref_mut()).0)
	}

	pub fn snd(self) -> Result<Term, Error> {
		Ok(try!(self.unpair()).1)
	}

	pub fn snd_ref(&self) -> Result<&Term, Error> {
		Ok(try!(self.unpair_ref()).1)
	}

	pub fn snd_ref_mut(&mut self) -> Result<&mut Term, Error> {
		Ok(try!(self.unpair_ref_mut()).1)
	}

	pub fn last_ref(&self) -> Result<&Term, Error> {
		let mut last_candidate = try!(self.snd_ref());

		while let Ok(ref second) = last_candidate.snd_ref() {
			last_candidate = *second;
		}

		Ok(last_candidate)
	}

	pub fn is_nil(&self) -> bool {
		*self == nil()
	}

	pub fn is_list(&self) -> bool {
		self.is_pair() && self.last_ref() == Ok(&nil())
	}

	pub fn uncons(self) -> Result<(Term, Term), Error> {
		if !self.is_list() {
			Err(NotAList)
		} else {
			self.unabs()
				.and_then(|t| t.snd())
				.and_then(|t| t.unpair())
		}
	}

	pub fn uncons_ref(&self) -> Result<(&Term, &Term), Error> {
		if !self.is_list() {
			Err(NotAList)
		} else {
			self.unabs_ref()
				.and_then(|t| t.snd_ref())
				.and_then(|t| t.unpair_ref())
		}
	}

	pub fn uncons_ref_mut(&mut self) -> Result<(&mut Term, &mut Term), Error> {
		if !self.is_list() {
			Err(NotAList)
		} else {
			self.unabs_ref_mut()
				.and_then(|t| t.snd_ref_mut())
				.and_then(|t| t.unpair_ref_mut())
		}
	}

	pub fn head(self) -> Result<Term, Error> {
		Ok(try!(self.uncons()).0)
	}

	pub fn head_ref(&self) -> Result<&Term, Error> {
		Ok(try!(self.uncons_ref()).0)
	}

	pub fn head_ref_mut(&mut self) -> Result<&mut Term, Error> {
		Ok(try!(self.uncons_ref_mut()).0)
	}

	pub fn tail(self) -> Result<Term, Error> {
		Ok(try!(self.uncons()).1)
	}

	pub fn tail_ref(&self) -> Result<&Term, Error> {
		Ok(try!(self.uncons_ref()).1)
	}

	pub fn tail_ref_mut(&mut self) -> Result<&mut Term, Error> {
		Ok(try!(self.uncons_ref_mut()).1)
	}

	pub fn len(&self) -> Result<usize, Error> {
		let mut inner = self;
		let mut n = 0;

		while *inner != nil() {
			n += 1;
			inner = try!(inner.tail_ref());
		}

		Ok(n)
	}

	pub fn push(self, t: Term) -> Term {
		normalize(cons().app(t).app(self))
	}

	pub fn pop(&mut self) -> Result<Term, Error> {
		let (head, tail) = try!(self.clone().uncons());
		*self = tail;

		Ok(head)
	}
}

impl From<Vec<Term>> for Term {
	fn from(terms: Vec<Term>) -> Self {
		let mut output = nil();

		for t in terms.into_iter().rev() {
			output = cons().app(t).app(output);
		}

		normalize(output)
	}
}

impl Iterator for Term {
	type Item = Term;

	fn next(&mut self) -> Option<Term> {
		if self.is_nil() {
			None
		} else {
			Some(self.pop().unwrap())
		}
	}
}

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

	#[test]
	fn pair_operations() {
		let pair_four_three = normalize(pair().app(to_cnum(4)).app(to_cnum(3)));

		assert!(pair_four_three.is_pair());

		assert_eq!(pair_four_three.fst_ref(), Ok(&to_cnum(4)));
		assert_eq!(pair_four_three.snd_ref(), Ok(&to_cnum(3)));

		let unpaired = pair_four_three.unpair();
		assert_eq!(unpaired, Ok((to_cnum(4), to_cnum(3))));
	}

	#[test]
	fn empty_list() {
		let nil = nil();

		assert!(nil.is_nil());
		assert!(!nil.is_list());
		assert_eq!(nil.uncons(), Err(NotAList));
	}

	#[test]
	fn list_push() {
		let list_pushed = nil().push(zero()).push(one()).push(one());
		let list_manual = normalize(cons().app(one()).app(cons().app(one()).app(cons().app(zero()).app(nil()))));

		assert_eq!(list_pushed, list_manual);
	}

	#[test]
	fn list_from_vector() {
		let list_from_vec = Term::from(vec![one(), one(), zero()]);
		let list_pushed = nil().push(zero()).push(one()).push(one());

		assert_eq!(list_from_vec, list_pushed);
	}

	#[test]
	fn list_length() {
		let list0 = nil();
		assert_eq!(list0.len(), Ok(0));
		let list1 = list0.push(one());
		assert_eq!(list1.len(), Ok(1));
		let list2 = list1.push(one());
		assert_eq!(list2.len(), Ok(2));
		let list3 = list2.push(one());
		assert_eq!(list3.len(), Ok(3));
	}

	#[test]
	fn list_operations() {
		let list_three_five_four = Term::from(vec![to_cnum(3), to_cnum(5), to_cnum(4)]);

		assert!(list_three_five_four.is_list());

		assert_eq!(list_three_five_four.head_ref(), Ok(&to_cnum(3)));
		assert_eq!(list_three_five_four.tail_ref(), Ok(&Term::from(vec![to_cnum(5), to_cnum(4)])));

		assert_eq!(list_three_five_four.tail_ref().and_then(|t| t.head_ref()), Ok(&to_cnum(5)));
		assert_eq!(list_three_five_four.tail_ref().and_then(|t| t.tail_ref()).and_then(|t| t.head_ref()), Ok(&to_cnum(4)));

		let unconsed = list_three_five_four.uncons();
		assert_eq!(unconsed, Ok((to_cnum(3), Term::from(vec![to_cnum(5), to_cnum(4)]))));
	}

	#[test]
	fn list_pop() {
		let mut list_poppable = Term::from(vec![one(), zero(), zero()]);

		assert_eq!(list_poppable.pop(), Ok(one()));
		assert_eq!(list_poppable.pop(), Ok(zero()));
		assert_eq!(list_poppable.pop(), Ok(zero()));
		assert_eq!(list_poppable.pop(), Err(NotAList));
	}

	#[test]
	fn iterating_list() {
		let list010 = Term::from(vec![zero(), one(), zero()]);
		let mut iter = list010.into_iter();

		assert_eq!(iter.next(), Some(zero()));
		assert_eq!(iter.next(), Some(one()));
		assert_eq!(iter.next(), Some(zero()));
		assert_eq!(iter.next(), None);
	}

}<commit_msg>Delete list.rs<commit_after><|endoftext|>


<commit_before>use rusqlite::Connection;
use std::result;

#[derive(Debug)]
pub struct WhenenvEnviroment {
    id: i32,
    fk_job: i32,
    fk_variable: i32,
}

pub fn table_create_enviroment(conn: &Connection)  {
    conn.execute("CREATE TABLE WHENENV_ENVIROMENT (
                  id                    INTEGER PRIMARY KEY ASC,
                  fk_session            INTEGER NOT NULL,
                  fk_variable_name           INTEGER NOT NULL,
                  FOREIGN KEY(fk_session) REFERENCES WHENENV_SESSION(id) ON UPDATE CASCADE
                  FOREIGN KEY(fk_variable) REFERENCES VARIABLE_NAME(id) ON UPDATE CASCADE
                  )", &[]).unwrap();
}

pub fn insert_enviroment(conn: &Connection, job: &i32, variable: &i32) -> Result<i32, &'static str> {
    let me = WhenenvEnviroment {
        id: 0,
        fk_job: *job,
        fk_variable: *variable,

    };
    let enviroment_instance = conn.execute("INSERT INTO WHENENV_ENVIROMENT (fk_job, fk_variable)
                  VALUES (?1, ?2)",
                 &[&me.fk_job, &me.fk_variable]);
    if enviroment_instance.is_err() {
        return Err("Insert failed");
    }
    enviroment_instance.unwrap();
    return Ok(0);
}

pub fn list_enviroment(conn: &Connection)-> Vec<WhenenvEnviroment> {
    let mut stmt = conn.prepare("SELECT id, fk_job, fk_variable  FROM WHENENV_ENVIROMENT").unwrap();
    let wraped_fs_file_iter = stmt.query_map(&[], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_job: row.get(1),
            fk_variable: row.get(2),
        }
    });
    let mut items = Vec::<WhenenvEnviroment>::new();
    if wraped_fs_file_iter.is_err() {
        return items;

    }
    let fs_file_iter = wraped_fs_file_iter.unwrap();
    for person in fs_file_iter {

        items.push(person.unwrap());
    }
    return items;
}

pub fn enviroment_list(conn: &Connection) {
    let mut stmt = conn.prepare("SELECT id, fk_job, fk_variable  FROM WHENENV_ENVIROMENT").unwrap();
    let person_iter = stmt.query_map(&[], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_job: row.get(1),
            fk_variable: row.get(2),
        }
    }).unwrap();

    for person in person_iter {
        println!("Found enviroment {:?}", person.unwrap());
    }
}

pub fn pk_enviroment_by_name(conn: &Connection, job: &i32, variable: &i32, pk: &mut i32) -> Result<i32, &'static str>{
    let mut stmt = conn.prepare("SELECT id, fk_job, fk_variable  FROM WHENENV_ENVIROMENT WHERE fk_job = ?1 AND fk_variable = ?2").unwrap();
    let enviroment_iter = stmt.query_map(&[job, variable], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_job: row.get(1),
            fk_variable: row.get(2),
        }
    });
    if enviroment_iter.is_err() {
        return Err("Insert failed dfdf");
    }
    let result = enviroment_iter.unwrap();
    let mut found = 0;
    let mut items = Vec::<i32>::new();
    for person in result {
        let bill= person.unwrap();
        *pk = bill.id;
        found = 1;
    }
    if found != 0 {
        return Ok(found);
    }
    return Err("None found");
}

<commit_msg>fixed copy and paste errors in table fields<commit_after>use rusqlite::Connection;
use std::result;

#[derive(Debug)]
pub struct WhenenvEnviroment {
    id: i32,
    fk_session: i32,
    fk_variable_name: i32,
}

pub fn table_create_enviroment(conn: &Connection)  {
    conn.execute("CREATE TABLE WHENENV_ENVIROMENT (
                  id                    INTEGER PRIMARY KEY ASC,
                  fk_session            INTEGER NOT NULL,
                  fk_variable_name           INTEGER NOT NULL,
                  FOREIGN KEY(fk_session) REFERENCES WHENENV_SESSION(id) ON UPDATE CASCADE
                  FOREIGN KEY(fk_variable_name) REFERENCES VARIABLE_NAME(id) ON UPDATE CASCADE
                  )", &[]).unwrap();
}

pub fn insert_enviroment(conn: &Connection, job: &i32, variable: &i32) -> Result<i32, &'static str> {
    let me = WhenenvEnviroment {
        id: 0,
        fk_session: *job,
        fk_variable_name: *variable,

    };
    let enviroment_instance = conn.execute("INSERT INTO WHENENV_ENVIROMENT (fk_session, fk_variable_name)
                  VALUES (?1, ?2)",
                 &[&me.fk_session, &me.fk_variable_name]);
    if enviroment_instance.is_err() {
        return Err("Insert failed");
    }
    enviroment_instance.unwrap();
    return Ok(0);
}

pub fn list_enviroment(conn: &Connection)-> Vec<WhenenvEnviroment> {
    let mut stmt = conn.prepare("SELECT id, fk_session, fk_variable_name  FROM WHENENV_ENVIROMENT").unwrap();
    let wraped_fs_file_iter = stmt.query_map(&[], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_session: row.get(1),
            fk_variable_name: row.get(2),
        }
    });
    let mut items = Vec::<WhenenvEnviroment>::new();
    if wraped_fs_file_iter.is_err() {
        return items;

    }
    let fs_file_iter = wraped_fs_file_iter.unwrap();
    for person in fs_file_iter {

        items.push(person.unwrap());
    }
    return items;
}

pub fn enviroment_list(conn: &Connection) {
    let mut stmt = conn.prepare("SELECT id, fk_session, fk_variable_name  FROM WHENENV_ENVIROMENT").unwrap();
    let person_iter = stmt.query_map(&[], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_session: row.get(1),
            fk_variable_name: row.get(2),
        }
    }).unwrap();

    for person in person_iter {
        println!("Found enviroment {:?}", person.unwrap());
    }
}

pub fn pk_enviroment_by_name(conn: &Connection, job: &i32, variable: &i32, pk: &mut i32) -> Result<i32, &'static str>{
    let mut stmt = conn.prepare("SELECT id, fk_session, fk_variable_name  FROM WHENENV_ENVIROMENT WHERE fk_session = ?1 AND fk_variable_name = ?2").unwrap();
    let enviroment_iter = stmt.query_map(&[job, variable], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_session: row.get(1),
            fk_variable_name: row.get(2),
        }
    });
    if enviroment_iter.is_err() {
        return Err("Insert failed dfdf");
    }
    let result = enviroment_iter.unwrap();
    let mut found = 0;
    let mut items = Vec::<i32>::new();
    for person in result {
        let bill= person.unwrap();
        *pk = bill.id;
        found = 1;
    }
    if found != 0 {
        return Ok(found);
    }
    return Err("None found");
}

<|endoftext|>