<commit_before>extern crate libc;
extern crate groonga_sys as ffi;
use std::mem;
use ffi::groonga;
use super::commandapi;

#[derive(Clone, Debug)]
pub struct LibGroonga {
    disposed: bool,
}

impl LibGroonga {
    pub fn new() -> Result<LibGroonga, String> {
        let rc = commandapi::groonga_init();
        if rc != groonga::GRN_SUCCESS {
            return Err("Couldn't initilize Groonga.".to_string());
        }
        Ok(LibGroonga { disposed: false })
    }

    fn close(&mut self) -> Result<(), String> {
        if self.disposed {
            return Ok(());
        }
        let rc = commandapi::groonga_fin();
        if rc != groonga::GRN_SUCCESS {
            return Err("Couldn't finalized Groonga.".to_string());
        }
        self.disposed = true;
        Ok(())
    }
}

impl Drop for LibGroonga {
    fn drop(&mut self) {
        self.close().unwrap();
    }
}

#[derive(Clone, Debug)]
pub struct Context {
    ctx: *mut groonga::grn_ctx,
    disposed: bool,
}

impl Context {
    pub fn new() -> Result<Context, String> {
        let ctx = commandapi::groonga_ctx_open(0);
        if ctx.is_null() {
            return Err("Couldn't create Groonga Context.".to_string());
        }
        Ok(Context {
            ctx: ctx,
            disposed: false,
        })
    }

    pub fn close(&mut self) -> Result<(), String> {
        if self.disposed {
            return Ok(());
        }
        let rc = commandapi::groonga_ctx_close(self.ctx);
        if rc != groonga::GRN_SUCCESS {
            return Err("Couldn't dispose Groonga Context.".to_string());
        }
        unsafe {
            self.ctx = mem::zeroed();
        }
        self.disposed = true;
        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct Database {
    ctx: *mut groonga::grn_ctx,
    disposed: bool,
}

impl Database {
    pub fn new(ctx: Context) -> Database {
        Database {
            ctx: ctx.ctx,
            disposed: false,
        }
    }

    pub fn uses(&mut self, dbpath: &str) {
        let _ = commandapi::groonga_db_use(self.ctx, dbpath);
    }

    fn close(&mut self) {
        if self.disposed {
            return;
        }
        unsafe {
            self.ctx = mem::zeroed();
        }
        self.disposed = true;
    }
}

impl Drop for Database {
    fn drop(&mut self) {
        self.close()
    }
}

#[derive(Clone, Debug)]
pub struct Command {
    ctx: *mut groonga::grn_ctx,
    disposed: bool,
}

impl Command {
    pub fn new(ctx: Context) -> Command {
        Command {
            ctx: ctx.ctx,
            disposed: false,
        }
    }

    pub fn groonga_version() -> &'static str {
        commandapi::get_groonga_version()
    }

    pub fn execute(&mut self, command: &str) -> String {
        let result = commandapi::groonga_execute_command(self.ctx, command);
        match result {
            Ok(v) => v,
            Err(_) => "".to_string(),
        }
    }

    fn close(&mut self) {
        if self.disposed {
            return;
        }
        unsafe {
            self.ctx = mem::zeroed();
        }
        self.disposed = true;
    }
}

impl Drop for Command {
    fn drop(&mut self) {
        self.close()
    }
}

#[cfg(test)]
mod test {
    extern crate tempdir;
    use super::*;
    use self::tempdir::TempDir;

    fn setup_dbpath() -> String {
        let dbdir = TempDir::new("ruroonga");
        let dbname = "test.db";
        let mut dbpath_buf = dbdir.unwrap().into_path();
        dbpath_buf.push(dbname);
        let dbpath = match dbpath_buf.to_str() {
            Some(v) => v,
            None => panic!("Could not get temporary database path."),
        };

        dbpath.to_owned()
    }

    #[test]
    fn integration_test() {
        let groonga = LibGroonga::new();
        assert!(groonga.is_ok());

        let context = Context::new();
        assert!(context.is_ok());

        let ctx = match context {
            Ok(v) => v,
            Err(_) => panic!("Could not get context."),
        };

        let dbpath = setup_dbpath();
        let _ = Database::new(ctx.clone()).uses(&*dbpath);

        let grn_command = "table_create Users TABLE_HASH_KEY ShortText";
        let mut command = Command::new(ctx.clone());
        let table_create_result = command.execute(grn_command.clone());
        assert_eq!("true", table_create_result);

        let dump = "dump";
        let result = command.execute(dump.clone());
        let dumped_command = "table_create Users TABLE_HASH_KEY ShortText\n";
        assert!(dumped_command == result || format!("{}\u{fffd}\u{7f}", dumped_command) == result);
    }
}
<commit_msg>libgroonga: Use lifetime parameter instead of static lifetime qualifier<commit_after>extern crate libc;
extern crate groonga_sys as ffi;
use std::mem;
use ffi::groonga;
use super::commandapi;

#[derive(Clone, Debug)]
pub struct LibGroonga {
    disposed: bool,
}

impl LibGroonga {
    pub fn new() -> Result<LibGroonga, String> {
        let rc = commandapi::groonga_init();
        if rc != groonga::GRN_SUCCESS {
            return Err("Couldn't initilize Groonga.".to_string());
        }
        Ok(LibGroonga { disposed: false })
    }

    fn close(&mut self) -> Result<(), String> {
        if self.disposed {
            return Ok(());
        }
        let rc = commandapi::groonga_fin();
        if rc != groonga::GRN_SUCCESS {
            return Err("Couldn't finalized Groonga.".to_string());
        }
        self.disposed = true;
        Ok(())
    }
}

impl Drop for LibGroonga {
    fn drop(&mut self) {
        self.close().unwrap();
    }
}

#[derive(Clone, Debug)]
pub struct Context {
    ctx: *mut groonga::grn_ctx,
    disposed: bool,
}

impl Context {
    pub fn new() -> Result<Context, String> {
        let ctx = commandapi::groonga_ctx_open(0);
        if ctx.is_null() {
            return Err("Couldn't create Groonga Context.".to_string());
        }
        Ok(Context {
            ctx: ctx,
            disposed: false,
        })
    }

