<commit_before>extern crate indicatif;

use std::thread;
use std::time::Duration;
use std::borrow::Cow;

use indicatif::{ProgressBar, MultiProgress, ProgressStyle, style};

fn main() {
    let mut m = MultiProgress::new();
    let mut sty = ProgressStyle::default();
    sty.bar_template = Cow::Owned(
        format!("{} {{wide_bar}} {{pos}}/{{len}}", style("{spinner}").cyan()));
    sty.progress_styles = vec![
        style('█').cyan(),
        style('█').magenta(),
        style(' ')
    ];

    let pb = m.add(ProgressBar::new(128));
    pb.enable_spinner();
    pb.set_style(sty.clone());
    let _ = thread::spawn(move || {
        for i in 0..128 {
            pb.set_message(&format!("item #{}", i + 1));
            pb.inc(1);
            thread::sleep(Duration::from_millis(15));
        }
        pb.finish_with_message("done");
    });

    let pb = m.add(ProgressBar::new(128));
    pb.enable_spinner();
    pb.set_style(sty.clone());
    let _ = thread::spawn(move || {
        for _ in 0..3 {
            pb.set_position(0);
            for i in 0..128 {
                pb.set_message(&format!("item #{}", i + 1));
                pb.inc(1);
                thread::sleep(Duration::from_millis(8));
            }
        }
        pb.finish_with_message("done");
    });

    let pb = m.add(ProgressBar::new(1024));
    pb.enable_spinner();
    pb.set_style(sty.clone());
    let _ = thread::spawn(move || {
        for i in 0..1024 {
            pb.set_message(&format!("item #{}", i + 1));
            pb.inc(1);
            thread::sleep(Duration::from_millis(2));
        }
        pb.finish_with_message("done");
    });

    m.join_and_clear().unwrap();
}
<commit_msg>Some changes to the example<commit_after>extern crate indicatif;

use std::thread;
use std::time::Duration;
use std::borrow::Cow;

use indicatif::{ProgressBar, MultiProgress, ProgressStyle, style};

fn main() {
    let mut m = MultiProgress::new();
    let mut sty = ProgressStyle::default();
    sty.tick_chars = "■□▪▫ ".chars().collect();
    sty.bar_template = Cow::Owned(
        format!("  {}   {{msg}}\n {{wide_bar}} {{pos}}/{{len}}  ", style("{spinner}").blue()));
    sty.progress_styles = vec![
        style('█').cyan(),
        style('█').white(),
        style(' ')
    ];

    let pb = m.add(ProgressBar::new(128));
    pb.enable_spinner();
    pb.set_style(sty.clone());
    let _ = thread::spawn(move || {
        for i in 0..128 {
            pb.set_message(&format!("item #{}", i + 1));
            pb.inc(1);
            thread::sleep(Duration::from_millis(15));
        }
        pb.finish_with_message("done");
    });

    let pb = m.add(ProgressBar::new(128));
    pb.enable_spinner();
    pb.set_style(sty.clone());
    let _ = thread::spawn(move || {
        for _ in 0..3 {
            pb.set_position(0);
            for i in 0..128 {
                pb.set_message(&format!("item #{}", i + 1));
                pb.inc(1);
                thread::sleep(Duration::from_millis(8));
            }
        }
        pb.finish_with_message("done");
    });

    let pb = m.add(ProgressBar::new(1024));
    pb.enable_spinner();
    pb.set_style(sty.clone());
    let _ = thread::spawn(move || {
        for i in 0..1024 {
            pb.set_message(&format!("item #{}", i + 1));
            pb.inc(1);
            thread::sleep(Duration::from_millis(2));
        }
        pb.finish_with_message("done");
    });

    m.join_and_clear().unwrap();
}
<|endoftext|>


<commit_before>//! Error types
use std::{result, io, str};
use base64;
use serde_json;
use hyper;

quick_error! {
    #[derive(Debug)]
    pub enum Error {

        Http(err: hyper::error::Error) {
            from()
            cause(err)
            description(err.description())
            display("http error: {}", err)
        }

        Json(err: serde_json::Error) {
            from()
            cause(err)
            description("json error")
            display("json error: {}", err)
        }

        Base64(err: base64::Base64Error) {
            from()
            cause(err)
            description("base64 error")
            display("base64 error: {}", err)
        }

        Io(err: io::Error) {
            from()
            cause(err)
            description("io error")
            display("io error: {}", err)
        }

        Utf8(err: str::Utf8Error) {
            from()
            cause(err)
            description("utf8 error")
            display("utf8 error: {}", err)
        }

        Api(err: ApiError) {
            from()
            description("api error")
            display("api error: {}", err.message)
        }

        InvalidContentType(t: String) {
            description("invalid content type")
            display("invalid content type: '{}'", t)
        }

        MismatchedContentType(expected: &'static str) {
            description("mismatched content type")
            display("content did not match content type: '{}'", expected)
        }

        UnexpectedContentType(expected: &'static str, actual: String) {
            description("unexpected content type")
            display("expected content type '{}', received '{}'", expected, actual)
        }

        MissingDataType {
            description("missing data type")
        }

        InvalidDataType(t: String) {
            description("invalid data type")
            display("invalid data type: '{}'", t)
        }

        UnexpectedDataType(expected: &'static str, actual: String) {
            description("unexpected data type")
            display("expected data type '{}', received '{}'", expected, actual)
        }

        InvalidDataPath(path: String) {
            description("invalid data path")
            display("invalid data path: '{}'", path)
        }

        UnsupportedInput {
            description("unsupported input type")
        }

    }
}

pub type Result<T> = result::Result<T, Error>;

#[derive(Deserialize, Debug)]
pub struct ApiError {
    pub message: String,
    pub stacktrace: Option<String>,
}

/// Struct for decoding Algorithmia API error responses
#[derive(Deserialize, Debug)]
pub struct ApiErrorResponse {
    pub error: ApiError,
}

pub fn decode(json_str: &str) -> Error {
    match serde_json::from_str::<ApiErrorResponse>(json_str) {
        Ok(err_res) => err_res.error.into(),
        Err(err) => Error::Json(err),
    }
}
<commit_msg>better API error Display<commit_after>//! Error types
use std::{result, fmt, io, str};
use std::fmt::Display;
use base64;
use serde_json;
use hyper;

quick_error! {
    #[derive(Debug)]
    pub enum Error {

        Http(err: hyper::error::Error) {
            from()
            cause(err)
            description(err.description())
            display("http error: {}", err)
        }

        Json(err: serde_json::Error) {
            from()
            cause(err)
            description("json error")
            display("json error: {}", err)
        }

        Base64(err: base64::Base64Error) {
            from()
            cause(err)
            description("base64 error")
            display("base64 error: {}", err)
        }

        Io(err: io::Error) {
            from()
            cause(err)
            description("io error")
            display("io error: {}", err)
        }

        Utf8(err: str::Utf8Error) {
            from()
            cause(err)
            description("utf8 error")
            display("utf8 error: {}", err)
        }

        Api(err: ApiError) {
            from()
            description("api error")
            display("api error: {}", err)
        }

        InvalidContentType(t: String) {
            description("invalid content type")
            display("invalid content type: '{}'", t)
        }

        MismatchedContentType(expected: &'static str) {
            description("mismatched content type")
            display("content did not match content type: '{}'", expected)
        }

        UnexpectedContentType(expected: &'static str, actual: String) {
            description("unexpected content type")
            display("expected content type '{}', received '{}'", expected, actual)
        }

        MissingDataType {
            description("missing data type")
        }

        InvalidDataType(t: String) {
            description("invalid data type")
            display("invalid data type: '{}'", t)
        }

        UnexpectedDataType(expected: &'static str, actual: String) {
            description("unexpected data type")
            display("expected data type '{}', received '{}'", expected, actual)
        }

        InvalidDataPath(path: String) {
            description("invalid data path")
            display("invalid data path: '{}'", path)
        }

        UnsupportedInput {
            description("unsupported input type")
        }

    }
}

pub type Result<T> = result::Result<T, Error>;

#[derive(Deserialize, Debug)]
pub struct ApiError {
    pub message: String,
    pub stacktrace: Option<String>,
}

impl Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.stacktrace {
            Some(ref trace) => write!(f, "{}\n{}", self.message, trace),
            None => write!(f, "{}", self.message),
        }
    }
}

/// Struct for decoding Algorithmia API error responses
#[derive(Deserialize, Debug)]
pub struct ApiErrorResponse {
    pub error: ApiError,
}

pub fn decode(json_str: &str) -> Error {
    match serde_json::from_str::<ApiErrorResponse>(json_str) {
        Ok(err_res) => err_res.error.into(),
        Err(err) => Error::Json(err),
    }
}
<|endoftext|>


<commit_before>// Rust JSON-RPC Library
// Written in 2015 by
//     Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

//! # Error handling
//!
//! Some useful methods for creating Error objects
//!

use std::{error, fmt};

use serde_json;

use Response;

/// A library error
#[derive(Debug)]
pub enum Error {
    /// A transport error
    Transport(Box<error::Error>),
    /// Json error
    Json(serde_json::Error),
    /// Error response
    Rpc(RpcError),
    /// Response to a request did not have the expected nonce
    NonceMismatch,
    /// Response to a request had a jsonrpc field other than "2.0"
    VersionMismatch,
    /// Batches can't be empty
    EmptyBatch,
    /// Too many responses returned in batch
    WrongBatchResponseSize,
    /// Batch response contained a duplicate ID
    BatchDuplicateResponseId(serde_json::Value),
    /// Batch response contained an ID that didn't correspond to any request ID
    WrongBatchResponseId(serde_json::Value),
}

impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Error {
        Error::Json(e)
    }
}

impl From<RpcError> for Error {
    fn from(e: RpcError) -> Error {
        Error::Rpc(e)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Transport(ref e) => write!(f, "transport error: {}", e),
            Error::Json(ref e) => write!(f, "JSON decode error: {}", e),
            Error::Rpc(ref r) => write!(f, "RPC error response: {:?}", r),
            Error::BatchDuplicateResponseId(ref v) => {
                write!(f, "duplicate RPC batch response ID: {}", v)
            }
            Error::WrongBatchResponseId(ref v) => write!(f, "wrong RPC batch response ID: {}", v),
            Error::NonceMismatch => write!(f, "Nonce of response did not match nonce of request"),
            Error::VersionMismatch => write!(f, "`jsonrpc` field set to non-\"2.0\""),
            Error::EmptyBatch => write!(f, "batches can't be empty"),
            Error::WrongBatchResponseSize => write!(f, "too many responses returned in batch"),
        }
    }
}

impl error::Error for Error {
    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::Transport(ref e) => Some(&**e),
            Error::Json(ref e) => Some(e),
            _ => None,
        }
    }
}

