<commit_before>use std::process::exit;

use libimagdiary::diary::Diary;
use libimagdiary::diaryid::DiaryId;
use libimagdiary::error::DiaryError as DE;
use libimagdiary::error::DiaryErrorKind as DEK;
use libimagentryedit::edit::Edit;
use libimagrt::runtime::Runtime;
use libimagerror::trace::trace_error;
use libimagdiary::entry::Entry;
use libimagdiary::result::Result;

use util::get_diary_name;

pub fn create(rt: &Runtime) {

    let diaryname = get_diary_name(rt);
    if diaryname.is_none() {
        warn!("No diary selected. Use either the configuration file or the commandline option");
        exit(1);
    }
    let diaryname = diaryname.unwrap();

    let prevent_edit = rt.cli().subcommand_matches("create").unwrap().is_present("no-edit");

    fn create_entry<'a>(diary: &'a Diary, rt: &Runtime) -> Result<Entry<'a>> {
        use std::str::FromStr;

        let create = rt.cli().subcommand_matches("create").unwrap();
        if !create.is_present("timed") {
            debug!("Creating non-timed entry");
            diary.new_entry_today()
        } else {
            let id = match create.value_of("timed") {
                Some("h") | Some("hourly") => {
                    debug!("Creating hourly-timed entry");
                    let time = DiaryId::now(String::from(diary.name()));
                    let hr = create
                        .value_of("hour")
                        .map(|v| { debug!("Creating hourly entry with hour = {:?}", v); v })
                        .and_then(|s| {
                            FromStr::from_str(s)
                                .map_err(|_| warn!("Could not parse hour: '{}'", s))
                                .ok()
                        })
                        .unwrap_or(time.hour());

                    time.with_hour(hr).with_minute(0)
                },

                Some("m") | Some("minutely") => {
                    debug!("Creating minutely-timed entry");
                    let time = DiaryId::now(String::from(diary.name()));
                    let hr = create
                        .value_of("hour")
                        .map(|h| { debug!("hour = {:?}", h); h })
                        .and_then(|s| {
                            FromStr::from_str(s)
                                .map_err(|_| warn!("Could not parse hour: '{}'", s))
                                .ok()
                        })
                        .unwrap_or(time.hour());

                    let min = create
                        .value_of("minute")
                        .map(|m| { debug!("minute = {:?}", m); m })
                        .and_then(|s| {
                            FromStr::from_str(s)
                                .map_err(|_| warn!("Could not parse minute: '{}'", s))
                                .ok()
                        })
                        .unwrap_or(time.minute());

                    time.with_hour(hr).with_minute(min)
                },

                Some(_) => {
                    warn!("Timed creation failed: Unknown spec '{}'",
                          create.value_of("timed").unwrap());
                    exit(1);
                },

                None => {
                    warn!("Unexpected error, cannot continue");
                    exit(1);
                },
            };

            diary.new_entry_by_id(id)
        }
    }

    let diary = Diary::open(rt.store(), &diaryname[..]);
    let res = create_entry(&diary, rt)
        .and_then(|mut entry| {
            if prevent_edit {
                debug!("Not editing new diary entry");
                Ok(())
            } else {
                debug!("Editing new diary entry");
                entry.edit_content(rt)
                    .map_err(|e| DE::new(DEK::DiaryEditError, Some(Box::new(e))))
            }
        });

    if let Err(e) = res {
        trace_error(&e);
    } else {
        info!("Ok!");
    }
}

<commit_msg>Refactor: use map_err_into() instead of manual building<commit_after>use std::process::exit;

use libimagdiary::diary::Diary;
use libimagdiary::diaryid::DiaryId;
use libimagdiary::error::DiaryErrorKind as DEK;
use libimagdiary::error::MapErrInto;
use libimagentryedit::edit::Edit;
use libimagrt::runtime::Runtime;
use libimagerror::trace::trace_error;
use libimagdiary::entry::Entry;
use libimagdiary::result::Result;

use util::get_diary_name;

pub fn create(rt: &Runtime) {

    let diaryname = get_diary_name(rt);
    if diaryname.is_none() {
        warn!("No diary selected. Use either the configuration file or the commandline option");
        exit(1);
    }
    let diaryname = diaryname.unwrap();

    let prevent_edit = rt.cli().subcommand_matches("create").unwrap().is_present("no-edit");

    fn create_entry<'a>(diary: &'a Diary, rt: &Runtime) -> Result<Entry<'a>> {
        use std::str::FromStr;

        let create = rt.cli().subcommand_matches("create").unwrap();
        if !create.is_present("timed") {
            debug!("Creating non-timed entry");
            diary.new_entry_today()
        } else {
            let id = match create.value_of("timed") {
                Some("h") | Some("hourly") => {
                    debug!("Creating hourly-timed entry");
                    let time = DiaryId::now(String::from(diary.name()));
                    let hr = create
                        .value_of("hour")
                        .map(|v| { debug!("Creating hourly entry with hour = {:?}", v); v })
                        .and_then(|s| {
                            FromStr::from_str(s)
                                .map_err(|_| warn!("Could not parse hour: '{}'", s))
                                .ok()
                        })
                        .unwrap_or(time.hour());

                    time.with_hour(hr).with_minute(0)
                },

                Some("m") | Some("minutely") => {
                    debug!("Creating minutely-timed entry");
                    let time = DiaryId::now(String::from(diary.name()));
                    let hr = create
                        .value_of("hour")
                        .map(|h| { debug!("hour = {:?}", h); h })
                        .and_then(|s| {
                            FromStr::from_str(s)
                                .map_err(|_| warn!("Could not parse hour: '{}'", s))
                                .ok()
                        })
                        .unwrap_or(time.hour());

                    let min = create
                        .value_of("minute")
                        .map(|m| { debug!("minute = {:?}", m); m })
                        .and_then(|s| {
                            FromStr::from_str(s)
                                .map_err(|_| warn!("Could not parse minute: '{}'", s))
                                .ok()
                        })
                        .unwrap_or(time.minute());

                    time.with_hour(hr).with_minute(min)
                },

                Some(_) => {
                    warn!("Timed creation failed: Unknown spec '{}'",
                          create.value_of("timed").unwrap());
                    exit(1);
                },

                None => {
                    warn!("Unexpected error, cannot continue");
                    exit(1);
                },
            };

            diary.new_entry_by_id(id)
        }
    }

    let diary = Diary::open(rt.store(), &diaryname[..]);
    let res = create_entry(&diary, rt)
        .and_then(|mut entry| {
            if prevent_edit {
                debug!("Not editing new diary entry");
                Ok(())
            } else {
                debug!("Editing new diary entry");
                entry.edit_content(rt).map_err_into(DEK::DiaryEditError)
            }
        });

    if let Err(e) = res {
        trace_error(&e);
    } else {
        info!("Ok!");
    }
}

<|endoftext|>


<commit_before><commit_msg>get -> try_get + get<commit_after><|endoftext|>


<commit_before><commit_msg>first tests are successful<commit_after>#![cfg(test)]
#![allow(non_upper_case_globals)]
#![allow(dead_code)]
extern crate core;
extern crate brotli_decompressor;
use super::{HeapAllocator, new_brotli_heap_alloc};
use brotli_decompressor::{SliceWrapperMut, SliceWrapper};
use super::brotli::enc::{BrotliEncoderParams, BrotliEncoderMaxCompressedSizeMulti};
use brotli::enc::threading::{SendAlloc,Owned};
use brotli::enc::singlethreading;

use super::brotli::concat::{BroCatli, BroCatliResult};
use std::io::{Read, Write};
use super::integration_tests::UnlimitedBuffer;
static RANDOM_THEN_UNICODE : &'static [u8] = include_bytes!("../../testdata/random_then_unicode");
static ALICE: &'static[u8]  = include_bytes!("../../testdata/alice29.txt");
use super::Rebox;

struct SliceRef<'a> (&'a [u8]);
impl<'a> SliceWrapper<u8> for SliceRef<'a> {
    fn slice(&self) -> &[u8] { self.0 }
}

fn single_threaded_split_compression_test(num_threads: usize, quality: i32, catable: bool, expected_size: usize) {
    let mut params = BrotliEncoderParams::default();
    let input_data = &RANDOM_THEN_UNICODE[..];
    params.quality = quality;
    params.magic_number = true;
    if catable {
        params.catable = true;
    }
    let mut output = Rebox::from(vec![0u8;BrotliEncoderMaxCompressedSizeMulti(RANDOM_THEN_UNICODE.len(), num_threads)]);
    let mut alloc_per_thread = [
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
        SendAlloc::new(new_brotli_heap_alloc()),
    ];
    if num_threads > alloc_per_thread.len() {
        panic!("Too many threads requested {} > {}", num_threads, alloc_per_thread.len());
    }
    let res = singlethreading::compress_multi(
        &params,
        &mut Owned::new(SliceRef(input_data)),
        output.slice_mut(),
        &mut alloc_per_thread[..num_threads],
    );
    assert_eq!(res.unwrap(), expected_size);
    let mut compressed_version = UnlimitedBuffer::new(&output.slice()[..res.unwrap()]);
    let mut rt = UnlimitedBuffer::new(&[]);
    match super::decompress(&mut compressed_version, &mut rt, 65536, Rebox::default()) {
        Ok(_) => {}
        Err(e) => panic!("Error {:?}", e),
    }
    assert_eq!(rt.data(), input_data);
}
#[test]
fn single_threaded_split_compression_test_1() {
    single_threaded_split_compression_test(1, 3, false, 155808)
}
#[test]
fn single_threaded_split_compression_test_2() {
    single_threaded_split_compression_test(2, 4, false, 151857)
}
#[test]
fn single_threaded_split_compression_test_3() {
    single_threaded_split_compression_test(3, 5, false, 144325)
}
#[test]
fn single_threaded_split_compression_test_4() {
    single_threaded_split_compression_test(4, 10, true, 136711)
}
#[test]
fn single_threaded_split_compression_test_5() {
    single_threaded_split_compression_test(5, 9, false, 139125)
}
<|endoftext|>


<commit_before><commit_msg>Changed tests for admin.model.pages<commit_after>#[cfg(test)]
mod pages_test {
    use params::{Map, Value};
    use super::super::*;
    use super::super::pages::*;
    #[test]
    // Test validation for current model
    fn validate_title_test() {
        // Test valid result
        let mut map = Map::new();
        map.assign("title", Value::String("Test Title".into())).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_none());