    pub fn close(&mut self) -> Result<(), String> {
        if self.disposed {
            return Ok(());
        }
        let rc = commandapi::groonga_ctx_close(self.ctx);
        if rc != groonga::GRN_SUCCESS {
            return Err("Couldn't dispose Groonga Context.".to_string());
        }
        unsafe {
            self.ctx = mem::zeroed();
        }
        self.disposed = true;
        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct Database {
    ctx: *mut groonga::grn_ctx,
    disposed: bool,
}

impl Database {
    pub fn new(ctx: Context) -> Database {
        Database {
            ctx: ctx.ctx,
            disposed: false,
        }
    }

    pub fn uses(&mut self, dbpath: &str) {
        let _ = commandapi::groonga_db_use(self.ctx, dbpath);
    }

    fn close(&mut self) {
        if self.disposed {
            return;
        }
        unsafe {
            self.ctx = mem::zeroed();
        }
        self.disposed = true;
    }
}

impl Drop for Database {
    fn drop(&mut self) {
        self.close()
    }
}

#[derive(Clone, Debug)]
pub struct Command {
    ctx: *mut groonga::grn_ctx,
    disposed: bool,
}

impl Command {
    pub fn new(ctx: Context) -> Command {
        Command {
            ctx: ctx.ctx,
            disposed: false,
        }
    }

    pub fn groonga_version<'a>() -> &'a str {
        commandapi::get_groonga_version()
    }

    pub fn execute(&mut self, command: &str) -> String {
        let result = commandapi::groonga_execute_command(self.ctx, command);
        match result {
            Ok(v) => v,
            Err(_) => "".to_string(),
        }
    }

    fn close(&mut self) {
        if self.disposed {
            return;
        }
        unsafe {
            self.ctx = mem::zeroed();
        }
        self.disposed = true;
    }
}

impl Drop for Command {
    fn drop(&mut self) {
        self.close()
    }
}

#[cfg(test)]
mod test {
    extern crate tempdir;
    use super::*;
    use self::tempdir::TempDir;

    fn setup_dbpath() -> String {
        let dbdir = TempDir::new("ruroonga");
        let dbname = "test.db";
        let mut dbpath_buf = dbdir.unwrap().into_path();
        dbpath_buf.push(dbname);
        let dbpath = match dbpath_buf.to_str() {
            Some(v) => v,
            None => panic!("Could not get temporary database path."),
        };

        dbpath.to_owned()
    }

    #[test]
    fn integration_test() {
        let groonga = LibGroonga::new();
        assert!(groonga.is_ok());

        let context = Context::new();
        assert!(context.is_ok());

        let ctx = match context {
            Ok(v) => v,
            Err(_) => panic!("Could not get context."),
        };

        let dbpath = setup_dbpath();
        let _ = Database::new(ctx.clone()).uses(&*dbpath);

        let grn_command = "table_create Users TABLE_HASH_KEY ShortText";
        let mut command = Command::new(ctx.clone());
        let table_create_result = command.execute(grn_command.clone());
        assert_eq!("true", table_create_result);

        let dump = "dump";
        let result = command.execute(dump.clone());
        let dumped_command = "table_create Users TABLE_HASH_KEY ShortText\n";
        assert!(dumped_command == result || format!("{}\u{fffd}\u{7f}", dumped_command) == result);
    }
}
<|endoftext|>


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

//! # The Rust Standard Library
//!
//! The Rust Standard Library provides the essential runtime
//! functionality for building portable Rust software.
//!
//! The Rust Standard Library is available to all Rust crates by
//! default, just as if contained an `extern crate std` import at the
//! crate root. Therefore the standard library can be accessed in
//! `use` statements through the path `std`, as in `use std::thread`,
//! or in expressions through the absolute path `::std`, as in
//! `::std::thread::sleep_ms(100)`.
//!
//! Furthermore, the standard library defines [The Rust
//! Prelude](prelude/index.html), a small collection of items, mostly
//! traits, that are imported into and available in every module.
//!
//! ## What is in the standard library
//!
//! The standard library is a set of minimal, battle-tested
//! core types and shared abstractions for the [broader Rust
//! ecosystem](https://crates.io) to build on.
//!
//! The [primitive types](#primitives), though not defined in the
//! standard library, are documented here, as are the predefined
//! [macros](#macros).
//!
//! ## Containers and collections
//!
//! The [`option`](option/index.html) and
//! [`result`](result/index.html) modules define optional and
//! error-handling types, `Option` and `Result`. The
//! [`iter`](iter/index.html) module defines Rust's iterator trait,
//! [`Iterator`](iter/trait.Iterator.html), which works with the `for`
//! loop to access collections.
//!
//! The common container type, `Vec`, a growable vector backed by an array,
//! lives in the [`vec`](vec/index.html) module. Contiguous, unsized regions
//! of memory, `[T]`, commonly called "slices", and their borrowed versions,
//! `&[T]`, commonly called "borrowed slices", are built-in types for which the
//! [`slice`](slice/index.html) module defines many methods.
//!
//! `&str`, a UTF-8 string, is a built-in type, and the standard library
//! defines methods for it on a variety of traits in the
//! [`str`](str/index.html) module. Rust strings are immutable;
//! use the `String` type defined in [`string`](string/index.html)
//! for a mutable string builder.
//!
//! For converting to strings use the [`format!`](fmt/index.html)
//! macro, and for converting from strings use the
//! [`FromStr`](str/trait.FromStr.html) trait.
//!
//! Data may be shared by placing it in a reference-counted box or the
//! [`Rc`](rc/index.html) type, and if further contained in a [`Cell`
//! or `RefCell`](cell/index.html), may be mutated as well as shared.
//! Likewise, in a concurrent setting it is common to pair an
//! atomically-reference-counted box, [`Arc`](sync/struct.Arc.html),
//! with a [`Mutex`](sync/struct.Mutex.html) to get the same effect.
//!
//! The [`collections`](collections/index.html) module defines maps,
//! sets, linked lists and other typical collection types, including
//! the common [`HashMap`](collections/struct.HashMap.html).
//!
//! ## Platform abstractions and I/O
//!
//! Besides basic data types, the standard library is largely concerned
//! with abstracting over differences in common platforms, most notably
//! Windows and Unix derivatives.
//!
//! Common types of I/O, including [files](fs/struct.File.html),
//! [TCP](net/struct.TcpStream.html),
//! [UDP](net/struct.UdpSocket.html), are defined in the
//! [`io`](io/index.html), [`fs`](fs/index.html), and
//! [`net`](net/index.html) modules.
//!
//! The [`thread`](thread/index.html) module contains Rust's threading
//! abstractions. [`sync`](sync/index.html) contains further
//! primitive shared memory types, including
//! [`atomic`](sync/atomic/index.html) and
//! [`mpsc`](sync/mpsc/index.html), which contains the channel types
//! for message passing.

// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "std"]
#![stable(feature = "rust1", since = "1.0.0")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/",
       html_playground_url = "http://play.rust-lang.org/",
       test(no_crate_inject, attr(deny(warnings))),
       test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]

#![feature(alloc)]
#![feature(allow_internal_unstable)]
#![feature(associated_consts)]
#![feature(borrow_state)]
#![feature(box_raw)]
#![feature(box_syntax)]
#![feature(char_internals)]
#![feature(clone_from_slice)]
#![feature(collections)]
#![feature(collections_bound)]
#![feature(const_fn)]
#![feature(core)]
#![feature(core_float)]
#![feature(core_intrinsics)]
#![feature(core_prelude)]
#![feature(core_simd)]
#![feature(fnbox)]
#![feature(heap_api)]
#![feature(int_error_internals)]
#![feature(into_cow)]
#![feature(iter_order)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(linkage, thread_local, asm)]
#![feature(macro_reexport)]
#![feature(slice_concat_ext)]
#![feature(slice_position_elem)]
#![feature(no_std)]
#![feature(oom)]
#![feature(optin_builtin_traits)]
#![feature(rand)]
#![feature(raw)]
#![feature(reflect_marker)]
#![feature(slice_bytes)]
#![feature(slice_patterns)]
#![feature(staged_api)]
#![feature(str_char)]
#![feature(str_internals)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unique)]
#![feature(unsafe_no_drop_flag, filling_drop)]
#![feature(vec_push_all)]
#![feature(vec_resize)]
#![feature(wrapping)]
#![feature(zero_one)]
#![cfg_attr(windows, feature(str_utf16))]
#![cfg_attr(test, feature(float_from_str_radix, range_inclusive, float_extras, hash_default))]
#![cfg_attr(test, feature(test, rustc_private, float_consts))]
#![cfg_attr(target_env = "msvc", feature(link_args))]

// Don't link to std. We are std.
#![no_std]

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

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

#[macro_use]
#[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq,
    unreachable, unimplemented, write, writeln)]
extern crate core;

#[macro_use]
#[macro_reexport(vec, format)]
extern crate collections as core_collections;

#[allow(deprecated)] extern crate rand as core_rand;
extern crate alloc;
extern crate rustc_unicode;
extern crate libc;

#[macro_use] #[no_link] extern crate rustc_bitflags;

// Make std testable by not duplicating lang items. See #2912
#[cfg(test)] extern crate std as realstd;
#[cfg(test)] pub use realstd::marker;
#[cfg(test)] pub use realstd::ops;
#[cfg(test)] pub use realstd::cmp;
#[cfg(test)] pub use realstd::boxed;

// NB: These reexports are in the order they should be listed in rustdoc

pub use core::any;
pub use core::cell;
pub use core::clone;
#[cfg(not(test))] pub use core::cmp;
pub use core::convert;
pub use core::default;
pub use core::hash;
pub use core::intrinsics;
pub use core::iter;
#[cfg(not(test))] pub use core::marker;
pub use core::mem;
#[cfg(not(test))] pub use core::ops;
pub use core::ptr;
pub use core::raw;
pub use core::simd;
pub use core::result;
pub use core::option;
pub mod error;

#[cfg(not(test))] pub use alloc::boxed;
pub use alloc::rc;

pub use core_collections::borrow;
pub use core_collections::fmt;
pub use core_collections::slice;
pub use core_collections::str;
pub use core_collections::string;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core_collections::vec;

pub use rustc_unicode::char;

/* Exported macros */

#[macro_use]
mod macros;

mod rtdeps;

/* The Prelude. */

pub mod prelude;

/* Primitive types */

// NB: slice and str are primitive types too, but their module docs + primitive doc pages
// are inlined from the public re-exports of core_collections::{slice, str} above.

#[path = "num/float_macros.rs"]
#[macro_use]
mod float_macros;

#[path = "num/int_macros.rs"]
#[macro_use]
mod int_macros;

#[path = "num/uint_macros.rs"]
#[macro_use]
mod uint_macros;

#[path = "num/isize.rs"]  pub mod isize;
#[path = "num/i8.rs"]   pub mod i8;
#[path = "num/i16.rs"]  pub mod i16;
#[path = "num/i32.rs"]  pub mod i32;
#[path = "num/i64.rs"]  pub mod i64;

#[path = "num/usize.rs"] pub mod usize;
#[path = "num/u8.rs"]   pub mod u8;
#[path = "num/u16.rs"]  pub mod u16;
#[path = "num/u32.rs"]  pub mod u32;
#[path = "num/u64.rs"]  pub mod u64;

#[path = "num/f32.rs"]   pub mod f32;
#[path = "num/f64.rs"]   pub mod f64;

pub mod ascii;

pub mod thunk;

/* Common traits */

pub mod num;

/* Runtime and platform support */

#[macro_use]
pub mod thread;

pub mod collections;
pub mod dynamic_lib;
pub mod env;
pub mod ffi;
pub mod fs;
pub mod io;
pub mod net;
pub mod os;
pub mod path;
pub mod process;
pub mod sync;
pub mod time;

#[macro_use]
#[path = "sys/common/mod.rs"] mod sys_common;

#[cfg(unix)]
#[path = "sys/unix/mod.rs"] mod sys;
#[cfg(windows)]
#[path = "sys/windows/mod.rs"] mod sys;

pub mod rt;
mod panicking;
mod rand;

// Some external utilities of the standard library rely on randomness (aka
// rustc_back::TempDir and tests) and need a way to get at the OS rng we've got
// here. This module is not at all intended for stabilization as-is, however,
// but it may be stabilized long-term. As a result we're exposing a hidden,
// unstable module so we can get our build working.
#[doc(hidden)]
#[unstable(feature = "rand")]
pub mod __rand {
    pub use rand::{thread_rng, ThreadRng, Rng};
}

// Modules that exist purely to document + host impl docs for primitive types

mod array;
mod bool;
mod unit;
mod tuple;

// A curious inner-module that's not exported that contains the binding
// 'std' so that macro-expanded references to std::error and such
// can be resolved within libstd.
#[doc(hidden)]
mod std {
    pub use sync; // used for select!()
    pub use error; // used for try!()
    pub use fmt; // used for any formatting strings
    pub use option; // used for thread_local!{}
    pub use rt; // used for panic!()
    pub use vec; // used for vec![]
    pub use cell; // used for tls!
    pub use thread; // used for thread_local!
    pub use marker;  // used for tls!

    // The test runner calls ::std::env::args() but really wants realstd
    #[cfg(test)] pub use realstd::env as env;
    // The test runner requires std::slice::Vector, so re-export std::slice just for it.
    //
    // It is also used in vec![]
    pub use slice;