/// Standard error responses, as described at at
/// http://www.jsonrpc.org/specification#error_object
///
/// # Documentation Copyright
/// Copyright (C) 2007-2010 by the JSON-RPC Working Group
///
/// This document and translations of it may be used to implement JSON-RPC, it
/// may be copied and furnished to others, and derivative works that comment
/// on or otherwise explain it or assist in its implementation may be prepared,
/// copied, published and distributed, in whole or in part, without restriction
/// of any kind, provided that the above copyright notice and this paragraph
/// are included on all such copies and derivative works. However, this document
/// itself may not be modified in any way.
///
/// The limited permissions granted above are perpetual and will not be revoked.
///
/// This document and the information contained herein is provided "AS IS" and
/// ALL WARRANTIES, EXPRESS OR IMPLIED are DISCLAIMED, INCLUDING BUT NOT LIMITED
/// TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY
/// RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
/// PARTICULAR PURPOSE.
///
#[derive(Debug)]
pub enum StandardError {
    /// Invalid JSON was received by the server.
    /// An error occurred on the server while parsing the JSON text.
    ParseError,
    /// The JSON sent is not a valid Request object.
    InvalidRequest,
    /// The method does not exist / is not available.
    MethodNotFound,
    /// Invalid method parameter(s).
    InvalidParams,
    /// Internal JSON-RPC error.
    InternalError,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
/// A JSONRPC error object
pub struct RpcError {
    /// The integer identifier of the error
    pub code: i32,
    /// A string describing the error
    pub message: String,
    /// Additional data specific to the error
    pub data: Option<Box<serde_json::value::RawValue>>,
}

/// Create a standard error responses
pub fn standard_error(code: StandardError, data: Option<Box<serde_json::value::RawValue>>) -> RpcError {
    match code {
        StandardError::ParseError => RpcError {
            code: -32700,
            message: "Parse error".to_string(),
            data: data,
        },
        StandardError::InvalidRequest => RpcError {
            code: -32600,
            message: "Invalid Request".to_string(),
            data: data,
        },
        StandardError::MethodNotFound => RpcError {
            code: -32601,
            message: "Method not found".to_string(),
            data: data,
        },
        StandardError::InvalidParams => RpcError {
            code: -32602,
            message: "Invalid params".to_string(),
            data: data,
        },
        StandardError::InternalError => RpcError {
            code: -32603,
            message: "Internal error".to_string(),
            data: data,
        },
    }
}

/// Converts a Rust `Result` to a JSONRPC response object
pub fn result_to_response(
    result: Result<serde_json::Value, RpcError>,
    id: serde_json::Value,
) -> Response {
    match result {
        Ok(data) => Response {
            result: Some(serde_json::value::RawValue::from_string(
                serde_json::to_string(&data).unwrap()
            ).unwrap()),
            error: None,
            id: id,
            jsonrpc: Some(String::from("2.0")),
        },
        Err(err) => Response {
            result: None,
            error: Some(err),
            id: id,
            jsonrpc: Some(String::from("2.0")),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::StandardError::{
        InternalError, InvalidParams, InvalidRequest, MethodNotFound, ParseError,
    };
    use super::{result_to_response, standard_error};
    use serde_json;

    #[test]
    fn test_parse_error() {
        let resp = result_to_response(Err(standard_error(ParseError, None)), From::from(1));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from(1));
        assert_eq!(resp.error.unwrap().code, -32700);
    }

    #[test]
    fn test_invalid_request() {
        let resp = result_to_response(Err(standard_error(InvalidRequest, None)), From::from(1));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from(1));
        assert_eq!(resp.error.unwrap().code, -32600);
    }

    #[test]
    fn test_method_not_found() {
        let resp = result_to_response(Err(standard_error(MethodNotFound, None)), From::from(1));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from(1));
        assert_eq!(resp.error.unwrap().code, -32601);
    }

    #[test]
    fn test_invalid_params() {
        let resp = result_to_response(Err(standard_error(InvalidParams, None)), From::from("123"));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from("123"));
        assert_eq!(resp.error.unwrap().code, -32602);
    }

    #[test]
    fn test_internal_error() {
        let resp = result_to_response(Err(standard_error(InternalError, None)), From::from(-1));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from(-1));
        assert_eq!(resp.error.unwrap().code, -32603);
    }
}
<commit_msg>Make Error::Transport's Box require Send and Sync<commit_after>// Rust JSON-RPC Library
// Written in 2015 by
//     Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

//! # Error handling
//!
//! Some useful methods for creating Error objects
//!

use std::{error, fmt};

use serde_json;

use Response;

/// A library error
#[derive(Debug)]
pub enum Error {
    /// A transport error
    Transport(Box<dyn error::Error + Send + Sync>),
    /// Json error
    Json(serde_json::Error),
    /// Error response
    Rpc(RpcError),
    /// Response to a request did not have the expected nonce
    NonceMismatch,
    /// Response to a request had a jsonrpc field other than "2.0"
    VersionMismatch,
    /// Batches can't be empty
    EmptyBatch,
    /// Too many responses returned in batch
    WrongBatchResponseSize,
    /// Batch response contained a duplicate ID
    BatchDuplicateResponseId(serde_json::Value),
    /// Batch response contained an ID that didn't correspond to any request ID
    WrongBatchResponseId(serde_json::Value),
}

impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Error {
        Error::Json(e)
    }
}

impl From<RpcError> for Error {
    fn from(e: RpcError) -> Error {
        Error::Rpc(e)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Transport(ref e) => write!(f, "transport error: {}", e),
            Error::Json(ref e) => write!(f, "JSON decode error: {}", e),
            Error::Rpc(ref r) => write!(f, "RPC error response: {:?}", r),
            Error::BatchDuplicateResponseId(ref v) => {
                write!(f, "duplicate RPC batch response ID: {}", v)
            }
            Error::WrongBatchResponseId(ref v) => write!(f, "wrong RPC batch response ID: {}", v),
            Error::NonceMismatch => write!(f, "Nonce of response did not match nonce of request"),
            Error::VersionMismatch => write!(f, "`jsonrpc` field set to non-\"2.0\""),
            Error::EmptyBatch => write!(f, "batches can't be empty"),
            Error::WrongBatchResponseSize => write!(f, "too many responses returned in batch"),
        }
    }
}

impl error::Error for Error {
    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::Transport(ref e) => Some(&**e),
            Error::Json(ref e) => Some(e),
            _ => None,
        }
    }
}

/// Standard error responses, as described at at
/// http://www.jsonrpc.org/specification#error_object
///
/// # Documentation Copyright
/// Copyright (C) 2007-2010 by the JSON-RPC Working Group
///
/// This document and translations of it may be used to implement JSON-RPC, it
/// may be copied and furnished to others, and derivative works that comment
/// on or otherwise explain it or assist in its implementation may be prepared,
/// copied, published and distributed, in whole or in part, without restriction
/// of any kind, provided that the above copyright notice and this paragraph
/// are included on all such copies and derivative works. However, this document
/// itself may not be modified in any way.
///
/// The limited permissions granted above are perpetual and will not be revoked.
///
/// This document and the information contained herein is provided "AS IS" and
/// ALL WARRANTIES, EXPRESS OR IMPLIED are DISCLAIMED, INCLUDING BUT NOT LIMITED
/// TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY
/// RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
/// PARTICULAR PURPOSE.
///
#[derive(Debug)]
pub enum StandardError {
    /// Invalid JSON was received by the server.
    /// An error occurred on the server while parsing the JSON text.
    ParseError,
    /// The JSON sent is not a valid Request object.
    InvalidRequest,
    /// The method does not exist / is not available.
    MethodNotFound,
    /// Invalid method parameter(s).
    InvalidParams,
    /// Internal JSON-RPC error.
    InternalError,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
/// A JSONRPC error object
pub struct RpcError {
    /// The integer identifier of the error
    pub code: i32,
    /// A string describing the error
    pub message: String,
    /// Additional data specific to the error
    pub data: Option<Box<serde_json::value::RawValue>>,
}

/// Create a standard error responses
pub fn standard_error(code: StandardError, data: Option<Box<serde_json::value::RawValue>>) -> RpcError {
    match code {
        StandardError::ParseError => RpcError {
            code: -32700,
            message: "Parse error".to_string(),
            data: data,
        },
        StandardError::InvalidRequest => RpcError {
            code: -32600,
            message: "Invalid Request".to_string(),
            data: data,
        },
        StandardError::MethodNotFound => RpcError {
            code: -32601,
            message: "Method not found".to_string(),
            data: data,
        },
        StandardError::InvalidParams => RpcError {
            code: -32602,
            message: "Invalid params".to_string(),
            data: data,
        },
        StandardError::InternalError => RpcError {
            code: -32603,
            message: "Internal error".to_string(),
            data: data,
        },
    }
}

/// Converts a Rust `Result` to a JSONRPC response object
pub fn result_to_response(
    result: Result<serde_json::Value, RpcError>,
    id: serde_json::Value,
) -> Response {
    match result {
        Ok(data) => Response {
            result: Some(serde_json::value::RawValue::from_string(
                serde_json::to_string(&data).unwrap()
            ).unwrap()),
            error: None,
            id: id,
            jsonrpc: Some(String::from("2.0")),
        },
        Err(err) => Response {
            result: None,
            error: Some(err),
            id: id,
            jsonrpc: Some(String::from("2.0")),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::StandardError::{
        InternalError, InvalidParams, InvalidRequest, MethodNotFound, ParseError,
    };
    use super::{result_to_response, standard_error};
    use serde_json;

    #[test]
    fn test_parse_error() {
        let resp = result_to_response(Err(standard_error(ParseError, None)), From::from(1));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from(1));
        assert_eq!(resp.error.unwrap().code, -32700);
    }

    #[test]
    fn test_invalid_request() {
        let resp = result_to_response(Err(standard_error(InvalidRequest, None)), From::from(1));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from(1));
        assert_eq!(resp.error.unwrap().code, -32600);
    }

    #[test]
    fn test_method_not_found() {
        let resp = result_to_response(Err(standard_error(MethodNotFound, None)), From::from(1));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from(1));
        assert_eq!(resp.error.unwrap().code, -32601);
    }

    #[test]
    fn test_invalid_params() {
        let resp = result_to_response(Err(standard_error(InvalidParams, None)), From::from("123"));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from("123"));
        assert_eq!(resp.error.unwrap().code, -32602);
    }

    #[test]
    fn test_internal_error() {
        let resp = result_to_response(Err(standard_error(InternalError, None)), From::from(-1));
        assert!(resp.result.is_none());
        assert!(resp.error.is_some());
        assert_eq!(resp.id, serde_json::Value::from(-1));
        assert_eq!(resp.error.unwrap().code, -32603);
    }
}
<|endoftext|>


<commit_before>// M_2_1_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * draws an oscillator
 *
 * KEYS
 * a                 : toggle oscillation animation
 * 1/2               : frequency -/+
 * arrow left/right  : phi -/+
 * s                 : save png
 */

fn main() {
    nannou::app(model).update(update).simple_window(view).run();
}

struct Model {
    point_count: u64,
    freq: f32,
    phi: f32,
    angle: f32,
    x: f32,
    y: f32,
    do_draw_animation: bool,
}