        // test unvalid result
        let mut map = Map::new();
        map.assign("title", Value::String("".into())).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_some());

        // test unvalid result
        let mut map = Map::new();
        map.assign("title", Value::String("  ".into())).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_some());
    }

    #[test]
    fn validate_published_test() {
        let mut map = Map::new();
        // Should setrequired field
        map.assign("title", Value::String("Test".into())).unwrap();
        map.assign("published", Value::Boolean(true)).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_none());

        let mut map = Map::new();
        map.assign("title", Value::String("Test".into())).unwrap();
        map.assign("published", Value::String("on".into())).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_none());

        let mut map = Map::new();
        map.assign("title", Value::String("Test".into())).unwrap();
        map.assign("published", Value::String("off".into())).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_none());

        let mut map = Map::new();
        map.assign("title", Value::String("Test".into())).unwrap();
        map.assign("published", Value::I64(1)).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_none());

        let mut map = Map::new();
        map.assign("title", Value::String("Test".into())).unwrap();
        map.assign("published", Value::I64(0)).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_none());

        let mut map = Map::new();
        map.assign("title", Value::String("Test".into())).unwrap();
        map.assign("published", Value::String("test".into())).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_some());

        let mut map = Map::new();
        map.assign("title", Value::String("Test".into())).unwrap();
        map.assign("published", Value::I64(-1)).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_some());

        let mut map = Map::new();
        map.assign("title", Value::String("Test".into())).unwrap();
        map.assign("published", Value::I64(2)).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_some());
    }

    #[test]
    fn validate_published_default_test() {
        let mut map = Map::new();
        // Should setrequired field
        map.assign("title", Value::String("Test".into())).unwrap();
        let validator = validate(&map);
        assert!(validator.get_errors().is_none());

        let page = init(validator.get_values());
        assert_eq!(page.published, false);
    }

    #[test]
    #[should_panic]
    fn wrong_type_test() {
        let mut map = Map::new();
        //map.assign("title", Value::String("Test Title".into())).unwrap();
        map.assign("title", Value::Boolean(true)).unwrap();

        // Weong type declaration
        let validator = ValidateResults(vec!(
            Validator::<bool>::new(btreemap! {
                "requiered".to_string() => true.to_json(),
                "vtype".to_string() => "bool".to_json(),
            }).validate("title".to_string(), map.find(&["title"])),
        ));
        // Should paniced
        assert!(validator.get_errors().is_none());
        // Should paniced
        // cause Page stuct `title` field is String not `bool`
        let _ = init(validator.get_values());
    }
}
<|endoftext|>


<commit_before>pub mod some_endpoint {
    use ruma_api::{ruma_api, Outgoing};
    use ruma_events::{collections::all, sticker::StickerEvent, tag::TagEvent, EventResult};
    use serde::Serialize;

    ruma_api! {
        metadata {
            description: "Does something.",
            method: POST, // An `http::Method` constant. No imports required.
            name: "some_endpoint",
            path: "/_matrix/some/endpoint/:baz",
            rate_limited: false,
            requires_authentication: false,
        }

        request {
            // With no attribute on the field, it will be put into the body of the request.
            pub foo: String,

            // This value will be put into the "Content-Type" HTTP header.
            #[ruma_api(header = CONTENT_TYPE)]
            pub content_type: String,

            // This value will be put into the query string of the request's URL.
            #[ruma_api(query)]
            pub bar: String,

            // This value will be inserted into the request's URL in place of the
            // ":baz" path component.
            #[ruma_api(path)]
            pub baz: String,
        }

        response {
            // This value will be extracted from the "Content-Type" HTTP header.
            #[ruma_api(header = CONTENT_TYPE)]
            pub content_type: String,

            // With no attribute on the field, it will be extracted from the body of the response.
            pub value: String,

            // You can use serde attributes on any kind of field
            #[serde(skip_serializing_if = "Option::is_none")]
            pub optional_flag: Option<bool>,

            // This is how you usually use `#[wrap_incoming]` with event types
            #[wrap_incoming(with EventResult)]
            pub event: TagEvent,

            // Same for lists of events
            #[wrap_incoming(all::RoomEvent with EventResult)]
            pub list_of_events: Vec<all::RoomEvent>,

            // This is how `#[wrap_incoming]` is used with nested `EventResult`s
            #[wrap_incoming]
            pub object: ObjectContainingEvents,
        }
    }

    #[derive(Clone, Debug, Serialize, Outgoing)]
    pub struct ObjectContainingEvents {
        #[wrap_incoming(TagEvent with EventResult)]
        pub event_list_1: Vec<TagEvent>,
        #[wrap_incoming(StickerEvent with EventResult)]
        pub event_list_2: Vec<StickerEvent>,
    }
}

pub mod newtype_body_endpoint {
    use ruma_api_macros::ruma_api;

    #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
    pub struct MyCustomType {
        pub foo: String,
    }

    ruma_api! {
        metadata {
            description: "Does something.",
            method: PUT,
            name: "newtype_body_endpoint",
            path: "/_matrix/some/newtype/body/endpoint",
            rate_limited: false,
            requires_authentication: false,
        }

        request {
            #[ruma_api(body)]
            pub list_of_custom_things: Vec<MyCustomType>,
        }

        response {
            #[ruma_api(body)]
            pub my_custom_thing: MyCustomType,
        }
    }
}

pub mod newtype_raw_body_endpoint {
    use ruma_api_macros::ruma_api;

    #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
    pub struct MyCustomType {
        pub foo: String,
    }

    ruma_api! {
        metadata {
            description: "Does something.",
            method: PUT,
            name: "newtype_body_endpoint",
            path: "/_matrix/some/newtype/body/endpoint",
            rate_limited: false,
            requires_authentication: false,
        }

        request {
            #[ruma_api(raw_body)]
            pub file: Vec<u8>,
        }

        response {
            #[ruma_api(raw_body)]
            pub file: Vec<u8>,
        }
    }
}

pub mod query_map_endpoint {
    use ruma_api_macros::ruma_api;

    ruma_api! {
        metadata {
            description: "Does something.",
            method: GET,
            name: "newtype_body_endpoint",
            path: "/_matrix/some/query/map/endpoint",
            rate_limited: false,
            requires_authentication: false,
        }

        request {
            #[ruma_api(query_map)]
            pub fields: Vec<(String, String)>,
        }

        response {
        }
    }
}
<commit_msg>Don't use ruma_api_macros directly in ruma_api tests<commit_after>pub mod some_endpoint {
    use ruma_api::{ruma_api, Outgoing};
    use ruma_events::{collections::all, sticker::StickerEvent, tag::TagEvent, EventResult};
    use serde::Serialize;

    ruma_api! {
        metadata {
            description: "Does something.",
            method: POST, // An `http::Method` constant. No imports required.
            name: "some_endpoint",
            path: "/_matrix/some/endpoint/:baz",
            rate_limited: false,
            requires_authentication: false,
        }

        request {
            // With no attribute on the field, it will be put into the body of the request.
            pub foo: String,

            // This value will be put into the "Content-Type" HTTP header.
            #[ruma_api(header = CONTENT_TYPE)]
            pub content_type: String,

            // This value will be put into the query string of the request's URL.
            #[ruma_api(query)]
            pub bar: String,

            // This value will be inserted into the request's URL in place of the
            // ":baz" path component.
            #[ruma_api(path)]
            pub baz: String,
        }

        response {
            // This value will be extracted from the "Content-Type" HTTP header.
            #[ruma_api(header = CONTENT_TYPE)]
            pub content_type: String,

            // With no attribute on the field, it will be extracted from the body of the response.
            pub value: String,

            // You can use serde attributes on any kind of field
            #[serde(skip_serializing_if = "Option::is_none")]
            pub optional_flag: Option<bool>,

            // This is how you usually use `#[wrap_incoming]` with event types
            #[wrap_incoming(with EventResult)]
            pub event: TagEvent,

            // Same for lists of events
            #[wrap_incoming(all::RoomEvent with EventResult)]
            pub list_of_events: Vec<all::RoomEvent>,

            // This is how `#[wrap_incoming]` is used with nested `EventResult`s
            #[wrap_incoming]
            pub object: ObjectContainingEvents,
        }
    }

    #[derive(Clone, Debug, Serialize, Outgoing)]
    pub struct ObjectContainingEvents {
        #[wrap_incoming(TagEvent with EventResult)]
        pub event_list_1: Vec<TagEvent>,
        #[wrap_incoming(StickerEvent with EventResult)]
        pub event_list_2: Vec<StickerEvent>,
    }
}

pub mod newtype_body_endpoint {
    use ruma_api::ruma_api;

    #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
    pub struct MyCustomType {
        pub foo: String,
    }

    ruma_api! {
        metadata {
            description: "Does something.",
            method: PUT,
            name: "newtype_body_endpoint",
            path: "/_matrix/some/newtype/body/endpoint",
            rate_limited: false,
            requires_authentication: false,
        }

        request {
            #[ruma_api(body)]
            pub list_of_custom_things: Vec<MyCustomType>,
        }

        response {
            #[ruma_api(body)]
            pub my_custom_thing: MyCustomType,
        }
    }
}

pub mod newtype_raw_body_endpoint {
    use ruma_api::ruma_api;

    #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
    pub struct MyCustomType {
        pub foo: String,
    }

    ruma_api! {
        metadata {
            description: "Does something.",
            method: PUT,
            name: "newtype_body_endpoint",
            path: "/_matrix/some/newtype/body/endpoint",
            rate_limited: false,
            requires_authentication: false,
        }

        request {
            #[ruma_api(raw_body)]
            pub file: Vec<u8>,
        }

        response {
            #[ruma_api(raw_body)]
            pub file: Vec<u8>,
        }
    }
}

pub mod query_map_endpoint {
    use ruma_api::ruma_api;

    ruma_api! {
        metadata {
            description: "Does something.",
            method: GET,
            name: "newtype_body_endpoint",
            path: "/_matrix/some/query/map/endpoint",
            rate_limited: false,
            requires_authentication: false,
        }

        request {
            #[ruma_api(query_map)]
            pub fields: Vec<(String, String)>,
        }

        response {
        }
    }
}
<|endoftext|>


<commit_before>//! Tests of the interactive console installer

extern crate rustup_mock;
extern crate rustup_utils;
#[macro_use]
extern crate lazy_static;
extern crate scopeguard;

use std::sync::Mutex;
use std::process::Stdio;
use std::io::Write;
use rustup_mock::clitools::{self, Config, Scenario,
                            SanitizedOutput,
                            expect_stdout_ok};
use rustup_mock::{get_path, restore_path};

pub fn setup(f: &Fn(&Config)) {
    clitools::setup(Scenario::SimpleV2, &|config| {
        // Lock protects environment variables
        lazy_static! {
            static ref LOCK: Mutex<()> = Mutex::new(());
        }
        let _g = LOCK.lock();

        // An windows these tests mess with the user's PATH. Save
        // and restore them here to keep from trashing things.
        let saved_path = get_path();
        let _g = scopeguard::guard(saved_path, |p| restore_path(p));

        f(config);
    });
}

fn run_input(config: &Config, args: &[&str], input: &str) -> SanitizedOutput {
    let mut cmd = clitools::cmd(config, &args[0], &args[1..]);
    clitools::env(config, &mut cmd);

    cmd.stdin(Stdio::piped());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    let mut child = cmd.spawn().unwrap();

    child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
    let out = child.wait_with_output().unwrap();

    SanitizedOutput {
        ok: out.status.success(),
        stdout: String::from_utf8(out.stdout).unwrap(),
        stderr: String::from_utf8(out.stderr).unwrap(),
    }
}

#[test]
fn smoke_test() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"], "\n\n");
        assert!(out.ok);
    });
}

#[test]
fn update() {
    setup(&|config| {
        run_input(config, &["rustup-init"], "\n\n");
        let out = run_input(config, &["rustup-init"], "\n\n");
        assert!(out.ok);
    });
}