    pub use boxed; // used for vec![]
}
<commit_msg>std: Remove some old #[cfg(test) hacks<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! # The Rust Standard Library
//!
//! The Rust Standard Library provides the essential runtime
//! functionality for building portable Rust software.
//!
//! The Rust Standard Library is available to all Rust crates by
//! default, just as if contained an `extern crate std` import at the
//! crate root. Therefore the standard library can be accessed in
//! `use` statements through the path `std`, as in `use std::thread`,
//! or in expressions through the absolute path `::std`, as in
//! `::std::thread::sleep_ms(100)`.
//!
//! Furthermore, the standard library defines [The Rust
//! Prelude](prelude/index.html), a small collection of items, mostly
//! traits, that are imported into and available in every module.
//!
//! ## What is in the standard library
//!
//! The standard library is a set of minimal, battle-tested
//! core types and shared abstractions for the [broader Rust
//! ecosystem](https://crates.io) to build on.
//!
//! The [primitive types](#primitives), though not defined in the
//! standard library, are documented here, as are the predefined
//! [macros](#macros).
//!
//! ## Containers and collections
//!
//! The [`option`](option/index.html) and
//! [`result`](result/index.html) modules define optional and
//! error-handling types, `Option` and `Result`. The
//! [`iter`](iter/index.html) module defines Rust's iterator trait,
//! [`Iterator`](iter/trait.Iterator.html), which works with the `for`
//! loop to access collections.
//!
//! The common container type, `Vec`, a growable vector backed by an array,
//! lives in the [`vec`](vec/index.html) module. Contiguous, unsized regions
//! of memory, `[T]`, commonly called "slices", and their borrowed versions,
//! `&[T]`, commonly called "borrowed slices", are built-in types for which the
//! [`slice`](slice/index.html) module defines many methods.
//!
//! `&str`, a UTF-8 string, is a built-in type, and the standard library
//! defines methods for it on a variety of traits in the
//! [`str`](str/index.html) module. Rust strings are immutable;
//! use the `String` type defined in [`string`](string/index.html)
//! for a mutable string builder.
//!
//! For converting to strings use the [`format!`](fmt/index.html)
//! macro, and for converting from strings use the
//! [`FromStr`](str/trait.FromStr.html) trait.
//!
//! Data may be shared by placing it in a reference-counted box or the
//! [`Rc`](rc/index.html) type, and if further contained in a [`Cell`
//! or `RefCell`](cell/index.html), may be mutated as well as shared.
//! Likewise, in a concurrent setting it is common to pair an
//! atomically-reference-counted box, [`Arc`](sync/struct.Arc.html),
//! with a [`Mutex`](sync/struct.Mutex.html) to get the same effect.
//!
//! The [`collections`](collections/index.html) module defines maps,
//! sets, linked lists and other typical collection types, including
//! the common [`HashMap`](collections/struct.HashMap.html).
//!
//! ## Platform abstractions and I/O
//!
//! Besides basic data types, the standard library is largely concerned
//! with abstracting over differences in common platforms, most notably
//! Windows and Unix derivatives.
//!
//! Common types of I/O, including [files](fs/struct.File.html),
//! [TCP](net/struct.TcpStream.html),
//! [UDP](net/struct.UdpSocket.html), are defined in the
//! [`io`](io/index.html), [`fs`](fs/index.html), and
//! [`net`](net/index.html) modules.
//!
//! The [`thread`](thread/index.html) module contains Rust's threading
//! abstractions. [`sync`](sync/index.html) contains further
//! primitive shared memory types, including
//! [`atomic`](sync/atomic/index.html) and
//! [`mpsc`](sync/mpsc/index.html), which contains the channel types
//! for message passing.

// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "std"]
#![stable(feature = "rust1", since = "1.0.0")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/",
       html_playground_url = "http://play.rust-lang.org/",
       test(no_crate_inject, attr(deny(warnings))),
       test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]

#![feature(alloc)]
#![feature(allow_internal_unstable)]
#![feature(associated_consts)]
#![feature(borrow_state)]
#![feature(box_raw)]
#![feature(box_syntax)]
#![feature(char_internals)]
#![feature(clone_from_slice)]
#![feature(collections)]
#![feature(collections_bound)]
#![feature(const_fn)]
#![feature(core)]
#![feature(core_float)]
#![feature(core_intrinsics)]
#![feature(core_prelude)]
#![feature(core_simd)]
#![feature(fnbox)]
#![feature(heap_api)]
#![feature(int_error_internals)]
#![feature(into_cow)]
#![feature(iter_order)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(linkage, thread_local, asm)]
#![feature(macro_reexport)]
#![feature(slice_concat_ext)]
#![feature(slice_position_elem)]
#![feature(no_std)]
#![feature(oom)]
#![feature(optin_builtin_traits)]
#![feature(rand)]
#![feature(raw)]
#![feature(reflect_marker)]
#![feature(slice_bytes)]
#![feature(slice_patterns)]
#![feature(staged_api)]
#![feature(str_char)]
#![feature(str_internals)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unique)]
#![feature(unsafe_no_drop_flag, filling_drop)]
#![feature(vec_push_all)]
#![feature(vec_resize)]
#![feature(wrapping)]
#![feature(zero_one)]
#![cfg_attr(windows, feature(str_utf16))]
#![cfg_attr(test, feature(float_from_str_radix, range_inclusive, float_extras, hash_default))]
#![cfg_attr(test, feature(test, rustc_private, float_consts))]
#![cfg_attr(target_env = "msvc", feature(link_args))]

// Don't link to std. We are std.
#![no_std]

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

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

#[macro_use]
#[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq,
    unreachable, unimplemented, write, writeln)]
extern crate core;

#[macro_use]
#[macro_reexport(vec, format)]
extern crate collections as core_collections;

#[allow(deprecated)] extern crate rand as core_rand;
extern crate alloc;
extern crate rustc_unicode;
extern crate libc;

#[macro_use] #[no_link] extern crate rustc_bitflags;

// Make std testable by not duplicating lang items and other globals. See #2912
#[cfg(test)] extern crate std as realstd;

// NB: These reexports are in the order they should be listed in rustdoc

pub use core::any;
pub use core::cell;
pub use core::clone;
pub use core::cmp;
pub use core::convert;
pub use core::default;
pub use core::hash;
pub use core::intrinsics;
pub use core::iter;
pub use core::marker;
pub use core::mem;
pub use core::ops;
pub use core::ptr;
pub use core::raw;
pub use core::simd;
pub use core::result;
pub use core::option;
pub mod error;

pub use alloc::boxed;
pub use alloc::rc;

pub use core_collections::borrow;
pub use core_collections::fmt;
pub use core_collections::slice;
pub use core_collections::str;
pub use core_collections::string;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core_collections::vec;

pub use rustc_unicode::char;

/* Exported macros */

#[macro_use]
mod macros;

mod rtdeps;

/* The Prelude. */

pub mod prelude;

/* Primitive types */

// NB: slice and str are primitive types too, but their module docs + primitive doc pages
// are inlined from the public re-exports of core_collections::{slice, str} above.

#[path = "num/float_macros.rs"]
#[macro_use]
mod float_macros;

#[path = "num/int_macros.rs"]
#[macro_use]
mod int_macros;

#[path = "num/uint_macros.rs"]
#[macro_use]
mod uint_macros;

#[path = "num/isize.rs"]  pub mod isize;
#[path = "num/i8.rs"]   pub mod i8;
#[path = "num/i16.rs"]  pub mod i16;
#[path = "num/i32.rs"]  pub mod i32;
#[path = "num/i64.rs"]  pub mod i64;

#[path = "num/usize.rs"] pub mod usize;
#[path = "num/u8.rs"]   pub mod u8;
#[path = "num/u16.rs"]  pub mod u16;
#[path = "num/u32.rs"]  pub mod u32;
#[path = "num/u64.rs"]  pub mod u64;

#[path = "num/f32.rs"]   pub mod f32;
#[path = "num/f64.rs"]   pub mod f64;

pub mod ascii;

pub mod thunk;

/* Common traits */

pub mod num;

/* Runtime and platform support */

#[macro_use]
pub mod thread;

pub mod collections;
pub mod dynamic_lib;
pub mod env;
pub mod ffi;
pub mod fs;
pub mod io;
pub mod net;
pub mod os;
pub mod path;
pub mod process;
pub mod sync;
pub mod time;

#[macro_use]
#[path = "sys/common/mod.rs"] mod sys_common;

#[cfg(unix)]
#[path = "sys/unix/mod.rs"] mod sys;
#[cfg(windows)]
#[path = "sys/windows/mod.rs"] mod sys;

pub mod rt;
mod panicking;
mod rand;

// Some external utilities of the standard library rely on randomness (aka
// rustc_back::TempDir and tests) and need a way to get at the OS rng we've got
// here. This module is not at all intended for stabilization as-is, however,
// but it may be stabilized long-term. As a result we're exposing a hidden,
// unstable module so we can get our build working.
#[doc(hidden)]
#[unstable(feature = "rand")]
pub mod __rand {
    pub use rand::{thread_rng, ThreadRng, Rng};
}

// Modules that exist purely to document + host impl docs for primitive types

mod array;
mod bool;
mod unit;
mod tuple;

// A curious inner-module that's not exported that contains the binding
// 'std' so that macro-expanded references to std::error and such
// can be resolved within libstd.
#[doc(hidden)]
mod std {
    pub use sync; // used for select!()
    pub use error; // used for try!()
    pub use fmt; // used for any formatting strings
    pub use option; // used for thread_local!{}
    pub use rt; // used for panic!()
    pub use vec; // used for vec![]
    pub use cell; // used for tls!
    pub use thread; // used for thread_local!
    pub use marker;  // used for tls!

    // The test runner calls ::std::env::args() but really wants realstd
    #[cfg(test)] pub use realstd::env as env;
    // The test runner requires std::slice::Vector, so re-export std::slice just for it.
    //
    // It is also used in vec![]
    pub use slice;

    pub use boxed; // used for vec![]
}
<|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 dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use dom::bindings::codegen::Bindings::DOMParserBinding;
use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods;
use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml};
use dom::bindings::error::Fallible;
use dom::bindings::error::Error::FailureUnknown;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::document::{Document, DocumentHelpers, IsHTMLDocument};
use dom::document::DocumentSource;
use dom::window::Window;
use parse::html::{HTMLInput, parse_html};
use servo_util::str::DOMString;

#[dom_struct]
pub struct DOMParser {
    reflector_: Reflector,
    window: JS<Window>, //XXXjdm Document instead?
}