fn model(_app: &App) -> Model {
    let point_count = 20;
    let freq = 1.0;
    let phi = 0.0;
    let angle = 0.0;
    let x = 0.0;
    let y = 0.0;
    let do_draw_animation = true;

    Model {
        point_count,
        freq,
        phi,
        angle,
        x,
        y,
        do_draw_animation,
    }
}

fn update(app: &App, model: &mut Model, update: Update) {
    for i in 0..model.point_count {
        model.angle = map_range(i, 0, model.point_count, 0.0, TAU);
        model.y = (model.angle * model.freq + deg_to_rad(model.phi)).sin();
        model.y *= 100.0;
    }

    if model.do_draw_animation {
        model.point_count = app.window_rect().w() as u64 - 250;

        let t = fmod(
            (app.elapsed_frames() as f64 / model.point_count as f64),
            1.0,
        );
        model.angle = map_range(t, 0.0, 1.0, 0.0, TAU);
        model.x = (model.angle * model.freq + deg_to_rad(model.phi));
        model.x *= 100.0 - 125.0;
        model.y = (model.angle * model.freq + deg_to_rad(model.phi));
        model.y = model.y * 100.0;
    } else {
        model.point_count = app.window_rect().w() as u64;
    }
}

fn view(app: &App, model: &Model, frame: &Frame) {
    // Begin drawing
    let draw = app.draw();

    draw.background().color(WHITE);

    // draw oscillator curve
    let vertices = (0..model.point_count)
        // A sine wave mapped to the range of the window.
        .map(|i| pt2(i as f32, model.y))
        .enumerate()
        // Colour each vertex uniquely based on its index.
        .map(|(i, p)| {
            let rgba = nannou::color::Rgba::new(0.0, 0.0, 0.0, 1.0);
            geom::vertex::Rgba(p, rgba)
        });

    // Draw the polyline.
    draw.polyline().vertices(2.0, vertices);

    if model.do_draw_animation {
        // Circle
        draw.ellipse()
            .x_y(-125.0, 0.0)
            .radius(200.0)
            .rgba(0.0, 0.0, 0.0, 0.5);

        // Lines
    }

    // Write the result of our drawing to the window's frame.
    draw.to_frame(app, &frame).unwrap();
}
<commit_msg>fixed compilation errors<commit_after>// M_2_1_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * draws an oscillator
 *
 * KEYS
 * a                 : toggle oscillation animation
 * 1/2               : frequency -/+
 * arrow left/right  : phi -/+
 * s                 : save png
 */
use nannou::prelude::*;

fn main() {
    nannou::app(model).update(update).simple_window(view).run();
}

struct Model {
    point_count: u64,
    freq: f32,
    phi: f32,
    angle: f32,
    x: f32,
    y: f32,
    do_draw_animation: bool,
}

fn model(_app: &App) -> Model {
    let point_count = 20;
    let freq = 1.0;
    let phi = 0.0;
    let angle = 0.0;
    let x = 0.0;
    let y = 0.0;
    let do_draw_animation = true;

    Model {
        point_count,
        freq,
        phi,
        angle,
        x,
        y,
        do_draw_animation,
    }
}

fn update(app: &App, model: &mut Model, update: Update) {
    for i in 0..model.point_count {
        model.angle = map_range(i, 0, model.point_count, 0.0, TAU);
        model.y = (model.angle * model.freq + deg_to_rad(model.phi)).sin();
        model.y *= 100.0;
    }

    if model.do_draw_animation {
        model.point_count = app.window_rect().w() as u64 - 250;

        let t = fmod(
            (app.elapsed_frames() as f64 / model.point_count as f64),
            1.0,
        );
        model.angle = map_range(t, 0.0, 1.0, 0.0, TAU);
        model.x = (model.angle * model.freq + deg_to_rad(model.phi));
        model.x *= 100.0 - 125.0;
        model.y = (model.angle * model.freq + deg_to_rad(model.phi));
        model.y = model.y * 100.0;
    } else {
        model.point_count = app.window_rect().w() as u64;
    }
}

fn view(app: &App, model: &Model, frame: &Frame) {
    // Begin drawing
    let draw = app.draw();

    draw.background().color(WHITE);

    // draw oscillator curve
    let vertices = (0..model.point_count)
        // A sine wave mapped to the range of the window.
        .map(|i| pt2(i as f32, model.y))
        .enumerate()
        // Colour each vertex uniquely based on its index.
        .map(|(i, p)| {
            let rgba = rgba(0.0, 0.0, 0.0, 1.0);
            (p, rgba)
        });

    // Draw the polyline.
    draw.polyline().colored_points(vertices);

    if model.do_draw_animation {
        // Circle
        draw.ellipse()
            .x_y(-125.0, 0.0)
            .radius(200.0)
            .stroke(rgb(0.0, 0.0, 0.0))
            .no_fill();

        // Lines
    }

    // Write the result of our drawing to the window's frame.
    draw.to_frame(app, &frame).unwrap();
}
<|endoftext|>


<commit_before>extern crate euclid;
extern crate image;

#[cfg(feature = "glium_backend")]
extern crate glium;
extern crate vitral;

fn main() { feature::main(); }

#[cfg(feature = "glium_backend")]
mod feature {
    use euclid::{Point2D, Rect, Size2D, point2, vec2};
    use glium::glutin;
    use image;
    use std::path::Path;
    use vitral::{self, Align, ButtonAction, Color, RectUtil};
    use vitral::glium_backend::DefaultVertex;

    type Core = vitral::Core<DefaultVertex>;
    type Backend = vitral::glium_backend::Backend<DefaultVertex>;
    type ImageData = vitral::ImageData;

    pub fn clamp<C: PartialOrd + Copy>(mn: C, mx: C, x: C) -> C {
        if x < mn {
            mn
        } else if x > mx {
            mx
        } else {
            x
        }
    }

    fn load_image(backend: &mut Backend, path: &str) -> ImageData {
        let image: vitral::ImageBuffer = image::open(&Path::new(path)).unwrap().into();
        let size = image.size;
        let texture = backend.make_texture(image);

        vitral::ImageData {
            texture,
            size,
            tex_coords: Rect::new(Point2D::new(0.0, 0.0), Size2D::new(1.0, 1.0)),
        }
    }

    struct App {
        core: Core,
        font: vitral::FontData,
        image: vitral::ImageData,
        fore_color: Color,
        back_color: Color,
        bounds: Rect<f32>,
    }

    impl App {
        pub fn new(core: Core, backend: &mut Backend) -> App {
            let bounds = core.bounds();
            let font = vitral::build_default_font(|img| backend.make_texture(img));
            let image = load_image(backend, "julia.png");
            App {
                core,
                font,
                image,
                fore_color: [1.0, 0.5, 0.1, 1.0],
                back_color: [0.0, 0.0, 0.0, 1.0],
                bounds,
            }
        }

        fn bright_color(&self) -> Color {
            [
                clamp(0.0, 1.0, self.fore_color[0] * 1.5),
                clamp(0.0, 1.0, self.fore_color[1] * 1.5),
                clamp(0.0, 1.0, self.fore_color[2] * 1.5),
                1.0,
            ]
        }

        fn begin(&mut self) { self.core.begin_frame(); }

        fn outline_text(&mut self, pos: Point2D<f32>, text: &str) -> Point2D<f32> {
            for offset in &[
                vec2(-1.0, 0.0),
                vec2(1.0, 0.0),
                vec2(0.0, -1.0),
                vec2(0.0, 1.0),
            ] {
                self.core.draw_text(
                    &self.font,
                    pos + *offset,
                    Align::Left,
                    self.back_color,
                    text,
                );
            }

            self.core
                .draw_text(&self.font, pos, Align::Left, self.fore_color, text)
        }

        fn title_bar(&mut self, bounds: &Rect<f32>, text: &str) {
            self.core.fill_rect(bounds, self.back_color);
            {
                let bounds = bounds.inclusivize();
                self.core.draw_line(
                    1.0,
                    self.fore_color,
                    bounds.bottom_left(),
                    bounds.bottom_right(),
                );
            }

            // Margin
            let bounds = bounds.inflate(-2.0, -2.0);

            self.core.draw_text(
                &self.font,
                bounds.anchor(&point2(0.0, -1.0)),
                Align::Center,
                self.fore_color,
                text,
            );
        }

        fn quit_button(&mut self, bounds: &Rect<f32>) -> bool {
            let click_state = self.core.click_state(bounds);

            let color = if click_state != ButtonAction::Inert {
                self.bright_color()
            } else {
                self.fore_color
            };

            self.core.fill_rect(bounds, color);
            self.core
                .fill_rect(&bounds.inflate(-1.0, -1.0), self.back_color);

            let inner = bounds.inflate(-3.0, -3.0).inclusivize();

            self.core
                .draw_line(1.0, color, inner.bottom_right(), inner.origin);

            self.core
                .draw_line(1.0, color, inner.top_right(), inner.bottom_left());

            self.core.click_state(bounds) == ButtonAction::LeftClicked
        }

        fn render(&mut self) {
            self.core
                .draw_image(&self.image, point2(20.0, 20.0), [1.0, 1.0, 1.0, 1.0]);
            self.outline_text(point2(22.0, 22.0), "Hello, world!");
        }
    }

    pub fn main() {
        let size = Size2D::new(640.0, 360.0);
        let mut backend: Backend = Backend::start(
            size.width as u32,
            size.height as u32,
            "Vitral Demo",
            vitral::glium_backend::DEFAULT_SHADER,
        ).expect("Failed to start Glium backend!");

        let core = vitral::Builder::new().build(size, |img| backend.make_texture(img));
        let mut app = App::new(core, &mut backend);

        loop {
            app.begin();
            app.render();
            let (_, title_area) = app.bounds.horizontal_split(12.0);
            app.title_bar(&title_area, "Vitral Demo");

            let (_, widget_area) = title_area.vertical_split(-12.0);
            if app.quit_button(&widget_area) {
                return;
            }

            while let Some(k) = backend.poll_key() {
                if k.state == glutin::ElementState::Released {
                    continue;
                }

                if k.virtual_keycode == Some(glutin::VirtualKeyCode::Q) {
                    return;
                }

                if k.virtual_keycode == Some(glutin::VirtualKeyCode::F12) {
                    let screenshot: image::ImageBuffer<image::Rgb<u8>, Vec<u8>> =
                        backend.screenshot().into();
                    image::save_buffer(
                        "screenshot.png",
                        &screenshot,
                        screenshot.width(),
                        screenshot.height(),
                        image::ColorType::RGB(8),
                    ).unwrap();
                    println!("Screenshot saved!");
                }
            }

            if !backend.update(&mut app.core) {
                break;
            }
        }
    }
}

#[cfg(not(feature = "glium_backend"))]
mod feature {
    pub fn main() {
        println!("Try running `cargo run --features \"glium_backend\" --example <example_name>");
    }
}
<commit_msg>Use atlas cache and tilesheets in example<commit_after>extern crate euclid;
extern crate image;

#[cfg(feature = "glium_backend")]
extern crate glium;
extern crate vitral;

fn main() { feature::main(); }