// Testing that the right number of blank lines are printed after the
// 'pre-install' message and before the 'post-install' messag.
#[test]
fn blank_lines_around_stderr_log_output_install() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"], "\n\n");

        // During an interactive session, after "Press the Enter
        // key..."  the UI emits a blank line, then there is a blank
        // line that comes from the user pressing enter, then log
        // output on stderr, then an explicit blank line on stdout
        // before printing $toolchain installed
        assert!(out.stdout.contains(r"
Press the Enter key to install Rust.

  stable installed - 1.1.0 (hash-s-2)

Rust is installed now. Great!
"));
    });
}

#[test]
fn blank_lines_around_stderr_log_output_update() {
    setup(&|config| {
        run_input(config, &["rustup-init"], "\n\n");
        let out = run_input(config, &["rustup-init"], "\n\n");

        assert!(out.stdout.contains(r"
Press the Enter key to install Rust.

Rust is installed now. Great!
"));
    });
}

#[test]
fn user_says_nope() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"], "n\n\n");
        assert!(out.ok);
        assert!(!config.cargodir.join("bin").exists());
    });
}

#[test]
fn with_no_modify_path() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init", "--no-modify-path"], "\n\n");
        assert!(out.ok);
        assert!(out.stdout.contains("This path needs to be in your PATH environment variable"));

        if cfg!(unix) {
            assert!(!config.homedir.join(".profile").exists());
        }
    });
}

#[test]
fn with_non_default_toolchain() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init", "--default-toolchain=nightly"], "\n\n");
        assert!(out.ok);

        expect_stdout_ok(config, &["rustup", "show"], "nightly");
    });
}

#[test]
fn set_nightly_toolchain() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"],
                            "a\nnightly\n\n\n\n");
        assert!(out.ok);

        expect_stdout_ok(config, &["rustup", "show"], "nightly");
    });
}

#[test]
fn set_no_modify_path() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"],
                            "a\n\nno\n\n\n");
        assert!(out.ok);

        if cfg!(unix) {
            assert!(!config.homedir.join(".profile").exists());
        }
    });
}

#[test]
fn set_nightly_toolchain_and_unset() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"],
                            "a\nnightly\n\na\nbeta\n\n\n\n");
        assert!(out.ok);

        expect_stdout_ok(config, &["rustup", "show"], "beta");
    });
}

#[test]
fn user_says_nope_after_advanced_install() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"],
                            "a\n\n\nn\n\n");
        assert!(out.ok);
        assert!(!config.cargodir.join("bin").exists());
    });
}
<commit_msg>Fix tests<commit_after>//! Tests of the interactive console installer

extern crate rustup_mock;
extern crate rustup_utils;
#[macro_use]
extern crate lazy_static;
extern crate scopeguard;

use std::sync::Mutex;
use std::process::Stdio;
use std::io::Write;
use rustup_mock::clitools::{self, Config, Scenario,
                            SanitizedOutput,
                            expect_stdout_ok};
use rustup_mock::{get_path, restore_path};

pub fn setup(f: &Fn(&Config)) {
    clitools::setup(Scenario::SimpleV2, &|config| {
        // Lock protects environment variables
        lazy_static! {
            static ref LOCK: Mutex<()> = Mutex::new(());
        }
        let _g = LOCK.lock();

        // An windows these tests mess with the user's PATH. Save
        // and restore them here to keep from trashing things.
        let saved_path = get_path();
        let _g = scopeguard::guard(saved_path, |p| restore_path(p));

        f(config);
    });
}

fn run_input(config: &Config, args: &[&str], input: &str) -> SanitizedOutput {
    let mut cmd = clitools::cmd(config, &args[0], &args[1..]);
    clitools::env(config, &mut cmd);

    cmd.stdin(Stdio::piped());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    let mut child = cmd.spawn().unwrap();

    child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
    let out = child.wait_with_output().unwrap();

    SanitizedOutput {
        ok: out.status.success(),
        stdout: String::from_utf8(out.stdout).unwrap(),
        stderr: String::from_utf8(out.stderr).unwrap(),
    }
}

#[test]
fn smoke_test() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"], "\n\n");
        assert!(out.ok);
    });
}

#[test]
fn update() {
    setup(&|config| {
        run_input(config, &["rustup-init"], "\n\n");
        let out = run_input(config, &["rustup-init"], "\n\n");
        assert!(out.ok);
    });
}

// Testing that the right number of blank lines are printed after the
// 'pre-install' message and before the 'post-install' messag.
#[test]
fn blank_lines_around_stderr_log_output_install() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"], "\n\n");

        // During an interactive session, after "Press the Enter
        // key..."  the UI emits a blank line, then there is a blank
        // line that comes from the user pressing enter, then log
        // output on stderr, then an explicit blank line on stdout
        // before printing $toolchain installed
        assert!(out.stdout.contains(r"
3) Cancel installation

  stable installed - 1.1.0 (hash-s-2)

Rust is installed now. Great!
"));
    });
}

#[test]
fn blank_lines_around_stderr_log_output_update() {
    setup(&|config| {
        run_input(config, &["rustup-init"], "\n\n");
        let out = run_input(config, &["rustup-init"], "\n\n");

        assert!(out.stdout.contains(r"
3) Cancel installation

Rust is installed now. Great!
"));
    });
}

#[test]
fn user_says_nope() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"], "n\n\n");
        assert!(out.ok);
        assert!(!config.cargodir.join("bin").exists());
    });
}

#[test]
fn with_no_modify_path() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init", "--no-modify-path"], "\n\n");
        assert!(out.ok);
        assert!(out.stdout.contains("This path needs to be in your PATH environment variable"));

        if cfg!(unix) {
            assert!(!config.homedir.join(".profile").exists());
        }
    });
}

#[test]
fn with_non_default_toolchain() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init", "--default-toolchain=nightly"], "\n\n");
        assert!(out.ok);

        expect_stdout_ok(config, &["rustup", "show"], "nightly");
    });
}

#[test]
fn set_nightly_toolchain() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"],
                            "2\nnightly\n\n\n\n");
        assert!(out.ok);

        expect_stdout_ok(config, &["rustup", "show"], "nightly");
    });
}

#[test]
fn set_no_modify_path() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"],
                            "2\n\nno\n\n\n");
        assert!(out.ok);

        if cfg!(unix) {
            assert!(!config.homedir.join(".profile").exists());
        }
    });
}

#[test]
fn set_nightly_toolchain_and_unset() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"],
                            "2\nnightly\n\n2\nbeta\n\n\n\n");
        assert!(out.ok);

        expect_stdout_ok(config, &["rustup", "show"], "beta");
    });
}

#[test]
fn user_says_nope_after_advanced_install() {
    setup(&|config| {
        let out = run_input(config, &["rustup-init"],
                            "2\n\n\nn\n\n");
        assert!(out.ok);
        assert!(!config.cargodir.join("bin").exists());
    });
}
<|endoftext|>


<commit_before><commit_msg>Extract per file ingestion, and an odd sense of deja-vu.<commit_after><|endoftext|>


<commit_before><commit_msg>remove unused code<commit_after><|endoftext|>


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

//! Buffering wrappers for I/O traits
//!
//! It can be excessively inefficient to work directly with a `Reader` or
//! `Writer`. Every call to `read` or `write` on `TcpStream` results in a
//! system call, for example. This module provides structures that wrap
//! `Readers`, `Writers`, and `Streams` and buffer input and output to them.
//!
//! # Examples
//!
//! ```
//! let tcp_stream = TcpStream::connect(addr);
//! let reader = BufferedReader::new(tcp_stream);
//!
//! let mut buf: ~[u8] = vec::from_elem(100, 0u8);
//! match reader.read(buf.as_slice()) {
//!     Some(nread) => println!("Read {} bytes", nread),
//!     None => println!("At the end of the stream!")
//! }
//! ```
//!
//! ```
//! let tcp_stream = TcpStream::connect(addr);
//! let writer = BufferedWriter::new(tcp_stream);
//!
//! writer.write("hello, world".as_bytes());
//! writer.flush();
//! ```
//!
//! ```
//! let tcp_stream = TcpStream::connect(addr);
//! let stream = BufferedStream::new(tcp_stream);
//!
//! stream.write("hello, world".as_bytes());
//! stream.flush();
//!
//! let mut buf = vec::from_elem(100, 0u8);
//! match stream.read(buf.as_slice()) {
//!     Some(nread) => println!("Read {} bytes", nread),
//!     None => println!("At the end of the stream!")
//! }
//! ```
//!

use prelude::*;

use num;
use vec;
use super::{Reader, Writer, Stream, Decorator};

// libuv recommends 64k buffers to maximize throughput
// https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
static DEFAULT_CAPACITY: uint = 64 * 1024;

/// Wraps a Reader and buffers input from it
pub struct BufferedReader<R> {
    priv inner: R,
    priv buf: ~[u8],
    priv pos: uint,
    priv cap: uint
}

impl<R: Reader> BufferedReader<R> {
    /// Creates a new `BufferedReader` with with the specified buffer capacity
    pub fn with_capacity(cap: uint, inner: R) -> BufferedReader<R> {
        BufferedReader {
            inner: inner,
            buf: vec::from_elem(cap, 0u8),
            pos: 0,
            cap: 0
        }
    }

    /// Creates a new `BufferedReader` with a default buffer capacity
    pub fn new(inner: R) -> BufferedReader<R> {
        BufferedReader::with_capacity(DEFAULT_CAPACITY, inner)
    }
}

impl<R: Reader> Reader for BufferedReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        if self.pos == self.cap {
            match self.inner.read(self.buf) {
                Some(cap) => {
                    self.pos = 0;
                    self.cap = cap;
                }
                None => return None
            }
        }

        let src = self.buf.slice(self.pos, self.cap);
        let nread = num::min(src.len(), buf.len());
        vec::bytes::copy_memory(buf, src, nread);
        self.pos += nread;
        Some(nread)
    }

    fn eof(&mut self) -> bool {
        self.pos == self.cap && self.inner.eof()
    }
}

impl<R: Reader> Decorator<R> for BufferedReader<R> {
    fn inner(self) -> R {
        self.inner
    }

    fn inner_ref<'a>(&'a self) -> &'a R {
        &self.inner
    }

    fn inner_mut_ref<'a>(&'a mut self) -> &'a mut R {
        &mut self.inner
    }
}

/// Wraps a Writer and buffers output to it
///
/// Note that `BufferedWriter` will NOT flush its buffer when dropped.
pub struct BufferedWriter<W> {
    priv inner: W,
    priv buf: ~[u8],
    priv pos: uint
}

impl<W: Writer> BufferedWriter<W> {
    /// Creates a new `BufferedWriter` with with the specified buffer capacity
    pub fn with_capacity(cap: uint, inner: W) -> BufferedWriter<W> {
        BufferedWriter {
            inner: inner,
            buf: vec::from_elem(cap, 0u8),
            pos: 0
        }
    }

    /// Creates a new `BufferedWriter` with a default buffer capacity
    pub fn new(inner: W) -> BufferedWriter<W> {
        BufferedWriter::with_capacity(DEFAULT_CAPACITY, inner)
    }
}

impl<W: Writer> Writer for BufferedWriter<W> {
    fn write(&mut self, buf: &[u8]) {
        if self.pos + buf.len() > self.buf.len() {
            self.flush();
        }

        if buf.len() > self.buf.len() {
            self.inner.write(buf);
        } else {
            let dst = self.buf.mut_slice_from(self.pos);
            vec::bytes::copy_memory(dst, buf, buf.len());
            self.pos += buf.len();
        }
    }