impl DOMParser {
    fn new_inherited(window: JSRef<Window>) -> DOMParser {
        DOMParser {
            reflector_: Reflector::new(),
            window: JS::from_rooted(window),
        }
    }

    pub fn new(window: JSRef<Window>) -> Temporary<DOMParser> {
        reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window),
                           DOMParserBinding::Wrap)
    }

    pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<DOMParser>> {
        Ok(DOMParser::new(global.as_window()))
    }
}

impl<'a> DOMParserMethods for JSRef<'a, DOMParser> {
    // http://domparsing.spec.whatwg.org/#the-domparser-interface
    fn ParseFromString(self,
                       s: DOMString,
                       ty: DOMParserBinding::SupportedType)
                       -> Fallible<Temporary<Document>> {
        let window = self.window.root().clone();
        let url = window.get_url();
        let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as uint].into_string();
        match ty {
            Text_html => {
                let document = Document::new(window, Some(url.clone()),
                                             IsHTMLDocument::HTMLDocument,
                                             Some(content_type),
                                             DocumentSource::FromParser).root().clone();
                parse_html(document, HTMLInput::InputString(s), &url);
                document.set_ready_state(DocumentReadyState::Complete);
                Ok(Temporary::from_rooted(document))
            }
            Text_xml => {
                //FIXME: this should probably be FromParser when we actually parse the string (#3756).
                Ok(Document::new(window, Some(url.clone()),
                                 IsHTMLDocument::NonHTMLDocument,
                                 Some(content_type),
                                 DocumentSource::NotFromParser))
            }
            _ => {
                Err(FailureUnknown)
            }
        }
    }
}

<commit_msg>Remove unsound Root::deref() calls in DOMParser::ParseFromString.<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 dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use dom::bindings::codegen::Bindings::DOMParserBinding;
use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods;
use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::{Text_html, Text_xml};
use dom::bindings::error::Fallible;
use dom::bindings::error::Error::FailureUnknown;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::document::{Document, DocumentHelpers, IsHTMLDocument};
use dom::document::DocumentSource;
use dom::window::Window;
use parse::html::{HTMLInput, parse_html};
use servo_util::str::DOMString;

#[dom_struct]
pub struct DOMParser {
    reflector_: Reflector,
    window: JS<Window>, //XXXjdm Document instead?
}

impl DOMParser {
    fn new_inherited(window: JSRef<Window>) -> DOMParser {
        DOMParser {
            reflector_: Reflector::new(),
            window: JS::from_rooted(window),
        }
    }

    pub fn new(window: JSRef<Window>) -> Temporary<DOMParser> {
        reflect_dom_object(box DOMParser::new_inherited(window), GlobalRef::Window(window),
                           DOMParserBinding::Wrap)
    }

    pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<DOMParser>> {
        Ok(DOMParser::new(global.as_window()))
    }
}

impl<'a> DOMParserMethods for JSRef<'a, DOMParser> {
    // http://domparsing.spec.whatwg.org/#the-domparser-interface
    fn ParseFromString(self,
                       s: DOMString,
                       ty: DOMParserBinding::SupportedType)
                       -> Fallible<Temporary<Document>> {
        let window = self.window.root();
        let url = window.r().get_url();
        let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as uint].into_string();
        match ty {
            Text_html => {
                let document = Document::new(window.r(), Some(url.clone()),
                                             IsHTMLDocument::HTMLDocument,
                                             Some(content_type),
                                             DocumentSource::FromParser).root();
                parse_html(document.r(), HTMLInput::InputString(s), &url);
                document.r().set_ready_state(DocumentReadyState::Complete);
                Ok(Temporary::from_rooted(document.r()))
            }
            Text_xml => {
                //FIXME: this should probably be FromParser when we actually parse the string (#3756).
                Ok(Document::new(window.r(), Some(url.clone()),
                                 IsHTMLDocument::NonHTMLDocument,
                                 Some(content_type),
                                 DocumentSource::NotFromParser))
            }
            _ => {
                Err(FailureUnknown)
            }
        }
    }
}

<|endoftext|>


<commit_before>use std::io;

fn empty_escape(esc:&mut Iterator<Item=char>) -> String {
    let mut out = String::new();
    loop {
        match esc.next() {
            Some(c) => out.push(c),
            None => break
        }
    }
    return out;
}

fn main() {
    let mut stdin = io::stdin();

    print!("Type a key: ");
    let c = stdin.read_char().unwrap();
    println!("In escaped form: {}", empty_escape(&mut c.escape_default()));
}
<commit_msg>Silence warnings about using unstable features<commit_after>#![allow(unstable)]
use std::io;

fn empty_escape(esc:&mut Iterator<Item=char>) -> String {
    let mut out = String::new();
    loop {
        match esc.next() {
            Some(c) => out.push(c),
            None => break
        }
    }
    return out;
}

fn main() {
    let mut stdin = io::stdin();

    print!("Type a key: ");
    let c = stdin.read_char().unwrap();
    println!("In escaped form: {}", empty_escape(&mut c.escape_default()));
}
<|endoftext|>


<commit_before>use std::process;
use clap::{App, Arg};
use config::types::Config;

pub struct Arguments {
  pub files: Vec<String>,
  pub message: Option<String>,
  pub service: Option<String>,
  pub private: bool,
  pub auth: bool,
  pub input: Option<String>
}

include!(concat!(env!("OUT_DIR"), "/git_short_tag.rs"));

fn get_name() -> String {
  option_env!("CARGO_PKG_NAME").unwrap_or("unknown_name").to_owned()
}

fn get_version() -> String {
  let version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown_version").to_owned();
  let git_tag = git_short_tag();
  format!("{}{}", version, git_tag)
}

pub fn get_arguments(config: &Config) -> Arguments {
  let mut arguments = Arguments {
    files: Vec::new(),
    message: None,
    service: config.lookup_str("defaults.service").map(|s| s.to_owned()),
    private: config.lookup_boolean_or("defaults.private", true),
    auth: config.lookup_boolean_or("default.auth", true),
    input: None
  };
  let name = get_name();
  let version = get_version();
  let res = App::new(name.as_ref())
    .version(version.as_ref())
    .about("A command-line pastebin client")
    .arg(Arg::with_name("files")
         .help("files to paste")
         .takes_value(true)
         .multiple(true))
    .arg(Arg::with_name("message")
         .short("m")
         .long("message")
         .help("message to paste")
         .use_delimiter(false)
         .takes_value(true))
    .arg(Arg::with_name("private")
         .short("p")
         .long("private")
         .help("if the paste should be private")
         .conflicts_with("public"))
    .arg(Arg::with_name("public")
         .short("P")
         .long("public")
         .help("if the paste should be public"))
    .arg(Arg::with_name("auth")
         .short("a")
         .long("auth")
         .help("if authentication (like api keys and tokens) should be used")
         .conflicts_with("anon"))
    .arg(Arg::with_name("anon")
         .short("A")
         .long("anon")
         .help("if pastes should be posted without authentication"))
    .arg(Arg::with_name("service")
         .short("s")
         .long("service")
         .help("pastebin service to use")
         .takes_value(true)
         .required(arguments.service.is_none()))
    .arg(Arg::with_name("list-services")
         .short("l")
         .long("list-services")
         .help("lists available bins and exits")
         .conflicts_with_all(&["files", "message", "private", "public", "auth", "anon", "service", "input"]))
    .arg(Arg::with_name("input")
         .short("i")
         .long("input")
         .takes_value(true)
         .conflicts_with_all(&["auth", "anon", "public", "private", "message", "service"]))
    .get_matches();
  if res.is_present("list-services") {
    println!("gist\nhastebin\npastebin\npastie\nsprunge");
    process::exit(0);
  }
  if let Some(files) = res.values_of("files") {
    arguments.files = files.map(|s| s.to_owned()).collect();
  }
  if let Some(message) = res.value_of("message") {
    arguments.message = Some(message.to_owned());
  }
  if let Some(service) = res.value_of("service") {
    arguments.service = Some(service.to_owned());
  }
  if let Some(input) = res.value_of("input") {
    arguments.input = Some(input.to_owned());
  }
  if res.is_present("private") {
    arguments.private = true;
  } else if res.is_present("public") {
    arguments.private = false;
  }
  if res.is_present("anon") {
    arguments.auth = false;
  } else if res.is_present("auth") {
    arguments.auth = true;
  }
  arguments
}
<commit_msg>fix(arguments): add help message to input option<commit_after>use std::process;
use clap::{App, Arg};
use config::types::Config;

pub struct Arguments {
  pub files: Vec<String>,
  pub message: Option<String>,
  pub service: Option<String>,
  pub private: bool,
  pub auth: bool,
  pub input: Option<String>
}

include!(concat!(env!("OUT_DIR"), "/git_short_tag.rs"));

fn get_name() -> String {
  option_env!("CARGO_PKG_NAME").unwrap_or("unknown_name").to_owned()
}

fn get_version() -> String {
  let version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown_version").to_owned();
  let git_tag = git_short_tag();
  format!("{}{}", version, git_tag)
}