#[cfg(feature = "glium_backend")]
mod feature {
    use euclid::{Point2D, Rect, Size2D, point2, vec2};
    use glium::glutin;
    use image;
    use std::path::Path;
    use vitral::{self, Align, ButtonAction, Color, RectUtil};
    use vitral::glium_backend::DefaultVertex;

    type Core = vitral::Core<DefaultVertex>;
    type Backend = vitral::glium_backend::Backend<DefaultVertex>;

    pub fn clamp<C: PartialOrd + Copy>(mn: C, mx: C, x: C) -> C {
        if x < mn {
            mn
        } else if x > mx {
            mx
        } else {
            x
        }
    }

    struct App {
        core: Core,
        atlas_cache: vitral::AtlasCache<String>,
        font: vitral::FontData,
        image: vitral::ImageData,
        fore_color: Color,
        back_color: Color,
        bounds: Rect<f32>,
    }

    impl App {
        pub fn new(core: Core, backend: &mut Backend) -> App {
            fn load_image(path: &str) -> image::DynamicImage {
                image::open(&Path::new(path)).unwrap()
            }

            let bounds = core.bounds();
            let mut atlas_cache = vitral::AtlasCache::new(512, backend.texture_count());

            let font = atlas_cache.add_tilesheet_font(
                "font",
                load_image("tilesheet-font.png"),
                (32u8..128).map(|c| c as char),
            );

            let image = atlas_cache.add_sheet("julia", load_image("julia.png"));
            let image = atlas_cache.get(&image).clone();

            App {
                core,
                atlas_cache,
                font,
                image,
                fore_color: [1.0, 0.5, 0.1, 1.0],
                back_color: [0.0, 0.0, 0.0, 1.0],
                bounds,
            }
        }

        fn bright_color(&self) -> Color {
            [
                clamp(0.0, 1.0, self.fore_color[0] * 1.5),
                clamp(0.0, 1.0, self.fore_color[1] * 1.5),
                clamp(0.0, 1.0, self.fore_color[2] * 1.5),
                1.0,
            ]
        }

        fn begin(&mut self) { self.core.begin_frame(); }

        fn outline_text(&mut self, pos: Point2D<f32>, text: &str) -> Point2D<f32> {
            for offset in &[
                vec2(-1.0, 0.0),
                vec2(1.0, 0.0),
                vec2(0.0, -1.0),
                vec2(0.0, 1.0),
            ] {
                self.core.draw_text(
                    &self.font,
                    pos + *offset,
                    Align::Left,
                    self.back_color,
                    text,
                );
            }

            self.core
                .draw_text(&self.font, pos, Align::Left, self.fore_color, text)
        }

        fn title_bar(&mut self, bounds: &Rect<f32>, text: &str) {
            self.core.fill_rect(bounds, self.back_color);
            {
                let bounds = bounds.inclusivize();
                self.core.draw_line(
                    1.0,
                    self.fore_color,
                    bounds.bottom_left(),
                    bounds.bottom_right(),
                );
            }

            // Margin
            let bounds = bounds.inflate(-2.0, -2.0);

            self.core.draw_text(
                &self.font,
                bounds.anchor(&point2(0.0, -1.0)),
                Align::Center,
                self.fore_color,
                text,
            );
        }

        fn quit_button(&mut self, bounds: &Rect<f32>) -> bool {
            let click_state = self.core.click_state(bounds);

            let color = if click_state != ButtonAction::Inert {
                self.bright_color()
            } else {
                self.fore_color
            };

            self.core.fill_rect(bounds, color);
            self.core
                .fill_rect(&bounds.inflate(-1.0, -1.0), self.back_color);

            let inner = bounds.inflate(-3.0, -3.0).inclusivize();

            self.core
                .draw_line(1.0, color, inner.bottom_right(), inner.origin);

            self.core
                .draw_line(1.0, color, inner.top_right(), inner.bottom_left());

            self.core.click_state(bounds) == ButtonAction::LeftClicked
        }

        fn render(&mut self) {
            self.core
                .draw_image(&self.image, point2(20.0, 20.0), [1.0, 1.0, 1.0, 1.0]);
            self.outline_text(point2(22.0, 22.0), "Hello, world!");
        }
    }

    pub fn main() {
        let size = Size2D::new(640.0, 360.0);
        let mut backend: Backend = Backend::start(
            size.width as u32,
            size.height as u32,
            "Vitral Demo",
            vitral::glium_backend::DEFAULT_SHADER,
        ).expect("Failed to start Glium backend!");

        let core = vitral::Builder::new().build(size, |img| backend.make_texture(img));
        let mut app = App::new(core, &mut backend);

        loop {
            backend.sync_with_atlas_cache(&mut app.atlas_cache);
            app.begin();
            app.render();
            let (_, title_area) = app.bounds.horizontal_split(12.0);
            app.title_bar(&title_area, "Vitral Demo");

            let (_, widget_area) = title_area.vertical_split(-12.0);
            if app.quit_button(&widget_area) {
                return;
            }

            while let Some(k) = backend.poll_key() {
                if k.state == glutin::ElementState::Released {
                    continue;
                }

                if k.virtual_keycode == Some(glutin::VirtualKeyCode::Q) {
                    return;
                }

                if k.virtual_keycode == Some(glutin::VirtualKeyCode::F12) {
                    let screenshot: image::ImageBuffer<image::Rgb<u8>, Vec<u8>> =
                        backend.screenshot().into();
                    image::save_buffer(
                        "screenshot.png",
                        &screenshot,
                        screenshot.width(),
                        screenshot.height(),
                        image::ColorType::RGB(8),
                    ).unwrap();
                    println!("Screenshot saved!");
                }
            }

            if !backend.update(&mut app.core) {
                break;
            }
        }
    }
}

#[cfg(not(feature = "glium_backend"))]
mod feature {
    pub fn main() {
        println!("Try running `cargo run --features \"glium_backend\" --example <example_name>");
    }
}
<|endoftext|>


<commit_before>use std::{io, path};
use std::rand;
use std::rand::Rng;

fn end(level: uint, state: ~[~str], word:~str){
	println("");
	println("|H| ||  /|A\\  |N|\\ ||   /|G\\\\");
	println("|H|H|| /A|_\\\\ |N| \\||  |G|  __ ");
	println("|H| || |A| || |N|  ||   \\|G/|  man ");
	let mut myfile: ~str = level.to_str();
	myfile = myfile + ".txt";

	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(myfile));

	if read.is_ok() {
	let file = read.unwrap();
	let text: ~[~str] = file.read_lines();
        for i in range(0, text.len()) {
		println(text[i]);

        }
	}
	println("");
	println("");

	print("   ");
	for j in range(0, state.len()){
		print(state[j]);
		print(" ");
	}
	println("");
	println("");
	println(fmt!("   The word was: %s",word.to_str()));
	println("   PLAY AGAIN? ");
}

fn draw(level: uint, state: ~[~str], past_guess: ~[~str]){
	println("");
	println("|H| ||  /|A\\  |N|\\ ||   /|G\\\\");
	println("|H|H|| /A|_\\\\ |N| \\||  |G|  __ ");
	println("|H| || |A| || |N|  ||   \\|G/|  man ");
	let mut myfile: ~str = level.to_str();
	myfile = myfile + ".txt";

	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(myfile));

	if read.is_ok() {
	let file = read.unwrap();
	let text: ~[~str] = file.read_lines();
        for i in range(0, text.len()) {
		println(text[i]);

        }
	}
	println("");
	println("");

	print("   ");
	for j in range(0, state.len()){
		print(state[j]);
		print(" ");
	}
	println("");
	println("");

	print("   Past Guesses: ");
	for j in range(0, past_guess.len()){
		print(past_guess[j]);
                print(" ");
	}
	println("");
	println("");
	print("   Enter Next Guess: ");
}

fn load(filename: ~str) -> ~[~str] {
	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(filename));

	if read.is_ok() {
	let file = read.unwrap();
	return file.read_lines();
	}

	println(fmt!("Error in reading the file: %?", read.unwrap_err()));
	return ~[];
}

fn isDuplicate(guess: char, guesses: ~[~str]) -> bool{

	for i in range(0,guesses.len()) {
		if (guess.to_str() == guesses[i]){
			return true;
		}
	}
	return false;

}

//fn searchChar(guess: char) -> bool{

//}

fn main() {
	let mut valid_level: bool = false;
	let mut dif: ~str = ~"";
	let mut max_guess : uint = 0;
	println("   Welcome to Hangman ");
        println("   Enter number to select game level: ");
	println("   (1) Normal");
	println("   (2) Expert");
	let mut level : ~str = ~"";
	while(!valid_level){
	  level = io::stdin().read_line();
	  if(level.len() > 0){
			if(level.char_at(0) == '1'){
				dif = ~"n_words.txt";
				max_guess = 9;
				valid_level = true;
			}else if(level.char_at(0)=='2'){
				dif = ~"x_words.txt";
				max_guess = 7;
				valid_level = true;
			}

             }

	}
        let mut rng = rand::task_rng();
	let dictionary: ~[~str] = load(dif);
	let max_size: uint = dictionary.len();
        let n: uint = rng.gen_integer_range(0u, max_size);
	let word: ~str = dictionary[n];
	let word_len: uint = word.char_len();

	//Stores the guessed word
	let mut i = 0;
	let mut stateWord: ~[~str] = ~[];
	while (i < word_len) {
        	stateWord = stateWord + ~[~"_"];
		i += 1;
        }

        //println(fmt!("%s Guessed Word: ", stateWord.to_str()));
	//println(word);

	let mut guesses: ~[~str] = ~[];

	let mut j = 0;

	let mut has_won: bool = false;
	while (j < max_guess  && !has_won){
		let mut is_valid: bool = false;
		has_won = true;
		for i in range(0,stateWord.len()) {
			if(stateWord[i]== ~"_"){
				has_won = false;
			}
		}
		if(has_won){
			end(11, stateWord.clone(), word.clone());
			break;
		}
		draw(j+1, stateWord.clone(), guesses.clone());
		let mut line : ~str = ~"";
		while(!is_valid){
		  line = io::stdin().read_line();
		  if(line.len() > 0){
			if(line.char_at(0).is_alphabetic()){
				is_valid = true;
			}
             }

		}
		let guess_char: char = line.char_at(0);
		//println(fmt!("%? guessed: ", guess_char));
		let has_char: bool = word.contains_char(guess_char);

		if(isDuplicate(guess_char, guesses.clone())){
			//println(fmt!("%? Pick another letter! You have already guess ", guess_char.to_str()));
		}else if (has_char){
			guesses.push(guess_char.to_str());
       			let mut i = 0;
			while (i < word_len) {
				if(word.char_at(i) != guess_char){
        	 			//print("_ ");
                		}else{
		 			stateWord[i] = guess_char.to_str();
				}
				i += 1;
       			 }
			//println("");
		}
		else{
			guesses.push(guess_char.to_str());
			//println("nope.");
			j += 1;
		}

	}
	if(j >= max_guess) {end(17, stateWord.clone(), word.clone());}
}
<commit_msg>added lives<commit_after>use std::{io, path};
use std::rand;
use std::rand::Rng;