    fn flush(&mut self) {
        if self.pos != 0 {
            self.inner.write(self.buf.slice_to(self.pos));
            self.pos = 0;
        }
        self.inner.flush();
    }
}

impl<W: Writer> Decorator<W> for BufferedWriter<W> {
    fn inner(self) -> W {
        self.inner
    }

    fn inner_ref<'a>(&'a self) -> &'a W {
        &self.inner
    }

    fn inner_mut_ref<'a>(&'a mut self) -> &'a mut W {
        &mut self.inner
    }
}

struct InternalBufferedWriter<W>(BufferedWriter<W>);

impl<W: Reader> Reader for InternalBufferedWriter<W> {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        self.inner.read(buf)
    }

    fn eof(&mut self) -> bool {
        self.inner.eof()
    }
}

/// Wraps a Stream and buffers input and output to and from it
///
/// Note that `BufferedStream` will NOT flush its output buffer when dropped.
pub struct BufferedStream<S> {
    priv inner: BufferedReader<InternalBufferedWriter<S>>
}

impl<S: Stream> BufferedStream<S> {
    pub fn with_capacities(reader_cap: uint, writer_cap: uint, inner: S)
                           -> BufferedStream<S> {
        let writer = BufferedWriter::with_capacity(writer_cap, inner);
        let internal_writer = InternalBufferedWriter(writer);
        let reader = BufferedReader::with_capacity(reader_cap,
                                                   internal_writer);
        BufferedStream { inner: reader }
    }

    pub fn new(inner: S) -> BufferedStream<S> {
        BufferedStream::with_capacities(DEFAULT_CAPACITY, DEFAULT_CAPACITY,
                                        inner)
    }
}

impl<S: Stream> Reader for BufferedStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        self.inner.read(buf)
    }

    fn eof(&mut self) -> bool {
        self.inner.eof()
    }
}

impl<S: Stream> Writer for BufferedStream<S> {
    fn write(&mut self, buf: &[u8]) {
        self.inner.inner.write(buf)
    }

    fn flush(&mut self) {
        self.inner.inner.flush()
    }
}

impl<S: Stream> Decorator<S> for BufferedStream<S> {
    fn inner(self) -> S {
        self.inner.inner.inner()
    }

    fn inner_ref<'a>(&'a self) -> &'a S {
        self.inner.inner.inner_ref()
    }

    fn inner_mut_ref<'a>(&'a mut self) -> &'a mut S {
        self.inner.inner.inner_mut_ref()
    }
}

#[cfg(test)]
mod test {
    use prelude::*;
    use super::*;
    use super::super::mem::{MemReader, MemWriter};

    #[test]
    fn test_buffered_reader() {
        let inner = MemReader::new(~[0, 1, 2, 3, 4]);
        let mut reader = BufferedReader::with_capacity(2, inner);

        let mut buf = [0, 0, 0];
        let nread = reader.read(buf);
        assert_eq!(Some(2), nread);
        assert_eq!([0, 1, 0], buf);
        assert!(!reader.eof());

        let mut buf = [0];
        let nread = reader.read(buf);
        assert_eq!(Some(1), nread);
        assert_eq!([2], buf);
        assert!(!reader.eof());

        let mut buf = [0, 0, 0];
        let nread = reader.read(buf);
        assert_eq!(Some(1), nread);
        assert_eq!([3, 0, 0], buf);
        assert!(!reader.eof());

        let nread = reader.read(buf);
        assert_eq!(Some(1), nread);
        assert_eq!([4, 0, 0], buf);
        assert!(reader.eof());

        assert_eq!(None, reader.read(buf));
    }

    #[test]
    fn test_buffered_writer() {
        let inner = MemWriter::new();
        let mut writer = BufferedWriter::with_capacity(2, inner);

        writer.write([0, 1]);
        assert_eq!([], writer.inner_ref().inner_ref().as_slice());

        writer.write([2]);
        assert_eq!([0, 1], writer.inner_ref().inner_ref().as_slice());

        writer.write([3]);
        assert_eq!([0, 1], writer.inner_ref().inner_ref().as_slice());

        writer.flush();
        assert_eq!([0, 1, 2, 3], writer.inner_ref().inner_ref().as_slice());

        writer.write([4]);
        writer.write([5]);
        assert_eq!([0, 1, 2, 3], writer.inner_ref().inner_ref().as_slice());

        writer.write([6]);
        assert_eq!([0, 1, 2, 3, 4, 5],
                   writer.inner_ref().inner_ref().as_slice());

        writer.write([7, 8]);
        assert_eq!([0, 1, 2, 3, 4, 5, 6],
                   writer.inner_ref().inner_ref().as_slice());

        writer.write([9, 10, 11]);
        assert_eq!([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
                   writer.inner_ref().inner_ref().as_slice());

        writer.flush();
        assert_eq!([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
                   writer.inner_ref().inner_ref().as_slice());
    }

    // This is just here to make sure that we don't infinite loop in the
    // newtype struct autoderef weirdness
    #[test]
    fn test_buffered_stream() {
        use rt;
        struct S;

        impl rt::io::Writer for S {
            fn write(&mut self, _: &[u8]) {}
            fn flush(&mut self) {}
        }

        impl rt::io::Reader for S {
            fn read(&mut self, _: &mut [u8]) -> Option<uint> { None }
            fn eof(&mut self) -> bool { true }
        }

        let mut stream = BufferedStream::new(S);
        let mut buf = [];
        stream.read(buf);
        stream.eof();
        stream.write(buf);
        stream.flush();
    }
}
<commit_msg>Implement BufferedReader.{read_until, read_line}<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Buffering wrappers for I/O traits
//!
//! It can be excessively inefficient to work directly with a `Reader` or
//! `Writer`. Every call to `read` or `write` on `TcpStream` results in a
//! system call, for example. This module provides structures that wrap
//! `Readers`, `Writers`, and `Streams` and buffer input and output to them.
//!
//! # Examples
//!
//! ```
//! let tcp_stream = TcpStream::connect(addr);
//! let reader = BufferedReader::new(tcp_stream);
//!
//! let mut buf: ~[u8] = vec::from_elem(100, 0u8);
//! match reader.read(buf.as_slice()) {
//!     Some(nread) => println!("Read {} bytes", nread),
//!     None => println!("At the end of the stream!")
//! }
//! ```
//!
//! ```
//! let tcp_stream = TcpStream::connect(addr);
//! let writer = BufferedWriter::new(tcp_stream);
//!
//! writer.write("hello, world".as_bytes());
//! writer.flush();
//! ```
//!
//! ```
//! let tcp_stream = TcpStream::connect(addr);
//! let stream = BufferedStream::new(tcp_stream);
//!
//! stream.write("hello, world".as_bytes());
//! stream.flush();
//!
//! let mut buf = vec::from_elem(100, 0u8);
//! match stream.read(buf.as_slice()) {
//!     Some(nread) => println!("Read {} bytes", nread),
//!     None => println!("At the end of the stream!")
//! }
//! ```
//!

use prelude::*;

use num;
use vec;
use str;
use super::{Reader, Writer, Stream, Decorator};

// libuv recommends 64k buffers to maximize throughput
// https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
static DEFAULT_CAPACITY: uint = 64 * 1024;

/// Wraps a Reader and buffers input from it
pub struct BufferedReader<R> {
    priv inner: R,
    priv buf: ~[u8],
    priv pos: uint,
    priv cap: uint
}

impl<R: Reader> BufferedReader<R> {
    /// Creates a new `BufferedReader` with with the specified buffer capacity
    pub fn with_capacity(cap: uint, inner: R) -> BufferedReader<R> {
        BufferedReader {
            inner: inner,
            buf: vec::from_elem(cap, 0u8),
            pos: 0,
            cap: 0
        }
    }

    /// Creates a new `BufferedReader` with a default buffer capacity
    pub fn new(inner: R) -> BufferedReader<R> {
        BufferedReader::with_capacity(DEFAULT_CAPACITY, inner)
    }

    /// Reads the next line of input, interpreted as a sequence of utf-8
    /// encoded unicode codepoints. If a newline is encountered, then the
    /// newline is contained in the returned string.
    pub fn read_line(&mut self) -> ~str {
        str::from_utf8_owned(self.read_until('\n' as u8))
    }

    /// Reads a sequence of bytes leading up to a specified delimeter. Once the
    /// specified byte is encountered, reading ceases and the bytes up to and
    /// including the delimiter are returned.
    pub fn read_until(&mut self, byte: u8) -> ~[u8] {
        let mut res = ~[];
        let mut used;
        loop {
            {
                let available = self.fill_buffer();
                match available.iter().position(|&b| b == byte) {
                    Some(i) => {
                        res.push_all(available.slice_to(i + 1));
                        used = i + 1;
                        break
                    }
                    None => {
                        res.push_all(available);
                        used = available.len();
                    }
                }
            }
            if used == 0 {
                break
            }
            self.pos += used;
        }
        self.pos += used;
        return res;
    }

    fn fill_buffer<'a>(&'a mut self) -> &'a [u8] {
        if self.pos == self.cap {
            match self.inner.read(self.buf) {
                Some(cap) => {
                    self.pos = 0;
                    self.cap = cap;
                }
                None => {}
            }
        }
        return self.buf.slice(self.pos, self.cap);
    }
}

impl<R: Reader> Reader for BufferedReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        let nread = {
            let available = self.fill_buffer();
            if available.len() == 0 {
                return None;
            }
            let nread = num::min(available.len(), buf.len());
            vec::bytes::copy_memory(buf, available, nread);
            nread
        };
        self.pos += nread;
        Some(nread)
    }

    fn eof(&mut self) -> bool {
        self.pos == self.cap && self.inner.eof()
    }
}

impl<R: Reader> Decorator<R> for BufferedReader<R> {
    fn inner(self) -> R {
        self.inner
    }

    fn inner_ref<'a>(&'a self) -> &'a R {
        &self.inner
    }

    fn inner_mut_ref<'a>(&'a mut self) -> &'a mut R {
        &mut self.inner
    }
}

/// Wraps a Writer and buffers output to it
///
/// Note that `BufferedWriter` will NOT flush its buffer when dropped.
pub struct BufferedWriter<W> {
    priv inner: W,
    priv buf: ~[u8],
    priv pos: uint
}

impl<W: Writer> BufferedWriter<W> {
    /// Creates a new `BufferedWriter` with with the specified buffer capacity
    pub fn with_capacity(cap: uint, inner: W) -> BufferedWriter<W> {
        BufferedWriter {
            inner: inner,
            buf: vec::from_elem(cap, 0u8),
            pos: 0
        }
    }

    /// Creates a new `BufferedWriter` with a default buffer capacity
    pub fn new(inner: W) -> BufferedWriter<W> {
        BufferedWriter::with_capacity(DEFAULT_CAPACITY, inner)
    }
}

impl<W: Writer> Writer for BufferedWriter<W> {
    fn write(&mut self, buf: &[u8]) {
        if self.pos + buf.len() > self.buf.len() {
            self.flush();
        }

        if buf.len() > self.buf.len() {
            self.inner.write(buf);
        } else {
            let dst = self.buf.mut_slice_from(self.pos);
            vec::bytes::copy_memory(dst, buf, buf.len());
            self.pos += buf.len();
        }
    }