pub fn get_arguments(config: &Config) -> Arguments {
  let mut arguments = Arguments {
    files: Vec::new(),
    message: None,
    service: config.lookup_str("defaults.service").map(|s| s.to_owned()),
    private: config.lookup_boolean_or("defaults.private", true),
    auth: config.lookup_boolean_or("default.auth", true),
    input: None
  };
  let name = get_name();
  let version = get_version();
  let res = App::new(name.as_ref())
    .version(version.as_ref())
    .about("A command-line pastebin client")
    .arg(Arg::with_name("files")
         .help("files to paste")
         .takes_value(true)
         .multiple(true))
    .arg(Arg::with_name("message")
         .short("m")
         .long("message")
         .help("message to paste")
         .use_delimiter(false)
         .takes_value(true))
    .arg(Arg::with_name("private")
         .short("p")
         .long("private")
         .help("if the paste should be private")
         .conflicts_with("public"))
    .arg(Arg::with_name("public")
         .short("P")
         .long("public")
         .help("if the paste should be public"))
    .arg(Arg::with_name("auth")
         .short("a")
         .long("auth")
         .help("if authentication (like api keys and tokens) should be used")
         .conflicts_with("anon"))
    .arg(Arg::with_name("anon")
         .short("A")
         .long("anon")
         .help("if pastes should be posted without authentication"))
    .arg(Arg::with_name("service")
         .short("s")
         .long("service")
         .help("pastebin service to use")
         .takes_value(true)
         .required(arguments.service.is_none()))
    .arg(Arg::with_name("list-services")
         .short("l")
         .long("list-services")
         .help("lists available bins and exits")
         .conflicts_with_all(&["files", "message", "private", "public", "auth", "anon", "service", "input"]))
    .arg(Arg::with_name("input")
         .short("i")
         .long("input")
         .help("displays raw contents of input paste")
         .takes_value(true)
         .conflicts_with_all(&["auth", "anon", "public", "private", "message", "service"]))
    .get_matches();
  if res.is_present("list-services") {
    println!("gist\nhastebin\npastebin\npastie\nsprunge");
    process::exit(0);
  }
  if let Some(files) = res.values_of("files") {
    arguments.files = files.map(|s| s.to_owned()).collect();
  }
  if let Some(message) = res.value_of("message") {
    arguments.message = Some(message.to_owned());
  }
  if let Some(service) = res.value_of("service") {
    arguments.service = Some(service.to_owned());
  }
  if let Some(input) = res.value_of("input") {
    arguments.input = Some(input.to_owned());
  }
  if res.is_present("private") {
    arguments.private = true;
  } else if res.is_present("public") {
    arguments.private = false;
  }
  if res.is_present("anon") {
    arguments.auth = false;
  } else if res.is_present("auth") {
    arguments.auth = true;
  }
  arguments
}
<|endoftext|>


<commit_before>use slack_api as slack;
use tokio_tungstenite as tungstenite;

use tokio::sync::mpsc;

use chrono::prelude::{Utc, DateTime};
use humantime::format_duration;

use std::result::Result;
use std::str::FromStr;
use std::time::Duration;

use crate::bot::build_info;

use crate::bot::query::karma::add_karma;
use crate::bot::query::partial::partial;
use crate::bot::query::ranking::ranking;
use crate::bot::query::reacji::add_reacji;
use crate::bot::query::top_n::top_n;
use crate::bot::query::{KarmaCol, KarmaTyp, OrdQuery, ReacjiAction};

use crate::core::cache;
use crate::core::command;
use crate::core::database::Query;

use crate::core::event::MsgId;
use crate::core::event::ReactionItem;
use crate::core::event::UserEvent;
use crate::core::event::send_simple_message;

pub async fn process_user_message<R>(
    msg_id: MsgId,
    msg: UserEvent,
    mut tx: mpsc::Sender<tungstenite::tungstenite::Message>,
    mut sql_tx: mpsc::Sender<Query>,
    start_time: DateTime<Utc>,
    cache: cache::Cache<R>,
) -> Result<(), Box<dyn std::error::Error>>
where
    R: slack::requests::SlackWebRequestSender + std::clone::Clone
{
    // Check if its a message/certain string, if so, reply
    match msg {
        UserEvent::Message {
            channel_id: Some(channel_id),
            subtype: None,
            text,
            user_id,
            thread_ts,
            hidden: _,
            ts: _,
        } => {
            // Check if user is a bot, if so ignore (this applies to myself as well)
            match cache.is_user_bot(&user_id).await {
                None => {
                    eprintln!("ERROR [User Event]: No info on user: {:?}", user_id);
                    return Ok(());
                },
                Some(is_bot) => {
                    if is_bot {
                        return Ok(());
                    }
                },
            }

            // Check if text message field is empty, if so (ignore)
            if text.is_empty() {
                return Ok(());
            }

            // Parse string to see if its a command one
            let res = command::parse(&text);

            match res {
                Ok(command::Command("version", _)) => {
                    let ver = build_info::PKG_VERSION;
                    let dat = build_info::BUILT_TIME_UTC;
                    let sha = build_info::GIT_COMMIT_HASH.unwrap_or("Unknown");

                    let _ = send_simple_message(
                        msg_id,
                        &mut tx,
                        channel_id,
                        thread_ts,
                        format!("<@{}>: Cargo Version: {} - Build Date: {}, - Build SHA: {}", user_id, ver, dat, sha),
                    ).await;
                },

                Ok(command::Command("uptime", _)) => {
                    let end_time: DateTime<Utc> = Utc::now();
                    let durt = end_time.signed_duration_since(start_time).to_std().unwrap_or(
                        Duration::from_secs(3122064000));

                    let _ = send_simple_message(
                        msg_id,
                        &mut tx,
                        channel_id,
                        thread_ts,
                        format!("<@{}>: {}", user_id, format_duration(durt).to_string()),
                    ).await;
                },

                Ok(command::Command("help", _)) => {
                    let help = "Available commands: !uptime !version !github !sidevotes !karma !givers !rank !ranksidevote !topkarma !topgivers !topsidevotes";
                    let _ = send_simple_message(
                        msg_id,
                        &mut tx,
                        channel_id,
                        thread_ts,
                        format!("<@{}>: {}", user_id, help),
                    ).await;
                },

                Ok(command::Command("github", _)) => {
                    let github = "Github repo: https://github.com/pharaun/Karmator";

                    let _ = send_simple_message(
                        msg_id,
                        &mut tx,
                        channel_id,
                        thread_ts,
                        format!("<@{}>: {}", user_id, github),
                    ).await;
                },

                Ok(command::Command("karma", arg)) => {
                    // asdf「asdf」asdf
                    // TODO: Implement a 'slack id' to unix name mapper
                    //  - for now can probs query it as needed, but should
                    //      be cached
                    if arg.is_empty() {
                        top_n(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Recieved,
                            OrdQuery::Desc,
                            KarmaCol::Recieved,
                            OrdQuery::Asc,
                            KarmaTyp::Total,
                            ("highest karma", "lowest karma"),
                            3u32,
                        ).await;
                    } else {
                        partial(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Recieved,
                            arg,
                        ).await;
                    }
                },

                Ok(command::Command("topkarma", arg)) => {
                    let mut err_tx = tx.clone();
                    let err_future = send_simple_message(
                        msg_id.clone(),
                        &mut err_tx,
                        channel_id.clone(),
                        thread_ts.clone(),
                        format!("<@{}>: {}", user_id, "Please specify a positive integer between 1 and 25."),
                    );

                    if arg.is_empty() {
                        let _ = err_future.await;
                    } else if arg.len() != 1 {
                        let _ = err_future.await;
                    } else {
                        // Parse the argument
                        let limit = u32::from_str(arg.get(0).unwrap());

                        match limit {
                            Ok(1..=25) => {
                                let limit = limit.unwrap();

                                top_n(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaCol::Recieved,
                                    OrdQuery::Desc,
                                    KarmaCol::Recieved,
                                    OrdQuery::Asc,
                                    KarmaTyp::Total,
                                    ("\nhighest karma", "\nlowest karma"),
                                    limit,
                                ).await;
                            },
                            _ => {
                                let _ = err_future.await;
                            },
                        }
                    }
                },

                Ok(command::Command("givers", arg)) => {
                    if arg.is_empty() {
                        top_n(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Given,
                            OrdQuery::Desc,
                            KarmaCol::Given,
                            OrdQuery::Asc,
                            KarmaTyp::Total,
                            ("most positive", "most negative"),
                            3u32,
                        ).await;
                    } else {
                        partial(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Given,
                            arg,
                        ).await;
                    }
                },

                Ok(command::Command("topgivers", arg)) => {
                    let mut err_tx = tx.clone();
                    let err_future = send_simple_message(
                        msg_id.clone(),
                        &mut err_tx,
                        channel_id.clone(),
                        thread_ts.clone(),
                        format!("<@{}>: {}", user_id, "Please specify a positive integer between 1 and 25."),
                    );

                    if arg.is_empty() {
                        let _ = err_future.await;
                    } else if arg.len() != 1 {
                        let _ = err_future.await;
                    } else {
                        // Parse the argument
                        let limit = u32::from_str(arg.get(0).unwrap());

                        match limit {
                            Ok(1..=25) => {
                                let limit = limit.unwrap();

                                top_n(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaCol::Given,
                                    OrdQuery::Desc,
                                    KarmaCol::Given,
                                    OrdQuery::Asc,
                                    KarmaTyp::Total,
                                    ("\nmost positive", "\nmost negative"),
                                    limit,
                                ).await;
                            },
                            _ => {
                                let _ = err_future.await;
                            },
                        }
                    }
                },

                Ok(command::Command("sidevotes", arg)) => {
                    if arg.is_empty() {
                        top_n(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Recieved,
                            OrdQuery::Desc,
                            KarmaCol::Given,
                            OrdQuery::Desc,
                            KarmaTyp::Side,
                            ("most sidevotes recieved", "most sidevotes given"),
                            3u32,
                        ).await;
                    } else {
                        let _ = send_simple_message(
                            msg_id,
                            &mut tx,
                            channel_id,
                            thread_ts,
                            format!("<@{}>: {}", user_id, "Not supported!"),
                        ).await;
                    }
                },

                Ok(command::Command("topsidevotes", arg)) => {
                    let mut err_tx = tx.clone();
                    let err_future = send_simple_message(
                        msg_id.clone(),
                        &mut err_tx,
                        channel_id.clone(),
                        thread_ts.clone(),
                        format!("<@{}>: {}", user_id, "Please specify a positive integer between 1 and 25."),
                    );

                    if arg.is_empty() {
                        let _ = err_future.await;
                    } else if arg.len() != 1 {
                        let _ = err_future.await;
                    } else {
                        // Parse the argument
                        let limit = u32::from_str(arg.get(0).unwrap());

                        match limit {
                            Ok(1..=25) => {
                                let limit = limit.unwrap();

                                top_n(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaCol::Recieved,
                                    OrdQuery::Desc,
                                    KarmaCol::Given,
                                    OrdQuery::Desc,
                                    KarmaTyp::Side,
                                    ("\nmost sidevotes recieved", "\nmost sidevotes given"),
                                    limit,
                                ).await;
                            },
                            _ => {
                                let _ = err_future.await;
                            },
                        }
                    }
                },

                Ok(command::Command("rank", arg)) => {
                    if arg.is_empty() {
                        // Rank with yourself
                        let username = cache.get_username(&user_id).await;

                        match username {
                            Some(ud) => {
                                ranking(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaTyp::Total,
                                    &ud,
                                    "Your",
                                ).await;
                            },
                            _ => {
                                let _ = send_simple_message(
                                    msg_id,
                                    &mut tx,
                                    channel_id,
                                    thread_ts,
                                    format!("<@{}>: {}", user_id, "Cant find your display name, thanks slack"),
                                ).await;
                            },
                        }
                    } else if arg.len() == 1 {
                        // Rank up with one target
                        let target = arg.get(0).unwrap();

                        ranking(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaTyp::Total,
                            target,
                            &format!("{}", target),
                        ).await;
                    } else {
                        let _ = send_simple_message(
                            msg_id,
                            &mut tx,
                            channel_id,
                            thread_ts,
                            format!("<@{}>: {}", user_id, "Can only rank one karma entry at a time!"),
                        ).await;
                    }
                },

                Ok(command::Command("ranksidevote", arg)) => {
                    if arg.is_empty() {
                        // Rank with yourself
                        let username = cache.get_username(&user_id).await;

                        match username {
                            Some(ud) => {
                                ranking(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaTyp::Side,
                                    &ud,
                                    "Your",
                                ).await;
                            },
                            _ => {
                                let _ = send_simple_message(
                                    msg_id,
                                    &mut tx,
                                    channel_id,
                                    thread_ts,
                                    format!("<@{}>: {}", user_id, "Cant find your display name, thanks slack"),
                                ).await;
                            },
                        }
                    } else if arg.len() == 1 {
                        // Rank up with one target
                        let target = arg.get(0).unwrap();

                        ranking(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaTyp::Side,
                            target,
                            &format!("{}", target),
                        ).await;
                    } else {
                        let _ = send_simple_message(
                            msg_id,
                            &mut tx,
                            channel_id,
                            thread_ts,
                            format!("<@{}>: {}", user_id, "Can only rank one karma entry at a time!"),
                        ).await;
                    }
                },

                Ok(command::Command(x, _)) => println!("INFO [User Event]: No handler: {:?}", x),

                Err(_) => {
                    add_karma(
                        &mut sql_tx,
                        &cache,
                        &text,
                        user_id,
                        channel_id,
                    ).await;
                },
            }
        },

        UserEvent::ReactionAdded {
            user_id, /* who performed this */
            reaction,
            item_user: _,
            item: ReactionItem::Message {
                channel_id,
                ts,
            },
            event_ts: _,
            ts: _,
        } => {
            add_reacji(
                &mut sql_tx,
                &cache,
                &reaction,
                user_id,
                channel_id,
                ts,
                ReacjiAction::Add,
            ).await;
        },

        UserEvent::ReactionRemoved {
            user_id, /* who performed this */
            reaction,
            item_user: _,
            item: ReactionItem::Message {
                channel_id,
                ts,
            },
            event_ts: _,
            ts: _,
        } => {
            add_reacji(
                &mut sql_tx,
                &cache,
                &reaction,
                user_id,
                channel_id,
                ts,
                ReacjiAction::Del,
            ).await;
        },

        _ => (),
    }
    Ok(())
}
<commit_msg>Remove more panics, the ones that remains are... well the whole app is busted or safe panics<commit_after>use slack_api as slack;
use tokio_tungstenite as tungstenite;