fn end(level: uint, state: ~[~str], word:~str){
	println("");
	println("|H| ||  /|A\\  |N|\\ ||   /|G\\\\");
	println("|H|H|| /A|_\\\\ |N| \\||  |G|  __ ");
	println("|H| || |A| || |N|  ||   \\|G/|  man ");
	let mut myfile: ~str = level.to_str();
	myfile = myfile + ".txt";

	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(myfile));

	if read.is_ok() {
	let file = read.unwrap();
	let text: ~[~str] = file.read_lines();
        for i in range(0, text.len()) {
		println(text[i]);
        }
	}
	println("");
	println("");

	print("   ");
	for j in range(0, state.len()){
		print(state[j]);
		print(" ");
	}
	println("");
	println("");
	println(fmt!("   The word was: %s",word.to_str()));
	println("   PLAY AGAIN? ");
}

fn draw(level: uint, state: ~[~str], past_guess: ~[~str], lives: uint){
	println("");
	println("|H| ||  /|A\\  |N|\\ ||   /|G\\\\");
	println("|H|H|| /A|_\\\\ |N| \\||  |G|  __ ");
	println("|H| || |A| || |N|  ||   \\|G/|  man ");
	let mut myfile: ~str = level.to_str();
	myfile = myfile + ".txt";

	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(myfile));

	if read.is_ok() {
	let file = read.unwrap();
	let text: ~[~str] = file.read_lines();
        for i in range(0, text.len()) {
		println(text[i]);

        }
	}
	println("");
	println("");

	print("   ");
	for j in range(0, state.len()){
		print(state[j]);
		print(" ");
	}
	println("");
	println("");

	print("   Past Guesses: ");
	for j in range(0, past_guess.len()){
		print(past_guess[j]);
                print(" ");
	}
	println(fmt!("   Lives Remaining: %s", lives.to_str()));
	println("");
	print("   Enter Next Guess: ");
}

fn load(filename: ~str) -> ~[~str] {
	let read: Result<@Reader, ~str>;
	read = io::file_reader(~path::Path(filename));

	if read.is_ok() {
	let file = read.unwrap();
	return file.read_lines();
	}

	println(fmt!("Error in reading the file: %?", read.unwrap_err()));
	return ~[];
}

fn isDuplicate(guess: char, guesses: ~[~str]) -> bool{

	for i in range(0,guesses.len()) {
		if (guess.to_str() == guesses[i]){
			return true;
		}
	}
	return false;

}

//fn searchChar(guess: char) -> bool{

//}

fn main() {
	let mut valid_level: bool = false;
	let mut dif: ~str = ~"";
	let mut max_guess : uint = 0;
	println("   Welcome to Hangman ");
        println("   Enter number to select game level: ");
	println("   (1) Normal");
	println("   (2) Expert");
	let mut level : ~str = ~"";
	while(!valid_level){
	  level = io::stdin().read_line();
	  if(level.len() > 0){
			if(level.char_at(0) == '1'){
				dif = ~"n_words.txt";
				max_guess = 9;
				valid_level = true;
			}else if(level.char_at(0)=='2'){
				dif = ~"x_words.txt";
				max_guess = 7;
				valid_level = true;
			}

             }

	}
        let mut rng = rand::task_rng();
	let dictionary: ~[~str] = load(dif);
	let max_size: uint = dictionary.len();
        let n: uint = rng.gen_integer_range(0u, max_size);
	let word: ~str = dictionary[n];
	let word_len: uint = word.char_len();

	//Stores the guessed word
	let mut i = 0;
	let mut stateWord: ~[~str] = ~[];
	while (i < word_len) {
        	stateWord = stateWord + ~[~"_"];
		i += 1;
        }

        //println(fmt!("%s Guessed Word: ", stateWord.to_str()));
	//println(word);

	let mut guesses: ~[~str] = ~[];

	let mut j = 0;

	let mut has_won: bool = false;
	while (j < max_guess  && !has_won){
		let mut is_valid: bool = false;
		has_won = true;
		for i in range(0,stateWord.len()) {
			if(stateWord[i]== ~"_"){
				has_won = false;
			}
		}
		if(has_won){
			end(11, stateWord.clone(), word.clone());
			break;
		}
		let lives: uint = max_guess - j;
		draw(j+1, stateWord.clone(), guesses.clone(), lives);
		let mut line : ~str = ~"";
		while(!is_valid){
		  line = io::stdin().read_line();
		  if(line.len() > 0){
			if(line.char_at(0).is_alphabetic()){
				is_valid = true;
			}
             }

		}
		let guess_char: char = line.char_at(0);
		//println(fmt!("%? guessed: ", guess_char));
		let has_char: bool = word.contains_char(guess_char);

		if(isDuplicate(guess_char, guesses.clone())){
			//println(fmt!("%? Pick another letter! You have already guess ", guess_char.to_str()));
		}else if (has_char){
			guesses.push(guess_char.to_str());
       			let mut i = 0;
			while (i < word_len) {
				if(word.char_at(i) != guess_char){
        	 			//print("_ ");
                		}else{
		 			stateWord[i] = guess_char.to_str();
				}
				i += 1;
       			 }
			//println("");
		}
		else{
			guesses.push(guess_char.to_str());
			//println("nope.");
			j += 1;
		}

	}
	if(j >= max_guess) {end(17, stateWord.clone(), word.clone());}
}
<|endoftext|>


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

use selectors::gecko_like_types as dummies;
use servo_arc::Arc;
use std::mem::{size_of, align_of};
use style;
use style::applicable_declarations::ApplicableDeclarationBlock;
use style::data::{ComputedStyle, ElementData, ElementStyles};
use style::gecko::selector_parser as real;
use style::properties::ComputedValues;
use style::rule_tree::StrongRuleNode;

#[test]
fn size_of_selectors_dummy_types() {
    assert_eq!(size_of::<dummies::PseudoClass>(), size_of::<real::NonTSPseudoClass>());
    assert_eq!(align_of::<dummies::PseudoClass>(), align_of::<real::NonTSPseudoClass>());

    assert_eq!(size_of::<dummies::PseudoElement>(), size_of::<real::PseudoElement>());
    assert_eq!(align_of::<dummies::PseudoElement>(), align_of::<real::PseudoElement>());

    assert_eq!(size_of::<dummies::Atom>(), size_of::<style::Atom>());
    assert_eq!(align_of::<dummies::Atom>(), align_of::<style::Atom>());
}

// The size of this is critical to performance on the bloom-basic microbenchmark.
// When iterating over a large Rule array, we want to be able to fast-reject
// selectors (with the inline hashes) with as few cache misses as possible.
size_of_test!(test_size_of_rule, style::stylist::Rule, 32);

size_of_test!(test_size_of_option_arc_cv, Option<Arc<ComputedValues>>, 8);
size_of_test!(test_size_of_option_rule_node, Option<StrongRuleNode>, 8);
size_of_test!(test_size_of_computed_style, ComputedStyle, 32);
size_of_test!(test_size_of_element_styles, ElementStyles, 48);
size_of_test!(test_size_of_element_data, ElementData, 56);

size_of_test!(test_size_of_property_declaration, style::properties::PropertyDeclaration, 32);

size_of_test!(test_size_of_application_declaration_block, ApplicableDeclarationBlock, 24);

// This is huge, but we allocate it on the stack and then never move it,
// we only pass `&mut SourcePropertyDeclaration` references around.
size_of_test!(test_size_of_parsed_declaration, style::properties::SourcePropertyDeclaration, 704);

#[test]
fn size_of_specified_values() {
    ::style::properties::test_size_of_specified_values();
}
<commit_msg>Add a size_of test for RuleNode.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use selectors::gecko_like_types as dummies;
use servo_arc::Arc;
use std::mem::{size_of, align_of};
use style;
use style::applicable_declarations::ApplicableDeclarationBlock;
use style::data::{ComputedStyle, ElementData, ElementStyles};
use style::gecko::selector_parser as real;
use style::properties::ComputedValues;
use style::rule_tree::{RuleNode, StrongRuleNode};

#[test]
fn size_of_selectors_dummy_types() {
    assert_eq!(size_of::<dummies::PseudoClass>(), size_of::<real::NonTSPseudoClass>());
    assert_eq!(align_of::<dummies::PseudoClass>(), align_of::<real::NonTSPseudoClass>());

    assert_eq!(size_of::<dummies::PseudoElement>(), size_of::<real::PseudoElement>());
    assert_eq!(align_of::<dummies::PseudoElement>(), align_of::<real::PseudoElement>());

    assert_eq!(size_of::<dummies::Atom>(), size_of::<style::Atom>());
    assert_eq!(align_of::<dummies::Atom>(), align_of::<style::Atom>());
}

// The size of this is critical to performance on the bloom-basic microbenchmark.
// When iterating over a large Rule array, we want to be able to fast-reject
// selectors (with the inline hashes) with as few cache misses as possible.
size_of_test!(test_size_of_rule, style::stylist::Rule, 32);

size_of_test!(test_size_of_option_arc_cv, Option<Arc<ComputedValues>>, 8);
size_of_test!(test_size_of_option_rule_node, Option<StrongRuleNode>, 8);
size_of_test!(test_size_of_computed_style, ComputedStyle, 32);
size_of_test!(test_size_of_element_styles, ElementStyles, 48);
size_of_test!(test_size_of_element_data, ElementData, 56);

size_of_test!(test_size_of_property_declaration, style::properties::PropertyDeclaration, 32);

size_of_test!(test_size_of_application_declaration_block, ApplicableDeclarationBlock, 24);

// FIXME(bholley): This can shrink with a little bit of work.
// See https://github.com/servo/servo/issues/17280
size_of_test!(test_size_of_rule_node, RuleNode, 96);

// This is huge, but we allocate it on the stack and then never move it,
// we only pass `&mut SourcePropertyDeclaration` references around.
size_of_test!(test_size_of_parsed_declaration, style::properties::SourcePropertyDeclaration, 704);

#[test]
fn size_of_specified_values() {
    ::style::properties::test_size_of_specified_values();
}
<|endoftext|>


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

use crate::{DecodeError, Decoded, FieldInfo};
use std::fmt::{self, Debug, Display, Formatter};

pub fn decode_iss_instruction_abort(iss: u64) -> Result<Decoded, DecodeError> {
    let res0a = FieldInfo::get(iss, "RES0", 13, 25).check_res0()?;
    let fnv = FieldInfo::get_bit(iss, "FnV", 10).describe_bit(describe_fnv);
    let ea = FieldInfo::get_bit(iss, "EA", 9);
    let res0b = FieldInfo::get_bit(iss, "RES0", 8).check_res0()?;
    let s1ptw = FieldInfo::get_bit(iss, "S1PTW", 7);
    let res0c = FieldInfo::get_bit(iss, "RES0", 6).check_res0()?;
    let ifsc = FieldInfo::get(iss, "IFSC", 0, 6).describe(describe_fsc)?;

    let set = if ifsc.value == 0b010000 {
        FieldInfo::get(iss, "SET", 11, 13).describe(describe_set)?
    } else {
        FieldInfo::get(iss, "RES0", 11, 13)
    };

    Ok(Decoded {
        description: None,
        fields: vec![res0a, set, fnv, ea, res0b, s1ptw, res0c, ifsc],
    })
}