    fn flush(&mut self) {
        if self.pos != 0 {
            self.inner.write(self.buf.slice_to(self.pos));
            self.pos = 0;
        }
        self.inner.flush();
    }
}

impl<W: Writer> Decorator<W> for BufferedWriter<W> {
    fn inner(self) -> W {
        self.inner
    }

    fn inner_ref<'a>(&'a self) -> &'a W {
        &self.inner
    }

    fn inner_mut_ref<'a>(&'a mut self) -> &'a mut W {
        &mut self.inner
    }
}

struct InternalBufferedWriter<W>(BufferedWriter<W>);

impl<W: Reader> Reader for InternalBufferedWriter<W> {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        self.inner.read(buf)
    }

    fn eof(&mut self) -> bool {
        self.inner.eof()
    }
}

/// Wraps a Stream and buffers input and output to and from it
///
/// Note that `BufferedStream` will NOT flush its output buffer when dropped.
pub struct BufferedStream<S> {
    priv inner: BufferedReader<InternalBufferedWriter<S>>
}

impl<S: Stream> BufferedStream<S> {
    pub fn with_capacities(reader_cap: uint, writer_cap: uint, inner: S)
                           -> BufferedStream<S> {
        let writer = BufferedWriter::with_capacity(writer_cap, inner);
        let internal_writer = InternalBufferedWriter(writer);
        let reader = BufferedReader::with_capacity(reader_cap,
                                                   internal_writer);
        BufferedStream { inner: reader }
    }

    pub fn new(inner: S) -> BufferedStream<S> {
        BufferedStream::with_capacities(DEFAULT_CAPACITY, DEFAULT_CAPACITY,
                                        inner)
    }
}

impl<S: Stream> Reader for BufferedStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        self.inner.read(buf)
    }

    fn eof(&mut self) -> bool {
        self.inner.eof()
    }
}

impl<S: Stream> Writer for BufferedStream<S> {
    fn write(&mut self, buf: &[u8]) {
        self.inner.inner.write(buf)
    }

    fn flush(&mut self) {
        self.inner.inner.flush()
    }
}

impl<S: Stream> Decorator<S> for BufferedStream<S> {
    fn inner(self) -> S {
        self.inner.inner.inner()
    }

    fn inner_ref<'a>(&'a self) -> &'a S {
        self.inner.inner.inner_ref()
    }

    fn inner_mut_ref<'a>(&'a mut self) -> &'a mut S {
        self.inner.inner.inner_mut_ref()
    }
}

#[cfg(test)]
mod test {
    use prelude::*;
    use super::*;
    use super::super::mem::{MemReader, MemWriter};

    #[test]
    fn test_buffered_reader() {
        let inner = MemReader::new(~[0, 1, 2, 3, 4]);
        let mut reader = BufferedReader::with_capacity(2, inner);

        let mut buf = [0, 0, 0];
        let nread = reader.read(buf);
        assert_eq!(Some(2), nread);
        assert_eq!([0, 1, 0], buf);
        assert!(!reader.eof());

        let mut buf = [0];
        let nread = reader.read(buf);
        assert_eq!(Some(1), nread);
        assert_eq!([2], buf);
        assert!(!reader.eof());

        let mut buf = [0, 0, 0];
        let nread = reader.read(buf);
        assert_eq!(Some(1), nread);
        assert_eq!([3, 0, 0], buf);
        assert!(!reader.eof());

        let nread = reader.read(buf);
        assert_eq!(Some(1), nread);
        assert_eq!([4, 0, 0], buf);
        assert!(reader.eof());

        assert_eq!(None, reader.read(buf));
    }

    #[test]
    fn test_buffered_writer() {
        let inner = MemWriter::new();
        let mut writer = BufferedWriter::with_capacity(2, inner);

        writer.write([0, 1]);
        assert_eq!([], writer.inner_ref().inner_ref().as_slice());

        writer.write([2]);
        assert_eq!([0, 1], writer.inner_ref().inner_ref().as_slice());

        writer.write([3]);
        assert_eq!([0, 1], writer.inner_ref().inner_ref().as_slice());

        writer.flush();
        assert_eq!([0, 1, 2, 3], writer.inner_ref().inner_ref().as_slice());

        writer.write([4]);
        writer.write([5]);
        assert_eq!([0, 1, 2, 3], writer.inner_ref().inner_ref().as_slice());

        writer.write([6]);
        assert_eq!([0, 1, 2, 3, 4, 5],
                   writer.inner_ref().inner_ref().as_slice());

        writer.write([7, 8]);
        assert_eq!([0, 1, 2, 3, 4, 5, 6],
                   writer.inner_ref().inner_ref().as_slice());

        writer.write([9, 10, 11]);
        assert_eq!([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
                   writer.inner_ref().inner_ref().as_slice());

        writer.flush();
        assert_eq!([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
                   writer.inner_ref().inner_ref().as_slice());
    }

    // This is just here to make sure that we don't infinite loop in the
    // newtype struct autoderef weirdness
    #[test]
    fn test_buffered_stream() {
        use rt;
        struct S;

        impl rt::io::Writer for S {
            fn write(&mut self, _: &[u8]) {}
            fn flush(&mut self) {}
        }

        impl rt::io::Reader for S {
            fn read(&mut self, _: &mut [u8]) -> Option<uint> { None }
            fn eof(&mut self) -> bool { true }
        }

        let mut stream = BufferedStream::new(S);
        let mut buf = [];
        stream.read(buf);
        stream.eof();
        stream.write(buf);
        stream.flush();
    }

    #[test]
    fn test_read_until() {
        let inner = MemReader::new(~[0, 1, 2, 1, 0]);
        let mut reader = BufferedReader::with_capacity(2, inner);
        assert_eq!(reader.read_until(0), Some(~[0]));
        assert_eq!(reader.read_until(2), Some(~[1, 2]));
        assert_eq!(reader.read_until(1), Some(~[1]));
        assert_eq!(reader.read_until(8), Some(~[0]));
        assert_eq!(reader.read_until(9), None);
    }
}
<|endoftext|>


<commit_before><commit_msg>Manually tune PIT values<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Added iron.new.<commit_after><|endoftext|>


<commit_before><commit_msg>Clear the background to white before rendering the scene. This means that we will be able to make layers use the correct "initial" value for background-color of transparent, which fixes specifying the background color for iframes.<commit_after><|endoftext|>


<commit_before><commit_msg>SyncFile: reduce a level of braces<commit_after><|endoftext|>


<commit_before><commit_msg>Always use stdout via output proxy<commit_after><|endoftext|>


<commit_before><commit_msg>Implement size_left method()<commit_after><|endoftext|>


<commit_before><commit_msg>Adding support for 8-Bit RLE offset markers<commit_after><|endoftext|>


<commit_before><commit_msg>Added rectangle overlap tests<commit_after><|endoftext|>


<commit_before><commit_msg>Lower stack space use, fewer recursive calls<commit_after><|endoftext|>


<commit_before><commit_msg>Handle all pending events in event loop<commit_after><|endoftext|>


<commit_before><commit_msg>laid out API for OnlineNMF<commit_after>extern crate nalgebra;
use nalgebra::{DMat};

extern crate num;
use num::traits::{Zero};

pub struct OnlineNMF<FloatT> {
    /// maps times (= rows) to hidden variables (= cols).
    /// will grow in size.
    pub weights: DMat<FloatT>,
    /// maps hidden variables (= rows) to observed variables (= cols).
    /// stays constant in size.
    pub hidden: DMat<FloatT>,
}

impl<FloatT: Zero + Clone + Copy> OnlineNMF<FloatT> {
    pub fn new(nobserved: usize, nhidden: usize) -> OnlineNMF<FloatT> {
        OnlineNMF {
            hidden: DMat::new_zeros(nhidden, nobserved),
            weights: DMat::new_zeros(0, nhidden)
        }
    }

    #[inline]
    pub fn nobserved(&self) -> usize {
        self.hidden.ncols()
    }

    #[inline]
    pub fn nhidden(&self) -> usize {
        self.hidden.nrows()
    }

    pub fn update(&mut self, new_observed_as_columns: &DMat<FloatT>) {
        assert_eq!(self.nobserved(), new_observed_as_columns.nrows());

        // do nothing for now
    }
}
<|endoftext|>


<commit_before><commit_msg>Test transparent attribute<commit_after>use anyhow::anyhow;
use std::error::Error as _;
use std::io;
use thiserror::Error;

#[test]
fn test_transparent_struct() {
    #[derive(Error, Debug)]
    #[error(transparent)]
    struct Error(ErrorKind);

    #[derive(Error, Debug)]
    enum ErrorKind {
        #[error("E0")]
        E0,
        #[error("E1")]
        E1(#[from] io::Error),
    }

    let error = Error(ErrorKind::E0);
    assert_eq!("E0", error.to_string());
    assert!(error.source().is_none());

    let io = io::Error::new(io::ErrorKind::Other, "oh no!");
    let error = Error(ErrorKind::from(io));
    assert_eq!("E1", error.to_string());
    error.source().unwrap().downcast_ref::<io::Error>().unwrap();
}

#[test]
fn test_transparent_enum() {
    #[derive(Error, Debug)]
    enum Error {
        #[error("this failed")]
        This,
        #[error(transparent)]
        Other(anyhow::Error),
    }

    let error = Error::This;
    assert_eq!("this failed", error.to_string());

    let error = Error::Other(anyhow!("inner").context("outer"));
    assert_eq!("outer", error.to_string());
    assert_eq!("inner", error.source().unwrap().to_string());
}

#[test]
fn test_anyhow() {
    #[derive(Error, Debug)]
    #[error(transparent)]
    struct Any(#[from] anyhow::Error);

    let error = Any::from(anyhow!("inner").context("outer"));
    assert_eq!("outer", error.to_string());
    assert_eq!("inner", error.source().unwrap().to_string());
}
<|endoftext|>


<commit_before><commit_msg>Disabled coloured logs, and use RFC3339 time formats.<commit_after><|endoftext|>


<commit_before>#![feature(custom_attribute)]
#![allow(dead_code, unused_attributes)]

use std::mem::{size_of, size_of_val};

#[miri_run]
fn main() {
    assert_eq!(size_of::<Option<i32>>(), 8);
    assert_eq!(size_of_val(&()), 0);
    assert_eq!(size_of_val(&42), 4);
    assert_eq!(size_of_val(&[] as &[i32]), 0);
    assert_eq!(size_of_val(&[1, 2, 3] as &[i32]), 12);
}
<commit_msg>Add test for size_of_val::<str>.<commit_after>#![feature(custom_attribute)]
#![allow(dead_code, unused_attributes)]

use std::mem::{size_of, size_of_val};

#[miri_run]
fn main() {
    assert_eq!(size_of::<Option<i32>>(), 8);
    assert_eq!(size_of_val(&()), 0);
    assert_eq!(size_of_val(&42), 4);
    assert_eq!(size_of_val(&[] as &[i32]), 0);
    assert_eq!(size_of_val(&[1, 2, 3] as &[i32]), 12);
    assert_eq!(size_of_val("foobar"), 6);
}
<|endoftext|>


<commit_before><commit_msg>Add tests of deserializing borrows<commit_after>#[macro_use]
extern crate serde_derive;

extern crate serde;
use serde::{Deserialize, Deserializer};

extern crate serde_test;
use serde_test::{
    Error,
    Token,
    assert_de_tokens,
    assert_de_tokens_error,
};

use std::borrow::Cow;

#[test]
fn test_borrowed_str() {
    assert_de_tokens(
        &"borrowed",
        &[
            Token::BorrowedStr("borrowed"),
        ]
    );
}

#[test]
fn test_borrowed_str_from_string() {
    assert_de_tokens_error::<&str>(
        &[
            Token::String("borrowed".to_owned()),
        ],
        Error::Message("invalid type: string \"borrowed\", expected a borrowed string".to_owned()),
    );
}

#[test]
fn test_borrowed_str_from_str() {
    assert_de_tokens_error::<&str>(
        &[
            Token::Str("borrowed"),
        ],
        Error::Message("invalid type: string \"borrowed\", expected a borrowed string".to_owned()),
    );
}

#[test]
fn test_string_from_borrowed_str() {
    assert_de_tokens(
        &"owned".to_owned(),
        &[
            Token::BorrowedStr("owned"),
        ]
    );
}

#[test]
fn test_borrowed_bytes() {
    assert_de_tokens(
        &&b"borrowed"[..],
        &[
            Token::BorrowedBytes(b"borrowed"),
        ]
    );
}

#[test]
fn test_borrowed_bytes_from_bytebuf() {
    assert_de_tokens_error::<&[u8]>(
        &[
            Token::ByteBuf(b"borrowed".to_vec()),
        ],
        Error::Message("invalid type: byte array, expected a borrowed byte array".to_owned()),
    );
}

#[test]
fn test_borrowed_bytes_from_bytes() {
    assert_de_tokens_error::<&[u8]>(
        &[
            Token::Bytes(b"borrowed"),
        ],
        Error::Message("invalid type: byte array, expected a borrowed byte array".to_owned()),
    );
}

#[test]
fn test_tuple() {
    assert_de_tokens(
        &("str", &b"bytes"[..]),
        &[
            Token::TupleStart(2),

            Token::TupleSep,
            Token::BorrowedStr("str"),

            Token::TupleSep,
            Token::BorrowedBytes(b"bytes"),

            Token::TupleEnd,
        ]
    );
}

#[test]
fn test_struct() {
    #[derive(Deserialize, Debug, PartialEq)]
    struct Borrowing<'a, 'b> {
        bs: &'a str,
        bb: &'b [u8],
    }

    assert_de_tokens(
        &Borrowing { bs: "str", bb: b"bytes" },
        &[
            Token::StructStart("Borrowing", 2),

            Token::StructSep,
            Token::BorrowedStr("bs"),
            Token::BorrowedStr("str"),

            Token::StructSep,
            Token::BorrowedStr("bb"),
            Token::BorrowedBytes(b"bytes"),

            Token::StructEnd,
        ]
    );
}

#[test]
fn test_cow() {
    #[derive(Deserialize)]
    struct Cows<'a, 'b> {
        copied: Cow<'a, str>,

        #[serde(borrow)]
        borrowed: Cow<'b, str>,
    }

    let tokens = vec![
        Token::StructStart("Cows", 2),

        Token::StructSep,
        Token::Str("copied"),
        Token::BorrowedStr("copied"),

        Token::StructSep,
        Token::Str("borrowed"),
        Token::BorrowedStr("borrowed"),

        Token::StructEnd,
    ];

    let mut de = serde_test::Deserializer::new(tokens.into_iter());
    let cows = Cows::deserialize(&mut de).unwrap();
    assert_eq!(de.next_token(), None);

    match cows.copied {
        Cow::Owned(ref s) if s == "copied" => {}
        _ => panic!("expected a copied string"),
    }

    match cows.borrowed {
        Cow::Borrowed("borrowed") => {}
        _ => panic!("expected a borrowed string"),
    }
}

#[test]
fn test_lifetimes() {
    #[derive(Deserialize)]
    struct Cows<'a, 'b> {
        _copied: Cow<'a, str>,

        #[serde(borrow)]
        _borrowed: Cow<'b, str>,
    }

    // Tests that `'de: 'a` is not required by the Deserialize impl.
    fn _cows_lifetimes<'de: 'b, 'a, 'b, D>(deserializer: D) -> Cows<'a, 'b>
        where D: Deserializer<'de>
    {
        Deserialize::deserialize(deserializer).unwrap()
    }

    #[derive(Deserialize)]
    struct Wrap<'a, 'b> {
        #[serde(borrow = "'b")]
        _cows: Cows<'a, 'b>,
    }

    // Tests that `'de: 'a` is not required by the Deserialize impl.
    fn _wrap_lifetimes<'de: 'b, 'a, 'b, D>(deserializer: D) -> Wrap<'a, 'b>
        where D: Deserializer<'de>
    {
        Deserialize::deserialize(deserializer).unwrap()
    }
}
<|endoftext|>


<commit_before><commit_msg>cargo fmt<commit_after><|endoftext|>


<commit_before><commit_msg>Get the program name from the name of the executable<commit_after><|endoftext|>


<commit_before><commit_msg>collinear: add Programming Assignment 3: Pattern Recognition<commit_after>// http://coursera.cs.princeton.edu/algs4/assignments/collinear.html
extern crate algs4;

use std::io::prelude::*;
use std::io;
use std::fmt;
use std::cmp::Ordering;

use algs4::quicksort::quick_sort;
use algs4::mergesort::comparator::Comparator;
use algs4::mergesort::comparator::insertion_sort;

#[derive(Copy, Clone)]
pub struct Point {
    x: i32,
    y: i32,
}

pub struct SlopeOrder<'a> {
    pt: &'a Point
}

impl<'a> Comparator<Point> for SlopeOrder<'a> {
    fn compare(&self, q1: &Point, q2: &Point) -> Ordering {
        // unsafe to refer :(
        self.pt.slope_to(q1).partial_cmp(&self.pt.slope_to(q2)).unwrap()
    }
}

/// represents a point in the plane
impl Point {
    /// construct the point (x, y)
    pub fn new(x: i32, y: i32) -> Point {
        Point { x: x, y: y }
    }

    /// draw this point
    pub fn draw(&self) {
        unimplemented!()
    }

    /// draw the line segment from this point to that point
    pub fn draw_to(&self, _other: &Point) {
        unimplemented!()
    }

    /// the slope between this point and that point
    pub fn slope_to(&self, other: &Point) -> f64 {
        ((other.y - self.y) as f64) / ((other.x - self.x) as f64)
    }

    #[allow(non_snake_case)]
    pub fn SLOPE_ORDER<'a>(&'a self) -> SlopeOrder<'a> {
        SlopeOrder { pt: self }
    }
}

impl PartialEq<Point> for Point {
    fn eq(&self, other: &Point) -> bool {
        self.x == other.x && self.y == other.y
    }
}

// is this point lexicographically smaller than that point?
impl PartialOrd<Point> for Point {
    fn partial_cmp(&self, other: &Point) -> Option<Ordering> {
        if self.y < other.y || (self.y == other.y && self.x < other.x) {
            Some(Ordering::Less)
        } else if self.x == other.x && self.y == other.y {
            Some(Ordering::Equal)
        } else {
            Some(Ordering::Greater)
        }
    }
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "({}, {})", self.x, self.y));
        Ok(())
    }
}