use tokio::sync::mpsc;

use chrono::prelude::{Utc, DateTime};
use humantime::format_duration;

use std::result::Result;
use std::str::FromStr;
use std::time::Duration;

use crate::bot::build_info;

use crate::bot::query::karma::add_karma;
use crate::bot::query::partial::partial;
use crate::bot::query::ranking::ranking;
use crate::bot::query::reacji::add_reacji;
use crate::bot::query::top_n::top_n;
use crate::bot::query::{KarmaCol, KarmaTyp, OrdQuery, ReacjiAction};

use crate::core::cache;
use crate::core::command;
use crate::core::database::Query;

use crate::core::event::MsgId;
use crate::core::event::ReactionItem;
use crate::core::event::UserEvent;
use crate::core::event::send_simple_message;

pub async fn process_user_message<R>(
    msg_id: MsgId,
    msg: UserEvent,
    mut tx: mpsc::Sender<tungstenite::tungstenite::Message>,
    mut sql_tx: mpsc::Sender<Query>,
    start_time: DateTime<Utc>,
    cache: cache::Cache<R>,
) -> Result<(), Box<dyn std::error::Error>>
where
    R: slack::requests::SlackWebRequestSender + std::clone::Clone
{
    // Check if its a message/certain string, if so, reply
    match msg {
        UserEvent::Message {
            channel_id: Some(channel_id),
            subtype: None,
            text,
            user_id,
            thread_ts,
            hidden: _,
            ts: _,
        } => {
            // Check if user is a bot, if so ignore (this applies to myself as well)
            match cache.is_user_bot(&user_id).await {
                None => {
                    eprintln!("ERROR [User Event]: No info on user: {:?}", user_id);
                    return Ok(());
                },
                Some(is_bot) => {
                    if is_bot {
                        return Ok(());
                    }
                },
            }

            // Check if text message field is empty, if so (ignore)
            if text.is_empty() {
                return Ok(());
            }

            // Parse string to see if its a command one
            let res = command::parse(&text);

            match res {
                Ok(command::Command("version", _)) => {
                    let ver = build_info::PKG_VERSION;
                    let dat = build_info::BUILT_TIME_UTC;
                    let sha = build_info::GIT_COMMIT_HASH.unwrap_or("Unknown");

                    let _ = send_simple_message(
                        msg_id,
                        &mut tx,
                        channel_id,
                        thread_ts,
                        format!("<@{}>: Cargo Version: {} - Build Date: {}, - Build SHA: {}", user_id, ver, dat, sha),
                    ).await;
                },

                Ok(command::Command("uptime", _)) => {
                    let end_time: DateTime<Utc> = Utc::now();
                    let durt = end_time.signed_duration_since(start_time).to_std().unwrap_or(
                        Duration::from_secs(3122064000));

                    let _ = send_simple_message(
                        msg_id,
                        &mut tx,
                        channel_id,
                        thread_ts,
                        format!("<@{}>: {}", user_id, format_duration(durt).to_string()),
                    ).await;
                },

                Ok(command::Command("help", _)) => {
                    let help = "Available commands: !uptime !version !github !sidevotes !karma !givers !rank !ranksidevote !topkarma !topgivers !topsidevotes";
                    let _ = send_simple_message(
                        msg_id,
                        &mut tx,
                        channel_id,
                        thread_ts,
                        format!("<@{}>: {}", user_id, help),
                    ).await;
                },

                Ok(command::Command("github", _)) => {
                    let github = "Github repo: https://github.com/pharaun/Karmator";

                    let _ = send_simple_message(
                        msg_id,
                        &mut tx,
                        channel_id,
                        thread_ts,
                        format!("<@{}>: {}", user_id, github),
                    ).await;
                },

                Ok(command::Command("karma", arg)) => {
                    // asdf「asdf」asdf
                    // TODO: Implement a 'slack id' to unix name mapper
                    //  - for now can probs query it as needed, but should
                    //      be cached
                    if arg.is_empty() {
                        top_n(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Recieved,
                            OrdQuery::Desc,
                            KarmaCol::Recieved,
                            OrdQuery::Asc,
                            KarmaTyp::Total,
                            ("highest karma", "lowest karma"),
                            3u32,
                        ).await;
                    } else {
                        partial(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Recieved,
                            arg,
                        ).await;
                    }
                },

                Ok(command::Command("topkarma", arg)) => {
                    let mut err_tx = tx.clone();
                    let err_future = send_simple_message(
                        msg_id.clone(),
                        &mut err_tx,
                        channel_id.clone(),
                        thread_ts.clone(),
                        format!("<@{}>: {}", user_id, "Please specify a positive integer between 1 and 25."),
                    );

                    if arg.is_empty() {
                        let _ = err_future.await;
                    } else if arg.len() != 1 {
                        let _ = err_future.await;
                    } else {
                        // Parse the argument
                        let limit = u32::from_str(arg.get(0).unwrap_or(&"1"));

                        match limit {
                            Ok(lim@1..=25) => {
                                top_n(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaCol::Recieved,
                                    OrdQuery::Desc,
                                    KarmaCol::Recieved,
                                    OrdQuery::Asc,
                                    KarmaTyp::Total,
                                    ("\nhighest karma", "\nlowest karma"),
                                    lim,
                                ).await;
                            },
                            _ => {
                                let _ = err_future.await;
                            },
                        }
                    }
                },

                Ok(command::Command("givers", arg)) => {
                    if arg.is_empty() {
                        top_n(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Given,
                            OrdQuery::Desc,
                            KarmaCol::Given,
                            OrdQuery::Asc,
                            KarmaTyp::Total,
                            ("most positive", "most negative"),
                            3u32,
                        ).await;
                    } else {
                        partial(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Given,
                            arg,
                        ).await;
                    }
                },

                Ok(command::Command("topgivers", arg)) => {
                    let mut err_tx = tx.clone();
                    let err_future = send_simple_message(
                        msg_id.clone(),
                        &mut err_tx,
                        channel_id.clone(),
                        thread_ts.clone(),
                        format!("<@{}>: {}", user_id, "Please specify a positive integer between 1 and 25."),
                    );

                    if arg.is_empty() {
                        let _ = err_future.await;
                    } else if arg.len() != 1 {
                        let _ = err_future.await;
                    } else {
                        // Parse the argument
                        let limit = u32::from_str(arg.get(0).unwrap_or(&"1"));

                        match limit {
                            Ok(lim@1..=25) => {
                                top_n(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaCol::Given,
                                    OrdQuery::Desc,
                                    KarmaCol::Given,
                                    OrdQuery::Asc,
                                    KarmaTyp::Total,
                                    ("\nmost positive", "\nmost negative"),
                                    lim,
                                ).await;
                            },
                            _ => {
                                let _ = err_future.await;
                            },
                        }
                    }
                },

                Ok(command::Command("sidevotes", arg)) => {
                    if arg.is_empty() {
                        top_n(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaCol::Recieved,
                            OrdQuery::Desc,
                            KarmaCol::Given,
                            OrdQuery::Desc,
                            KarmaTyp::Side,
                            ("most sidevotes recieved", "most sidevotes given"),
                            3u32,
                        ).await;
                    } else {
                        let _ = send_simple_message(
                            msg_id,
                            &mut tx,
                            channel_id,
                            thread_ts,
                            format!("<@{}>: {}", user_id, "Not supported!"),
                        ).await;
                    }
                },

                Ok(command::Command("topsidevotes", arg)) => {
                    let mut err_tx = tx.clone();
                    let err_future = send_simple_message(
                        msg_id.clone(),
                        &mut err_tx,
                        channel_id.clone(),
                        thread_ts.clone(),
                        format!("<@{}>: {}", user_id, "Please specify a positive integer between 1 and 25."),
                    );

                    if arg.is_empty() {
                        let _ = err_future.await;
                    } else if arg.len() != 1 {
                        let _ = err_future.await;
                    } else {
                        // Parse the argument
                        let limit = u32::from_str(arg.get(0).unwrap_or(&"1"));

                        match limit {
                            Ok(lim@1..=25) => {
                                top_n(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaCol::Recieved,
                                    OrdQuery::Desc,
                                    KarmaCol::Given,
                                    OrdQuery::Desc,
                                    KarmaTyp::Side,
                                    ("\nmost sidevotes recieved", "\nmost sidevotes given"),
                                    lim,
                                ).await;
                            },
                            _ => {
                                let _ = err_future.await;
                            },
                        }
                    }
                },

                Ok(command::Command("rank", arg)) => {
                    if arg.is_empty() {
                        // Rank with yourself
                        let username = cache.get_username(&user_id).await;

                        match username {
                            Some(ud) => {
                                ranking(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaTyp::Total,
                                    &ud,
                                    "Your",
                                ).await;
                            },
                            _ => {
                                let _ = send_simple_message(
                                    msg_id,
                                    &mut tx,
                                    channel_id,
                                    thread_ts,
                                    format!("<@{}>: {}", user_id, "Cant find your display name, thanks slack"),
                                ).await;
                            },
                        }
                    } else if arg.len() == 1 {
                        // Rank up with one target
                        let target = arg.get(0).unwrap_or(&"INVALID");

                        ranking(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaTyp::Total,
                            target,
                            &format!("{}", target),
                        ).await;
                    } else {
                        let _ = send_simple_message(
                            msg_id,
                            &mut tx,
                            channel_id,
                            thread_ts,
                            format!("<@{}>: {}", user_id, "Can only rank one karma entry at a time!"),
                        ).await;
                    }
                },

                Ok(command::Command("ranksidevote", arg)) => {
                    if arg.is_empty() {
                        // Rank with yourself
                        let username = cache.get_username(&user_id).await;

                        match username {
                            Some(ud) => {
                                ranking(
                                    msg_id,
                                    &mut tx,
                                    &mut sql_tx,
                                    channel_id,
                                    thread_ts,
                                    user_id,
                                    KarmaTyp::Side,
                                    &ud,
                                    "Your",
                                ).await;
                            },
                            _ => {
                                let _ = send_simple_message(
                                    msg_id,
                                    &mut tx,
                                    channel_id,
                                    thread_ts,
                                    format!("<@{}>: {}", user_id, "Cant find your display name, thanks slack"),
                                ).await;
                            },
                        }
                    } else if arg.len() == 1 {
                        // Rank up with one target
                        let target = arg.get(0).unwrap_or(&"INVALID");

                        ranking(
                            msg_id,
                            &mut tx,
                            &mut sql_tx,
                            channel_id,
                            thread_ts,
                            user_id,
                            KarmaTyp::Side,
                            target,
                            &format!("{}", target),
                        ).await;
                    } else {
                        let _ = send_simple_message(
                            msg_id,
                            &mut tx,
                            channel_id,
                            thread_ts,
                            format!("<@{}>: {}", user_id, "Can only rank one karma entry at a time!"),
                        ).await;
                    }
                },

                Ok(command::Command(x, _)) => println!("INFO [User Event]: No handler: {:?}", x),

                Err(_) => {
                    add_karma(
                        &mut sql_tx,
                        &cache,
                        &text,
                        user_id,
                        channel_id,
                    ).await;
                },
            }
        },

        UserEvent::ReactionAdded {
            user_id, /* who performed this */
            reaction,
            item_user: _,
            item: ReactionItem::Message {
                channel_id,
                ts,
            },
            event_ts: _,
            ts: _,
        } => {
            add_reacji(
                &mut sql_tx,
                &cache,
                &reaction,
                user_id,
                channel_id,
                ts,
                ReacjiAction::Add,
            ).await;
        },

        UserEvent::ReactionRemoved {
            user_id, /* who performed this */
            reaction,
            item_user: _,
            item: ReactionItem::Message {
                channel_id,
                ts,
            },
            event_ts: _,
            ts: _,
        } => {
            add_reacji(
                &mut sql_tx,
                &cache,
                &reaction,
                user_id,
                channel_id,
                ts,
                ReacjiAction::Del,
            ).await;
        },

        _ => (),
    }
    Ok(())
}
<|endoftext|>