pub fn decode_iss_data_abort(iss: u64) -> Result<Decoded, DecodeError> {
    let isv = FieldInfo::get_bit(iss, "ISV", 24).describe_bit(describe_isv);

    let intruction_syndrome_fields = if isv.as_bit() {
        // These fields are part of the instruction syndrome, and are only valid if ISV is true.
        let sas = FieldInfo::get(iss, "SAS", 22, 24);
        let sas_value = match sas.value {
            0b00 => SyndromeAccessSize::Byte,
            0b01 => SyndromeAccessSize::Halfword,
            0b10 => SyndromeAccessSize::Word,
            0b11 => SyndromeAccessSize::Doubleword,
            _ => unreachable!(),
        };
        let sas = sas.with_decoded(Decoded {
            description: Some(sas_value.to_string()),
            fields: vec![],
        });
        let sse = FieldInfo::get_bit(iss, "SSE", 21);
        let srt = FieldInfo::get(iss, "SRT", 16, 21);
        let sf = FieldInfo::get_bit(iss, "SF", 15).describe_bit(describe_sf);
        let ar = FieldInfo::get_bit(iss, "AR", 14).describe_bit(describe_ar);
        vec![sas, sse, srt, sf, ar]
    } else {
        let res0 = FieldInfo::get(iss, "RES0", 14, 24);
        if res0.value != 0 {
            return Err(DecodeError::UnexpectedInstructionSyndrome { is: res0.value });
        }
        vec![res0]
    };

    let vncr = FieldInfo::get_bit(iss, "VNCR", 13);
    let fnv = FieldInfo::get_bit(iss, "FnV", 10).describe_bit(describe_fnv);
    let ea = FieldInfo::get_bit(iss, "EA", 9);
    let cm = FieldInfo::get_bit(iss, "CM", 8);
    let s1ptw = FieldInfo::get_bit(iss, "S1PTW", 7);
    let wnr = FieldInfo::get_bit(iss, "WnR", 6).describe_bit(describe_wnr);
    let dfsc = FieldInfo::get(iss, "DFSC", 0, 6).describe(describe_fsc)?;

    let mut fields = vec![isv];
    fields.extend(intruction_syndrome_fields);
    fields.extend(vec![vncr, fnv, ea, cm, s1ptw, wnr, dfsc]);
    Ok(Decoded {
        description: None,
        fields,
    })
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum SyndromeAccessSize {
    Byte = 0b00,
    Halfword = 0b01,
    Word = 0b10,
    Doubleword = 0b11,
}

impl Display for SyndromeAccessSize {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let s = match self {
            Self::Byte => "byte",
            Self::Halfword => "halfword",
            Self::Word => "word",
            Self::Doubleword => "doubleword",
        };
        write!(f, "{}", s)
    }
}

fn describe_isv(isv: bool) -> &'static str {
    if isv {
        "Valid instruction syndrome"
    } else {
        "No valid instruction syndrome"
    }
}

fn describe_sf(sf: bool) -> &'static str {
    if sf {
        "64-bit wide register"
    } else {
        "32-bit wide register"
    }
}

fn describe_ar(ar: bool) -> &'static str {
    if ar {
        "Acquire/release semantics"
    } else {
        "No acquire/release semantics"
    }
}

fn describe_fnv(fnv: bool) -> &'static str {
    if fnv {
        "FAR is not valid, it holds an unknown value"
    } else {
        "FAR is valid"
    }
}

fn describe_wnr(wnr: bool) -> &'static str {
    if wnr {
        "Abort caused by writing to memory"
    } else {
        "Abort caused by reading from memory"
    }
}

fn describe_fsc(fsc: u64) -> Result<&'static str, DecodeError> {
    let description = match fsc {
        0b000000 => "Address size fault, level 0 of translation or translation table base register.",
        0b000001 => "Address size fault, level 1.",
        0b000010 => "Address size fault, level 2.",
        0b000011 => "Address size fault, level 3.",
        0b000100 => "Translation fault, level 0.",
        0b000101 => "Translation fault, level 1.",
        0b000110 => "Translation fault, level 2.",
        0b000111 => "Translation fault, level 3.",
        0b001001 => "Access flag fault, level 1.",
        0b001010 => "Access flag fault, level 2.",
        0b001011 => "Access flag fault, level 3.",
        0b001000 => "Access flag fault, level 0.",
        0b001100 => "Permission fault, level 0.",
        0b001101 => "Permission fault, level 1.",
        0b001110 => "Permission fault, level 2.",
        0b001111 => "Permission fault, level 3.",
        0b010000 => "Synchronous External abort, not on translation table walk or hardware update of translation table.",
        0b010001 => "Synchronous Tag Check Fault.",
        0b010011 => "Synchronous External abort on translation table walk or hardware update of translation table, level -1.",
        0b010100 => "Synchronous External abort on translation table walk or hardware update of translation table, level 0.",
        0b010101 => "Synchronous External abort on translation table walk or hardware update of translation table, level 1.",
        0b010110 => "Synchronous External abort on translation table walk or hardware update of translation table, level 2.",
        0b010111 => "Synchronous External abort on translation table walk or hardware update of translation table, level 3.",
        0b011000 => "Synchronous parity or ECC error on memory access, not on translation table walk.",
        0b011011 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level -1.",
        0b011100 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 0.",
        0b011101 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 1.",
        0b011110 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 2.",
        0b011111 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 3.",
        0b100001 => "Alignment fault.",
        0b101001 => "Address size fault, level -1.",
        0b101011 => "Translation fault, level -1.",
        0b110000 => "TLB conflict abort.",
        0b110001 => "Unsupported atomic hardware update fault.",
        0b110100 => "IMPLEMENTATION DEFINED fault (Lockdown).",
        0b110101 => "IMPLEMENTATION DEFINED fault (Unsupported Exclusive or Atomic access).",
        _ => return Err(DecodeError::InvalidFsc { fsc }),
    };
    Ok(description)
}

fn describe_set(set: u64) -> Result<&'static str, DecodeError> {
    Ok(match set {
        0b00 => "Recoverable state (UER)",
        0b10 => "Uncontainable (UC)",
        0b11 => "Restartable state (UEO)",
        _ => return Err(DecodeError::InvalidSet { set }),
    })
}
<commit_msg>Decode SET for data abort.<commit_after>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{DecodeError, Decoded, FieldInfo};
use std::fmt::{self, Debug, Display, Formatter};

pub fn decode_iss_instruction_abort(iss: u64) -> Result<Decoded, DecodeError> {
    let res0a = FieldInfo::get(iss, "RES0", 13, 25).check_res0()?;
    let fnv = FieldInfo::get_bit(iss, "FnV", 10).describe_bit(describe_fnv);
    let ea = FieldInfo::get_bit(iss, "EA", 9);
    let res0b = FieldInfo::get_bit(iss, "RES0", 8).check_res0()?;
    let s1ptw = FieldInfo::get_bit(iss, "S1PTW", 7);
    let res0c = FieldInfo::get_bit(iss, "RES0", 6).check_res0()?;
    let ifsc = FieldInfo::get(iss, "IFSC", 0, 6).describe(describe_fsc)?;

    let set = if ifsc.value == 0b010000 {
        FieldInfo::get(iss, "SET", 11, 13).describe(describe_set)?
    } else {
        FieldInfo::get(iss, "RES0", 11, 13)
    };

    Ok(Decoded {
        description: None,
        fields: vec![res0a, set, fnv, ea, res0b, s1ptw, res0c, ifsc],
    })
}

pub fn decode_iss_data_abort(iss: u64) -> Result<Decoded, DecodeError> {
    let isv = FieldInfo::get_bit(iss, "ISV", 24).describe_bit(describe_isv);

    let intruction_syndrome_fields = if isv.as_bit() {
        // These fields are part of the instruction syndrome, and are only valid if ISV is true.
        let sas = FieldInfo::get(iss, "SAS", 22, 24);
        let sas_value = match sas.value {
            0b00 => SyndromeAccessSize::Byte,
            0b01 => SyndromeAccessSize::Halfword,
            0b10 => SyndromeAccessSize::Word,
            0b11 => SyndromeAccessSize::Doubleword,
            _ => unreachable!(),
        };
        let sas = sas.with_decoded(Decoded {
            description: Some(sas_value.to_string()),
            fields: vec![],
        });
        let sse = FieldInfo::get_bit(iss, "SSE", 21);
        let srt = FieldInfo::get(iss, "SRT", 16, 21);
        let sf = FieldInfo::get_bit(iss, "SF", 15).describe_bit(describe_sf);
        let ar = FieldInfo::get_bit(iss, "AR", 14).describe_bit(describe_ar);
        vec![sas, sse, srt, sf, ar]
    } else {
        let res0 = FieldInfo::get(iss, "RES0", 14, 24);
        if res0.value != 0 {
            return Err(DecodeError::UnexpectedInstructionSyndrome { is: res0.value });
        }
        vec![res0]
    };

    let vncr = FieldInfo::get_bit(iss, "VNCR", 13);
    let fnv = FieldInfo::get_bit(iss, "FnV", 10).describe_bit(describe_fnv);
    let ea = FieldInfo::get_bit(iss, "EA", 9);
    let cm = FieldInfo::get_bit(iss, "CM", 8);
    let s1ptw = FieldInfo::get_bit(iss, "S1PTW", 7);
    let wnr = FieldInfo::get_bit(iss, "WnR", 6).describe_bit(describe_wnr);
    let dfsc = FieldInfo::get(iss, "DFSC", 0, 6).describe(describe_fsc)?;
    let set = if dfsc.value == 0b010000 {
        FieldInfo::get(iss, "SET", 11, 13).describe(describe_set)?
    } else {
        FieldInfo::get(iss, "RES0", 11, 13)
    };

    let mut fields = vec![isv];
    fields.extend(intruction_syndrome_fields);
    fields.extend(vec![vncr, set, fnv, ea, cm, s1ptw, wnr, dfsc]);
    Ok(Decoded {
        description: None,
        fields,
    })
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum SyndromeAccessSize {
    Byte = 0b00,
    Halfword = 0b01,
    Word = 0b10,
    Doubleword = 0b11,
}

impl Display for SyndromeAccessSize {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let s = match self {
            Self::Byte => "byte",
            Self::Halfword => "halfword",
            Self::Word => "word",
            Self::Doubleword => "doubleword",
        };
        write!(f, "{}", s)
    }
}

fn describe_isv(isv: bool) -> &'static str {
    if isv {
        "Valid instruction syndrome"
    } else {
        "No valid instruction syndrome"
    }
}

fn describe_sf(sf: bool) -> &'static str {
    if sf {
        "64-bit wide register"
    } else {
        "32-bit wide register"
    }
}

fn describe_ar(ar: bool) -> &'static str {
    if ar {
        "Acquire/release semantics"
    } else {
        "No acquire/release semantics"
    }
}