// examines 4 points at a time and checks whether they all lie on the same line segment,
// printing out any such line segments to standard output and drawing them using standard drawing.
// To check whether the 4 points p, q, r, and s are collinear, check whether the slopes between
// p and q, between p and r, and between p and s are all equal.
fn brute_force(points: &[Point]) {
    for p in points.iter() {
        for q in points.iter() {
            if p == q { break }
            for r in points.iter() {
                if r == p || r == q { break }
                for s in points.iter() {
                    if s == p || s == q || s == r { break }
                    let slope = p.slope_to(q);
                    if slope == p.slope_to(r) && slope == p.slope_to(s) {
                        println!("{} -> {} -> {} -> {}", p, q, r, s);
                    }
                }
            }
        }
    }
}

// A faster, sorting-based solution. Remarkably, it is possible to solve the problem much faster
// than the brute-force solution described above. Given a point p, the following method determines
// whether p participates in a set of 4 or more collinear points.
// - Think of p as the origin.
// - For each other point q, determine the slope it makes with p.
// - Sort the points according to the slopes they makes with p.
// - Check if any 3 (or more) adjacent points in the sorted order have equal slopes with respect
//   to p. If so, these points, together with p, are collinear.
fn sorting_based(points: &[Point]) {
    let n = points.len();

    let mut points = points.to_vec();
    assert!(n > 4);
    let mut result: Vec<Vec<Point>> = Vec::new();

    for i in 1 .. n {
        // 0th is our origin
        points.swap(0, i);

        let mut points = points.clone();
        let p = points[0].clone();

        insertion_sort(&mut points[1..], p.SLOPE_ORDER());

        let mut n = 0usize;
        // always 0th item
        let mut coll_points_idx = vec![0];
        let mut prev_slope = 99999.9;

        for (idx, slope) in points.iter().map(|q| p.slope_to(q)).enumerate() {
            if slope == prev_slope {
                n += 1;
                coll_points_idx.push(idx);
            } else {
                if n >= 3 {
                    let mut line: Vec<Point> = coll_points_idx.iter().map(|&i| points[i].clone()).collect();
                    quick_sort(&mut line);
                    if !result.contains(&line) {
                        result.push(line)
                    }
                }
                n = 0;
                coll_points_idx = vec![0, idx];
            }
            prev_slope = slope;
        }
        // FIXME: duplicated logic
        if n >= 3 {
            let mut line: Vec<Point> = coll_points_idx.iter().map(|&i| points[i].clone()).collect();
            quick_sort(&mut line);
            // FIXME: not work!
            if !result.contains(&line) {
                result.push(line)
            }
        }
        for line in result.iter() {
            let desc = line.iter().map(|i| format!("{}", i)).collect::<Vec<String>>().connect(" -> ");
            println!("{}", desc);

        }
    }
}

fn main() {
    let mut lines = io::BufReader::new(io::stdin()).lines();
    let n = lines.next().unwrap().unwrap().parse().unwrap();

    let mut points: Vec<Point> = Vec::new();
    for _ in 0 .. n {
        let segs: Vec<i32> = lines.next().unwrap().unwrap().split(' ').
            filter(|s| !s.is_empty()).map(|n| n.parse().unwrap()).collect();
        let x = segs[0];
        let y = segs[1];

        // println!("x = {} y = {}", x, y);
        points.push(Point::new(x, y));
    }

    println!("# Brute force");
    brute_force(&points);

    println!("# A faster, sorting-based solution");
    sorting_based(&mut points);
}
<|endoftext|>


<commit_before><commit_msg>Add json_char example<commit_after>extern crate pom;
use pom::{Input, Train};
use pom::parser::*;

use std::str::FromStr;
use std::iter::FromIterator;
use std::collections::HashMap;

#[derive(Debug, PartialEq)]
pub enum JsonValue {
	Null,
	Bool(bool),
	Str(String),
	Num(f64),
	Array(Vec<JsonValue>),
	Object(HashMap<String,JsonValue>)
}

fn space() -> Parser<char, ()> {
	one_of(" \t\r\n").repeat(0..).discard()
}

