<commit_before>extern crate libc;

use self::libc::{c_char, c_uchar};

/// Signs and sends transaction message to validator pool.
///
/// Adds submitter information to passed transaction json, signs it with submitter
/// sign key (see wallet_sign_by_my_did), and sends signed transaction message
/// to validator pool (see ledger_write_txn).
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// submitter_did: Id of Identity stored in secured Wallet.
/// txn_json: Transaction data json.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn ledger_sign_and_send_txn(client_handle: i32, command_handle: i32,
                                submitter_did: *const c_char, txn_json: *const c_char,
                                cb: extern fn(xcommand_handle: i32, err: i32,
                                              txn_result_json: *const c_char)) {
    unimplemented!();
}

/// Sends transaction message to validator pool (no signing, unlike ledger_sign_and_write_txn).
///
/// The transaction is sent to the validator pool as is. It's assumed that it's already prepared.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// txn_json: Transaction data json.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn ledger_send_txn(client_handle: i32, command_handle: i32,
                                txn_json: *const c_char,
                                cb: extern fn(xcommand_handle: i32, err: i32,
                                              txn_result_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs a txn to get a DDO.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
#[no_mangle]
pub extern fn create_get_ddo_txn(client_handle: i32, command_handle: i32,
                               sign: int,
                               submitter_did: *const c_char, target_did: *const c_char,
                               cb: extern fn(xcommand_handle: i32, err: i32,
                                             txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs NYM transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
#[no_mangle]
pub extern fn create_nym_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                                   submitter_did: *const c_char,
                                   target_did: *const c_char,
                                   verkey: *const c_char, xref: *const c_char,
                                   data: *const c_char, role: *const c_char,
                                   cb: extern fn(xcommand_handle: i32, err: i32,
                                                 txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs ATTRIB transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
#[no_mangle]
pub extern fn create_attrib_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                                      submitter_did: *const c_char, target_did: *const c_char,
                                      hash: *const c_char, raw: *const c_char, enc: *const c_char,
                                      cb: extern fn(xcommand_handle: i32, err: i32,
                                                    txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs GET_ATTRIB transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
pub extern fn create_get_attrib_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                                 submitter_did: *const c_char, target_did: *const c_char,
                                 data: *const c_char,
                                 cb: extern fn(xcommand_handle: i32, err: i32,
                                               txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs GET_NYM transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
#[no_mangle]
pub extern fn create_get_nym_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                              submitter_did: *const c_char, target_did: *const c_char,
                              cb: extern fn(xcommand_handle: i32, err: i32,
                                            txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs SCHEMA transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
#[no_mangle]
pub extern fn create_schema_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                                      submitter_did: *const c_char, data: *const c_char,
                                      cb: extern fn(xcommand_handle: i32, err: i32,
                                                    txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs GET_SCHEMA transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
#[no_mangle]
pub extern fn create_get_schema_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                                 submitter_did: *const c_char, data: *const c_char,
                                 cb: extern fn(xcommand_handle: i32, err: i32,
                                               txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs ISSUER_KEY transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
#[no_mangle]
pub extern fn create_issuer_key_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                                          submitter_did: *const c_char, xref: *const c_char,
                                          data: *const c_char,
                                          cb: extern fn(xcommand_handle: i32, err: i32,
                                                        txn_result_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs GET_ISSUER_KEY transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
pub extern fn crate_get_issuer_key_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                                     submitter_did: *const c_char, xref: *const c_char,
                                     cb: extern fn(xcommand_handle: i32, err: i32,
                                                   txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs NODE transaction.
/// Call ledger_send_txn or ledger_sign_and_send_txn to send txn to the Validator Pool.
#[no_mangle]
pub extern fn create_node_txn(client_handle: i32, command_handle: i32,
                                   sign: int,
                                    submitter_did: *const c_char, target_did: *const c_char,
                                    data: *const c_char,
                                    cb: extern fn(xcommand_handle: i32, err: i32,
                                                  txn_json: *const c_char)) {
    unimplemented!();
}<commit_msg>added documentation for ledger api<commit_after>extern crate libc;

use self::libc::{c_char, c_uchar};

/// Signs and sends transaction message to validator pool.
///
/// Adds submitter information to passed transaction json, signs it with submitter
/// sign key (see wallet_sign_by_my_did), and sends signed transaction message
/// to validator pool (see ledger_write_txn).
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// submitter_did: Id of Identity stored in secured Wallet.
/// txn_json: Transaction data json.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn ledger_sign_and_send_txn(client_handle: i32, command_handle: i32,
                                       submitter_did: *const c_char, txn_json: *const c_char,
                                       cb: extern fn(xcommand_handle: i32, err: i32,
                                                     txn_result_json: *const c_char)) {
    unimplemented!();
}

/// Sends transaction message to validator pool (no signing, unlike ledger_sign_and_write_txn).
///
/// The transaction is sent to the validator pool as is. It's assumed that it's already prepared.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// txn_json: Transaction data json.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn ledger_send_txn(client_handle: i32, command_handle: i32,
                              txn_json: *const c_char,
                              cb: extern fn(xcommand_handle: i32, err: i32,
                                            txn_result_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs a txn to get a DDO.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// target_did: Id of Identity stored in secured Wallet.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn create_get_ddo_txn(client_handle: i32, command_handle: i32, sign: i32,
                                 submitter_did: *const c_char, target_did: *const c_char,
                                 cb: extern fn(xcommand_handle: i32, err: i32,
                                               txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs NYM transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// target_did: Id of Identity stored in secured Wallet.
/// verkey:
/// xref:
/// data:
/// role:
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn create_nym_txn(client_handle: i32, command_handle: i32, sign: i32,
                             submitter_did: *const c_char,
                             target_did: *const c_char,
                             verkey: *const c_char, xref: *const c_char,
                             data: *const c_char, role: *const c_char,
                             cb: extern fn(xcommand_handle: i32, err: i32,
                                           txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs ATTRIB transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// target_did: Id of Identity stored in secured Wallet.
/// hash:
/// raw:
/// enc:
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn create_attrib_txn(client_handle: i32, command_handle: i32, sign: i32,
                                submitter_did: *const c_char, target_did: *const c_char,
                                hash: *const c_char, raw: *const c_char, enc: *const c_char,
                                cb: extern fn(xcommand_handle: i32, err: i32,
                                              txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs GET_ATTRIB transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// target_did: Id of Identity stored in secured Wallet.
/// data:
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub extern fn create_get_attrib_txn(client_handle: i32, command_handle: i32, sign: i32,
                                    submitter_did: *const c_char, target_did: *const c_char,
                                    data: *const c_char,
                                    cb: extern fn(xcommand_handle: i32, err: i32,
                                                  txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs GET_NYM transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// target_did: Id of Identity stored in secured Wallet.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn create_get_nym_txn(client_handle: i32, command_handle: i32, sign: i32,
                                 submitter_did: *const c_char, target_did: *const c_char,
                                 cb: extern fn(xcommand_handle: i32, err: i32,
                                               txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs SCHEMA transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// data:
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn create_schema_txn(client_handle: i32, command_handle: i32, sign: i32,
                                submitter_did: *const c_char, data: *const c_char,
                                cb: extern fn(xcommand_handle: i32, err: i32,
                                              txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs GET_SCHEMA transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// data:
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn create_get_schema_txn(client_handle: i32, command_handle: i32, sign: i32,
                                    submitter_did: *const c_char, data: *const c_char,
                                    cb: extern fn(xcommand_handle: i32, err: i32,
                                                  txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs ISSUER_KEY transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// xref:
/// data:
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn create_issuer_key_txn(client_handle: i32, command_handle: i32, sign: i32,
                                    submitter_did: *const c_char, xref: *const c_char,
                                    data: *const c_char,
                                    cb: extern fn(xcommand_handle: i32, err: i32,
                                                  txn_result_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs GET_ISSUER_KEY transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// xref:
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
pub extern fn crate_get_issuer_key_txn(client_handle: i32, command_handle: i32, sign: i32,
                                       submitter_did: *const c_char, xref: *const c_char,
                                       cb: extern fn(xcommand_handle: i32, err: i32,
                                                     txn_json: *const c_char)) {
    unimplemented!();
}

/// Creates and optionally signs NODE transaction.
///
/// #Params
/// client_handle: id of Ledger client instance.
/// command_handle: command id to map of callback to user context.
/// sign:
/// submitter_did: Id of Identity stored in secured Wallet.
/// target_did: Id of Identity stored in secured Wallet.
/// data:
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Transaction result as json.
///
/// #Errors
/// No method specific errors.
/// See `LedgerError` docs for common errors description.
#[no_mangle]
pub extern fn create_node_txn(client_handle: i32, command_handle: i32, sign: i32,
                              submitter_did: *const c_char, target_did: *const c_char,
                              data: *const c_char,
                              cb: extern fn(xcommand_handle: i32, err: i32,
                                            txn_json: *const c_char)) {
    unimplemented!();
}<|endoftext|>


<commit_before><commit_msg>Fix: Negation error<commit_after><|endoftext|>


<commit_before><commit_msg>imag-contact: Replace read with typed read<commit_after><|endoftext|>


<commit_before><commit_msg>add identify<commit_after>// (c) 2016 Productize SPRL <joost@productize.be>

extern crate rustykicad;

fn main() {
    let mut args = std::env::args();
    args.next();
    let name = args.next().unwrap();
    let f = rustykicad::read_kicad_file(&name, rustykicad::Expected::Any).unwrap();
    println!("found: {}", f);
}

<|endoftext|>


<commit_before><commit_msg>Added a codegen test for a recent optimization for overflow-checks=on<commit_after>// no-system-llvm
// compile-flags: -O -C overflow-checks=on

#![crate_type = "lib"]

pub struct S1<'a> {
    data: &'a [u8],
    position: usize,
}

// CHECK-LABEL: @slice_no_index_order
#[no_mangle]
pub fn slice_no_index_order<'a>(s: &'a mut S1, n: usize) -> &'a [u8] {
    // CHECK-NOT: slice_index_order_fail
    let d = &s.data[s.position..s.position+n];
    s.position += n;
    return d;
}

// CHECK-LABEL: @test_check
#[no_mangle]
pub fn test_check<'a>(s: &'a mut S1, x: usize, y: usize) -> &'a [u8] {
    // CHECK: slice_index_order_fail
    &s.data[x..y]
}
<|endoftext|>


<commit_before><commit_msg>Add test for #17994<commit_after>// Copyright 2015 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.

trait Tr {}
type Huh<T> where T: Tr = isize; //~ ERROR type parameter `T` is unused
fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add models for Clue and Category<commit_after>use chrono::*;

pub struct Clue {
    pub id: u64,
    pub answer: String,
    pub question: String,
    pub value: i32,
    pub airdate: DateTime<UTC>,
    pub created_at: Option<DateTime<UTC>>,
    pub updated_at: Option<DateTime<UTC>>,
    pub category_id: u64,
    pub game_id: Option<u64>,
    pub invalid_count: Option<u32>,
    pub category: Option<Category>,
}

pub struct Category {
    pub id: u64,
    pub title: String,
    pub created_at: Option<DateTime<UTC>>,
    pub updated_at: Option<DateTime<UTC>>,
    pub clues_count: u32,
    pub clues: Option<Vec<Clue>>,
}
<|endoftext|>


<commit_before><commit_msg>Add version/build info to panic! output<commit_after><|endoftext|>


<commit_before><commit_msg>added Condition struct for having, refactored filter to use condition<commit_after><|endoftext|>


<commit_before><commit_msg>Update remove() and delete().<commit_after><|endoftext|>


<commit_before>//! HTTP Server
use std::io::net::tcp::{TcpListener, TcpAcceptor};
use std::io::{Acceptor, Listener, IoResult, EndOfFile};
use std::io::net::ip::{IpAddr, Port, SocketAddr};

pub use self::request::Request;
pub use self::response::Response;

pub mod request;
pub mod response;

/// A server can listen on a TCP socket.
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
pub struct Server {
    ip: IpAddr,
    port: Port
}

impl Server {

    /// Creates a server to be used for `http` conenctions.
    pub fn http(ip: IpAddr, port: Port) -> Server {
        Server {
            ip: ip,
            port: port
        }
    }

    /// Binds to a socket, and starts handling connections.
    pub fn listen<H: Handler + 'static>(&self, mut handler: H) -> IoResult<Listening> {
        let mut listener = try!(TcpListener::bind(self.ip.to_string().as_slice(), self.port));
        let socket = try!(listener.socket_name());
        let acceptor = try!(listener.listen());
        let worker = acceptor.clone();

        spawn(proc() {
            let mut acceptor = worker;
            for conn in acceptor.incoming() {
                match conn {
                    Ok(stream) => {
                        debug!("Incoming stream");
                        let clone = stream.clone();
                        let req = match Request::new(stream) {
                            Ok(r) => r,
                            Err(err) => {
                                error!("creating Request: {}", err);
                                continue;
                            }
                        };
                        let mut res = Response::new(clone);
                        res.version = req.version;
                        match handler.handle(req, res) {
                            Ok(..) => debug!("Stream handled"),
                            Err(e) => {
                                error!("Error from handler: {}", e)
                                //TODO try to send a status code
                            }
                        }
                    },
                    Err(ref e) if e.kind == EndOfFile => break, // server closed
                    Err(e) => {
                        error!("Connection failed: {}", e);
                    }
                }
            }
        });

        Ok(Listening {
            acceptor: acceptor,
            socket_addr: socket,
        })
    }

}

/// A listening server, which can later be closed.
pub struct Listening {
    acceptor: TcpAcceptor,
    /// The socket address that the server is bound to.
    pub socket_addr: SocketAddr,
}

impl Listening {
    /// Stop the server from listening to it's socket address.
    pub fn close(mut self) -> IoResult<()> {
        debug!("closing server");
        self.acceptor.close_accept()
    }
}

/// A handler that can handle incoming requests for a server.
pub trait Handler: Send {
    /// Receives a `Request`/`Response` pair, and should perform some action on them.
    ///
    /// This could reading from the request, and writing to the response.
    fn handle(&mut self, req: Request, res: Response) -> IoResult<()>;
}

impl Handler for fn(Request, Response) -> IoResult<()> {
    fn handle(&mut self, req: Request, res: Response) -> IoResult<()> {
        (*self)(req, res)
    }
}
<commit_msg>consume Server upon listen<commit_after>//! HTTP Server
use std::io::net::tcp::{TcpListener, TcpAcceptor};
use std::io::{Acceptor, Listener, IoResult, EndOfFile};
use std::io::net::ip::{IpAddr, Port, SocketAddr};

pub use self::request::Request;
pub use self::response::Response;

pub mod request;
pub mod response;

/// A server can listen on a TCP socket.
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
pub struct Server {
    ip: IpAddr,
    port: Port
}

impl Server {

    /// Creates a server to be used for `http` conenctions.
    pub fn http(ip: IpAddr, port: Port) -> Server {
        Server {
            ip: ip,
            port: port
        }
    }

    /// Binds to a socket, and starts handling connections.
    pub fn listen<H: Handler + 'static>(self, mut handler: H) -> IoResult<Listening> {
        let mut listener = try!(TcpListener::bind(self.ip.to_string().as_slice(), self.port));
        let socket = try!(listener.socket_name());
        let acceptor = try!(listener.listen());
        let worker = acceptor.clone();

        spawn(proc() {
            let mut acceptor = worker;
            for conn in acceptor.incoming() {
                match conn {
                    Ok(stream) => {
                        debug!("Incoming stream");
                        let clone = stream.clone();
                        let req = match Request::new(stream) {
                            Ok(r) => r,
                            Err(err) => {
                                error!("creating Request: {}", err);
                                continue;
                            }
                        };
                        let mut res = Response::new(clone);
                        res.version = req.version;
                        match handler.handle(req, res) {
                            Ok(..) => debug!("Stream handled"),
                            Err(e) => {
                                error!("Error from handler: {}", e)
                                //TODO try to send a status code
                            }
                        }
                    },
                    Err(ref e) if e.kind == EndOfFile => break, // server closed
                    Err(e) => {
                        error!("Connection failed: {}", e);
                    }
                }
            }
        });

        Ok(Listening {
            acceptor: acceptor,
            socket_addr: socket,
        })
    }

}

/// A listening server, which can later be closed.
pub struct Listening {
    acceptor: TcpAcceptor,
    /// The socket address that the server is bound to.
    pub socket_addr: SocketAddr,
}

impl Listening {
    /// Stop the server from listening to it's socket address.
    pub fn close(mut self) -> IoResult<()> {
        debug!("closing server");
        self.acceptor.close_accept()
    }
}

/// A handler that can handle incoming requests for a server.
pub trait Handler: Send {
    /// Receives a `Request`/`Response` pair, and should perform some action on them.
    ///
    /// This could reading from the request, and writing to the response.
    fn handle(&mut self, req: Request, res: Response) -> IoResult<()>;
}

impl Handler for fn(Request, Response) -> IoResult<()> {
    fn handle(&mut self, req: Request, res: Response) -> IoResult<()> {
        (*self)(req, res)
    }
}
<|endoftext|>


<commit_before><commit_msg>debuginfo: Add test case for destructured for-loop variable.<commit_after>// Copyright 2013-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.

// ignore-android: FIXME(#10381)
// min-lldb-version: 310

// compile-flags:-g

// === GDB TESTS ===================================================================================

// gdb-command:run

// DESTRUCTURED STRUCT
// gdb-command:print x
// gdb-check:$1 = 400
// gdb-command:print y
// gdb-check:$2 = 401.5
// gdb-command:print z
// gdb-check:$3 = true
// gdb-command:continue

// DESTRUCTURED TUPLE
// gdb-command:print/x _i8
// gdb-check:$4 = 0x6f
// gdb-command:print/x _u8
// gdb-check:$5 = 0x70
// gdb-command:print _i16
// gdb-check:$6 = -113
// gdb-command:print _u16
// gdb-check:$7 = 114
// gdb-command:print _i32
// gdb-check:$8 = -115
// gdb-command:print _u32
// gdb-check:$9 = 116
// gdb-command:print _i64
// gdb-check:$10 = -117
// gdb-command:print _u64
// gdb-check:$11 = 118
// gdb-command:print _f32
// gdb-check:$12 = 119.5
// gdb-command:print _f64
// gdb-check:$13 = 120.5
// gdb-command:continue

// MORE COMPLEX CASE
// gdb-command:print v1
// gdb-check:$14 = 80000
// gdb-command:print x1
// gdb-check:$15 = 8000
// gdb-command:print *y1
// gdb-check:$16 = 80001.5
// gdb-command:print z1
// gdb-check:$17 = false
// gdb-command:print *x2
// gdb-check:$18 = -30000
// gdb-command:print y2
// gdb-check:$19 = -300001.5
// gdb-command:print *z2
// gdb-check:$20 = true
// gdb-command:print v2
// gdb-check:$21 = 854237.5
// gdb-command:continue

// === LLDB TESTS ==================================================================================

// lldb-command:type format add --format hex char
// lldb-command:type format add --format hex 'unsigned char'

// lldb-command:run

// DESTRUCTURED STRUCT
// lldb-command:print x
// lldb-check:[...]$0 = 400
// lldb-command:print y
// lldb-check:[...]$1 = 401.5
// lldb-command:print z
// lldb-check:[...]$2 = true
// lldb-command:continue

// DESTRUCTURED TUPLE
// lldb-command:print _i8
// lldb-check:[...]$3 = 0x6f
// lldb-command:print _u8
// lldb-check:[...]$4 = 0x70
// lldb-command:print _i16
// lldb-check:[...]$5 = -113
// lldb-command:print _u16
// lldb-check:[...]$6 = 114
// lldb-command:print _i32
// lldb-check:[...]$7 = -115
// lldb-command:print _u32
// lldb-check:[...]$8 = 116
// lldb-command:print _i64
// lldb-check:[...]$9 = -117
// lldb-command:print _u64
// lldb-check:[...]$10 = 118
// lldb-command:print _f32
// lldb-check:[...]$11 = 119.5
// lldb-command:print _f64
// lldb-check:[...]$12 = 120.5
// lldb-command:continue

// MORE COMPLEX CASE
// lldb-command:print v1
// lldb-check:[...]$13 = 80000
// lldb-command:print x1
// lldb-check:[...]$14 = 8000
// lldb-command:print *y1
// lldb-check:[...]$15 = 80001.5
// lldb-command:print z1
// lldb-check:[...]$16 = false
// lldb-command:print *x2
// lldb-check:[...]$17 = -30000
// lldb-command:print y2
// lldb-check:[...]$18 = -300001.5
// lldb-command:print *z2
// lldb-check:[...]$19 = true
// lldb-command:print v2
// lldb-check:[...]$20 = 854237.5
// lldb-command:continue

struct Struct {
    x: i16,
    y: f32,
    z: bool
}

fn main() {

    let s = Struct {
        x: 400,
        y: 401.5,
        z: true
    };

    for &Struct { x, y, z } in [s].iter() {
        zzz(); // #break
    }

    let tuple: (i8, u8, i16, u16, i32, u32, i64, u64, f32, f64) =
        (0x6f, 0x70, -113, 114, -115, 116, -117, 118, 119.5, 120.5);

    for &(_i8, _u8, _i16, _u16, _i32, _u32, _i64, _u64, _f32, _f64) in [tuple].iter() {
        zzz(); // #break
    }

    let more_complex: (i32, &Struct, Struct, Box<f64>) =
        (80000,
         &Struct {
            x: 8000,
            y: 80001.5,
            z: false
         },
         Struct {
            x: -30000,
            y: -300001.5,
            z: true
         },
         box 854237.5);

    for &(v1,
          &Struct { x: x1, y: ref y1, z: z1 },
          Struct { x: ref x2, y: y2, z: ref z2 },
          box v2) in [more_complex].iter() {
        zzz(); // #break
    }
}

fn zzz() {()}
<|endoftext|>


<commit_before><commit_msg>autocommit 2015-06-02 01:56:46 CEST<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/.

#[prelude_import] use base::prelude::*;
use syscall::{getresuid, getresgid, setresuid, setresgid, setgroups, getgroups};
use base::error::{self};
use cty::alias::{UserId, GroupId};
use fmt::{Debug, Write};

/// User ids of a thread.
#[derive(Pod, Eq)]
pub struct UserIds {
    /// Real id
    pub real: UserId,
    /// Effective id
    pub effective: UserId,
    /// Saved id
    pub saved: UserId,
}

impl UserIds {
    /// Retrieves the user ids of this thread.
    pub fn get() -> UserIds {
        let mut ids = UserIds {
            real:      0,
            effective: 0,
            saved:     0,
        };
        getresuid(&mut ids.real, &mut ids.effective, &mut ids.saved);
        ids
    }

    /// Sets the user ids of this thread.
    pub fn set(&self) -> Result {
        rv!(setresuid(self.real, self.effective, self.saved))
    }
}

impl Debug for UserIds {
    fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
        write!(w, "UserIds {{ real: {}, effective: {}, saved {} }}",
               self.real, self.effective, self.saved)
    }
}

/// Group ids of a thread.
#[derive(Pod, Eq)]
pub struct GroupIds {
    /// Real id
    pub real: GroupId,
    /// Effective id
    pub effective: GroupId,
    /// Saved id
    pub saved: GroupId,
}

impl GroupIds {
    /// Retrieves the group ids of this thread.
    pub fn get() -> GroupIds {
        let mut ids = GroupIds {
            real:      0,
            effective: 0,
            saved:     0,
        };
        getresgid(&mut ids.real, &mut ids.effective, &mut ids.saved);
        ids
    }

    /// Sets the group ids of this process.
    pub fn set(&self) -> Result {
        rv!(setresgid(self.real, self.effective, self.saved))
    }
}

impl Debug for GroupIds {
    fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
        write!(w, "GroupIds {{ real: {}, effective: {}, saved {} }}",
               self.real, self.effective, self.saved)
    }
}

/// Sets all user ids of this thread to the real id.
pub fn drop_user_privileges() -> Result {
    let mut ids = UserIds::get();
    ids.effective = ids.real;
    ids.saved     = ids.real;
    ids.set()
}

/// Sets all group ids of this thread to the real id.
pub fn drop_group_privileges() -> Result {
    let mut ids = GroupIds::get();
    ids.effective = ids.real;
    ids.saved     = ids.real;
    ids.set()
}

/// Sets the effective user id of this thread.
///
/// [argument, id]
/// The new effective user id of the thread.
pub fn set_effective_user_id(id: UserId) -> Result {
    rv!(setresuid(-1, id, -1))
}

/// Sets the effective group id of this thread.
///
/// [argument, id]
/// The new effective group id of the thread.
pub fn set_effective_group_id(id: GroupId) -> Result {
    rv!(setresgid(-1, id, -1))
}

/// Returns the number of supplementary groups of this thread.
pub fn num_supplementary_groups() -> usize {
    getgroups(&mut []) as usize
}

const MAX_SUP_GROUPS: usize = 65536;

/// Retrieves the supplementary groups of this thread.
///
/// [argument, buf]
/// The buffer in which the supplementary groups will be stored.
///
/// [return_value]
/// Returns the number of supplementary groups stored
pub fn supplementary_groups(buf: &mut [GroupId]) -> Result<usize> {
    if buf.len() > MAX_SUP_GROUPS {
        rv!(getgroups(&mut buf[..MAX_SUP_GROUPS]), -> usize)
    } else {
        rv!(getgroups(buf), -> usize)
    }
}

/// Sets the supplementary groups of this thread.
///
/// [argument, buf]
/// The buffer which contains the new supplementary groups.
pub fn set_supplementary_groups(buf: &[GroupId]) -> Result {
    if buf.len() > MAX_SUP_GROUPS {
        return Err(error::InvalidArgument);
    }
    rv!(setgroups(buf))
}
<|endoftext|>


<commit_before><commit_msg>add smol example<commit_after>use futures_util::future;
use lapin::{
    message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
    BasicProperties, Connection, ConnectionProperties, Result,
};
use lapinou::*;
use log::info;

fn main() -> Result<()> {
    env_logger::init();

    let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());

    // spawn a thread pool
    for _ in 0..5 {
        std::thread::spawn(|| smol::run(future::pending::<()>()));
    }

    smol::run(async {
        let conn = Connection::connect(&addr, ConnectionProperties::default().with_smol()).await?;

        info!("CONNECTED");

        let channel_a = conn.create_channel().await?;
        let channel_b = conn.create_channel().await?;

        let queue = channel_a
            .queue_declare(
                "hello",
                QueueDeclareOptions::default(),
                FieldTable::default(),
            )
            .await?;

        info!("Declared queue {:?}", queue);

        let consumer = channel_b
            .clone()
            .basic_consume(
                "hello",
                "my_consumer",
                BasicConsumeOptions::default(),
                FieldTable::default(),
            )
            .await?;

        consumer.set_delegate(move |delivery: DeliveryResult| {
            let channel_b = channel_b.clone();
            async move {
                let delivery = delivery.expect("error caught in in consumer");
                if let Some(delivery) = delivery {
                    channel_b
                        .basic_ack(delivery.delivery_tag, BasicAckOptions::default())
                        .await
                        .expect("failed to ack");
                }
            }
        });

        let payload = b"Hello world!";

        loop {
            let confirm = channel_a
                .basic_publish(
                    "",
                    "hello",
                    BasicPublishOptions::default(),
                    payload.to_vec(),
                    BasicProperties::default(),
                )
                .await?
                .await?;
            assert_eq!(confirm, Confirmation::NotRequested);
        }
    })
}
<|endoftext|>


<commit_before><commit_msg>new file:   src/event.rs<commit_after><|endoftext|>


<commit_before><commit_msg>fix ??? avatar loading<commit_after><|endoftext|>


<commit_before>#![allow(unused_variables)]

extern crate sdl2;

/*struct SDL_handles<'a> {
    context: sdl2::sdl::Sdl,
    video: sdl2::sdl::VideoSubsystem,
    renderer: sdl2::render::Renderer<'a>,
}*/

pub fn bootstrap<'a>(win_width: i32, win_height: i32, win_name: &str) -> (sdl2::render::Renderer<'a>, sdl2::EventPump) {
    let sdl_context = sdl2::init().unwrap(); // context
    let sdl_video = sdl_context.video().unwrap(); // video
    let mut event_pump = sdl_context.event_pump().unwrap();

    // Make a new window
    let window = sdl_video.window(win_name, 1280, 720)
        .position_centered()
        .opengl()
        .build()
        .expect("Failed on creating a new window!");

    // turn window into a renderer, cannot do anything with window from now on.
    let mut renderer = window.renderer().build().unwrap();

    (renderer, event_pump)
}<commit_msg>Added an Engine struct to store variables used to drawing.<commit_after>#![allow(unused_variables)]

extern crate sdl2;

use super::vid;

/*struct SDL_handles<'a> {
    context: sdl2::sdl::Sdl,
    video: sdl2::sdl::VideoSubsystem,
    renderer: sdl2::render::Renderer<'a>,
}*/

pub struct Engine<'a> {
    pub screen_x: u32,
    pub screen_y: u32,

    pub camera_x: f32,
    pub camera_y: f32,
    pub camera_z: f32,

    pub camera_x_y: f32,
    pub camera_x_z: f32,
    pub camera_y_z: f32,

    pub renderer: sdl2::render::Renderer<'a>,

    pub event_pump: sdl2::EventPump,

    pub render_queue: Vec<vid::Triangle>,
}

impl<'a> Engine<'a> {
    pub fn new(screen_x: u32, screen_y: u32, window_name: String) -> Engine<'a> {
        let sdl_ctx = sdl2::init().unwrap();
        let sdl_vid = sdl_ctx.video().unwrap();

        let sdl_win = sdl_vid.window(&window_name, screen_x, screen_y)
                        .position_centered()
                        .opengl()
                        .build()
                        .expect("Failed on creating a new window!");
        Engine {
            screen_x: screen_x,
            screen_y: screen_y,

            camera_x: 0.0,
            camera_y: 0.0,
            camera_z: 0.0,

            camera_x_y: 0.0,
            camera_x_z: 0.0,
            camera_y_z: 0.0,

            renderer: sdl_win.renderer().build().unwrap(),

            event_pump: sdl_ctx.event_pump().unwrap(),

            render_queue: Vec::new(),
        }
    }

    pub fn render(&mut self) {
        for mut triangle in &mut self.render_queue {
            let flat_1 = triangle.p1.flat_point(self.screen_x, self.screen_y,
                                                triangle.x + self.camera_x,
                                                triangle.y + self.camera_y,
                                                triangle.z + self.camera_z).make_sdl();
            let flat_2 = triangle.p2.flat_point(self.screen_x, self.screen_y,
                                                triangle.x + self.camera_x,
                                                triangle.y + self.camera_y,
                                                triangle.z + self.camera_z).make_sdl();
            let flat_3 = triangle.p3.flat_point(self.screen_x, self.screen_y,
                                                triangle.x + self.camera_x,
                                                triangle.y + self.camera_y,
                                                triangle.z + self.camera_z).make_sdl();

            self.renderer.draw_lines(&[flat_1, flat_2, flat_3, flat_1]);
        }

        self.render_queue = Vec::new();
    }
}

pub fn bootstrap<'a>(win_width: i32, win_height: i32, win_name: &str) -> (sdl2::render::Renderer<'a>, sdl2::EventPump) {
    let sdl_context = sdl2::init().unwrap(); // context
    let sdl_video = sdl_context.video().unwrap(); // video
    let mut event_pump = sdl_context.event_pump().unwrap();

    // Make a new window
    let window = sdl_video.window(win_name, 1280, 720)
        .position_centered()
        .opengl()
        .build()
        .expect("Failed on creating a new window!");

    // turn window into a renderer, cannot do anything with window from now on.
    let mut renderer = window.renderer().build().unwrap();

    (renderer, event_pump)
}<|endoftext|>


<commit_before><commit_msg>Fix struct paths<commit_after><|endoftext|>


<commit_before><commit_msg>Documentation of music<commit_after><|endoftext|>


<commit_before><commit_msg>implement probabilistic choice<commit_after>extern crate rand;

use rand::distributions::{IndependentSample, Sample, Weighted, WeightedChoice};
use rand::{weak_rng, Rng};

const DATA: [(&str, f64); 8] = [
    ("aleph", 1.0 / 5.0),
    ("beth", 1.0 / 6.0),
    ("gimel", 1.0 / 7.0),
    ("daleth", 1.0 / 8.0),
    ("he", 1.0 / 9.0),
    ("waw", 1.0 / 10.0),
    ("zayin", 1.0 / 11.0),
    ("heth", 1759.0 / 27720.0),
];

const SAMPLES: usize = 1_000_000;

// Generate a mapping to be used by `WeightedChoice`
fn gen_mapping() -> Vec<Weighted<usize>> {
    DATA.iter()
        .enumerate()
        .map(|(i, &(_, p))| Weighted {
            // `WeightedChoice` requires `u32` weights rather than raw probabilities.  For each
            // probability, we convert it to a `u32` weight, and associate it with an index. We
            // multiply by a constant because small numbers such as 0.2 when casted to `u32`
            // become `0`.  This conversion decreases the accuracy of the mapping, which is why we
            // provide an implementation which uses `f64`s for the best accuracy.
            weight: (p * 1_000_000_000.0) as u32,
            item: i,
        })
        .collect()
}

// Generate a mapping of the raw probabilities
fn gen_mapping_float() -> Vec<f64> {
    // This does the work of `WeightedChoice::new`, splitting a number into various ranges.  The
    // `item` of `Weighted` is represented here merely by the probability's position in the `Vec`.
    let mut running_total = 0.0;
    DATA.iter()
        .map(|&(_, p)| {
            running_total += p;
            running_total
        })
        .collect()
}

// An implementation of `WeightedChoice` which uses probabilities rather than weights.  Refer to
// the `WeightedChoice` source for serious usage.
struct WcFloat {
    mapping: Vec<f64>,
}

impl WcFloat {
    fn new(mapping: &[f64]) -> Self {
        Self {
            mapping: mapping.to_vec(),
        }
    }

    // This is roughly the same logic as `WeightedChoice::ind_sample` (though is likely slower)
    fn search(&self, sample_prob: f64) -> usize {
        let idx = self.mapping
            .binary_search_by(|p| p.partial_cmp(&sample_prob).unwrap());
        match idx {
            Ok(i) | Err(i) => i,
        }
    }
}

impl IndependentSample<usize> for WcFloat {
    fn ind_sample<R: Rng>(&self, rng: &mut R) -> usize {
        // Because we know the total is exactly 1.0, we can merely use a raw float value.
        // Otherwise caching `Range::new(0.0, running_total)` and sampling with
        // `range.ind_sample(&mut rng)` is recommended.
        let sample_prob = rng.next_f64();
        self.search(sample_prob)
    }
}

impl Sample<usize> for WcFloat {
    fn sample<R: Rng>(&mut self, rng: &mut R) -> usize {
        self.ind_sample(rng)
    }
}

fn take_samples<R: Rng, T>(rng: &mut R, wc: &T) -> [usize; 8]
where
    T: IndependentSample<usize>,
{
    let mut counts = [0; 8];
    for _ in 0..SAMPLES {
        let sample = wc.ind_sample(rng);
        counts[sample] += 1;
    }
    counts
}

fn print_mapping(counts: &[usize]) {
    println!("Item   | Expected | Actual   ");
    println!("-------+----------+----------");
    for (&(name, expected), &count) in DATA.iter().zip(counts.iter()) {
        let real = count as f64 / SAMPLES as f64;
        println!("{:06} | {:.6} | {:.6}", name, expected, real);
    }
}

fn main() {
    let mut rng = weak_rng();

    println!("    ~~~ U32 METHOD ~~~");
    let mut mapping = gen_mapping();
    let wc = WeightedChoice::new(&mut mapping);

    let counts = take_samples(&mut rng, &wc);
    print_mapping(&counts);

    println!();

    println!("   ~~~ FLOAT METHOD ~~~");
    // initialize the float version of `WeightedChoice`
    let mapping = gen_mapping_float();
    let wc = WcFloat::new(&mapping);

    let counts = take_samples(&mut rng, &wc);
    print_mapping(&counts);
}

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

    fn test_sample_logic(samples: usize) {
        let mut rng = weak_rng();

        let mapping = gen_mapping_float();
        let wc = WcFloat::new(&mapping);

        for _ in 0..samples {
            let prob = rng.next_f64();
            let i = wc.search(prob);

            assert!(prob <= mapping[i], "p:{} m:{}", prob, mapping[i]);
            if i != 0 {
                assert!(mapping[i - 1] <= prob, "p:{} m:{}", prob, mapping[i - 1]);
            }
        }
    }

    #[test]
    fn small_logic() {
        test_sample_logic(1000);
    }

    #[test]
    #[ignore]
    fn large_logic() {
        test_sample_logic(100_000_000);
    }

    fn test_deviation<T: IndependentSample<usize>>(wc: T) {
        let mut rng = weak_rng();

        let counts = take_samples(&mut rng, &wc);
        for (&(_, expected), &count) in DATA.iter().zip(counts.iter()) {
            let real = count as f64 / SAMPLES as f64;
            let dev = (1.0 - real / expected).abs();
            assert!(dev < 0.01, "{}", dev);
        }
    }

    #[test]
    fn wcf_deviation() {
        let mapping = gen_mapping_float();
        let wc = WcFloat::new(&mapping);

        test_deviation(wc);
    }

    #[test]
    fn wc_deviation() {
        let mut mapping = gen_mapping();
        let wc = WeightedChoice::new(&mut mapping);

        test_deviation(wc);
    }
}
<|endoftext|>


<commit_before>//! Program x86 segmentation hardware.

use core::fmt;

/// Specifies which element to load into a segment from
/// descriptor tables (i.e., is a index to LDT or GDT table
/// with some additional flags).
bitflags! {
    flags SegmentSelector: u16 {
        /// Requestor Privilege Level
        const RPL_0 = 0b00,
        const RPL_1 = 0b01,
        const RPL_2 = 0b10,
        const RPL_3 = 0b11,

        /// Table Indicator (TI) 0 means GDT is used.
        const TI_GDT = 0 << 3,
        /// Table Indicator (TI) 1 means LDT is used.
        const TI_LDT = 1 << 3,
    }
}

impl SegmentSelector {
    /// Create a new SegmentSelector
    ///
    /// # Arguments
    ///  * `index` index in GDT or LDT array.
    ///
    pub fn new(index: u16) -> SegmentSelector {
        SegmentSelector { bits: index << 3 }
    }

    pub fn from_raw(bits: u16) -> SegmentSelector {
        SegmentSelector { bits: bits }
    }
}

impl fmt::Debug for SegmentSelector {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let r0 = match self.contains(RPL_0) {
            false => "",
            true => "Ring 0 segment selector.",
        };
        let r1 = match self.contains(RPL_1) {
            false => "",
            true => "Ring 1 segment selector.",
        };
        let r2 = match self.contains(RPL_2) {
            false => "",
            true => "Ring 2 segment selector.",
        };
        let r3 = match self.contains(RPL_3) {
            false => "",
            true => "Ring 3 segment selector.",
        };
        let tbl = match self.contains(TI_LDT) {
            false => "GDT Table",
            true => "LDT Table",
        };

        write!(f,
               "Index {} in {}, {}{}{}{}",
               self.bits >> 3,
               tbl,
               r0,
               r1,
               r2,
               r3)
        // write!(f, "Index")
    }
}

/// Entry for GDT or LDT. Provides size and location of a segment.
bitflags! {
    flags SegmentDescriptor: u64 {
        /// Descriptor type (0 = system; 1 = code or data).
        const DESC_S    = 1 << (32+12),
        /// Descriptor privilege level 0.
        const DESC_DPL0 = 0b00 << (32+13),
        /// Descriptor privilege level 1.
        const DESC_DPL1 = 0b01 << (32+13),
        /// Descriptor privilege level 2.
        const DESC_DPL2 = 0b10 << (32+13),
        /// Descriptor privilege level 3.
        const DESC_DPL3 = 0b11 << (32+13),
        /// Descriptor is Present.
        const DESC_P = 1 << (32+15),
        /// Available for use by system software.
        const DESC_AVL  = 1 << (32+20),
        /// 64-bit code segment (IA-32e mode only).
        const DESC_L    = 1 << (32+21),
        /// Default operation size (0 = 16-bit segment, 1 = 32-bit segment)
        const DESC_DB   = 1 << (32+22),
        ///  Granularity.
        const DESC_G    = 1 << (32+23),

        // System-Segment and Gate-Descriptor Types for IA32e mode.
        // When the S (descriptor type) flag in a segment descriptor is clear,
        // the descriptor type is a system descriptor.

        const TYPE_SYS_LDT = 0b0010 << (32+8),
        const TYPE_SYS_TSS_AVAILABLE = 0b1001 << (32+8),
        const TYPE_SYS_TSS_BUSY = 0b1011 << (32+8),
        const TYPE_SYS_CALL_GATE = 0b1100 << (32+8),
        const TYPE_SYS_INTERRUPT_GATE = 0b1110 << (32+8),
        const TYPE_SYS_TRAP_GATE = 0b1111 << (32+8),

        // Code- and Data-Segment Descriptor Types.
        // When the S (descriptor type) flag in a segment descriptor is set,
        // the descriptor is for either a code or a data segment.

        /// Data Read-Only
        const TYPE_D_RO = 0b0000 << (32+8),
        /// Data Read-Only, accessed
        const TYPE_D_ROA = 0b0001 << (32+8),
        /// Data Read/Write
        const TYPE_D_RW = 0b0010 << (32+8),
        /// Data Read/Write, accessed
        const TYPE_D_RWA = 0b0011 << (32+8),
        /// Data Read-Only, expand-down
        const TYPE_D_ROEXD = 0b0100 << (32+8),
        /// Data Read-Only, expand-down, accessed
        const TYPE_D_ROEXDA = 0b0101 << (32+8),
        /// Data Read/Write, expand-down
        const TYPE_D_RWEXD = 0b0110 << (32+8),
        /// Data Read/Write, expand-down, accessed
        const TYPE_D_RWEXDA = 0b0111 << (32+8),

        /// Code Execute-Only
        const TYPE_C_EO = 0b1000 << (32+8),
        /// Code Execute-Only, accessed
        const TYPE_C_EOA = 0b1001 << (32+8),
        /// Code Execute/Read
        const TYPE_C_ER = 0b1010 << (32+8),
        /// Code Execute/Read, accessed
        const TYPE_C_ERA = 0b1011 << (32+8),
        /// Code Execute-Only, conforming
        const TYPE_C_EOC = 0b1100 << (32+8),
        /// Code Execute-Only, conforming, accessed
        const TYPE_C_EOCA = 0b1101 << (32+8),
        /// Code Execute/Read, conforming
        const TYPE_C_ERC = 0b1110 << (32+8),
        /// Code Execute/Read, conforming, accessed
        const TYPE_C_ERCA = 0b1111 << (32+8),
    }
}

/// This is data-structure is a ugly mess thing so we provide some
/// convenience function to program it.
impl SegmentDescriptor {
    pub fn new(base: u32, limit: u32) -> SegmentDescriptor {
        let base_low: u64 = base as u64 & 0xffffff;
        let base_high: u64 = (base as u64 >> 24) & 0xff;

        let limit_low: u64 = limit as u64 & 0xffff;
        let limit_high: u64 = (limit as u64 & (0b1111 << 16)) >> 16;

        SegmentDescriptor {
            bits: limit_low | base_low << 16 | limit_high << (32 + 16) | base_high << (32 + 24),
        }
    }
}

impl fmt::Debug for SegmentDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "SD: 0x{:x}", self.bits)
    }
}

/// Reload stack segment register.
pub unsafe fn load_ss(sel: SegmentSelector) {
    asm!("movw $0, %ss " :: "r" (sel) : "memory");
}

/// Reload data segment register.
pub unsafe fn load_ds(sel: SegmentSelector) {
    asm!("movw $0, %ds " :: "r" (sel) : "memory");
}

/// Reload fs segment register.
pub unsafe fn load_es(sel: SegmentSelector) {
    asm!("movw $0, %es " :: "r" (sel) : "memory");
}

/// Reload fs segment register.
pub unsafe fn load_fs(sel: SegmentSelector) {
    asm!("movw $0, %fs " :: "r" (sel) : "memory");
}

/// Reload gs segment register.
pub unsafe fn load_gs(sel: SegmentSelector) {
    asm!("movw $0, %gs " :: "r" (sel) : "memory");
}

/// Reload code segment register.
/// Note this is special since we can not directly move
/// to %cs. Instead we push the new segment selector
/// and return value on the stack and use lretq
/// to reload cs and continue at 1:.
pub unsafe fn load_cs(sel: SegmentSelector) {
    asm!("pushq $0
         lea 1f(%rip), %rax
         pushq %rax
         lretq
         1:" :: "r" (sel.bits() as u64) : "{rax}" "memory");
}
<commit_msg>Add method to retrieve current code segment selector<commit_after>//! Program x86 segmentation hardware.

use core::fmt;

/// Specifies which element to load into a segment from
/// descriptor tables (i.e., is a index to LDT or GDT table
/// with some additional flags).
bitflags! {
    flags SegmentSelector: u16 {
        /// Requestor Privilege Level
        const RPL_0 = 0b00,
        const RPL_1 = 0b01,
        const RPL_2 = 0b10,
        const RPL_3 = 0b11,

        /// Table Indicator (TI) 0 means GDT is used.
        const TI_GDT = 0 << 3,
        /// Table Indicator (TI) 1 means LDT is used.
        const TI_LDT = 1 << 3,
    }
}

impl SegmentSelector {
    /// Create a new SegmentSelector
    ///
    /// # Arguments
    ///  * `index` index in GDT or LDT array.
    ///
    pub fn new(index: u16) -> SegmentSelector {
        SegmentSelector { bits: index << 3 }
    }

    pub fn from_raw(bits: u16) -> SegmentSelector {
        SegmentSelector { bits: bits }
    }
}

impl fmt::Debug for SegmentSelector {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let r0 = match self.contains(RPL_0) {
            false => "",
            true => "Ring 0 segment selector.",
        };
        let r1 = match self.contains(RPL_1) {
            false => "",
            true => "Ring 1 segment selector.",
        };
        let r2 = match self.contains(RPL_2) {
            false => "",
            true => "Ring 2 segment selector.",
        };
        let r3 = match self.contains(RPL_3) {
            false => "",
            true => "Ring 3 segment selector.",
        };
        let tbl = match self.contains(TI_LDT) {
            false => "GDT Table",
            true => "LDT Table",
        };

        write!(f,
               "Index {} in {}, {}{}{}{}",
               self.bits >> 3,
               tbl,
               r0,
               r1,
               r2,
               r3)
        // write!(f, "Index")
    }
}

/// Entry for GDT or LDT. Provides size and location of a segment.
bitflags! {
    flags SegmentDescriptor: u64 {
        /// Descriptor type (0 = system; 1 = code or data).
        const DESC_S    = 1 << (32+12),
        /// Descriptor privilege level 0.
        const DESC_DPL0 = 0b00 << (32+13),
        /// Descriptor privilege level 1.
        const DESC_DPL1 = 0b01 << (32+13),
        /// Descriptor privilege level 2.
        const DESC_DPL2 = 0b10 << (32+13),
        /// Descriptor privilege level 3.
        const DESC_DPL3 = 0b11 << (32+13),
        /// Descriptor is Present.
        const DESC_P = 1 << (32+15),
        /// Available for use by system software.
        const DESC_AVL  = 1 << (32+20),
        /// 64-bit code segment (IA-32e mode only).
        const DESC_L    = 1 << (32+21),
        /// Default operation size (0 = 16-bit segment, 1 = 32-bit segment)
        const DESC_DB   = 1 << (32+22),
        ///  Granularity.
        const DESC_G    = 1 << (32+23),

        // System-Segment and Gate-Descriptor Types for IA32e mode.
        // When the S (descriptor type) flag in a segment descriptor is clear,
        // the descriptor type is a system descriptor.

        const TYPE_SYS_LDT = 0b0010 << (32+8),
        const TYPE_SYS_TSS_AVAILABLE = 0b1001 << (32+8),
        const TYPE_SYS_TSS_BUSY = 0b1011 << (32+8),
        const TYPE_SYS_CALL_GATE = 0b1100 << (32+8),
        const TYPE_SYS_INTERRUPT_GATE = 0b1110 << (32+8),
        const TYPE_SYS_TRAP_GATE = 0b1111 << (32+8),

        // Code- and Data-Segment Descriptor Types.
        // When the S (descriptor type) flag in a segment descriptor is set,
        // the descriptor is for either a code or a data segment.

        /// Data Read-Only
        const TYPE_D_RO = 0b0000 << (32+8),
        /// Data Read-Only, accessed
        const TYPE_D_ROA = 0b0001 << (32+8),
        /// Data Read/Write
        const TYPE_D_RW = 0b0010 << (32+8),
        /// Data Read/Write, accessed
        const TYPE_D_RWA = 0b0011 << (32+8),
        /// Data Read-Only, expand-down
        const TYPE_D_ROEXD = 0b0100 << (32+8),
        /// Data Read-Only, expand-down, accessed
        const TYPE_D_ROEXDA = 0b0101 << (32+8),
        /// Data Read/Write, expand-down
        const TYPE_D_RWEXD = 0b0110 << (32+8),
        /// Data Read/Write, expand-down, accessed
        const TYPE_D_RWEXDA = 0b0111 << (32+8),

        /// Code Execute-Only
        const TYPE_C_EO = 0b1000 << (32+8),
        /// Code Execute-Only, accessed
        const TYPE_C_EOA = 0b1001 << (32+8),
        /// Code Execute/Read
        const TYPE_C_ER = 0b1010 << (32+8),
        /// Code Execute/Read, accessed
        const TYPE_C_ERA = 0b1011 << (32+8),
        /// Code Execute-Only, conforming
        const TYPE_C_EOC = 0b1100 << (32+8),
        /// Code Execute-Only, conforming, accessed
        const TYPE_C_EOCA = 0b1101 << (32+8),
        /// Code Execute/Read, conforming
        const TYPE_C_ERC = 0b1110 << (32+8),
        /// Code Execute/Read, conforming, accessed
        const TYPE_C_ERCA = 0b1111 << (32+8),
    }
}

/// This is data-structure is a ugly mess thing so we provide some
/// convenience function to program it.
impl SegmentDescriptor {
    pub fn new(base: u32, limit: u32) -> SegmentDescriptor {
        let base_low: u64 = base as u64 & 0xffffff;
        let base_high: u64 = (base as u64 >> 24) & 0xff;

        let limit_low: u64 = limit as u64 & 0xffff;
        let limit_high: u64 = (limit as u64 & (0b1111 << 16)) >> 16;

        SegmentDescriptor {
            bits: limit_low | base_low << 16 | limit_high << (32 + 16) | base_high << (32 + 24),
        }
    }
}

impl fmt::Debug for SegmentDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "SD: 0x{:x}", self.bits)
    }
}

/// Reload stack segment register.
pub unsafe fn load_ss(sel: SegmentSelector) {
    asm!("movw $0, %ss " :: "r" (sel) : "memory");
}

/// Reload data segment register.
pub unsafe fn load_ds(sel: SegmentSelector) {
    asm!("movw $0, %ds " :: "r" (sel) : "memory");
}

/// Reload fs segment register.
pub unsafe fn load_es(sel: SegmentSelector) {
    asm!("movw $0, %es " :: "r" (sel) : "memory");
}

/// Reload fs segment register.
pub unsafe fn load_fs(sel: SegmentSelector) {
    asm!("movw $0, %fs " :: "r" (sel) : "memory");
}

/// Reload gs segment register.
pub unsafe fn load_gs(sel: SegmentSelector) {
    asm!("movw $0, %gs " :: "r" (sel) : "memory");
}

/// Reload code segment register.
/// Note this is special since we can not directly move
/// to %cs. Instead we push the new segment selector
/// and return value on the stack and use lretq
/// to reload cs and continue at 1:.
pub unsafe fn load_cs(sel: SegmentSelector) {
    asm!("pushq $0
         lea 1f(%rip), %rax
         pushq %rax
         lretq
         1:" :: "r" (sel.bits() as u64) : "{rax}" "memory");
}

/// Returns the current value of the code segment register.
pub fn cs() -> SegmentSelector {
    let segment: u16;
    unsafe { asm!("mov %cs, $0" : "=r" (segment) ) };
    SegmentSelector::from_raw(segment)
}
<|endoftext|>


<commit_before><commit_msg>can borrow after closure goes out of scope<commit_after><|endoftext|>


<commit_before><commit_msg>store_buffer: Add storing buffer implemantaion<commit_after>use std::fs::File;
use std::io::Write;
use std::fmt::Debug;
use retry_conf::RetryConf;
use retry::RetryError;
use rustc_serialize::Encodable;
use record::FluentError;

pub fn maybe_write_file<T>(conf: &RetryConf, record: T, err: RetryError) -> Result<(), FluentError>
    where T: Encodable + Debug
{
    let store_needed = conf.clone().need_to_store();
    let store_path = conf.clone().store_path();
    if store_needed && store_path.is_some() {
        match File::create(store_path.unwrap()) {
            Ok(mut f) => {
                let mut w = Vec::new();
                write!(&mut w, "{:?}", record).unwrap();
                try!(f.write(&w));
            },
            Err(e) => return Err(From::from(e)),
        }
        Ok(())
    }
    else {
        Err(From::from(err))
    }
}
<|endoftext|>


<commit_before>use {io};
use sys::unix::{nix, Io};
use std::net::SocketAddr;
use std::os::unix::io::{AsRawFd, RawFd};
pub use net::tcp::Shutdown;

pub fn socket(family: nix::AddressFamily, ty: nix::SockType, nonblock: bool) -> io::Result<RawFd> {
    let opts = if nonblock {
        nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
    } else {
        nix::SOCK_CLOEXEC
    };

    nix::socket(family, ty, opts)
        .map_err(super::from_nix_error)
}

pub fn connect(io: &Io, addr: &nix::SockAddr) -> io::Result<bool> {
    match nix::connect(io.as_raw_fd(), addr) {
        Ok(_) => Ok(true),
        Err(e) => {
            match e {
                nix::Error::Sys(nix::EINPROGRESS) => Ok(false),
                _ => Err(super::from_nix_error(e))
            }
        }
    }
}

pub fn bind(io: &Io, addr: &nix::SockAddr) -> io::Result<()> {
    nix::bind(io.as_raw_fd(), addr)
        .map_err(super::from_nix_error)
}

pub fn listen(io: &Io, backlog: usize) -> io::Result<()> {
    nix::listen(io.as_raw_fd(), backlog)
        .map_err(super::from_nix_error)
}

pub fn accept(io: &Io, nonblock: bool) -> io::Result<RawFd> {
    let opts = if nonblock {
        nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
    } else {
        nix::SOCK_CLOEXEC
    };

    nix::accept4(io.as_raw_fd(), opts)
        .map_err(super::from_nix_error)
}

pub fn shutdown(io: &Io, how: Shutdown) -> io::Result<()> {
    let how: nix::Shutdown = match how {
        Shutdown::Read  => nix::Shutdown::Read,
        Shutdown::Write => nix::Shutdown::Write,
        Shutdown::Both  => nix::Shutdown::Both,
    };
    nix::shutdown(io.as_raw_fd(), &how)
        .map_err(super::from_nix_error)
}

// UDP & UDS
#[inline]
pub fn recvfrom(io: &Io, buf: &mut [u8]) -> io::Result<(usize, nix::SockAddr)> {
    nix::recvfrom(io.as_raw_fd(), buf)
        .map_err(super::from_nix_error)
}

// UDP & UDS
#[inline]
pub fn sendto(io: &Io, buf: &[u8], target: &nix::SockAddr) -> io::Result<usize> {
    nix::sendto(io.as_raw_fd(), buf, target, nix::MSG_DONTWAIT)
        .map_err(super::from_nix_error)
}

pub fn getpeername(io: &Io) -> io::Result<nix::SockAddr> {
    nix::getpeername(io.as_raw_fd())
        .map_err(super::from_nix_error)
}

pub fn getsockname(io: &Io) -> io::Result<nix::SockAddr> {
    nix::getsockname(io.as_raw_fd())
        .map_err(super::from_nix_error)
}

#[inline]
pub fn dup(io: &Io) -> io::Result<Io> {
    nix::dup(io.as_raw_fd())
        .map_err(super::from_nix_error)
        .map(|fd| Io::from_raw_fd(fd))
}

/*
 *
 * ===== Helpers =====
 *
 */

pub fn to_nix_addr(addr: &SocketAddr) -> nix::SockAddr {
    nix::SockAddr::Inet(nix::InetAddr::from_std(addr))
}

pub fn to_std_addr(addr: nix::SockAddr) -> SocketAddr {
    match addr {
        nix::SockAddr::Inet(ref addr) => addr.to_std(),
        _ => panic!("unexpected unix socket address"),
    }
}
<commit_msg>Bugfix: sync with carllerche/nix-rust<commit_after>use {io};
use sys::unix::{nix, Io};
use std::net::SocketAddr;
use std::os::unix::io::{AsRawFd, RawFd};
pub use net::tcp::Shutdown;

pub fn socket(family: nix::AddressFamily, ty: nix::SockType, nonblock: bool) -> io::Result<RawFd> {
    let opts = if nonblock {
        nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
    } else {
        nix::SOCK_CLOEXEC
    };

    nix::socket(family, ty, opts)
        .map_err(super::from_nix_error)
}

pub fn connect(io: &Io, addr: &nix::SockAddr) -> io::Result<bool> {
    match nix::connect(io.as_raw_fd(), addr) {
        Ok(_) => Ok(true),
        Err(e) => {
            match e {
                nix::Error::Sys(nix::EINPROGRESS) => Ok(false),
                _ => Err(super::from_nix_error(e))
            }
        }
    }
}

pub fn bind(io: &Io, addr: &nix::SockAddr) -> io::Result<()> {
    nix::bind(io.as_raw_fd(), addr)
        .map_err(super::from_nix_error)
}

pub fn listen(io: &Io, backlog: usize) -> io::Result<()> {
    nix::listen(io.as_raw_fd(), backlog)
        .map_err(super::from_nix_error)
}

pub fn accept(io: &Io, nonblock: bool) -> io::Result<RawFd> {
    let opts = if nonblock {
        nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
    } else {
        nix::SOCK_CLOEXEC
    };

    nix::accept4(io.as_raw_fd(), opts)
        .map_err(super::from_nix_error)
}

pub fn shutdown(io: &Io, how: Shutdown) -> io::Result<()> {
    let how: nix::Shutdown = match how {
        Shutdown::Read  => nix::Shutdown::Read,
        Shutdown::Write => nix::Shutdown::Write,
        Shutdown::Both  => nix::Shutdown::Both,
    };
    nix::shutdown(io.as_raw_fd(), how)
        .map_err(super::from_nix_error)
}

// UDP & UDS
#[inline]
pub fn recvfrom(io: &Io, buf: &mut [u8]) -> io::Result<(usize, nix::SockAddr)> {
    nix::recvfrom(io.as_raw_fd(), buf)
        .map_err(super::from_nix_error)
}

// UDP & UDS
#[inline]
pub fn sendto(io: &Io, buf: &[u8], target: &nix::SockAddr) -> io::Result<usize> {
    nix::sendto(io.as_raw_fd(), buf, target, nix::MSG_DONTWAIT)
        .map_err(super::from_nix_error)
}

pub fn getpeername(io: &Io) -> io::Result<nix::SockAddr> {
    nix::getpeername(io.as_raw_fd())
        .map_err(super::from_nix_error)
}

pub fn getsockname(io: &Io) -> io::Result<nix::SockAddr> {
    nix::getsockname(io.as_raw_fd())
        .map_err(super::from_nix_error)
}

#[inline]
pub fn dup(io: &Io) -> io::Result<Io> {
    nix::dup(io.as_raw_fd())
        .map_err(super::from_nix_error)
        .map(|fd| Io::from_raw_fd(fd))
}

/*
 *
 * ===== Helpers =====
 *
 */

pub fn to_nix_addr(addr: &SocketAddr) -> nix::SockAddr {
    nix::SockAddr::Inet(nix::InetAddr::from_std(addr))
}

pub fn to_std_addr(addr: nix::SockAddr) -> SocketAddr {
    match addr {
        nix::SockAddr::Inet(ref addr) => addr.to_std(),
        _ => panic!("unexpected unix socket address"),
    }
}
<|endoftext|>


<commit_before><commit_msg>Add code for palindrome-products<commit_after>#[derive(Debug, PartialEq, Eq)]
pub struct Palindrome {
    v: Vec<(u64, u64)>,
}

impl Palindrome {
    pub fn new(a: u64, b: u64) -> Palindrome {
        Palindrome { v: vec![(a, b)] }
    }

    pub fn insert(&mut self, a: u64, b: u64) {
        self.v.push((a, b))
    }
}

fn is_palindrome(value: u64) -> bool {
    let mut v = value;
    let mut r = 0;

    while v > 0 {
        r = r * 10 + v % 10;
        v /= 10;
    }

    r == value
}

pub fn palindrome_products(min: u64, max: u64) -> Option<(Palindrome, Palindrome)> {
    if min > max {
        return None;
    }

    let mut min_value = u64::MAX;
    let mut max_value = u64::MIN;

    let mut min_set = Palindrome::new(0, 0);
    let mut max_set = Palindrome::new(0, 0);

    for i in min..=max {
        for j in i..=max {
            let v = i * j;
            if !is_palindrome(v) {
                continue;
            }

            if v < min_value {
                min_value = v;
                min_set = Palindrome::new(i, j);
            } else if v == min_value {
                min_set.insert(i, j);
            } else if v > max_value {
                max_value = v;
                max_set = Palindrome::new(i, j);
            } else if v == max_value {
                max_set.insert(i, j);
            }
        }
    }

    if min_value == u64::MAX {
        None
    } else {
        Some((min_set, max_set))
    }
}
<|endoftext|>


<commit_before>use std::default::Default;
use ::internal::prelude::*;

macro_rules! colour {
    ($(#[$attr:meta] $name:ident, $val:expr;)*) => {
        impl Colour {
            $(
                #[$attr]
                pub fn $name() -> Colour {
                    Colour::new($val)
                }
            )*
        }
    }
}

/// A utility struct to help with working with the basic representation of a
/// colour. This is particularly useful when working with a [`Role`]'s colour,
/// as the API works with an integer value instead of an RGB value.
///
/// Instances can be created by using the struct's associated functions. These
/// produce presets equivilant to those found in the official client's colour
/// picker.
///
/// # Examples
///
/// Passing in a role's colour, and then retrieving its green component
/// via [`get_g`]:
///
/// ```rust,ignore
/// use serenity::utils::Colour;
///
/// // assuming a `role` has already been bound
///
/// let colour = Colour::new(role.colour);
/// let green = colour.get_g();
///
/// println!("The green component is: {}", green);
/// ```
///
/// Creating an instance with the [`dark_teal`] presets:
///
/// ```rust
/// use serenity::utils::Colour;
///
/// let colour = Colour::dark_teal();
///
/// assert_eq!(colour.get_tuple(), (17, 128, 106));
/// ```
///
/// [`Role`]: ../model/struct.Role.html
/// [`dark_teal`]: #method.dark_teal
/// [`get_g`]: #method.get_g
#[derive(Clone, Copy, Debug)]
pub struct Colour {
    /// The raw inner 32-bit unsigned integer value of this Colour. This is
    /// worked with to generate values such as the red component value.
    pub value: u32,
}

impl Colour {
    /// Generates a new Colour with the given integer value set.
    ///
    /// # Examples
    ///
    /// Create a new Colour, and then ensure that its inner value is equivilant
    /// to a specific RGB value, retrieved via [`get_tuple`]:
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// let colour = Colour::new(6573123);
    ///
    /// assert_eq!(colour.get_tuple(), (100, 76, 67));
    /// ```
    ///
    /// [`get_tuple`]: #method.get_tuple
    pub fn new(value: u32) -> Colour {
        Colour {
            value: value,
        }
    }

    /// Generates a new Colour from an RGB value, creating an inner u32
    /// representation.
    ///
    /// # Examples
    ///
    /// Creating a `Colour` via its RGB values will set its inner u32 correctly:
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert!(Colour::from_rgb(255, 0, 0).value == 0xFF0000);
    /// assert!(Colour::from_rgb(217, 23, 211).value == 0xD917D3);
    /// ```
    ///
    /// And you can then retrieve those same RGB values via its methods:
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// let colour = Colour::from_rgb(217, 45, 215);
    ///
    /// assert_eq!(colour.get_r(), 217);
    /// assert_eq!(colour.get_g(), 45);
    /// assert_eq!(colour.get_b(), 215);
    /// assert_eq!(colour.get_tuple(), (217, 45, 215));
    /// ```
    pub fn from_rgb(r: u8, g: u8, b: u8) -> Colour {
        let mut uint = r as u32;
        uint = (uint << 8) | (g as u32);
        uint = (uint << 8) | (b as u32);

        Colour::new(uint)
    }

    #[doc(hidden)]
    pub fn decode(value: Value) -> Result<Colour> {
        match value {
            Value::U64(v) => Ok(Colour::new(v as u32)),
            Value::I64(v) => Ok(Colour::new(v as u32)),
            other => Err(Error::Decode("Expected valid colour", other)),
        }
    }

    /// Returns the red RGB component of this Colour.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::new(6573123).get_r(), 100);
    /// ```
    pub fn get_r(&self) -> u8 {
        ((self.value >> 16) & 255) as u8
    }

    /// Returns the green RGB component of this Colour.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::new(6573123).get_g(), 76);
    /// ```
    pub fn get_g(&self) -> u8 {
        ((self.value >> 8) & 255) as u8
    }

    /// Returns the blue RGB component of this Colour.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::new(6573123).get_b(), 67);
    pub fn get_b(&self) -> u8 {
        (self.value & 255) as u8
    }

    /// Returns a tuple of the red, green, and blue components of this Colour.
    ///
    /// This is equivilant to creating a tuple with the return values of
    /// [`get_r`], [`get_g`], and [`get_b`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::new(6573123).get_tuple(), (100, 76, 67));
    /// ```
    ///
    /// [`get_r`]: #method.get_r
    /// [`get_g`]: #method.get_g
    /// [`get_b`]: #method.get_b
    pub fn get_tuple(&self) -> (u8, u8, u8) {
        (self.get_r(), self.get_g(), self.get_b())
    }
}

impl From<i32> for Colour {
    /// Constructs a Colour from a i32.
    ///
    /// This is used for functions that accept `Into<Colour>`.
    ///
    /// This is useful when providing hex values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::from(0xDEA584).get_tuple(), (222, 165, 132));
    /// ```
    fn from(value: i32) -> Colour {
        Colour::new(value as u32)
    }
}

impl From<u32> for Colour {
    /// Constructs a Colour from a u32.
    ///
    /// This is used for functions that accept `Into<Colour>`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::from(6573123u32).get_r(), 100);
    /// ```
    fn from(value: u32) -> Colour {
        Colour::new(value)
    }
}

impl From<u64> for Colour {
    /// Constructs a Colour from a u32.
    ///
    /// This is used for functions that accept `Into<Colour>`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::from(6573123u64).get_r(), 100);
    /// ```
    fn from(value: u64) -> Colour {
        Colour::new(value as u32)
    }
}

colour! {
    /// Creates a new `Colour`, setting its RGB value to `(111, 198, 226)`.
    blitz_blue, 0x6FC6E2;
    /// Creates a new `Colour`, setting its RGB value to `(52, 152, 219)`.
    blue, 0x3498DB;
    /// Creates a new `Colour`, setting its RGB value to `(114, 137, 218)`.
    blurple, 0x7289DA;
    /// Creates a new `Colour`, setting its RGB value to `(32, 102, 148)`.
    dark_blue, 0x206694;
    /// Creates a new `Colour`, setting its RGB value to `(194, 124, 14)`.
    dark_gold, 0xC27C0E;
    /// Creates a new `Colour`, setting its RGB value to `(31, 139, 76)`.
    dark_green, 0x1F8B4C;
    /// Creates a new `Colour`, setting its RGB value to `(96, 125, 139)`.
    dark_grey, 0x607D8B;
    /// Creates a new `Colour`, setting its RGB value to `(173, 20, 87)`.
    dark_magenta, 0xAD1457;
    /// Creates a new `Colour`, setting its RGB value to `(168, 67, 0)`.
    dark_orange, 0xA84300;
    /// Creates a new `Colour`, setting its RGB value to `(113, 54, 138)`.
    dark_purple, 0x71368A;
    /// Creates a new `Colour`, setting its RGB value to `(153, 45, 34)`.
    dark_red, 0x992D22;
    /// Creates a new `Colour`, setting its RGB value to `(17, 128, 106)`.
    dark_teal, 0x11806A;
    /// Creates a new `Colour`, setting its RGB value to `(84, 110, 122)`.
    darker_grey, 0x546E7A;
    /// Creates a new `Colour`, setting its RGB value to `(250, 177, 237)`.
    fabled_pink, 0xFAB1ED
    /// Creates a new `Colour`, setting its RGB value to `(241, 196, 15)`.
    gold, 0xF1C40F;
    /// Creates a new `Colour`, setting its RGB value to `(186, 218, 85)`.
    kerbal, 0xBADA55;
    /// Creates a new `Colour`, setting its RGB value to `(151, 156, 159)`.
    light_grey, 0x979C9F;
    /// Creates a new `Colour`, setting its RGB value to `(149, 165, 166)`.
    lighter_grey, 0x95A5A6;
    /// Creates a new `Colour`, setting its RGB value to `(233, 30, 99)`.
    magenta, 0xE91E63;
    /// Creates a new `Colour`, setting its RGB value to `(230, 126, 34)`.
    orange, 0xE67E22;
    /// Creates a new `Colour`, setting its RGB value to `(155, 89, 182)`.
    purple, 0x9B59B6;
    /// Creates a new `Colour`, setting its RGB value to `(231, 76, 60)`.
    red, 0xE74C3C;
    /// Creates a new `Colour`, setting its RGB value to `(26, 188, 156)`.
    teal, 0x1ABC9C;
}

impl Default for Colour {
    /// Creates a default value for a `Colour`, setting the inner value to `0`.
    /// This is equivilant to setting the RGB value to `(0, 0, 0)`.
    fn default() -> Colour {
        Colour {
            value: 0,
        }
    }
}
<commit_msg>Add 'fooyoo' to Colour struct<commit_after>use std::default::Default;
use ::internal::prelude::*;

macro_rules! colour {
    ($(#[$attr:meta] $name:ident, $val:expr;)*) => {
        impl Colour {
            $(
                #[$attr]
                pub fn $name() -> Colour {
                    Colour::new($val)
                }
            )*
        }
    }
}

/// A utility struct to help with working with the basic representation of a
/// colour. This is particularly useful when working with a [`Role`]'s colour,
/// as the API works with an integer value instead of an RGB value.
///
/// Instances can be created by using the struct's associated functions. These
/// produce presets equivilant to those found in the official client's colour
/// picker.
///
/// # Examples
///
/// Passing in a role's colour, and then retrieving its green component
/// via [`get_g`]:
///
/// ```rust,ignore
/// use serenity::utils::Colour;
///
/// // assuming a `role` has already been bound
///
/// let colour = Colour::new(role.colour);
/// let green = colour.get_g();
///
/// println!("The green component is: {}", green);
/// ```
///
/// Creating an instance with the [`dark_teal`] presets:
///
/// ```rust
/// use serenity::utils::Colour;
///
/// let colour = Colour::dark_teal();
///
/// assert_eq!(colour.get_tuple(), (17, 128, 106));
/// ```
///
/// [`Role`]: ../model/struct.Role.html
/// [`dark_teal`]: #method.dark_teal
/// [`get_g`]: #method.get_g
#[derive(Clone, Copy, Debug)]
pub struct Colour {
    /// The raw inner 32-bit unsigned integer value of this Colour. This is
    /// worked with to generate values such as the red component value.
    pub value: u32,
}

impl Colour {
    /// Generates a new Colour with the given integer value set.
    ///
    /// # Examples
    ///
    /// Create a new Colour, and then ensure that its inner value is equivilant
    /// to a specific RGB value, retrieved via [`get_tuple`]:
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// let colour = Colour::new(6573123);
    ///
    /// assert_eq!(colour.get_tuple(), (100, 76, 67));
    /// ```
    ///
    /// [`get_tuple`]: #method.get_tuple
    pub fn new(value: u32) -> Colour {
        Colour {
            value: value,
        }
    }

    /// Generates a new Colour from an RGB value, creating an inner u32
    /// representation.
    ///
    /// # Examples
    ///
    /// Creating a `Colour` via its RGB values will set its inner u32 correctly:
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert!(Colour::from_rgb(255, 0, 0).value == 0xFF0000);
    /// assert!(Colour::from_rgb(217, 23, 211).value == 0xD917D3);
    /// ```
    ///
    /// And you can then retrieve those same RGB values via its methods:
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// let colour = Colour::from_rgb(217, 45, 215);
    ///
    /// assert_eq!(colour.get_r(), 217);
    /// assert_eq!(colour.get_g(), 45);
    /// assert_eq!(colour.get_b(), 215);
    /// assert_eq!(colour.get_tuple(), (217, 45, 215));
    /// ```
    pub fn from_rgb(r: u8, g: u8, b: u8) -> Colour {
        let mut uint = r as u32;
        uint = (uint << 8) | (g as u32);
        uint = (uint << 8) | (b as u32);

        Colour::new(uint)
    }

    #[doc(hidden)]
    pub fn decode(value: Value) -> Result<Colour> {
        match value {
            Value::U64(v) => Ok(Colour::new(v as u32)),
            Value::I64(v) => Ok(Colour::new(v as u32)),
            other => Err(Error::Decode("Expected valid colour", other)),
        }
    }

    /// Returns the red RGB component of this Colour.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::new(6573123).get_r(), 100);
    /// ```
    pub fn get_r(&self) -> u8 {
        ((self.value >> 16) & 255) as u8
    }

    /// Returns the green RGB component of this Colour.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::new(6573123).get_g(), 76);
    /// ```
    pub fn get_g(&self) -> u8 {
        ((self.value >> 8) & 255) as u8
    }

    /// Returns the blue RGB component of this Colour.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::new(6573123).get_b(), 67);
    pub fn get_b(&self) -> u8 {
        (self.value & 255) as u8
    }

    /// Returns a tuple of the red, green, and blue components of this Colour.
    ///
    /// This is equivilant to creating a tuple with the return values of
    /// [`get_r`], [`get_g`], and [`get_b`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::new(6573123).get_tuple(), (100, 76, 67));
    /// ```
    ///
    /// [`get_r`]: #method.get_r
    /// [`get_g`]: #method.get_g
    /// [`get_b`]: #method.get_b
    pub fn get_tuple(&self) -> (u8, u8, u8) {
        (self.get_r(), self.get_g(), self.get_b())
    }
}

impl From<i32> for Colour {
    /// Constructs a Colour from a i32.
    ///
    /// This is used for functions that accept `Into<Colour>`.
    ///
    /// This is useful when providing hex values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::from(0xDEA584).get_tuple(), (222, 165, 132));
    /// ```
    fn from(value: i32) -> Colour {
        Colour::new(value as u32)
    }
}

impl From<u32> for Colour {
    /// Constructs a Colour from a u32.
    ///
    /// This is used for functions that accept `Into<Colour>`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::from(6573123u32).get_r(), 100);
    /// ```
    fn from(value: u32) -> Colour {
        Colour::new(value)
    }
}

impl From<u64> for Colour {
    /// Constructs a Colour from a u32.
    ///
    /// This is used for functions that accept `Into<Colour>`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::utils::Colour;
    ///
    /// assert_eq!(Colour::from(6573123u64).get_r(), 100);
    /// ```
    fn from(value: u64) -> Colour {
        Colour::new(value as u32)
    }
}

colour! {
    /// Creates a new `Colour`, setting its RGB value to `(111, 198, 226)`.
    blitz_blue, 0x6FC6E2;
    /// Creates a new `Colour`, setting its RGB value to `(52, 152, 219)`.
    blue, 0x3498DB;
    /// Creates a new `Colour`, setting its RGB value to `(114, 137, 218)`.
    blurple, 0x7289DA;
    /// Creates a new `Colour`, setting its RGB value to `(32, 102, 148)`.
    dark_blue, 0x206694;
    /// Creates a new `Colour`, setting its RGB value to `(194, 124, 14)`.
    dark_gold, 0xC27C0E;
    /// Creates a new `Colour`, setting its RGB value to `(31, 139, 76)`.
    dark_green, 0x1F8B4C;
    /// Creates a new `Colour`, setting its RGB value to `(96, 125, 139)`.
    dark_grey, 0x607D8B;
    /// Creates a new `Colour`, setting its RGB value to `(173, 20, 87)`.
    dark_magenta, 0xAD1457;
    /// Creates a new `Colour`, setting its RGB value to `(168, 67, 0)`.
    dark_orange, 0xA84300;
    /// Creates a new `Colour`, setting its RGB value to `(113, 54, 138)`.
    dark_purple, 0x71368A;
    /// Creates a new `Colour`, setting its RGB value to `(153, 45, 34)`.
    dark_red, 0x992D22;
    /// Creates a new `Colour`, setting its RGB value to `(17, 128, 106)`.
    dark_teal, 0x11806A;
    /// Creates a new `Colour`, setting its RGB value to `(84, 110, 122)`.
    darker_grey, 0x546E7A;
    /// Creates a new `Colour`, setting its RGB value to `(250, 177, 237)`.
    fabled_pink, 0xFAB1ED;
    /// Creates a new `Colour`, setting its RGB value to `(17, 202, 128)`.
    fooyoo, 0x11CA80;
    /// Creates a new `Colour`, setting its RGB value to `(241, 196, 15)`.
    gold, 0xF1C40F;
    /// Creates a new `Colour`, setting its RGB value to `(186, 218, 85)`.
    kerbal, 0xBADA55;
    /// Creates a new `Colour`, setting its RGB value to `(151, 156, 159)`.
    light_grey, 0x979C9F;
    /// Creates a new `Colour`, setting its RGB value to `(149, 165, 166)`.
    lighter_grey, 0x95A5A6;
    /// Creates a new `Colour`, setting its RGB value to `(233, 30, 99)`.
    magenta, 0xE91E63;
    /// Creates a new `Colour`, setting its RGB value to `(230, 126, 34)`.
    orange, 0xE67E22;
    /// Creates a new `Colour`, setting its RGB value to `(155, 89, 182)`.
    purple, 0x9B59B6;
    /// Creates a new `Colour`, setting its RGB value to `(231, 76, 60)`.
    red, 0xE74C3C;
    /// Creates a new `Colour`, setting its RGB value to `(26, 188, 156)`.
    teal, 0x1ABC9C;
}

impl Default for Colour {
    /// Creates a default value for a `Colour`, setting the inner value to `0`.
    /// This is equivilant to setting the RGB value to `(0, 0, 0)`.
    fn default() -> Colour {
        Colour {
            value: 0,
        }
    }
}
<|endoftext|>


<commit_before>use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::is_ty_param_diagnostic_item;
use rustc_hir::{self as hir, def_id::DefId, QPath};
use rustc_lint::LateContext;
use rustc_span::symbol::sym;

use super::BOX_COLLECTION;

pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_>, def_id: DefId) -> bool {
    if_chain! {
        if Some(def_id) == cx.tcx.lang_items().owned_box();
        if let Some(item_type) = get_std_collection(cx, qpath);
        then {
            let generic = if item_type == "String" {
                ""
            } else {
                "<..>"
            };
            span_lint_and_help(
                cx,
                BOX_COLLECTION,
                hir_ty.span,
                &format!(
                    "you seem to be trying to use `Box<{outer}{generic}>`. Consider using just `{outer}{generic}`",
                    outer=item_type,
                    generic = generic),
                None,
                &format!(
                    "`{outer}{generic}` is already on the heap, `Box<{outer}{generic}>` makes an extra allocation",
                    outer=item_type,
                    generic = generic)
            );
            true
        } else {
            false
        }
    }
}

fn get_std_collection(cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<String> {
    if is_ty_param_diagnostic_item(cx, qpath, sym::vec_type).is_some() {
        Some(String::from("Vec"))
    } else if is_ty_param_diagnostic_item(cx, qpath, sym::string_type).is_some() {
        Some(String::from("String"))
    } else if is_ty_param_diagnostic_item(cx, qpath, sym::hashmap_type).is_some() {
        Some(String::from("HashMap"))
    } else {
        None
    }
}
<commit_msg>Avoid needless heap allocation in box_collection<commit_after>use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::is_ty_param_diagnostic_item;
use rustc_hir::{self as hir, def_id::DefId, QPath};
use rustc_lint::LateContext;
use rustc_span::symbol::sym;

use super::BOX_COLLECTION;

pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_>, def_id: DefId) -> bool {
    if_chain! {
        if Some(def_id) == cx.tcx.lang_items().owned_box();
        if let Some(item_type) = get_std_collection(cx, qpath);
        then {
            let generic = if item_type == "String" {
                ""
            } else {
                "<..>"
            };
            span_lint_and_help(
                cx,
                BOX_COLLECTION,
                hir_ty.span,
                &format!(
                    "you seem to be trying to use `Box<{outer}{generic}>`. Consider using just `{outer}{generic}`",
                    outer=item_type,
                    generic = generic),
                None,
                &format!(
                    "`{outer}{generic}` is already on the heap, `Box<{outer}{generic}>` makes an extra allocation",
                    outer=item_type,
                    generic = generic)
            );
            true
        } else {
            false
        }
    }
}

fn get_std_collection(cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<&'static str> {
    if is_ty_param_diagnostic_item(cx, qpath, sym::vec_type).is_some() {
        Some("Vec")
    } else if is_ty_param_diagnostic_item(cx, qpath, sym::string_type).is_some() {
        Some("String")
    } else if is_ty_param_diagnostic_item(cx, qpath, sym::hashmap_type).is_some() {
        Some("HashMap")
    } else {
        None
    }
}
<|endoftext|>


<commit_before><commit_msg>rust stack<commit_after>struct Stack<T> {
    data: Vec<T>,
}

impl<T> Stack<T> {
    //  Returns a new Stack
    fn new() -> Stack<T> {
        Stack { data: vec![] }
    }

    // Pushes the elemnt to top of stack
    fn push(&mut self, e: T) {
        self.data.push(e)
    }

    // Returns Option with top element of the stack
    fn pop(&mut self) -> Option<T> {
        self.data.pop()
    }

    // Returns true if stack is empty
    fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    // Returns length of Stack
    fn len(&self) -> usize {
        self.data.len()
    }
}
<|endoftext|>


<commit_before><commit_msg>Update common error with more details<commit_after><|endoftext|>