fn describe_fnv(fnv: bool) -> &'static str {
    if fnv {
        "FAR is not valid, it holds an unknown value"
    } else {
        "FAR is valid"
    }
}

fn describe_wnr(wnr: bool) -> &'static str {
    if wnr {
        "Abort caused by writing to memory"
    } else {
        "Abort caused by reading from memory"
    }
}

fn describe_fsc(fsc: u64) -> Result<&'static str, DecodeError> {
    let description = match fsc {
        0b000000 => "Address size fault, level 0 of translation or translation table base register.",
        0b000001 => "Address size fault, level 1.",
        0b000010 => "Address size fault, level 2.",
        0b000011 => "Address size fault, level 3.",
        0b000100 => "Translation fault, level 0.",
        0b000101 => "Translation fault, level 1.",
        0b000110 => "Translation fault, level 2.",
        0b000111 => "Translation fault, level 3.",
        0b001001 => "Access flag fault, level 1.",
        0b001010 => "Access flag fault, level 2.",
        0b001011 => "Access flag fault, level 3.",
        0b001000 => "Access flag fault, level 0.",
        0b001100 => "Permission fault, level 0.",
        0b001101 => "Permission fault, level 1.",
        0b001110 => "Permission fault, level 2.",
        0b001111 => "Permission fault, level 3.",
        0b010000 => "Synchronous External abort, not on translation table walk or hardware update of translation table.",
        0b010001 => "Synchronous Tag Check Fault.",
        0b010011 => "Synchronous External abort on translation table walk or hardware update of translation table, level -1.",
        0b010100 => "Synchronous External abort on translation table walk or hardware update of translation table, level 0.",
        0b010101 => "Synchronous External abort on translation table walk or hardware update of translation table, level 1.",
        0b010110 => "Synchronous External abort on translation table walk or hardware update of translation table, level 2.",
        0b010111 => "Synchronous External abort on translation table walk or hardware update of translation table, level 3.",
        0b011000 => "Synchronous parity or ECC error on memory access, not on translation table walk.",
        0b011011 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level -1.",
        0b011100 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 0.",
        0b011101 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 1.",
        0b011110 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 2.",
        0b011111 => "Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 3.",
        0b100001 => "Alignment fault.",
        0b101001 => "Address size fault, level -1.",
        0b101011 => "Translation fault, level -1.",
        0b110000 => "TLB conflict abort.",
        0b110001 => "Unsupported atomic hardware update fault.",
        0b110100 => "IMPLEMENTATION DEFINED fault (Lockdown).",
        0b110101 => "IMPLEMENTATION DEFINED fault (Unsupported Exclusive or Atomic access).",
        _ => return Err(DecodeError::InvalidFsc { fsc }),
    };
    Ok(description)
}

fn describe_set(set: u64) -> Result<&'static str, DecodeError> {
    Ok(match set {
        0b00 => "Recoverable state (UER)",
        0b10 => "Uncontainable (UC)",
        0b11 => "Restartable state (UEO)",
        _ => return Err(DecodeError::InvalidSet { set }),
    })
}
<|endoftext|>


<commit_before>use crate::slot_height::SlotHeight;
/// The `Slot` and `Epoch` types are defined as newtypes over u64 to enforce type-safety between
/// the two types.
///
/// `Slot` and `Epoch` have implementations which permit conversion, comparison and math operations
/// between each and `u64`, however specifically not between each other.
///
/// All math operations on `Slot` and `Epoch` are saturating, they never wrap.
///
/// It would be easy to define `PartialOrd` and other traits generically across all types which
/// implement `Into<u64>`, however this would allow operations between `Slots` and `Epochs` which
/// may lead to programming errors which are not detected by the compiler.
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::Serialize;
use slog;
use ssz::{hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash};
use std::cmp::{Ord, Ordering};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::Iterator;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, Sub, SubAssign};

#[derive(Eq, Debug, Clone, Copy, Default, Serialize)]
pub struct Slot(u64);

#[derive(Eq, Debug, Clone, Copy, Default, Serialize)]
pub struct Epoch(u64);

impl_common!(Slot);
impl_common!(Epoch);

impl Slot {
    pub fn new(slot: u64) -> Slot {
        Slot(slot)
    }

    pub fn epoch(self, epoch_length: u64) -> Epoch {
        Epoch::from(self.0 / epoch_length)
    }

    pub fn height(self, genesis_slot: Slot) -> SlotHeight {
        SlotHeight::from(self.0.saturating_sub(genesis_slot.as_u64()))
    }

    pub fn max_value() -> Slot {
        Slot(u64::max_value())
    }
}

impl Epoch {
    pub fn new(slot: u64) -> Epoch {
        Epoch(slot)
    }

    pub fn max_value() -> Epoch {
        Epoch(u64::max_value())
    }

    pub fn start_slot(self, epoch_length: u64) -> Slot {
        Slot::from(self.0.saturating_mul(epoch_length))
    }

    pub fn end_slot(self, epoch_length: u64) -> Slot {
        Slot::from(
            self.0
                .saturating_add(1)
                .saturating_mul(epoch_length)
                .saturating_sub(1),
        )
    }

    pub fn slot_iter(&self, epoch_length: u64) -> SlotIter {
        SlotIter {
            current: self.start_slot(epoch_length),
            epoch: self,
            epoch_length,
        }
    }
}

pub struct SlotIter<'a> {
    current: Slot,
    epoch: &'a Epoch,
    epoch_length: u64,
}

impl<'a> Iterator for SlotIter<'a> {
    type Item = Slot;

    fn next(&mut self) -> Option<Slot> {
        if self.current == self.epoch.end_slot(self.epoch_length) {
            None
        } else {
            let previous = self.current;
            self.current += 1;
            Some(previous)
        }
    }
}

#[cfg(test)]
mod slot_tests {
    use super::*;
    use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
    use ssz::ssz_encode;

    all_tests!(Slot);
}

#[cfg(test)]
mod epoch_tests {
    use super::*;
    use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
    use ssz::ssz_encode;

    all_tests!(Epoch);
}
<commit_msg>Fix bug in Epoch.slot_iter()<commit_after>use crate::slot_height::SlotHeight;
/// The `Slot` and `Epoch` types are defined as newtypes over u64 to enforce type-safety between
/// the two types.
///
/// `Slot` and `Epoch` have implementations which permit conversion, comparison and math operations
/// between each and `u64`, however specifically not between each other.
///
/// All math operations on `Slot` and `Epoch` are saturating, they never wrap.
///
/// It would be easy to define `PartialOrd` and other traits generically across all types which
/// implement `Into<u64>`, however this would allow operations between `Slots` and `Epochs` which
/// may lead to programming errors which are not detected by the compiler.
use crate::test_utils::TestRandom;
use rand::RngCore;
use serde_derive::Serialize;
use slog;
use ssz::{hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash};
use std::cmp::{Ord, Ordering};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::Iterator;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, Sub, SubAssign};

#[derive(Eq, Debug, Clone, Copy, Default, Serialize)]
pub struct Slot(u64);

#[derive(Eq, Debug, Clone, Copy, Default, Serialize)]
pub struct Epoch(u64);

impl_common!(Slot);
impl_common!(Epoch);

impl Slot {
    pub fn new(slot: u64) -> Slot {
        Slot(slot)
    }

    pub fn epoch(self, epoch_length: u64) -> Epoch {
        Epoch::from(self.0 / epoch_length)
    }

    pub fn height(self, genesis_slot: Slot) -> SlotHeight {
        SlotHeight::from(self.0.saturating_sub(genesis_slot.as_u64()))
    }

    pub fn max_value() -> Slot {
        Slot(u64::max_value())
    }
}

impl Epoch {
    pub fn new(slot: u64) -> Epoch {
        Epoch(slot)
    }

    pub fn max_value() -> Epoch {
        Epoch(u64::max_value())
    }

    pub fn start_slot(self, epoch_length: u64) -> Slot {
        Slot::from(self.0.saturating_mul(epoch_length))
    }

    pub fn end_slot(self, epoch_length: u64) -> Slot {
        Slot::from(
            self.0
                .saturating_add(1)
                .saturating_mul(epoch_length)
                .saturating_sub(1),
        )
    }

    pub fn slot_iter(&self, epoch_length: u64) -> SlotIter {
        SlotIter {
            current_iteration: 0,
            epoch: self,
            epoch_length,
        }
    }
}

pub struct SlotIter<'a> {
    current_iteration: u64,
    epoch: &'a Epoch,
    epoch_length: u64,
}

impl<'a> Iterator for SlotIter<'a> {
    type Item = Slot;

    fn next(&mut self) -> Option<Slot> {
        if self.current_iteration >= self.epoch_length {
            None
        } else {
            let start_slot = self.epoch.start_slot(self.epoch_length);
            let previous = self.current_iteration;
            self.current_iteration += 1;
            Some(start_slot + previous)
        }
    }
}

#[cfg(test)]
mod slot_tests {
    use super::*;
    use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
    use ssz::ssz_encode;

    all_tests!(Slot);
}

#[cfg(test)]
mod epoch_tests {
    use super::*;
    use crate::test_utils::{SeedableRng, TestRandom, XorShiftRng};
    use ssz::ssz_encode;

    all_tests!(Epoch);

    #[test]
    fn slot_iter() {
        let epoch_length = 8;

        let epoch = Epoch::new(0);

        let mut slots = vec![];
        for slot in epoch.slot_iter(epoch_length) {
            slots.push(slot);
        }

        assert_eq!(slots.len(), epoch_length as usize);

        for i in 0..epoch_length {
            assert_eq!(Slot::from(i), slots[i as usize])
        }
    }
}
<|endoftext|>


<commit_before>extern crate portaudio;
use portaudio as pa;

use std::sync::mpsc::*;

const SAMPLE_RATE: f64 = 44100.0;
const FRAMES: usize = 512;

pub fn init() -> Result<pa::PortAudio, pa::Error> {
    pa::PortAudio::new()
}

pub fn get_device_list(pa: &pa::PortAudio) -> Result<Vec<(u32, String)>, pa::Error> {
    // This pa.devices gives a Result of devices, each of which is
    // also a Result. So a Result<Collection<Result<Device>>>. We
    // mould it into devices: a Vec<(index, DeviceInfo)>.
    let devices = try!(try!(pa.devices()).map(|device| {
        device.map(|(pa::DeviceIndex(idx), info)| (idx, info))
    }).collect::<Result<Vec<_>, _>>());

    let list = devices.iter().filter(|&&(_, ref info)| info.max_input_channels > 0)
        .map(|&(idx, ref info)| (idx, info.name.to_string()))
        .collect();
    Ok(list)
}

#[test]
fn get_device_list_returns_devices() {
    let pa = init().expect("Could not init portaudio");
    let devices = get_device_list(&pa).expect("Getting devices had an error");

    // all machines should have at least one input stream, even if
    // that's just a virtual stream with a name like "default".
    assert!(devices.len() > 0);
}

pub struct OpenRecordingChannel<'a> {
    receiver: Receiver<Vec<f64>>,
    //pa: &'a portaudio::PortAudio,
    stream: pa::Stream<'a, pa::NonBlocking, pa::Input<f32>>
}