fn number() -> Parser<char, f64> {
	let integer = one_of("123456789") - one_of("0123456789").repeat(0..) | term('0');
	let frac = term('.') + one_of("0123456789").repeat(1..);
	let exp = one_of("eE") + one_of("+-").opt() + one_of("0123456789").repeat(1..);
	let number = term('-').opt() + integer + frac.opt() + exp.opt();
	number.collect().map(|v|String::from_iter(v)).map(|s|f64::from_str(&s).unwrap())
}

fn string() -> Parser<char, String> {
	let special_char = term('\\') | term('/') | term('"')
		| term('b').map(|_|'\x08') | term('f').map(|_|'\x0C')
		| term('n').map(|_|'\n') | term('r').map(|_|'\r') | term('t').map(|_|'\t');
	let escape_sequence = term('\\') * special_char;
	let string = term('"') * (none_of("\\\"") | escape_sequence).repeat(0..) - term('"');
	string.map(|v|String::from_iter(v))
}

fn array() -> Parser<char, Vec<JsonValue>> {
	let elems = list(call(value), term(',') * space());
	let arr = term('[') * space() * elems.opt() - term(']');
	arr.map(|elems|elems.unwrap_or(vec![]))
}

fn object() -> Parser<char, HashMap<String, JsonValue>> {
	let member = string() - space() - term(':') - space() + call(value);
	let members = list(member, term(',') * space());
	let obj = term('{') * space() * members.opt() - term('}');
	obj.map(|members|members.unwrap_or(vec![]).into_iter().collect::<HashMap<String,JsonValue>>())
}

fn value() -> Parser<char, JsonValue> {
	( seq("null").map(|_|JsonValue::Null)
	| seq("true").map(|_|JsonValue::Bool(true))
	| seq("false").map(|_|JsonValue::Bool(false))
	| number().map(|num|JsonValue::Num(num))
	| string().map(|text|JsonValue::Str(text))
	| array().map(|arr|JsonValue::Array(arr))
	| object().map(|obj|JsonValue::Object(obj))
	) - space()
}

pub fn json() -> Parser<char, JsonValue> {
	space() * value() - eof()
}

fn main() {
	let test = r#"
	{
        "Image": {
            "Width":  800,
            "Height": 600,
            "Title":  "View from 15th Floor",
            "Thumbnail": {
                "Url":    "http://www.example.com/image/481989943",
                "Height": 125,
                "Width":  100
            },
            "Animated" : false,
            "IDs": [116, 943, 234, 38793]
        }
    }"#.knots();

	let mut input = Input::new(test.as_slice());
	println!("{:?}", json().parse(&mut input));
}
<|endoftext|>


<commit_before><commit_msg>add example<commit_after>extern crate readline;

fn main() {
    loop {
        let input = match readline::readline("Next: ") {
            Some(input) => input,
            None => {
                println!("");
                break;
            },
        };

        if input == "quit" {
            break;
        }

        println!("Input: '{}'", input);
    }
}
<|endoftext|>


<commit_before><commit_msg>Fixed tests<commit_after><|endoftext|>


<commit_before><commit_msg>Added example to work with and_then<commit_after>#![allow(dead_code)]

#[derive(Debug)] enum Food {CordonBleu, Steak, Sushi}
#[derive(Debug)] enum Day {Monday, Tuesday, Wednesday}

fn have_ingredients(food: Food) -> Option<Food> {
    match food {
        Food::Sushi => None,
                  _ => Some(food),
    }
}
fn have_recipe(food: Food) -> Option<Food> {
    match food {
        Food::CordonBleu => None,
                  _ => Some(food),
    }
}

fn cookable_v1(food: Food) ->Option<Food> {
    match have_ingredients(food) {
        None => None,
        Some(food) => match have_recipe(food) {
            None => None,
            Some(food) => Some(food),
        },
    }
}

fn cookable_v2(food: Food) -> Option<Food> {
    have_ingredients(food).and_then(have_recipe)
}

fn eat(food: Food, day: Day) {
    match cookable_v2(food) {
        Some(food) => println!("Yay! On {:?} we get to eat {:?}.", day, food),
        None => println!("Oh no. We don t get to eat on {:?}?", day),
    }
}

fn main () {
    let (cordon_bleu, steak, sushi) = (Food::CordonBleu, Food::Steak, Food::Sushi);
    eat(cordon_bleu, Day::Monday);
    eat(steak, Day::Tuesday);
    eat(sushi, Day::Wednesday);
}
<|endoftext|>


<commit_before><commit_msg>Add a test for Weak::new() not crashing for uninhabited types<commit_after>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

fn main() {
    enum Void {}
    std::rc::Weak::<Void>::new();
    std::sync::Weak::<Void>::new();
}
<|endoftext|>


<commit_before><commit_msg>add `str::as_bytes`<commit_after><|endoftext|>


<commit_before><commit_msg>Keep one config per parser.<commit_after><|endoftext|>


<commit_before><commit_msg>move back play to LIDAR sensing<commit_after><|endoftext|>


<commit_before><commit_msg>added tests that catch the bugs I noticed<commit_after><|endoftext|>


<commit_before><commit_msg>Panic on SSL context creation fail<commit_after><|endoftext|>


<commit_before><commit_msg>Update cookie last access time.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unnecessary lifetime qualifiers<commit_after><|endoftext|>


<commit_before><commit_msg>Move Json just before FromJson.<commit_after><|endoftext|>


<commit_before><commit_msg>json related changes<commit_after><|endoftext|>


<commit_before><commit_msg>Fix connected tests on OSX<commit_after><|endoftext|>


<commit_before><commit_msg>Add `lib.rs` mock<commit_after>mod ffi;

<|endoftext|>


<commit_before><commit_msg>Named tasks<commit_after><|endoftext|>


<commit_before><commit_msg>Change remove_all signature<commit_after><|endoftext|>


<commit_before><commit_msg>Set a struct to represent points, set up boilerplate<commit_after>// Using structs to represent 2D points
// and calculating the Euclidean distance between them

struct Point {
    x: f64,
    y: f64,
}

mod pointutils {
    pub fn euclidean(point_a: Point, point_b: Point) {

    }

}

fn main() {
    let point_a: Point = { x: 0.3, y: 20.0 };
    let point_b: Point = { x: 4.0, y: -0.03 };

}
<|endoftext|>


<commit_before>//! # The Redox Library
//!
//! The Redox Library contains a collection of commonly used low-level software
//! constructs to be used on top of the base operating system, including graphics
//! support and windowing, a basic filesystem, audio support, a simple console
//! with shell style functions, an event system, and environment argument support.

#![crate_type="rlib"]
#![feature(alloc)]
#![feature(allocator)]
#![feature(allow_internal_unstable)]
#![feature(asm)]
#![feature(associated_consts)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(collections_bound)]
#![feature(core)]
#![feature(core_intrinsics)]
#![feature(core_panic)]
#![feature(core_simd)]
#![feature(int_error_internals)]
#![feature(lang_items)]
#![feature(macro_reexport)]
#![feature(rand)]
#![feature(raw)]
#![feature(reflect_marker)]
#![feature(slice_concat_ext)]
#![feature(unicode)]
#![feature(unsafe_no_drop_flag)]
#![feature(box_patterns)]
#![feature(vec_push_all)]
#![feature(wrapping)]
#![feature(zero_one)]
#![feature(no_std)]
#![no_std]

//#![warn(missing_docs)]

/* STD COPY { */
    // We want to reexport a few macros from core but libcore has already been
    // imported by the compiler (via our #[no_std] attribute) In this case we just
    // add a new crate name so we can attach the reexports to it.
    #[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq,
                    unreachable, unimplemented, write, writeln)]
    extern crate core as __core;

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

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

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

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

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

    pub use core_collections::borrow;
    pub use core_collections::fmt;
    pub use core_collections::slice;
    pub use core_collections::str;
    pub use core_collections::string;
    pub use core_collections::vec;

    pub use rustc_unicode::char;

    /* Exported macros */

    #[macro_use]
    pub mod macros;

    // TODO mod rtdeps;

    /* The Prelude. */
    pub mod prelude;

    /* Primitive types */

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

    pub use core::isize;
    pub use core::i8;
    pub use core::i16;
    pub use core::i32;
    pub use core::i64;

    pub use core::usize;
    pub use core::u8;
    pub use core::u16;
    pub use core::u32;
    pub use core::u64;

    // TODO: Add methods to f64
    pub use core::num;

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

    pub mod ascii;

    /* Common traits */

    pub mod floating_num;

    /* Runtime and platform support */

    #[macro_use]
    pub mod thread;

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

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

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

    pub mod rt;
    //TODO mod panicking;
    pub use __core::panicking;

    pub mod rand_old;
    pub mod hashmap;

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

/* Additional Stuff { */
    pub use boxed::Box;
    pub use env::*;
    pub use fs::*;
    pub use io::*;
    pub use rand_old::*;
    pub use string::*;
    pub use vec::Vec;

    pub use url::*;
    pub use get_slice::*;
    pub use to_num::*;

    pub mod alloc_system;

    /// A module for necessary C and assembly constructs
    #[path="../../kernel/externs.rs"]
    pub mod externs;

    pub mod start;

    /// A module for system calls
    pub mod syscall;

    /// A module for audio
    pub mod audio;

    pub mod panic;

    pub mod url;

    pub mod get_slice;
    pub mod to_num;
/* } Additional Stuff */
<commit_msg>Add prelude<commit_after>//! # The Redox Library
//!
//! The Redox Library contains a collection of commonly used low-level software
//! constructs to be used on top of the base operating system, including graphics
//! support and windowing, a basic filesystem, audio support, a simple console
//! with shell style functions, an event system, and environment argument support.

#![crate_type="rlib"]
#![feature(alloc)]
#![feature(allocator)]
#![feature(allow_internal_unstable)]
#![feature(asm)]
#![feature(associated_consts)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(collections_bound)]
#![feature(core)]
#![feature(core_intrinsics)]
#![feature(core_panic)]
#![feature(core_simd)]
#![feature(int_error_internals)]
#![feature(lang_items)]
#![feature(macro_reexport)]
#![feature(rand)]
#![feature(raw)]
#![feature(reflect_marker)]
#![feature(slice_concat_ext)]
#![feature(unicode)]
#![feature(unsafe_no_drop_flag)]
#![feature(box_patterns)]
#![feature(vec_push_all)]
#![feature(wrapping)]
#![feature(zero_one)]
#![feature(no_std)]
#![feature(prelude_import)]
#![no_std]

//#![warn(missing_docs)]

/* STD COPY { */
    // We want to reexport a few macros from core but libcore has already been
    // imported by the compiler (via our #[no_std] attribute) In this case we just
    // add a new crate name so we can attach the reexports to it.
    #[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq,
                    unreachable, unimplemented, write, writeln)]
    extern crate core as __core;

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

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

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

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

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

    pub use core_collections::borrow;
    pub use core_collections::fmt;
    pub use core_collections::slice;
    pub use core_collections::str;
    pub use core_collections::string;
    pub use core_collections::vec;

    pub use rustc_unicode::char;

    /* Exported macros */

    #[macro_use]
    pub mod macros;

    // TODO mod rtdeps;

    /* The Prelude. */
    #[prelude_import]
    pub mod prelude;

    /* Primitive types */

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

    pub use core::isize;
    pub use core::i8;
    pub use core::i16;
    pub use core::i32;
    pub use core::i64;

    pub use core::usize;
    pub use core::u8;
    pub use core::u16;
    pub use core::u32;
    pub use core::u64;

    // TODO: Add methods to f64
    pub use core::num;

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

    pub mod ascii;

    /* Common traits */

    pub mod floating_num;

    /* Runtime and platform support */

    #[macro_use]
    pub mod thread;

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

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

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

    pub mod rt;
    //TODO mod panicking;
    pub use __core::panicking;

    pub mod rand_old;
    pub mod hashmap;

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