<commit_before>use std::io;

pub struct State(imp::State);

impl State {
    /// Captures the current state of all CPUs on the system.
    ///
    /// The `State` returned here isn't too meaningful in terms of
    /// interpretation across platforms, but it can be compared to previous
    /// states to get a meaningful cross-platform number.
    pub fn current() -> io::Result<State> {
        imp::current().map(State)
    }

    /// Returns the percentage of time CPUs were idle from the current state
    /// relative to the previous state, as a percentage from 0.0 to 100.0.
    ///
    /// This function will return, as a percentage, the amount of time that the
    /// entire system was idle between the `previous` state and this own state.
    /// This can be useful to compare two snapshots in time of CPU usage to see
    /// how the CPU usage compares between the two.
    pub fn idle_since(&self, previous: &State) -> f64 {
        imp::pct_idle(&previous.0, &self.0)
    }
}

#[cfg(target_os = "linux")]
mod imp {
    use std::fs::File;
    use std::io::{self, Read};

    pub struct State {
        user: u64,
        nice: u64,
        system: u64,
        idle: u64,
        iowait: u64,
        irq: u64,
        softirq: u64,
        steal: u64,
        guest: u64,
        guest_nice: u64,
    }

    pub fn current() -> io::Result<State> {
        let mut state = String::new();
        File::open("/proc/stat")?.read_to_string(&mut state)?;
        let mut parts = state.lines().next().unwrap().split_whitespace();
        if parts.next() != Some("cpu") {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "cannot parse /proc/stat",
            ));
        }

        Ok(State {
            user: parts.next().unwrap().parse::<u64>().unwrap(),
            nice: parts.next().unwrap().parse::<u64>().unwrap(),
            system: parts.next().unwrap().parse::<u64>().unwrap(),
            idle: parts.next().unwrap().parse::<u64>().unwrap(),
            iowait: parts.next().unwrap().parse::<u64>().unwrap(),
            irq: parts.next().unwrap().parse::<u64>().unwrap(),
            softirq: parts.next().unwrap().parse::<u64>().unwrap(),
            steal: parts.next().unwrap().parse::<u64>().unwrap(),
            guest: parts.next().unwrap().parse::<u64>().unwrap(),
            guest_nice: parts.next().unwrap().parse::<u64>().unwrap(),
        })
    }

    pub fn pct_idle(prev: &State, next: &State) -> f64 {
        let user = next.user - prev.user;
        let nice = next.nice - prev.nice;
        let system = next.system - prev.system;
        let idle = next.idle - prev.idle;
        let iowait = next.iowait - prev.iowait;
        let irq = next.irq - prev.irq;
        let softirq = next.softirq - prev.softirq;
        let steal = next.steal - prev.steal;
        let guest = next.guest - prev.guest;
        let guest_nice = next.guest_nice - prev.guest_nice;
        let total =
            user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice;

        (idle as f64) / (total as f64) * 100.0
    }
}

#[cfg(target_os = "macos")]
#[allow(bad_style)]
mod imp {
    use std::io;
    use std::ptr;
    use std::slice;

    type host_t = u32;
    type mach_port_t = u32;
    type processor_flavor_t = i32;
    type natural_t = u32;
    type processor_info_array_t = *mut i32;
    type mach_msg_type_number_t = i32;
    type kern_return_t = i32;

    const PROESSOR_CPU_LOAD_INFO: processor_flavor_t = 2;
    const CPU_STATE_USER: usize = 0;
    const CPU_STATE_SYSTEM: usize = 1;
    const CPU_STATE_IDLE: usize = 2;
    const CPU_STATE_NICE: usize = 3;

    extern "C" {
        fn mach_host_self() -> mach_port_t;
        fn host_processor_info(
            host: host_t,
            flavor: processor_flavor_t,
            out_processor_count: *mut natural_t,
            out_processor_info: *mut processor_info_array_t,
            out_processor_infoCnt: *mut mach_msg_type_number_t,
        ) -> kern_return_t;
    }

    pub struct State {
        user: u64,
        system: u64,
        idle: u64,
        nice: u64,
    }