pub fn start_listening<'a>(pa: &'a pa::PortAudio, device_index: u32) -> Result<OpenRecordingChannel<'a>, pa::Error> {
    //let pa = try!(pa::PortAudio::new());
    let device_info = try!(pa.device_info(pa::DeviceIndex(device_index)));
    let latency = device_info.default_low_input_latency;

    // Construct the input stream parameters.

    let input_params = pa::StreamParameters::<f32>::new(pa::DeviceIndex(device_index), 1, true, latency);

    // Check that the stream format is supported.
    try!(pa.is_input_format_supported(input_params, SAMPLE_RATE));

    // Construct the settings with which we'll open our stream.
    let stream_settings = pa::InputStreamSettings::new(input_params, SAMPLE_RATE, FRAMES as u32);

    // This channel will let us read from and control the audio stream
    let (sender, receiver) = channel();

    // This callback A callback to pass to the non-blocking stream.
    let callback = move |pa::InputStreamCallbackArgs { buffer, .. }| {
        sender.send(buffer.iter().map(|x| *x as f64).collect()).ok();
        pa::Continue
    };

    let mut stream = try!(pa.open_non_blocking_stream(stream_settings, callback));
    try!(stream.start());

    //How do I call this? try!(stream.stop());

    Ok(OpenRecordingChannel {
        receiver: receiver,
//        pa: &pa,
        stream: stream
    })
}

/*
   let mut samples_index = 0;
    while let Ok(samples) = receiver.recv() {
        samples_index += 1;
        if samples_index % 100 != 0 {
            continue;
        }

        let frequency_domain = ::transforms::fft(samples, SAMPLE_RATE);

        let max_frequency = frequency_domain.iter()
            .fold(None as Option<::transforms::FrequencyBucket>, |max, next|
                  if max.is_none() || max.clone().unwrap().intensity < next.intensity { Some(next.clone()) } else { max }
            ).unwrap().max_freq;
        println!("{}Hz", max_frequency.floor());
    }
*/
<commit_msg>Added destructor to close channels<commit_after>extern crate portaudio;
use portaudio as pa;

use std::sync::mpsc::*;
use std::io;
use std::io::Write;

const SAMPLE_RATE: f64 = 44100.0;
const FRAMES: usize = 512;

pub fn init() -> Result<pa::PortAudio, pa::Error> {
    pa::PortAudio::new()
}

pub fn get_device_list(pa: &pa::PortAudio) -> Result<Vec<(u32, String)>, pa::Error> {
    // This pa.devices gives a Result of devices, each of which is
    // also a Result. So a Result<Collection<Result<Device>>>. We
    // mould it into devices: a Vec<(index, DeviceInfo)>.
    let devices = try!(try!(pa.devices()).map(|device| {
        device.map(|(pa::DeviceIndex(idx), info)| (idx, info))
    }).collect::<Result<Vec<_>, _>>());

    let list = devices.iter().filter(|&&(_, ref info)| info.max_input_channels > 0)
        .map(|&(idx, ref info)| (idx, info.name.to_string()))
        .collect();
    Ok(list)
}

#[test]
fn get_device_list_returns_devices() {
    let pa = init().expect("Could not init portaudio");
    let devices = get_device_list(&pa).expect("Getting devices had an error");

    // all machines should have at least one input stream, even if
    // that's just a virtual stream with a name like "default".
    assert!(devices.len() > 0);
}

pub struct OpenRecordingChannel<'a> {
    receiver: Receiver<Vec<f64>>,
    stream: pa::Stream<'a, pa::NonBlocking, pa::Input<f32>>
}

impl<'a> Drop for OpenRecordingChannel<'a> {
    fn drop(&mut self) {
         //if stream doesn't close cleanly, don't end the world. It's probably fine.
        match self.stream.stop() {
            Result::Err(err) => {writeln!(io::stderr(), "Failed to close audio stream. {}", err).ok();},
            _ => {}
        }
    }
}

pub fn start_listening<'a>(pa: &'a pa::PortAudio, device_index: u32) -> Result<OpenRecordingChannel<'a>, pa::Error> {
    //let pa = try!(pa::PortAudio::new());
    let device_info = try!(pa.device_info(pa::DeviceIndex(device_index)));
    let latency = device_info.default_low_input_latency;

    // Construct the input stream parameters.

    let input_params = pa::StreamParameters::<f32>::new(pa::DeviceIndex(device_index), 1, true, latency);

    // Check that the stream format is supported.
    try!(pa.is_input_format_supported(input_params, SAMPLE_RATE));

    // Construct the settings with which we'll open our stream.
    let stream_settings = pa::InputStreamSettings::new(input_params, SAMPLE_RATE, FRAMES as u32);

    // This channel will let us read from and control the audio stream
    let (sender, receiver) = channel();

    // This callback A callback to pass to the non-blocking stream.
    let callback = move |pa::InputStreamCallbackArgs { buffer, .. }| {
        sender.send(buffer.iter().map(|x| *x as f64).collect()).ok();
        pa::Continue
    };

    let mut stream = try!(pa.open_non_blocking_stream(stream_settings, callback));
    try!(stream.start());

    Ok(OpenRecordingChannel {
        receiver: receiver,
        stream: stream
    })
}

#[test]
fn start_listening_returns_successfully() {
    let pa = init().expect("Could not init portaudio");
    let devices = get_device_list(&pa).expect("Getting devices had an error");
    let device = devices.first().expect("Should have at least one device");
    let recording_channel = start_listening(&pa, device.0).expect("Error starting listening to first channel");
}

/*
   let mut samples_index = 0;
    while let Ok(samples) = receiver.recv() {
        samples_index += 1;
        if samples_index % 100 != 0 {
            continue;
        }

        let frequency_domain = ::transforms::fft(samples, SAMPLE_RATE);

        let max_frequency = frequency_domain.iter()
            .fold(None as Option<::transforms::FrequencyBucket>, |max, next|
                  if max.is_none() || max.clone().unwrap().intensity < next.intensity { Some(next.clone()) } else { max }
            ).unwrap().max_freq;
        println!("{}Hz", max_frequency.floor());
    }
*/
<|endoftext|>


<commit_before>use client::GetResponse;
use hyper::Client;
use hyper::header::{ByteRangeSpec, Headers, Range};
use MirrorsList;
use URL;
use std::path::Path;
use std::time::{Duration, Instant};

/// Number of times to ping the remote server
const PING_TIMES: usize = 5;
/// Number of bytes to download from the remote server
const LEN_BENCH_CHUNK: u64 = 64;

/// Launch a benchmark on a single URL
/// This benchmark tests the network for this URL, downloading five times a 64 bits packet
/// The result is the mean of the five measures
fn launch_bench<'a>(bench_client: &Client, url: URL<'a>) -> u32 {
    let mut c_ping_time: [u32; PING_TIMES] = [0; PING_TIMES];
    for index in 0..PING_TIMES {
        let now = Instant::now();
        let mut header = Headers::new();
        header.set(Range::Bytes(vec![ByteRangeSpec::FromTo(0, LEN_BENCH_CHUNK)]));
        match bench_client.get_head_response_using_headers(url, header) {
            Ok(_) => c_ping_time[index] = now.elapsed().subsec_nanos(),
            Err(_) => break,
        }
    }
    // Return 0 if an error occured - the mirror is automatically removed
    if c_ping_time.iter().any(|&x| x == 0) {
        return 0;
    }
    // Return the mean value
    let sum: u32 = c_ping_time.iter().sum();
    sum / PING_TIMES as u32
}

/// Test each URL to download the required file
/// This function returns a list of URLs, which is sorted by median measures (the first URL is the fastest server)
pub fn bench_mirrors<'a>(mirrors: MirrorsList<'a>, filename: &str) -> MirrorsList<'a> {
    // Hyper client to make benchmarks
    let mut bench_client = Client::default();
    bench_client.set_read_timeout(Some(Duration::from_secs(3)));
    // Get mirrors list
    let mut b_mirrors: Vec<(&'a str, u32)> = Vec::with_capacity(PING_TIMES);
    for mirror in mirrors.iter() {
        let mirror_file = Path::new(mirror).join(filename);
        match mirror_file.to_str() {
            Some(_mirror) => {
                let subsec_nano = launch_bench(&bench_client, _mirror);
                if subsec_nano != 0 {
                    b_mirrors.push((mirror, subsec_nano));
                }
                println!("{}: {}", mirror, subsec_nano);
            }
            None => (),
        }
    }
    b_mirrors.sort_by_key(|k| k.1);
    b_mirrors.iter().map(|x| x.0).collect()
}
<commit_msg>Remove debug log statement<commit_after>use client::GetResponse;
use hyper::Client;
use hyper::header::{ByteRangeSpec, Headers, Range};
use MirrorsList;
use URL;
use std::path::Path;
use std::time::{Duration, Instant};

/// Number of times to ping the remote server
const PING_TIMES: usize = 5;
/// Number of bytes to download from the remote server
const LEN_BENCH_CHUNK: u64 = 64;

/// Launch a benchmark on a single URL
/// This benchmark tests the network for this URL, downloading five times a 64 bits packet
/// The result is the mean of the five measures
fn launch_bench<'a>(bench_client: &Client, url: URL<'a>) -> u32 {
    let mut c_ping_time: [u32; PING_TIMES] = [0; PING_TIMES];
    for index in 0..PING_TIMES {
        let now = Instant::now();
        let mut header = Headers::new();
        header.set(Range::Bytes(vec![ByteRangeSpec::FromTo(0, LEN_BENCH_CHUNK)]));
        match bench_client.get_head_response_using_headers(url, header) {
            Ok(_) => c_ping_time[index] = now.elapsed().subsec_nanos(),
            Err(_) => break,
        }
    }
    // Return 0 if an error occured - the mirror is automatically removed
    if c_ping_time.iter().any(|&x| x == 0) {
        return 0;
    }
    // Return the mean value
    let sum: u32 = c_ping_time.iter().sum();
    sum / PING_TIMES as u32
}

/// Test each URL to download the required file
/// This function returns a list of URLs, which is sorted by median measures (the first URL is the fastest server)
pub fn bench_mirrors<'a>(mirrors: MirrorsList<'a>, filename: &str) -> MirrorsList<'a> {
    // Hyper client to make benchmarks
    let mut bench_client = Client::default();
    bench_client.set_read_timeout(Some(Duration::from_secs(3)));
    // Get mirrors list
    let mut b_mirrors: Vec<(&'a str, u32)> = Vec::with_capacity(PING_TIMES);
    for mirror in mirrors.iter() {
        let mirror_file = Path::new(mirror).join(filename);
        match mirror_file.to_str() {
            Some(_mirror) => {
                let subsec_nano = launch_bench(&bench_client, _mirror);
                if subsec_nano != 0 {
                    b_mirrors.push((mirror, subsec_nano));
                }
            }
            None => (),
        }
    }
    b_mirrors.sort_by_key(|k| k.1);
    b_mirrors.iter().map(|x| x.0).collect()
}
<|endoftext|>