/* Additional Stuff { */
    pub use boxed::Box;
    pub use env::*;
    pub use fs::*;
    pub use io::*;
    pub use rand_old::*;
    pub use string::*;
    pub use vec::Vec;

    pub use url::*;
    pub use get_slice::*;
    pub use to_num::*;

    pub mod alloc_system;

    /// A module for necessary C and assembly constructs
    #[path="../../kernel/externs.rs"]
    pub mod externs;

    pub mod start;

    /// A module for system calls
    pub mod syscall;

    /// A module for audio
    pub mod audio;

    pub mod panic;

    pub mod url;

    pub mod get_slice;
    pub mod to_num;
/* } Additional Stuff */
<|endoftext|>


<commit_before><commit_msg>Create main.rs<commit_after>
enum Direction {
    North, South, East, West
}

struct Coord {
    x: i32,
    y: i32
}

impl Direction {
    fn next(&self, turn: &str) -> Direction {
        let right = "R" == turn;

        match self {
            &Direction::North => if right { Direction::East } else { Direction::West },
            &Direction::East => if right { Direction::South } else { Direction::North },
            &Direction::South => if right { Direction::West } else { Direction::East },
            &Direction::West => if right { Direction::North } else { Direction::South }
        }
    }
}

impl Coord {
    fn walk(&self, facing: &Direction, distance: i32) -> Coord {
        match facing {
            &Direction::North => Coord { y: self.y + distance, x: self.x },
            &Direction::South => Coord { y: self.y - distance, x: self.x },
            &Direction::East => Coord { y: self.y, x: self.x + distance },
            &Direction::West => Coord { y: self.y, x: self.x - distance },
        }
    }
}

fn main() {
    let buffer = "R2, L3"; // output is 5
    let buffer = "R2, R2, R2"; // output is 2
    let buffer = "R5, L5, R5, R3"; // output is 12

    let steps = buffer.trim().split(",").map(|x| x.trim().to_string());
    let mut direction = Direction::North;
    let mut pos = Coord { y: 0, x: 0 };

    for step in steps {
        let (dir, dist) = step.split_at(1);
        let dist: i32 = dist.parse().unwrap();

        direction = direction.next(dir);
        pos = pos.walk(&direction, dist);
    }

    println!("{}+{}={}", pos.y, pos.x, (pos.y+pos.x).abs());
}
<|endoftext|>


<commit_before><commit_msg>Move Loop into match statement<commit_after><|endoftext|>


<commit_before><commit_msg>slice: fix missing pinnable slice<commit_after>
use std::fmt;
use std::slice;
use std::ops;
use std::os::raw::c_char;

use rocks_sys as ll;

use to_raw::ToRaw;

/// A Slice that can be pinned with some cleanup tasks, which will be run upon
/// `::Reset()` or object destruction, whichever is invoked first. This can be used
/// to avoid memcpy by having the `PinnsableSlice` object referring to the data
/// that is locked in the memory and release them after the data is consuned.
pub struct PinnableSlice {
    raw: *mut ll::rocks_pinnable_slice_t,
}

impl ToRaw<ll::rocks_pinnable_slice_t> for PinnableSlice {
    fn raw(&self) -> *mut ll::rocks_pinnable_slice_t {
        self.raw
    }
}

impl Drop for PinnableSlice {
    fn drop(&mut self) {
        unsafe {
            ll::rocks_pinnable_slice_destroy(self.raw);
        }
    }
}

impl PinnableSlice {
    pub fn new() -> PinnableSlice {
        PinnableSlice {
            raw: unsafe { ll::rocks_pinnable_slice_create() },
        }
    }

    #[inline]
    pub fn data(&self) -> *const u8 {
        unsafe {
            ll::rocks_pinnable_slice_data(self.raw) as *const u8
        }
    }

    #[inline]
    pub fn size(&self) -> usize {
        unsafe {
            ll::rocks_pinnable_slice_size(self.raw) as usize
        }
    }
}

impl fmt::Debug for PinnableSlice {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s = unsafe { slice::from_raw_parts(self.data(), self.len()) };
        write!(f, "{}", String::from_utf8_lossy(s))
    }
}

impl Default for PinnableSlice {
    fn default() -> Self {
        PinnableSlice::new()
    }
}

impl ops::Deref for PinnableSlice {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        unsafe { slice::from_raw_parts(self.data(), self.size()) }
    }
}

impl AsRef<[u8]> for PinnableSlice {
    fn as_ref(&self) -> &[u8] {
        unsafe { slice::from_raw_parts(self.data(), self.len()) }
    }
}

impl<'a> PartialEq<&'a [u8]> for PinnableSlice {
    fn eq(&self, rhs: &&[u8]) -> bool {
        &self.as_ref() == rhs
    }
}

impl<'a, 'b> PartialEq<&'b [u8]> for &'a PinnableSlice {
    fn eq(&self, rhs: &&[u8]) -> bool {
        &self.as_ref() == rhs
    }
}

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

    #[test]
    fn pinnable_slice() {
        let s = PinnableSlice::new();
        assert_eq!(s, b"");
        assert_eq!(&format!("{:?}", s), "");
    }
}
<|endoftext|>


<commit_before><commit_msg>Added missing import to utils tests<commit_after><|endoftext|>


<commit_before>enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String, // TODO: What to name this string type?
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    Hrtime,
    Nvlist, // TODO: What to name this ?
    NvlistArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array
}

struct NvPair {
    nvp_size:       i32, // size of this nvpair
    nvp_name_sz:    i16, // length of name string
    nvp_reserve:    i16, // not used
    nvp_value_elem: i32, // number of elements for array types
    nvp_type:       DataType, // type of value
    // name string
    // aligned ptr array for string arrays
    // aligned array of data for value
}

// nvlist header
struct NvList {
    nvl_version: i32
    nvl_nvflag:  u32 // persistent flags
    nvl_priv:    u64 // ptr to private data if not packed
    nvl_flag:    u32
    nvl_pad:     i32 // currently not used, for alignment
}

// nvp implementation version
const NV_VERSION: i32 = 0;

// nvlist pack encoding
const NV_ENCODE_NATIVE: u8 = 0;
const NV_ENCODE_XDR:    u8 = 1;

// nvlist persistent unique name flags, stored in nvl_nvflags
const NV_UNIQUE_NAME:      u32 = 0x1;
const NV_UNIQUE_NAME_TYPE: u32 = 0x2;

// nvlist lookup pairs related flags
const NV_FLAG_NOENTOK: isize = 0x1;

/* What to do about these macros?
// convenience macros
#define NV_ALIGN(x)     (((ulong_t)(x) + 7ul) & ~7ul)
#define NV_ALIGN4(x)        (((x) + 3) & ~3)

#define NVP_SIZE(nvp)       ((nvp)->nvp_size)
#define NVP_NAME(nvp)       ((char *)(nvp) + sizeof (nvpair_t))
#define NVP_TYPE(nvp)       ((nvp)->nvp_type)
#define NVP_NELEM(nvp)      ((nvp)->nvp_value_elem)
#define NVP_VALUE(nvp)      ((char *)(nvp) + NV_ALIGN(sizeof (nvpair_t) \
                + (nvp)->nvp_name_sz))

#define NVL_VERSION(nvl)    ((nvl)->nvl_version)
#define NVL_SIZE(nvl)       ((nvl)->nvl_size)
#define NVL_FLAG(nvl)       ((nvl)->nvl_flag)
*/

// NV allocator framework
struct NvAllocOps;

struct NvAlloc<> {
    nva_ops: &'static NvAllocOps,
    nva_arg: Any, // This was a void pointer type.
                  // Not sure if Any is the correct type.
}

/*
struct NvAllocOps {
    int (*nv_ao_init)(nv_alloc_t *, __va_list);
    void (*nv_ao_fini)(nv_alloc_t *);
    void *(*nv_ao_alloc)(nv_alloc_t *, size_t);
    void (*nv_ao_free)(nv_alloc_t *, void *, size_t);
    void (*nv_ao_reset)(nv_alloc_t *);
}
*/
<commit_msg>Fix the enum variant naming for consistency<commit_after>enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String,
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    HrTime,
    NvList,
    NvListArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array
}

struct NvPair {
    nvp_size:       i32, // size of this nvpair
    nvp_name_sz:    i16, // length of name string
    nvp_reserve:    i16, // not used
    nvp_value_elem: i32, // number of elements for array types
    nvp_type:       DataType, // type of value
    // name string
    // aligned ptr array for string arrays
    // aligned array of data for value
}

// nvlist header
struct NvList {
    nvl_version: i32
    nvl_nvflag:  u32 // persistent flags
    nvl_priv:    u64 // ptr to private data if not packed
    nvl_flag:    u32
    nvl_pad:     i32 // currently not used, for alignment
}

// nvp implementation version
const NV_VERSION: i32 = 0;

// nvlist pack encoding
const NV_ENCODE_NATIVE: u8 = 0;
const NV_ENCODE_XDR:    u8 = 1;

// nvlist persistent unique name flags, stored in nvl_nvflags
const NV_UNIQUE_NAME:      u32 = 0x1;
const NV_UNIQUE_NAME_TYPE: u32 = 0x2;

// nvlist lookup pairs related flags
const NV_FLAG_NOENTOK: isize = 0x1;

/* What to do about these macros?
// convenience macros
#define NV_ALIGN(x)     (((ulong_t)(x) + 7ul) & ~7ul)
#define NV_ALIGN4(x)        (((x) + 3) & ~3)

#define NVP_SIZE(nvp)       ((nvp)->nvp_size)
#define NVP_NAME(nvp)       ((char *)(nvp) + sizeof (nvpair_t))
#define NVP_TYPE(nvp)       ((nvp)->nvp_type)
#define NVP_NELEM(nvp)      ((nvp)->nvp_value_elem)
#define NVP_VALUE(nvp)      ((char *)(nvp) + NV_ALIGN(sizeof (nvpair_t) \
                + (nvp)->nvp_name_sz))

#define NVL_VERSION(nvl)    ((nvl)->nvl_version)
#define NVL_SIZE(nvl)       ((nvl)->nvl_size)
#define NVL_FLAG(nvl)       ((nvl)->nvl_flag)
*/

// NV allocator framework
struct NvAllocOps;

struct NvAlloc<> {
    nva_ops: &'static NvAllocOps,
    nva_arg: Any, // This was a void pointer type.
                  // Not sure if Any is the correct type.
}

/*
struct NvAllocOps {
    int (*nv_ao_init)(nv_alloc_t *, __va_list);
    void (*nv_ao_fini)(nv_alloc_t *);
    void *(*nv_ao_alloc)(nv_alloc_t *, size_t);
    void (*nv_ao_free)(nv_alloc_t *, void *, size_t);
    void (*nv_ao_reset)(nv_alloc_t *);
}
*/
<|endoftext|>