    pub fn current() -> io::Result<State> {
        unsafe {
            let mut num_cpus_u = 0;
            let mut cpu_info = ptr::null_mut();
            let mut cpu_info_cnt = 0;
            let err = host_processor_info(
                mach_host_self(),
                PROESSOR_CPU_LOAD_INFO,
                &mut num_cpus_u,
                &mut cpu_info,
                &mut cpu_info_cnt,
            );
            if err != 0 {
                return Err(io::Error::last_os_error());
            }
            let cpu_info = slice::from_raw_parts(cpu_info, cpu_info_cnt as usize);
            let mut ret = State {
                user: 0,
                system: 0,
                idle: 0,
                nice: 0,
            };
            for chunk in cpu_info.chunks(num_cpus_u as usize) {
                ret.user += chunk[CPU_STATE_USER] as u64;
                ret.system += chunk[CPU_STATE_SYSTEM] as u64;
                ret.idle += chunk[CPU_STATE_IDLE] as u64;
                ret.nice += chunk[CPU_STATE_NICE] as u64;
            }
            Ok(ret)
        }
    }

    pub fn pct_idle(prev: &State, next: &State) -> f64 {
        let user = next.user - prev.user;
        let system = next.system - prev.system;
        let idle = next.idle - prev.idle;
        let nice = next.nice - prev.nice;
        let total = user + system + idle + nice;
        (idle as f64) / (total as f64) * 100.0
    }
}

#[cfg(windows)]
mod imp {
    use std::io;
    use std::mem;
    use winapi::shared::minwindef::*;
    use winapi::um::processthreadsapi::*;

    pub struct State {
        idle: FILETIME,
        kernel: FILETIME,
        user: FILETIME,
    }

    pub fn current() -> io::Result<State> {
        unsafe {
            let mut ret = mem::zeroed::<State>();
            let r = GetSystemTimes(&mut ret.idle, &mut ret.kernel, &mut ret.user);
            if r != 0 {
                Ok(ret)
            } else {
                Err(io::Error::last_os_error())
            }
        }
    }

    pub fn pct_idle(prev: &State, next: &State) -> f64 {
        fn to_u64(a: &FILETIME) -> u64 {
            ((a.dwHighDateTime as u64) << 32) | (a.dwLowDateTime as u64)
        }

        let idle = to_u64(&next.idle) - to_u64(&prev.idle);
        let kernel = to_u64(&next.kernel) - to_u64(&prev.kernel);
        let user = to_u64(&next.user) - to_u64(&prev.user);
        let total = user + kernel;
        (idle as f64) / (total as f64) * 100.0
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
mod imp {
    use std::io;

    pub struct State;

    pub fn current() -> io::Result<State> {
        Err(io::Error::new(
            io::ErrorKind::Other,
            "unsupported platform to learn CPU state",
        ))
    }

    pub fn pct_idle(_prev: &State, _next: &State) -> f64 {
        unimplemented!()
    }
}
<commit_msg>Call `vm_deallocate` on OSX for CPU statistics<commit_after>use std::io;

pub struct State(imp::State);

impl State {
    /// Captures the current state of all CPUs on the system.
    ///
    /// The `State` returned here isn't too meaningful in terms of
    /// interpretation across platforms, but it can be compared to previous
    /// states to get a meaningful cross-platform number.
    pub fn current() -> io::Result<State> {
        imp::current().map(State)
    }

    /// Returns the percentage of time CPUs were idle from the current state
    /// relative to the previous state, as a percentage from 0.0 to 100.0.
    ///
    /// This function will return, as a percentage, the amount of time that the
    /// entire system was idle between the `previous` state and this own state.
    /// This can be useful to compare two snapshots in time of CPU usage to see
    /// how the CPU usage compares between the two.
    pub fn idle_since(&self, previous: &State) -> f64 {
        imp::pct_idle(&previous.0, &self.0)
    }
}

#[cfg(target_os = "linux")]
mod imp {
    use std::fs::File;
    use std::io::{self, Read};

    pub struct State {
        user: u64,
        nice: u64,
        system: u64,
        idle: u64,
        iowait: u64,
        irq: u64,
        softirq: u64,
        steal: u64,
        guest: u64,
        guest_nice: u64,
    }

    pub fn current() -> io::Result<State> {
        let mut state = String::new();
        File::open("/proc/stat")?.read_to_string(&mut state)?;
        let mut parts = state.lines().next().unwrap().split_whitespace();
        if parts.next() != Some("cpu") {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "cannot parse /proc/stat",
            ));
        }

        Ok(State {
            user: parts.next().unwrap().parse::<u64>().unwrap(),
            nice: parts.next().unwrap().parse::<u64>().unwrap(),
            system: parts.next().unwrap().parse::<u64>().unwrap(),
            idle: parts.next().unwrap().parse::<u64>().unwrap(),
            iowait: parts.next().unwrap().parse::<u64>().unwrap(),
            irq: parts.next().unwrap().parse::<u64>().unwrap(),
            softirq: parts.next().unwrap().parse::<u64>().unwrap(),
            steal: parts.next().unwrap().parse::<u64>().unwrap(),
            guest: parts.next().unwrap().parse::<u64>().unwrap(),
            guest_nice: parts.next().unwrap().parse::<u64>().unwrap(),
        })
    }

    pub fn pct_idle(prev: &State, next: &State) -> f64 {
        let user = next.user - prev.user;
        let nice = next.nice - prev.nice;
        let system = next.system - prev.system;
        let idle = next.idle - prev.idle;
        let iowait = next.iowait - prev.iowait;
        let irq = next.irq - prev.irq;
        let softirq = next.softirq - prev.softirq;
        let steal = next.steal - prev.steal;
        let guest = next.guest - prev.guest;
        let guest_nice = next.guest_nice - prev.guest_nice;
        let total =
            user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice;

        (idle as f64) / (total as f64) * 100.0
    }
}

#[cfg(target_os = "macos")]
#[allow(bad_style)]
mod imp {
    use std::io;
    use std::ptr;
    use std::slice;

    type host_t = u32;
    type mach_port_t = u32;
    type vm_map_t = mach_port_t;
    type vm_offset_t = usize;
    type vm_size_t = usize;
    type vm_address_t = vm_offset_t;
    type processor_flavor_t = i32;
    type natural_t = u32;
    type processor_info_array_t = *mut i32;
    type mach_msg_type_number_t = i32;
    type kern_return_t = i32;

    const PROESSOR_CPU_LOAD_INFO: processor_flavor_t = 2;
    const CPU_STATE_USER: usize = 0;
    const CPU_STATE_SYSTEM: usize = 1;
    const CPU_STATE_IDLE: usize = 2;
    const CPU_STATE_NICE: usize = 3;

    extern "C" {
        static mut mach_task_self_: mach_port_t;

        fn mach_host_self() -> mach_port_t;
        fn host_processor_info(
            host: host_t,
            flavor: processor_flavor_t,
            out_processor_count: *mut natural_t,
            out_processor_info: *mut processor_info_array_t,
            out_processor_infoCnt: *mut mach_msg_type_number_t,
        ) -> kern_return_t;
        fn vm_deallocate(
            target_task: vm_map_t,
            address: vm_address_t,
            size: vm_size_t,
        ) -> kern_return_t;
    }

    pub struct State {
        user: u64,
        system: u64,
        idle: u64,
        nice: u64,
    }

    pub fn current() -> io::Result<State> {
        unsafe {
            let mut num_cpus_u = 0;
            let mut cpu_info = ptr::null_mut();
            let mut cpu_info_cnt = 0;
            let err = host_processor_info(
                mach_host_self(),
                PROESSOR_CPU_LOAD_INFO,
                &mut num_cpus_u,
                &mut cpu_info,
                &mut cpu_info_cnt,
            );
            if err != 0 {
                return Err(io::Error::last_os_error());
            }
            let cpu_info_slice = slice::from_raw_parts(cpu_info, cpu_info_cnt as usize);
            let mut ret = State {
                user: 0,
                system: 0,
                idle: 0,
                nice: 0,
            };
            for chunk in cpu_info_slice.chunks(num_cpus_u as usize) {
                ret.user += chunk[CPU_STATE_USER] as u64;
                ret.system += chunk[CPU_STATE_SYSTEM] as u64;
                ret.idle += chunk[CPU_STATE_IDLE] as u64;
                ret.nice += chunk[CPU_STATE_NICE] as u64;
            }
            vm_deallocate(
                mach_task_self_,
                cpu_info as vm_address_t,
                cpu_info_cnt as usize,
            );
            Ok(ret)
        }
    }

    pub fn pct_idle(prev: &State, next: &State) -> f64 {
        let user = next.user - prev.user;
        let system = next.system - prev.system;
        let idle = next.idle - prev.idle;
        let nice = next.nice - prev.nice;
        let total = user + system + idle + nice;
        (idle as f64) / (total as f64) * 100.0
    }
}

#[cfg(windows)]
mod imp {
    use std::io;
    use std::mem;
    use winapi::shared::minwindef::*;
    use winapi::um::processthreadsapi::*;

    pub struct State {
        idle: FILETIME,
        kernel: FILETIME,
        user: FILETIME,
    }

    pub fn current() -> io::Result<State> {
        unsafe {
            let mut ret = mem::zeroed::<State>();
            let r = GetSystemTimes(&mut ret.idle, &mut ret.kernel, &mut ret.user);
            if r != 0 {
                Ok(ret)
            } else {
                Err(io::Error::last_os_error())
            }
        }
    }

    pub fn pct_idle(prev: &State, next: &State) -> f64 {
        fn to_u64(a: &FILETIME) -> u64 {
            ((a.dwHighDateTime as u64) << 32) | (a.dwLowDateTime as u64)
        }

        let idle = to_u64(&next.idle) - to_u64(&prev.idle);
        let kernel = to_u64(&next.kernel) - to_u64(&prev.kernel);
        let user = to_u64(&next.user) - to_u64(&prev.user);
        let total = user + kernel;
        (idle as f64) / (total as f64) * 100.0
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
mod imp {
    use std::io;

    pub struct State;

    pub fn current() -> io::Result<State> {
        Err(io::Error::new(
            io::ErrorKind::Other,
            "unsupported platform to learn CPU state",
        ))
    }

    pub fn pct_idle(_prev: &State, _next: &State) -> f64 {
        unimplemented!()
    }
}
<|endoftext|>