<commit_before>/// Exercise 8.3 Rewrite the program in Figure 8.6 to
/// use waitid instead of wait. Instead of calling
/// pr_exit, determine the equivalent information from
/// the siginfo structure.
///
/// Takeaway:
/// - I could not catch the exit signals 6 and 8 (the second and third fork)
///   it *should* have worked, the struct definition seems to match the headers in /usr/include..
/// - on Linux the field `si_status` is missing in libc, since the headers on Linux are a mess..

extern crate libc;
extern crate apue;

use libc::{exit, fork, abort, raise, siginfo_t, SIGFPE};
use apue::my_libc::{waitid, idtype_t, WEXITED, CLD_DUMPED, CLD_EXITED, CLD_STOPPED};
use apue::LibcResult;
use std::panic;

fn handle_panic(e: &panic::PanicInfo) {
    match e.payload().downcast_ref::<String>() {
        Some(as_string) if as_string == "attempt to divide by zero" => {
            unsafe { raise(SIGFPE) };
        }
        _ => {
            panic!("unknown error occurred");
        }
    }
}

#[cfg(target_os = "macos")]
fn pr_exit(i: siginfo_t) {
    let sigcode = i.si_code;
    let status = i.si_status;
    match sigcode {
        CLD_EXITED => println!("normal termination, exit status = {}", status),
        CLD_STOPPED => println!("child stoped, signal number = {}", status),
        _ => {
            println!("abnormal termination, signal number = {}", status);
            if sigcode == CLD_DUMPED {
                println!("(core file generated)");
            }
        }
    }
}

/// si_status is missing in Linux in libc, no wonder: header files is a mess there
#[cfg(target_os = "linux")]
fn pr_exit(i: siginfo_t) {
    let sigcode = i.si_code;
    match sigcode {
        CLD_EXITED => println!("normal termination"),
        CLD_STOPPED => println!("child stoped"),
        _ => {
            println!("abnormal termination");
            if sigcode == CLD_DUMPED {
                println!("(core file generated)");
            }
        }
    }
}

fn main() {
    panic::set_hook(Box::new(handle_panic));
    unsafe {
        let mut siginfo: siginfo_t = std::mem::uninitialized();
        let mut pid = fork().to_option().expect("fork error");
        if pid == 0 {
            // child
            exit(7);
        }
        waitid(idtype_t::P_PID, pid as _, &mut siginfo, WEXITED).to_option().expect("waitid error");

        pr_exit(siginfo);

        pid = fork().to_option().expect("fork error");
        if pid == 0 {
            // child
            abort(); // generate SIGABRT
        }
        waitid(idtype_t::P_PID, pid as _, &mut siginfo, WEXITED).to_option().expect("waitid error");
        pr_exit(siginfo);

        pid = fork().to_option().expect("fork error");
        if pid == 0 {
            // child
            let z = 0;
            pid = 1 / z; // divide by 0 generates SIGFPE
        }

        waitid(idtype_t::P_PID, pid as _, &mut siginfo, WEXITED).to_option().expect("waitid error");
        pr_exit(siginfo);
    }
}
<commit_msg>Add comments how a C program in Linux and Macos behaves with the same code<commit_after>/// Exercise 8.3 Rewrite the program in Figure 8.6 to
/// use waitid instead of wait. Instead of calling
/// pr_exit, determine the equivalent information from
/// the siginfo structure.
///
/// Takeaway:
/// - I could not catch the exit signals 6 and 8 (the second and third fork)
///   it *should* have worked, the struct definition seems to match the headers in /usr/include..
/// - the same program in C (e.g. http://bit.ly/2iSLMid) yields the same results. On Linux
///   it works though, but on MacOs it prints signal number = 0 also for the 2nd and 3rd line
/// - on Linux the field `si_status` is missing in libc, since the headers on Linux are a mess..

extern crate apue;

use libc::{exit, fork, abort, raise, siginfo_t, SIGFPE};
use apue::my_libc::{waitid, idtype_t, WEXITED, CLD_DUMPED, CLD_EXITED, CLD_STOPPED};
use apue::LibcResult;
use std::panic;

fn handle_panic(e: &panic::PanicInfo) {
    match e.payload().downcast_ref::<String>() {
        Some(as_string) if as_string == "attempt to divide by zero" => {
            unsafe { raise(SIGFPE) };
        }
        _ => {
            panic!("unknown error occurred");
        }
    }
}

#[cfg(target_os = "macos")]
fn pr_exit(i: siginfo_t) {
    let sigcode = i.si_code;
    let status = i.si_status;
    match sigcode {
        CLD_EXITED => println!("normal termination, exit status = {}", status),
        CLD_STOPPED => println!("child stoped, signal number = {}", status),
        _ => {
            println!("abnormal termination, signal number = {}", status);
            if sigcode == CLD_DUMPED {
                println!("(core file generated)");
            }
        }
    }
}

/// si_status is missing in Linux in libc, no wonder: header files is a mess there
#[cfg(target_os = "linux")]
fn pr_exit(i: siginfo_t) {
    let sigcode = i.si_code;
    match sigcode {
        CLD_EXITED => println!("normal termination"),
        CLD_STOPPED => println!("child stoped"),
        _ => {
            println!("abnormal termination");
            if sigcode == CLD_DUMPED {
                println!("(core file generated)");
            }
        }
    }
}

fn main() {
    panic::set_hook(Box::new(handle_panic));
    unsafe {
        let mut siginfo: siginfo_t = std::mem::uninitialized();
        let mut pid = fork().to_option().expect("fork error");
        if pid == 0 {
            // child
            exit(7);
        }
        waitid(idtype_t::P_PID, pid as _, &mut siginfo, WEXITED).to_option().expect("waitid error");

        pr_exit(siginfo);

        pid = fork().to_option().expect("fork error");
        if pid == 0 {
            // child
            abort(); // generate SIGABRT
        }
        waitid(idtype_t::P_PID, pid as _, &mut siginfo, WEXITED).to_option().expect("waitid error");
        pr_exit(siginfo);

        pid = fork().to_option().expect("fork error");
        if pid == 0 {
            // child
            let z = 0;
            pid = 1 / z; // divide by 0 generates SIGFPE
        }

        waitid(idtype_t::P_PID, pid as _, &mut siginfo, WEXITED).to_option().expect("waitid error");
        pr_exit(siginfo);
    }
}
<|endoftext|>


<commit_before>//! Types for the *m.room.avatar* event.

use ruma_events_macros::StateEventContent;
use serde::{Deserialize, Serialize};

use super::ImageInfo;
use crate::StateEvent;

/// A picture that is associated with the room.
///
/// This can be displayed alongside the room information.
pub type AvatarEvent = StateEvent<AvatarEventContent>;

/// The payload for `AvatarEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, StateEventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.room.avatar")]
pub struct AvatarEventContent {
    /// Information about the avatar image.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<Box<ImageInfo>>,

    /// URL of the avatar image.
    pub url: String,
}

impl AvatarEventContent {
    /// Create an `AvatarEventContent` from the given image URL.
    pub fn new(url: String) -> Self {
        Self { info: None, url }
    }
}
<commit_msg>events: Allow the url in m.room.avatar to be null / missing<commit_after>//! Types for the *m.room.avatar* event.

use ruma_events_macros::StateEventContent;
use serde::{Deserialize, Serialize};

use super::ImageInfo;
use crate::StateEvent;

/// A picture that is associated with the room.
///
/// This can be displayed alongside the room information.
pub type AvatarEvent = StateEvent<AvatarEventContent>;

/// The payload for `AvatarEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, StateEventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[cfg_attr(feature = "unstable-pre-spec", derive(Default))]
#[ruma_event(type = "m.room.avatar")]
pub struct AvatarEventContent {
    /// Information about the avatar image.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<Box<ImageInfo>>,

    /// URL of the avatar image.
    #[cfg(not(feature = "unstable-pre-spec"))]
    pub url: String,

    /// URL of the avatar image.
    #[cfg(feature = "unstable-pre-spec")]
    pub url: Option<String>,
}

impl AvatarEventContent {
    /// Create an `AvatarEventContent` from the given image URL.
    #[cfg(not(feature = "unstable-pre-spec"))]
    pub fn new(url: String) -> Self {
        Self { info: None, url }
    }

    /// Create an empty `AvatarEventContent`.
    #[cfg(feature = "unstable-pre-spec")]
    pub fn new() -> Self {
        Self::default()
    }
}
<|endoftext|>


<commit_before>
use wtest_basic::*;

#[cfg( feature = "in_wtools" )]
use wtools::string as TheModule;
#[cfg( not( feature = "in_wtools" ) )]
use wstring_tools as TheModule;

use TheModule::string::parse as parse;
use std::collections::HashMap;

//

fn _basic()
{
  let src = "";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = " ";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = " ";
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "  \t ";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = "  \t ";
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );
}

fn _with_subject_and_map()
{
  let src = "subj";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = "subj";
  exp.subject = "subj".to_string();
  exp.subjects = vec![ "subj".to_string() ];
  exp.maps = vec![ HashMap::new() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj with space";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = "subj with space";
  exp.subject = "subj with space".to_string();
  exp.subjects = vec![ "subj with space".to_string() ];
  exp.maps = vec![ HashMap::new() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj v:1";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options = HashMap::new();
  options.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj v:1";
  exp.subject = "subj".to_string();
  exp.subjects = vec![ "subj".to_string() ];
  exp.map = options.clone();
  exp.maps = vec![ options.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj v:1 r:some";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options = HashMap::new();
  options.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  options.insert( String::from( "r" ), parse::OpType::Primitive( String::from( "some" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj v:1 r:some";
  exp.subject = "subj".to_string();
  exp.subjects = vec![ "subj".to_string() ];
  exp.map = options.clone();
  exp.maps = vec![ options.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  /* */

  let src = "subj1 ; subj2";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = "subj1 ; subj2";
  exp.subject = "subj1".to_string();
  exp.subjects = vec![ "subj1".to_string(), "subj2".to_string() ];
  exp.maps = vec![ HashMap::new(), HashMap::new() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj1 v:1 ; subj2";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options = HashMap::new();
  options.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj1 v:1 ; subj2";
  exp.subject = "subj1".to_string();
  exp.subjects = vec![ "subj1".to_string(), "subj2".to_string() ];
  exp.map = options.clone();
  exp.maps = vec![ options.clone(), HashMap::new() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj1 v:1 ; subj2 v:2";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options1 = HashMap::new();
  options1.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  let mut options2 = HashMap::new();
  options2.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "2" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj1 v:1 ; subj2 v:2";
  exp.subject = "subj1".to_string();
  exp.subjects = vec![ "subj1".to_string(), "subj2".to_string() ];
  exp.map = options1.clone();
  exp.maps = vec![ options1.clone(), options2.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj1 v:1 ne:-2 ; subj2 v:2 r:some";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options1 = HashMap::new();
  options1.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  options1.insert( String::from( "ne" ), parse::OpType::Primitive( String::from( "-2" ) ) );
  let mut options2 = HashMap::new();
  options2.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "2" ) ) );
  options2.insert( String::from( "r" ), parse::OpType::Primitive( String::from( "some" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj1 v:1 ne:-2 ; subj2 v:2 r:some";
  exp.subject = "subj1".to_string();
  exp.subjects = vec![ "subj1".to_string(), "subj2".to_string() ];
  exp.map = options1.clone();
  exp.maps = vec![ options1.clone(), options2.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );
}

//

test_suite!
{
  basic,
  with_subject_and_map,
}
<commit_msg>Write test routine `with_several_values`<commit_after>
use wtest_basic::*;

#[cfg( feature = "in_wtools" )]
use wtools::string as TheModule;
#[cfg( not( feature = "in_wtools" ) )]
use wstring_tools as TheModule;

use TheModule::string::parse as parse;
use std::collections::HashMap;

//

fn _basic()
{
  let src = "";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = " ";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = " ";
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "  \t ";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = "  \t ";
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );
}

//

fn _with_subject_and_map()
{
  let src = "subj";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = "subj";
  exp.subject = "subj".to_string();
  exp.subjects = vec![ "subj".to_string() ];
  exp.maps = vec![ HashMap::new() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj with space";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = "subj with space";
  exp.subject = "subj with space".to_string();
  exp.subjects = vec![ "subj with space".to_string() ];
  exp.maps = vec![ HashMap::new() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj v:1";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options = HashMap::new();
  options.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj v:1";
  exp.subject = "subj".to_string();
  exp.subjects = vec![ "subj".to_string() ];
  exp.map = options.clone();
  exp.maps = vec![ options.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj v:1 r:some";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options = HashMap::new();
  options.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  options.insert( String::from( "r" ), parse::OpType::Primitive( String::from( "some" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj v:1 r:some";
  exp.subject = "subj".to_string();
  exp.subjects = vec![ "subj".to_string() ];
  exp.map = options.clone();
  exp.maps = vec![ options.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  /* */

  let src = "subj1 ; subj2";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut exp = parse::Request::default();
  exp.original = "subj1 ; subj2";
  exp.subject = "subj1".to_string();
  exp.subjects = vec![ "subj1".to_string(), "subj2".to_string() ];
  exp.maps = vec![ HashMap::new(), HashMap::new() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj1 v:1 ; subj2";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options = HashMap::new();
  options.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj1 v:1 ; subj2";
  exp.subject = "subj1".to_string();
  exp.subjects = vec![ "subj1".to_string(), "subj2".to_string() ];
  exp.map = options.clone();
  exp.maps = vec![ options.clone(), HashMap::new() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj1 v:1 ; subj2 v:2";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options1 = HashMap::new();
  options1.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  let mut options2 = HashMap::new();
  options2.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "2" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj1 v:1 ; subj2 v:2";
  exp.subject = "subj1".to_string();
  exp.subjects = vec![ "subj1".to_string(), "subj2".to_string() ];
  exp.map = options1.clone();
  exp.maps = vec![ options1.clone(), options2.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj1 v:1 ne:-2 ; subj2 v:2 r:some";
  let req = TheModule::string::request_parse()
  .src( src )
  .perform();
  let mut options1 = HashMap::new();
  options1.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "1" ) ) );
  options1.insert( String::from( "ne" ), parse::OpType::Primitive( String::from( "-2" ) ) );
  let mut options2 = HashMap::new();
  options2.insert( String::from( "v" ), parse::OpType::Primitive( String::from( "2" ) ) );
  options2.insert( String::from( "r" ), parse::OpType::Primitive( String::from( "some" ) ) );
  let mut exp = parse::Request::default();
  exp.original = "subj1 v:1 ne:-2 ; subj2 v:2 r:some";
  exp.subject = "subj1".to_string();
  exp.subjects = vec![ "subj1".to_string(), "subj2".to_string() ];
  exp.map = options1.clone();
  exp.maps = vec![ options1.clone(), options2.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );
}

//

fn _with_several_values()
{
  let src = "subj v:1 v:2";
  let req = TheModule::string::request_parse()
  .src( src )
  .several_values( false )
  .perform();
  let mut options = HashMap::new();
  options.insert( String::from( "v" ), parse::OpType::Primitive( "2".to_string() ) );
  let mut exp = parse::Request::default();
  exp.original = "subj v:1 v:2";
  exp.subject = "subj".to_string();
  exp.subjects = vec![ "subj".to_string() ];
  exp.map = options.clone();
  exp.maps = vec![ options.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );

  let src = "subj v:1 v:2";
  let req = TheModule::string::request_parse()
  .src( src )
  .several_values( true )
  .perform();
  let mut options = HashMap::new();
  options.insert( String::from( "v" ), parse::OpType::Vector( vec![ "1".to_string(), "2".to_string() ] ) );
  let mut exp = parse::Request::default();
  exp.original = "subj v:1 v:2";
  exp.subject = "subj".to_string();
  exp.subjects = vec![ "subj".to_string() ];
  exp.map = options.clone();
  exp.maps = vec![ options.clone() ];
  exp.key_val_delimeter = ":";
  exp.commands_delimeter = ";";
  assert_eq!( req, exp );
}

//

test_suite!
{
  basic,
  with_subject_and_map,
  with_several_values,
}
<|endoftext|>


<commit_before>// pretty-printers are not loaded
// compile-flags:-g

// min-gdb-version: 8.1
// min-cdb-version: 10.0.18317.1001

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

// gdb-command:run

// gdb-command:print r
// gdb-check:[...]$1 = Rc(strong=2, weak=1) = {value = 42, strong = 2, weak = 1}
// gdb-command:print a
// gdb-check:[...]$2 = Arc(strong=2, weak=1) = {value = 42, strong = 2, weak = 1}

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

// lldb-command:run

// lldb-command:print r
// lldb-check:[...]$0 = strong=2, weak=1 { value = 42 }
// lldb-command:print a
// lldb-check:[...]$1 = strong=2, weak=1 { data = 42 }

// === CDB TESTS ==================================================================================

// cdb-command:g

// cdb-command:dx r,d
// cdb-check:r,d              : 42 [Type: alloc::rc::Rc<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::rc::Rc<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::cell::Cell<usize>]
// cdb-check:    [Weak reference count] : 2 [Type: core::cell::Cell<usize>]

// cdb-command:dx r1,d
// cdb-check:r1,d             : 42 [Type: alloc::rc::Rc<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::rc::Rc<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::cell::Cell<usize>]
// cdb-check:    [Weak reference count] : 2 [Type: core::cell::Cell<usize>]

// cdb-command:dx w1,d
// cdb-check:w1,d             : 42 [Type: alloc::rc::Weak<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::rc::Weak<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::cell::Cell<usize>]
// cdb-check:    [Weak reference count] : 2 [Type: core::cell::Cell<usize>]

// cdb-command:dx a,d
// cdb-check:a,d              : 42 [Type: alloc::sync::Arc<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::sync::Arc<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::sync::atomic::AtomicUsize]
// cdb-check:    [Weak reference count] : 2 [Type: core::sync::atomic::AtomicUsize]

// cdb-command:dx a1,d
// cdb-check:a1,d             : 42 [Type: alloc::sync::Arc<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::sync::Arc<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::sync::atomic::AtomicUsize]
// cdb-check:    [Weak reference count] : 2 [Type: core::sync::atomic::AtomicUsize]

// cdb-command:dx w2,d
// cdb-check:w2,d             : 42 [Type: alloc::sync::Weak<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::sync::Weak<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::sync::atomic::AtomicUsize]
// cdb-check:    [Weak reference count] : 2 [Type: core::sync::atomic::AtomicUsize]

use std::rc::Rc;
use std::sync::Arc;

fn main() {
    let r = Rc::new(42);
    let r1 = Rc::clone(&r);
    let w1 = Rc::downgrade(&r);

    let a = Arc::new(42);
    let a1 = Arc::clone(&a);
    let w2 = Arc::downgrade(&a);

    print!(""); // #break
}
<commit_msg>Fix a debuginfo test<commit_after>// pretty-printers are not loaded
// compile-flags:-g

// min-gdb-version: 8.1
// min-cdb-version: 10.0.18317.1001

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

// gdb-command:run

// gdb-command:print r
// gdb-check:[...]$1 = Rc(strong=2, weak=1) = {value = 42, strong = 2, weak = 1}
// gdb-command:print a
// gdb-check:[...]$2 = Arc(strong=2, weak=1) = {value = 42, strong = 2, weak = 1}

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

// lldb-command:run

// lldb-command:print r
// lldb-check:[...]$0 = strong=2, weak=1 { value = 42 }
// lldb-command:print a
// lldb-check:[...]$1 = strong=2, weak=1 { data = 42 }

// === CDB TESTS ==================================================================================

// cdb-command:g

// cdb-command:dx r,d
// cdb-check:r,d              : 42 [Type: alloc::rc::Rc<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::rc::Rc<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::cell::Cell<usize>]
// cdb-check:    [Weak reference count] : 2 [Type: core::cell::Cell<usize>]

// cdb-command:dx r1,d
// cdb-check:r1,d             : 42 [Type: alloc::rc::Rc<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::rc::Rc<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::cell::Cell<usize>]
// cdb-check:    [Weak reference count] : 2 [Type: core::cell::Cell<usize>]

// cdb-command:dx w1,d
// cdb-check:w1,d             : 42 [Type: alloc::rc::Weak<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::rc::Weak<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::cell::Cell<usize>]
// cdb-check:    [Weak reference count] : 2 [Type: core::cell::Cell<usize>]

// cdb-command:dx a,d
// cdb-check:a,d              : 42 [Type: alloc::sync::Arc<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::sync::Arc<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::sync::atomic::AtomicUsize]
// cdb-check:    [Weak reference count] : 2 [Type: core::sync::atomic::AtomicUsize]

// cdb-command:dx a1,d
// cdb-check:a1,d             : 42 [Type: alloc::sync::Arc<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::sync::Arc<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::sync::atomic::AtomicUsize]
// cdb-check:    [Weak reference count] : 2 [Type: core::sync::atomic::AtomicUsize]

// cdb-command:dx w2,d
// cdb-check:w2,d             : 42 [Type: alloc::sync::Weak<i32>]
// cdb-check:    [<Raw View>]     [Type: alloc::sync::Weak<i32>]
// cdb-check:    [Reference count] : 2 [Type: core::sync::atomic::AtomicUsize]
// cdb-check:    [Weak reference count] : 2 [Type: core::sync::atomic::AtomicUsize]

use std::rc::Rc;
use std::sync::Arc;

fn main() {
    let r = Rc::new(42);
    let r1 = Rc::clone(&r);
    let w1 = Rc::downgrade(&r);

    let a = Arc::new(42);
    let a1 = Arc::clone(&a);
    let w2 = Arc::downgrade(&a);

    zzz(); // #break
}

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


<commit_before>#[macro_use]
extern crate cake;

build! {
    go_minotaur(compile_go_minotaur) => cmd!("target/cubes-go", "cubes-go/minotaur.json"),

    compile_go_minotaur() => cmd!(
        "go", "build", "-o", "target/cubes-go",
        "cubes-go/cubes.go",
        "cubes-go/doc.go",
        "cubes-go/cubes_test.go",
        "cubes-go/main.go",
        "cubes-go/sincos.go",
        "cubes-go/vec3.go",
        "cubes-go/vec3_test.go"
    ),
}
<commit_msg>Remove cake.<commit_after><|endoftext|>


<commit_before>#[crate_id(name = "tac", vers = "1.0.0", author = "Arcterus")];

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Arcterus <arcterus@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#[feature(macro_rules)];

extern crate getopts;

use std::io;
use std::os;

#[path = "../common/util.rs"]
mod util;

static NAME: &'static str = "tac";
static VERSION: &'static str = "1.0.0";

fn main() {
    let args = os::args();
    let program = args[0].clone();

    let opts = ~[
        getopts::optflag("b", "before", "attach the separator before instead of after"),
        getopts::optflag("r", "regex", "interpret the sequence as a regular expression (NOT IMPLEMENTED)"),
        getopts::optopt("s", "separator", "use STRING as the separator instead of newline", "STRING"),
        getopts::optflag("h", "help", "display this help and exit"),
        getopts::optflag("V", "version", "output version information and exit")
    ];
    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(f) => crash!(1, "{}", f.to_err_msg())
    };
    if matches.opt_present("help") {
        println!("tac {}", VERSION);
        println!("");
        println!("Usage:");
        println!("  {0:s} [OPTION]... [FILE]...", program);
        println!("");
        print!("{}", getopts::usage("Write each file to standard output, last line first.", opts));
    } else if matches.opt_present("version") {
        println!("tac {}", VERSION);
    } else {
        let before = matches.opt_present("b");
        let regex = matches.opt_present("r");
        let separator = match matches.opt_str("s") {
            Some(m) => m,
            None => ~"\n"
        };
        tac(matches.free, before, regex, separator);
    }
}

fn tac(filenames: ~[~str], before: bool, _: bool, separator: ~str) {
    for filename in filenames.move_iter() {
        let mut file = io::BufferedReader::new(
                           crash_if_err!(1, io::File::open(&Path::new(filename))));
        let data = crash_if_err!(1, file.read_to_str());
        let mut split_vec: ~[&str] = data.split_str(separator).collect();
        split_vec.pop();  // removes blank line that is inserted otherwise
        let rev: ~str = split_vec.rev_iter().fold(~"", |a, &b|
            a + if before {
                separator + b
            } else {
                b + separator
            }
        );
        print!("{}", rev);
    }
}
<commit_msg>tac: fix an issue with --separator<commit_after>#[crate_id(name = "tac", vers = "1.0.0", author = "Arcterus")];

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Arcterus <arcterus@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#[feature(macro_rules)];

extern crate getopts;

use std::io;
use std::os;

#[path = "../common/util.rs"]
mod util;

static NAME: &'static str = "tac";
static VERSION: &'static str = "1.0.0";

fn main() {
    let args = os::args();
    let program = args[0].clone();

    let opts = ~[
        getopts::optflag("b", "before", "attach the separator before instead of after"),
        getopts::optflag("r", "regex", "interpret the sequence as a regular expression (NOT IMPLEMENTED)"),
        getopts::optopt("s", "separator", "use STRING as the separator instead of newline", "STRING"),
        getopts::optflag("h", "help", "display this help and exit"),
        getopts::optflag("V", "version", "output version information and exit")
    ];
    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(f) => crash!(1, "{}", f.to_err_msg())
    };
    if matches.opt_present("help") {
        println!("tac {}", VERSION);
        println!("");
        println!("Usage:");
        println!("  {0:s} [OPTION]... [FILE]...", program);
        println!("");
        print!("{}", getopts::usage("Write each file to standard output, last line first.", opts));
    } else if matches.opt_present("version") {
        println!("tac {}", VERSION);
    } else {
        let before = matches.opt_present("b");
        let regex = matches.opt_present("r");
        let separator = match matches.opt_str("s") {
            Some(m) => {
                if m.len() == 0 {
                    crash!(1, "separator cannot be empty")
                } else {
                    m
                }
            }
            None => ~"\n"
        };
        tac(matches.free, before, regex, separator);
    }
}

fn tac(filenames: ~[~str], before: bool, _: bool, separator: ~str) {
    for filename in filenames.move_iter() {
        let mut file = io::BufferedReader::new(
                           crash_if_err!(1, io::File::open(&Path::new(filename))));
        let mut data = crash_if_err!(1, file.read_to_str());
        if data.ends_with("\n") {
            data.pop_char();  // removes blank line that is inserted otherwise
        }
        let split_vec: ~[&str] = data.split_str(separator).collect();
        let rev: ~str = split_vec.rev_iter().fold(~"", |a, &b|
            a + if before {
                separator + b
            } else {
                b + separator
            }
        );
        print!("{}", rev);
    }
}
<|endoftext|>


<commit_before>use super::formatter::FormatStr;

pub struct GeneralFormatter;

const line_len: usize = 80;

impl FormatStr for GeneralFormatter {
    fn format(&self, s: &str) -> String {
        let r = self.format_to_length(s);
        r
    }
}

impl GeneralFormatter {
    fn format_to_length(&self, s: &str) -> String {
        let mut r = s.to_owned();
        let words = r.split(" ");
        let mut result: String = String::new();
        let mut characters_since_newline: usize = 0;
        for word in words {
            if word != "\n" && !word.contains('\n') {
                characters_since_newline += word.len() + 1;
            } else {
                characters_since_newline = 0;
            }
            if characters_since_newline > line_len {
                // todo this does not work well when there already exists newlines on the line, e.g when tag formatting replaces <p> with \n
                result.push('\n');
                characters_since_newline = 0;
            }
            result.push_str(word);
            result.push(' ');
        }
        result
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::collections::btree_map::BTreeMap;

    #[test]
    fn test_line_len_formatting() {
        let f = GeneralFormatter;
        let s: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas maximus \
                       eleifend nibh, eget fringilla augue mattis ac. Nunc rhoncus dolor lorem, \
                       sed gravida mi tempus a. Maecenas libero nunc, mollis sit amet ex at, \
                       luctus bibendum dui. Donec dignissim, sapien nec commodo vehicula, tortor \
                       sem euismod leo, ac convallis risus.";
        let r = f.format_to_length(s);
        let mut counts = BTreeMap::new();
        for c in r.chars() {
            *counts.entry(c).or_insert(0) += 1;
        }
        let count = counts.get(&'\n').unwrap();
        assert_eq!(*count, s.len() / line_len);
        assert!(*count > 0);

    }
}
<commit_msg>Fixes the test and adds comment<commit_after>use super::formatter::FormatStr;

pub struct GeneralFormatter;

const line_len: usize = 80;

impl FormatStr for GeneralFormatter {
    fn format(&self, s: &str) -> String {
        let r = self.format_to_length(s);
        r
    }
}

impl GeneralFormatter {
    fn format_to_length(&self, s: &str) -> String {
        let mut r = s.to_owned();
        let words = r.split(" ");
        let mut result: String = String::new();
        let mut characters_since_newline: usize = 0;
        for word in words {
            if word != "\n" && !word.contains('\n') {
                characters_since_newline += word.len() + 1;
            } else {
                characters_since_newline = 0;
            }
            if characters_since_newline >= line_len { // Currently since the plus is before it'll
                result.push('\n');                    // add newline if the line would be over the limit and then push the word
                characters_since_newline = 0;
            }
            result.push_str(word);
            result.push(' ');
        }
        result
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::collections::btree_map::BTreeMap;

    #[test]
    fn test_line_len_formatting() {
        let f = GeneralFormatter;
        let s: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas maximus \
                       eleifend nibh, eget fringilla augue mattis ac. Nunc rhoncus dolor lorem, \
                       sed gravida mi tempus a. Maecenas libero nunc, mollis sit amet ex at, \
                       luctus bibendum dui. Donec dignissim, sapien nec commodo vehicula, tortor \
                       sem euismod leo, ac convallis risus.";
        let r = f.format_to_length(s);
        let mut counts = BTreeMap::new();
        for c in r.chars() {
            *counts.entry(c).or_insert(0) += 1;
        }
        let count = counts.get(&'\n').unwrap();
        assert_eq!(*count, (s.len() / line_len) - 1); // there's no newline at the end
        assert!(*count > 0);

    }
}
<|endoftext|>


<commit_before>//! Simple script to verify the coding style of this library
//!
//! ## How to run
//!
//! The first argument to this script is the directory to run on, so running
//! this script should be as simple as:
//!
//! ```notrust
//! rustc ci/style.rs
//! ./style src
//! ```
//!
//! ## Guidelines
//!
//! The current style is:
//!
//! * No trailing whitespace
//! * No tabs
//! * 80-character lines
//! * `extern` instead of `extern "C"`
//! * Specific module layout:
//!     1. use directives
//!     2. typedefs
//!     3. structs
//!     4. constants
//!     5. f! { ... } functions
//!     6. extern functions
//!     7. modules + pub use
//!
//! Things not verified:
//!
//! * alignment
//! * 4-space tabs
//! * leading colons on paths

use std::env;
use std::fs;
use std::io::prelude::*;
use std::path::Path;

macro_rules! t {
    ($e:expr) => (match $e {
        Ok(e) => e,
        Err(e) => panic!("{} failed with {}", stringify!($e), e),
    })
}

fn main() {
    let arg = env::args().skip(1).next().unwrap_or(".".to_string());

    let mut errors = Errors { errs: false };
    walk(Path::new(&arg), &mut errors);

    if errors.errs {
        panic!("found some lint errors");
    } else {
        println!("good style!");
    }
}

fn walk(path: &Path, err: &mut Errors) {
    for entry in t!(path.read_dir()).map(|e| t!(e)) {
        let path = entry.path();
        if t!(entry.file_type()).is_dir() {
            walk(&path, err);
            continue
        }

        let name = entry.file_name().into_string().unwrap();
        match &name[..] {
            n if !n.ends_with(".rs") => continue,

            "dox.rs" |
            "lib.rs" |
            "ctypes.rs" |
            "libc.rs" |
            "macros.rs" => continue,

            _ => {}
        }

        let mut contents = String::new();
        t!(t!(fs::File::open(&path)).read_to_string(&mut contents));

        check_style(&contents, &path, err);
    }
}

struct Errors {
    errs: bool,
}

#[derive(Clone, Copy, PartialEq)]
enum State {
    Start,
    Imports,
    Typedefs,
    Structs,
    Constants,
    FunctionDefinitions,
    Functions,
    Modules,
}

fn check_style(file: &str, path: &Path, err: &mut Errors) {
    let mut state = State::Start;
    let mut s_macros = 0;
    let mut f_macros = 0;
    let mut prev_blank = false;

    for (i, line) in file.lines().enumerate() {
        if line == "" {
            if prev_blank {
                err.error(path, i, "double blank line");
            }
            prev_blank = true;
        } else {
            prev_blank = false;
        }
        if line != line.trim_end() {
            err.error(path, i, "trailing whitespace");
        }
        if line.contains("\t") {
            err.error(path, i, "tab character");
        }
        if line.len() > 80 {
            err.error(path, i, "line longer than 80 chars");
        }
        if line.contains("extern \"C\"") {
            err.error(path, i, "use `extern` instead of `extern \"C\"");
        }
        if line.contains("#[cfg(") && !line.contains(" if ")
            && !(line.contains("target_endian") ||
                 line.contains("target_arch"))
        {
            if state != State::Structs {
                err.error(path, i, "use cfg_if! and submodules \
                                    instead of #[cfg]");
            }
        }

        let line = line.trim_start();
        let is_pub = line.starts_with("pub ");
        let line = if is_pub {&line[4..]} else {line};

        let line_state = if line.starts_with("use ") {
            if line.contains("c_void") {
                continue;
            }
            if is_pub {
                State::Modules
            } else {
                State::Imports
            }
        } else if line.starts_with("const ") {
            State::Constants
        } else if line.starts_with("type ") {
            State::Typedefs
        } else if line.starts_with("s! {") {
            s_macros += 1;
            State::Structs
        } else if line.starts_with("f! {") {
            f_macros += 1;
            State::FunctionDefinitions
        } else if line.starts_with("extern ") {
            State::Functions
        } else if line.starts_with("mod ") {
            State::Modules
        } else {
            continue
        };

        if state as usize > line_state as usize {
            err.error(path, i, &format!("{} found after {} when \
                                         it belongs before",
                                        line_state.desc(), state.desc()));
        }

        if f_macros == 2 {
            f_macros += 1;
            err.error(path, i, "multiple f! macros in one module");
        }
        if s_macros == 2 {
            s_macros += 1;
            err.error(path, i, "multiple s! macros in one module");
        }

        state = line_state;
    }
}

impl State {
    fn desc(&self) -> &str {
        match *self {
            State::Start => "start",
            State::Imports => "import",
            State::Typedefs => "typedef",
            State::Structs => "struct",
            State::Constants => "constant",
            State::FunctionDefinitions => "function definition",
            State::Functions => "extern function",
            State::Modules => "module",
        }
    }
}

impl Errors {
    fn error(&mut self, path: &Path, line: usize, msg: &str) {
        self.errs = true;
        println!("{}:{} - {}", path.display(), line + 1, msg);
    }
}
<commit_msg>Do not require using extern instead of extern C<commit_after>//! Simple script to verify the coding style of this library
//!
//! ## How to run
//!
//! The first argument to this script is the directory to run on, so running
//! this script should be as simple as:
//!
//! ```notrust
//! rustc ci/style.rs
//! ./style src
//! ```
//!
//! ## Guidelines
//!
//! The current style is:
//!
//! * No trailing whitespace
//! * No tabs
//! * 80-character lines
//! * Specific module layout:
//!     1. use directives
//!     2. typedefs
//!     3. structs
//!     4. constants
//!     5. f! { ... } functions
//!     6. extern functions
//!     7. modules + pub use
//!
//! Things not verified:
//!
//! * alignment
//! * 4-space tabs
//! * leading colons on paths

use std::env;
use std::fs;
use std::io::prelude::*;
use std::path::Path;

macro_rules! t {
    ($e:expr) => (match $e {
        Ok(e) => e,
        Err(e) => panic!("{} failed with {}", stringify!($e), e),
    })
}

fn main() {
    let arg = env::args().skip(1).next().unwrap_or(".".to_string());

    let mut errors = Errors { errs: false };
    walk(Path::new(&arg), &mut errors);

    if errors.errs {
        panic!("found some lint errors");
    } else {
        println!("good style!");
    }
}

fn walk(path: &Path, err: &mut Errors) {
    for entry in t!(path.read_dir()).map(|e| t!(e)) {
        let path = entry.path();
        if t!(entry.file_type()).is_dir() {
            walk(&path, err);
            continue
        }

        let name = entry.file_name().into_string().unwrap();
        match &name[..] {
            n if !n.ends_with(".rs") => continue,

            "dox.rs" |
            "lib.rs" |
            "ctypes.rs" |
            "libc.rs" |
            "macros.rs" => continue,

            _ => {}
        }

        let mut contents = String::new();
        t!(t!(fs::File::open(&path)).read_to_string(&mut contents));

        check_style(&contents, &path, err);
    }
}

struct Errors {
    errs: bool,
}

#[derive(Clone, Copy, PartialEq)]
enum State {
    Start,
    Imports,
    Typedefs,
    Structs,
    Constants,
    FunctionDefinitions,
    Functions,
    Modules,
}

fn check_style(file: &str, path: &Path, err: &mut Errors) {
    let mut state = State::Start;
    let mut s_macros = 0;
    let mut f_macros = 0;
    let mut prev_blank = false;

    for (i, line) in file.lines().enumerate() {
        if line == "" {
            if prev_blank {
                err.error(path, i, "double blank line");
            }
            prev_blank = true;
        } else {
            prev_blank = false;
        }
        if line != line.trim_end() {
            err.error(path, i, "trailing whitespace");
        }
        if line.contains("\t") {
            err.error(path, i, "tab character");
        }
        if line.len() > 80 {
            err.error(path, i, "line longer than 80 chars");
        }
        if line.contains("#[cfg(") && !line.contains(" if ")
            && !(line.contains("target_endian") ||
                 line.contains("target_arch"))
        {
            if state != State::Structs {
                err.error(path, i, "use cfg_if! and submodules \
                                    instead of #[cfg]");
            }
        }

        let line = line.trim_start();
        let is_pub = line.starts_with("pub ");
        let line = if is_pub {&line[4..]} else {line};

        let line_state = if line.starts_with("use ") {
            if line.contains("c_void") {
                continue;
            }
            if is_pub {
                State::Modules
            } else {
                State::Imports
            }
        } else if line.starts_with("const ") {
            State::Constants
        } else if line.starts_with("type ") {
            State::Typedefs
        } else if line.starts_with("s! {") {
            s_macros += 1;
            State::Structs
        } else if line.starts_with("f! {") {
            f_macros += 1;
            State::FunctionDefinitions
        } else if line.starts_with("extern ") {
            State::Functions
        } else if line.starts_with("mod ") {
            State::Modules
        } else {
            continue
        };

        if state as usize > line_state as usize {
            err.error(path, i, &format!("{} found after {} when \
                                         it belongs before",
                                        line_state.desc(), state.desc()));
        }

        if f_macros == 2 {
            f_macros += 1;
            err.error(path, i, "multiple f! macros in one module");
        }
        if s_macros == 2 {
            s_macros += 1;
            err.error(path, i, "multiple s! macros in one module");
        }

        state = line_state;
    }
}

impl State {
    fn desc(&self) -> &str {
        match *self {
            State::Start => "start",
            State::Imports => "import",
            State::Typedefs => "typedef",
            State::Structs => "struct",
            State::Constants => "constant",
            State::FunctionDefinitions => "function definition",
            State::Functions => "extern function",
            State::Modules => "module",
        }
    }
}

impl Errors {
    fn error(&mut self, path: &Path, line: usize, msg: &str) {
        self.errs = true;
        println!("{}:{} - {}", path.display(), line + 1, msg);
    }
}
<|endoftext|>


<commit_before>extern crate time;

extern crate hyper;
extern crate iron;
extern crate iron_test;
extern crate staticfile;

#[cfg(feature = "cache")]
mod cache {
    use time;
    use time::{Timespec};

    #[cfg(feature = "cache")]
    use std::time::Duration;

    use iron::Headers;
    use iron::status::Status;
    use iron::headers::HttpDate;
    use hyper::header::{IfModifiedSince, CacheControl, CacheDirective, LastModified};
    use iron_test::ProjectBuilder;
    use iron_test::request;
    use staticfile::Static;

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_return_cache_headers() {
        let p = ProjectBuilder::new("example").file("file1.html", "this is file1");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let iron_res = request::get("http://localhost:3000/file1.html", Headers::new(), &st);

        match iron_res {
            Ok(res) => {
                assert!(res.headers.get::<CacheControl>().is_some());
                assert!(res.headers.get::<LastModified>().is_some());
                let cache = res.headers.get::<CacheControl>().unwrap();
                let directives = vec![CacheDirective::Public, CacheDirective::MaxAge(2592000)];
                assert_eq!(*cache, CacheControl(directives));
            },
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_return_the_file_if_client_sends_no_modified_time() {
        let p = ProjectBuilder::new("example").file("file1.html", "this is file1");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let iron_res = request::get("http://localhost:3000/file1.html", Headers::new(), &st);

        match iron_res {
            Ok(res) => assert_eq!(res.status.unwrap(), Status::Ok),
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_return_the_file_if_client_has_old_version() {
        let p = ProjectBuilder::new("example").file("file1.html", "this is file1");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));

        let now = time::get_time();
        let one_hour_ago = Timespec::new(now.sec - 3600, now.nsec);
        let mut headers = Headers::new();
        headers.set(IfModifiedSince(HttpDate(time::at(one_hour_ago))));
        let iron_res = request::get("http://localhost:3000/file1.html", headers, &st);

        match iron_res {
            Ok(res) => assert_eq!(res.status.unwrap(), Status::Ok),
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_return_304_if_client_has_file_cached() {
        let p = ProjectBuilder::new("example").file("file1.html", "this is file1");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let mut headers = Headers::new();
        headers.set(IfModifiedSince(HttpDate(time::now_utc())));
        let iron_res = request::get("http://localhost:3000/file1.html", headers, &st);

        match iron_res {
            Ok(res) => assert_eq!(res.status.unwrap(), Status::NotModified),
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_cache_index_html_for_directory_path() {
        let p = ProjectBuilder::new("example").file("dir/index.html", "this is index");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let mut headers = Headers::new();
        headers.set(IfModifiedSince(HttpDate(time::now_utc())));
        let iron_res = request::get("http://localhost:3000/dir/", headers, &st);

        match iron_res {
            Ok(res) => assert_eq!(res.status.unwrap(), Status::NotModified),
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_defer_to_static_handler_if_directory_misses_trailing_slash() {
        let p = ProjectBuilder::new("example").file("dir/index.html", "this is index");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let mut headers = Headers::new();
        headers.set(IfModifiedSince(HttpDate(time::now_utc())));
        let iron_res = request::get("http://localhost:3000/dir", headers, &st);

        match iron_res {
            Ok(res) => {
                assert_eq!(res.status.unwrap(), Status::MovedPermanently);
                assert!(res.headers.get::<LastModified>().is_none());
            },
            Err(e) => panic!("{}", e)
        }
    }
}
<commit_msg>Remove execute bit from tests/cache.rs.<commit_after>extern crate time;

extern crate hyper;
extern crate iron;
extern crate iron_test;
extern crate staticfile;

#[cfg(feature = "cache")]
mod cache {
    use time;
    use time::{Timespec};

    #[cfg(feature = "cache")]
    use std::time::Duration;

    use iron::Headers;
    use iron::status::Status;
    use iron::headers::HttpDate;
    use hyper::header::{IfModifiedSince, CacheControl, CacheDirective, LastModified};
    use iron_test::ProjectBuilder;
    use iron_test::request;
    use staticfile::Static;

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_return_cache_headers() {
        let p = ProjectBuilder::new("example").file("file1.html", "this is file1");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let iron_res = request::get("http://localhost:3000/file1.html", Headers::new(), &st);

        match iron_res {
            Ok(res) => {
                assert!(res.headers.get::<CacheControl>().is_some());
                assert!(res.headers.get::<LastModified>().is_some());
                let cache = res.headers.get::<CacheControl>().unwrap();
                let directives = vec![CacheDirective::Public, CacheDirective::MaxAge(2592000)];
                assert_eq!(*cache, CacheControl(directives));
            },
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_return_the_file_if_client_sends_no_modified_time() {
        let p = ProjectBuilder::new("example").file("file1.html", "this is file1");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let iron_res = request::get("http://localhost:3000/file1.html", Headers::new(), &st);

        match iron_res {
            Ok(res) => assert_eq!(res.status.unwrap(), Status::Ok),
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_return_the_file_if_client_has_old_version() {
        let p = ProjectBuilder::new("example").file("file1.html", "this is file1");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));

        let now = time::get_time();
        let one_hour_ago = Timespec::new(now.sec - 3600, now.nsec);
        let mut headers = Headers::new();
        headers.set(IfModifiedSince(HttpDate(time::at(one_hour_ago))));
        let iron_res = request::get("http://localhost:3000/file1.html", headers, &st);

        match iron_res {
            Ok(res) => assert_eq!(res.status.unwrap(), Status::Ok),
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_return_304_if_client_has_file_cached() {
        let p = ProjectBuilder::new("example").file("file1.html", "this is file1");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let mut headers = Headers::new();
        headers.set(IfModifiedSince(HttpDate(time::now_utc())));
        let iron_res = request::get("http://localhost:3000/file1.html", headers, &st);

        match iron_res {
            Ok(res) => assert_eq!(res.status.unwrap(), Status::NotModified),
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_cache_index_html_for_directory_path() {
        let p = ProjectBuilder::new("example").file("dir/index.html", "this is index");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let mut headers = Headers::new();
        headers.set(IfModifiedSince(HttpDate(time::now_utc())));
        let iron_res = request::get("http://localhost:3000/dir/", headers, &st);

        match iron_res {
            Ok(res) => assert_eq!(res.status.unwrap(), Status::NotModified),
            Err(e) => panic!("{}", e)
        }
    }

    #[cfg(feature = "cache")]
    #[test]
    fn it_should_defer_to_static_handler_if_directory_misses_trailing_slash() {
        let p = ProjectBuilder::new("example").file("dir/index.html", "this is index");
        p.build();

        let st = Static::new(p.root().clone()).cache(Duration::from_secs(30*24*60*60));
        let mut headers = Headers::new();
        headers.set(IfModifiedSince(HttpDate(time::now_utc())));
        let iron_res = request::get("http://localhost:3000/dir", headers, &st);

        match iron_res {
            Ok(res) => {
                assert_eq!(res.status.unwrap(), Status::MovedPermanently);
                assert!(res.headers.get::<LastModified>().is_none());
            },
            Err(e) => panic!("{}", e)
        }
    }
}
<|endoftext|>


<commit_before>use crates_index_diff::*;
use git2::Reference;
use std::{collections::HashMap, env, path::PathBuf};
use tempdir::TempDir;

const NUM_VERSIONS_AT_RECENT_COMMIT: usize = 39752;
const REV_ONE_ADDED: &'static str = "615c9c41942a3ba13e088fbcb1470c61b169a187";
const REV_ONE_YANKED: &'static str = "8cf8fbad7876586ced34c4b778f6a80fadd2a59b";
const REV_ONE_UNYANKED: &'static str = "f8cb00181";

#[test]
#[ignore] // This test takes too long for my taste, this library is stable by now
fn clone_if_needed() {
    let tmp = TempDir::new("new-index").unwrap();
    Index::from_path_or_cloned(tmp.path()).expect("successful clone to be created");
    Index::from_path_or_cloned(tmp.path()).expect("second instance re-uses existing clone");
}

fn make_index() -> (Index, TempDir) {
    let tmp = TempDir::new("new-index").unwrap();
    let index = Index::from_path_or_cloned(
        env::var("CRATES_INDEX_DIFF_TEST_EXISTING_INDEX")
            .map(PathBuf::from)
            .unwrap_or(tmp.path().to_owned()),
    )
    .expect("successful clone");
    (index, tmp)
}

fn origin_master_of(index: &Index) -> Reference<'_> {
    index
        .repository()
        .find_reference("refs/remotes/origin/master")
        .unwrap()
}

#[test]
fn quick_changes_since_last_fetch() {
    let (mut index, _tmp) = make_index();
    index.seen_ref_name = "refs/our-test-ref_because-we-can_hidden-from-ui";
    index
        .last_seen_reference()
        .and_then(|mut r| r.delete())
        .ok();
    let num_changes_since_first_commit = index.fetch_changes().unwrap().len();
    assert!(
        num_changes_since_first_commit >= NUM_VERSIONS_AT_RECENT_COMMIT,
        "should have fetched enough commits"
    );
    let mut seen_marker_ref = index
        .last_seen_reference()
        .expect("must be created/update now");
    assert!(
        seen_marker_ref == origin_master_of(&index),
        "should update the last_seen_reference to latest remote origin master"
    );

    // reset to previous one
    seen_marker_ref
        .set_target(
            index
                .repository()
                .revparse_single(REV_ONE_UNYANKED)
                .unwrap()
                .id(),
            "resetting to previous commit",
        )
        .expect("reset success");
    let num_seen_after_reset = index.fetch_changes().unwrap().len();
    let origin_master = origin_master_of(&index);
    assert!(
        seen_marker_ref == origin_master,
        "{} ({}) != {} ({})",
        seen_marker_ref.name().unwrap(),
        seen_marker_ref.peel_to_commit().unwrap().id(),
        origin_master.name().unwrap(),
        origin_master.peel_to_commit().unwrap().id()
    );
    assert!(num_seen_after_reset < num_changes_since_first_commit);
    assert!(num_seen_after_reset > 1000);

    // nothing if there was no change
    assert_eq!(index.fetch_changes().unwrap().len(), 0);
}

#[test]
fn peek_changes_since_last_fetch() {
    let (mut index, _tmp) = make_index();
    index.seen_ref_name = "refs/our-test-ref_because-we-can_hidden-from-ui";
    index
        .last_seen_reference()
        .and_then(|mut r| r.delete())
        .ok();
    let (changes, last_seen_rev) = index.peek_changes().unwrap();
    assert!(changes.len() >= NUM_VERSIONS_AT_RECENT_COMMIT);
    assert_eq!(
        last_seen_rev,
        origin_master_of(&index).target().unwrap(),
        "last seen reference should be origin"
    );
    assert!(
        index.last_seen_reference().is_err(),
        "the last-seen reference has not been created (or updated, but we don't test that yet)"
    );
}

fn changes_of(index: &Index, commit: &str) -> Vec<CrateVersion> {
    index
        .changes(format!("{}~1^{{tree}}", commit), format!("{}", commit))
        .expect("id to be valid and diff OK")
}

#[test]
fn quick_traverse_unyanked_crates() {
    //    [CrateVersion { dependencies: [Dependency { name: "freetype-rs", required_version: "^0.11", features: [], optional: false, default_features: true, target: None, kind: Some("normal"), package: None }, Dependency { name: "gfx", required_version: "^0.12.2", features: [], optional: false, default_features: true, target: None, kind: Some("normal"), package: None }, Dependency { name: "glutin", required_version: "^0.6", features: [], optional: false, default_features: true, target: None, kind: Some("dev"), package: None }, Dependency { name: "gfx_window_glutin", required_version: "^0.12", features: [], optional: false, default_features: true, target: None, kind: Some("dev"), package: None }] }]
    let (index, _tmp) = make_index();

    let crates = changes_of(&index, REV_ONE_UNYANKED);
    assert_eq!(
        crates,
        vec![CrateVersion {
            name: "gfx_text".to_owned(),
            kind: ChangeKind::Added,
            version: "0.13.2".to_owned(),
            dependencies: vec![
                Dependency {
                    name: "freetype-rs".into(),
                    required_version: "^0.11".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("normal".into()),
                    package: None
                },
                Dependency {
                    name: "gfx".into(),
                    required_version: "^0.12.2".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("normal".into()),
                    package: None
                },
                Dependency {
                    name: "glutin".into(),
                    required_version: "^0.6".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("dev".into()),
                    package: None
                },
                Dependency {
                    name: "gfx_window_glutin".into(),
                    required_version: "^0.12".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("dev".into()),
                    package: None
                }
            ],
            features: {
                let mut h = HashMap::new();
                h.insert("default".to_string(), vec!["include-font".to_string()]);
                h.insert("include-font".into(), vec![]);
                h
            },
            checksum: "d0b1240e3627e646f69685ddd3e7d83dd3ff3d586afe83bf3679082028183f2d".into(),
        }]
    );
}

#[test]
fn quick_traverse_yanked_crates() {
    let (index, _tmp) = make_index();

    let crates = changes_of(&index, REV_ONE_YANKED);
    assert_eq!(
        crates,
        vec![CrateVersion {
            name: "sha3".to_owned(),
            kind: ChangeKind::Yanked,
            version: "0.0.0".to_owned(),
            dependencies: Vec::new(),
            features: HashMap::new(),
            checksum: "dbba9d72d3d04e2167fb9c76ce22aed118eb003727bbe59774b9bf3603fa1f43".into(),
        }]
    );
}

#[test]
fn quick_traverse_added_crates() {
    let (index, _tmp) = make_index();
    assert_eq!(index.changes("foo", REV_ONE_ADDED).is_err(), true);
    assert_eq!(index.changes(REV_ONE_ADDED, "bar").is_err(), true);

    let crates = changes_of(&index, REV_ONE_ADDED);
    assert_eq!(
        crates,
        vec![CrateVersion {
            name: "rpwg".to_owned(),
            kind: ChangeKind::Added,
            version: "0.1.0".to_owned(),
            dependencies: vec![
                Dependency {
                    name: "rand".into(),
                    required_version: "^0.3".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("normal".into()),
                    package: None
                },
                Dependency {
                    name: "clap".into(),
                    required_version: "^2.19".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("normal".into()),
                    package: None
                }
            ],
            features: HashMap::new(),
            checksum: "14437a3702699dba0c49ddc401a0529898e83f8b769348549985a0f4d818d3ca".into(),
        }]
    );
}
<commit_msg>ignore certain tests fo now until new hashes are found that work<commit_after>use crates_index_diff::*;
use git2::Reference;
use std::{collections::HashMap, env, path::PathBuf};
use tempdir::TempDir;

const NUM_VERSIONS_AT_RECENT_COMMIT: usize = 39752;
// TODO: find new hashes for the ones below with similar states as they don't exist anymore. See ignored tests.
const REV_ONE_ADDED: &'static str = "615c9c41942a3ba13e088fbcb1470c61b169a187";
const REV_ONE_YANKED: &'static str = "8cf8fbad7876586ced34c4b778f6a80fadd2a59b";
const REV_ONE_UNYANKED: &'static str = "f8cb00181";

#[test]
#[ignore] // This test takes too long for my taste, this library is stable by now
fn clone_if_needed() {
    let tmp = TempDir::new("new-index").unwrap();
    Index::from_path_or_cloned(tmp.path()).expect("successful clone to be created");
    Index::from_path_or_cloned(tmp.path()).expect("second instance re-uses existing clone");
}

fn make_index() -> (Index, TempDir) {
    let tmp = TempDir::new("new-index").unwrap();
    let index = Index::from_path_or_cloned(
        env::var("CRATES_INDEX_DIFF_TEST_EXISTING_INDEX")
            .map(PathBuf::from)
            .unwrap_or(tmp.path().to_owned()),
    )
    .expect("successful clone");
    (index, tmp)
}

fn origin_master_of(index: &Index) -> Reference<'_> {
    index
        .repository()
        .find_reference("refs/remotes/origin/master")
        .unwrap()
}

#[test]
#[ignore]
fn quick_changes_since_last_fetch() {
    let (mut index, _tmp) = make_index();
    index.seen_ref_name = "refs/our-test-ref_because-we-can_hidden-from-ui";
    index
        .last_seen_reference()
        .and_then(|mut r| r.delete())
        .ok();
    let num_changes_since_first_commit = index.fetch_changes().unwrap().len();
    assert!(
        num_changes_since_first_commit >= NUM_VERSIONS_AT_RECENT_COMMIT,
        "should have fetched enough commits"
    );
    let mut seen_marker_ref = index
        .last_seen_reference()
        .expect("must be created/update now");
    assert!(
        seen_marker_ref == origin_master_of(&index),
        "should update the last_seen_reference to latest remote origin master"
    );

    // reset to previous one
    seen_marker_ref
        .set_target(
            index
                .repository()
                .revparse_single(REV_ONE_UNYANKED)
                .unwrap()
                .id(),
            "resetting to previous commit",
        )
        .expect("reset success");
    let num_seen_after_reset = index.fetch_changes().unwrap().len();
    let origin_master = origin_master_of(&index);
    assert!(
        seen_marker_ref == origin_master,
        "{} ({}) != {} ({})",
        seen_marker_ref.name().unwrap(),
        seen_marker_ref.peel_to_commit().unwrap().id(),
        origin_master.name().unwrap(),
        origin_master.peel_to_commit().unwrap().id()
    );
    assert!(num_seen_after_reset < num_changes_since_first_commit);
    assert!(num_seen_after_reset > 1000);

    // nothing if there was no change
    assert_eq!(index.fetch_changes().unwrap().len(), 0);
}

#[test]
fn peek_changes_since_last_fetch() {
    let (mut index, _tmp) = make_index();
    index.seen_ref_name = "refs/our-test-ref_because-we-can_hidden-from-ui";
    index
        .last_seen_reference()
        .and_then(|mut r| r.delete())
        .ok();
    let (changes, last_seen_rev) = index.peek_changes().unwrap();
    assert!(changes.len() >= NUM_VERSIONS_AT_RECENT_COMMIT);
    assert_eq!(
        last_seen_rev,
        origin_master_of(&index).target().unwrap(),
        "last seen reference should be origin"
    );
    assert!(
        index.last_seen_reference().is_err(),
        "the last-seen reference has not been created (or updated, but we don't test that yet)"
    );
}

fn changes_of(index: &Index, commit: &str) -> Vec<CrateVersion> {
    index
        .changes(format!("{}~1^{{tree}}", commit), format!("{}", commit))
        .expect("id to be valid and diff OK")
}

#[test]
#[ignore]
fn quick_traverse_unyanked_crates() {
    //    [CrateVersion { dependencies: [Dependency { name: "freetype-rs", required_version: "^0.11", features: [], optional: false, default_features: true, target: None, kind: Some("normal"), package: None }, Dependency { name: "gfx", required_version: "^0.12.2", features: [], optional: false, default_features: true, target: None, kind: Some("normal"), package: None }, Dependency { name: "glutin", required_version: "^0.6", features: [], optional: false, default_features: true, target: None, kind: Some("dev"), package: None }, Dependency { name: "gfx_window_glutin", required_version: "^0.12", features: [], optional: false, default_features: true, target: None, kind: Some("dev"), package: None }] }]
    let (index, _tmp) = make_index();

    let crates = changes_of(&index, REV_ONE_UNYANKED);
    assert_eq!(
        crates,
        vec![CrateVersion {
            name: "gfx_text".to_owned(),
            kind: ChangeKind::Added,
            version: "0.13.2".to_owned(),
            dependencies: vec![
                Dependency {
                    name: "freetype-rs".into(),
                    required_version: "^0.11".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("normal".into()),
                    package: None
                },
                Dependency {
                    name: "gfx".into(),
                    required_version: "^0.12.2".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("normal".into()),
                    package: None
                },
                Dependency {
                    name: "glutin".into(),
                    required_version: "^0.6".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("dev".into()),
                    package: None
                },
                Dependency {
                    name: "gfx_window_glutin".into(),
                    required_version: "^0.12".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("dev".into()),
                    package: None
                }
            ],
            features: {
                let mut h = HashMap::new();
                h.insert("default".to_string(), vec!["include-font".to_string()]);
                h.insert("include-font".into(), vec![]);
                h
            },
            checksum: "d0b1240e3627e646f69685ddd3e7d83dd3ff3d586afe83bf3679082028183f2d".into(),
        }]
    );
}

#[test]
#[ignore]
fn quick_traverse_yanked_crates() {
    let (index, _tmp) = make_index();

    let crates = changes_of(&index, REV_ONE_YANKED);
    assert_eq!(
        crates,
        vec![CrateVersion {
            name: "sha3".to_owned(),
            kind: ChangeKind::Yanked,
            version: "0.0.0".to_owned(),
            dependencies: Vec::new(),
            features: HashMap::new(),
            checksum: "dbba9d72d3d04e2167fb9c76ce22aed118eb003727bbe59774b9bf3603fa1f43".into(),
        }]
    );
}

#[test]
#[ignore]
fn quick_traverse_added_crates() {
    let (index, _tmp) = make_index();
    assert_eq!(index.changes("foo", REV_ONE_ADDED).is_err(), true);
    assert_eq!(index.changes(REV_ONE_ADDED, "bar").is_err(), true);

    let crates = changes_of(&index, REV_ONE_ADDED);
    assert_eq!(
        crates,
        vec![CrateVersion {
            name: "rpwg".to_owned(),
            kind: ChangeKind::Added,
            version: "0.1.0".to_owned(),
            dependencies: vec![
                Dependency {
                    name: "rand".into(),
                    required_version: "^0.3".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("normal".into()),
                    package: None
                },
                Dependency {
                    name: "clap".into(),
                    required_version: "^2.19".into(),
                    features: vec![],
                    optional: false,
                    default_features: true,
                    target: None,
                    kind: Some("normal".into()),
                    package: None
                }
            ],
            features: HashMap::new(),
            checksum: "14437a3702699dba0c49ddc401a0529898e83f8b769348549985a0f4d818d3ca".into(),
        }]
    );
}
<|endoftext|>


<commit_before>// Copyright 2017 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.

// See Cargo.toml for a comment explaining this crate.
#![allow(unused_extern_crates)]

extern crate bitflags;
extern crate log;
<commit_msg>[nll] librustc_cratesio_shim: enable feature(nll) for bootstrap<commit_after>// Copyright 2017 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.

// See Cargo.toml for a comment explaining this crate.
#![allow(unused_extern_crates)]

#![cfg_attr(not(stage0), feature(nll))]

extern crate bitflags;
extern crate log;
<|endoftext|>


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

#![feature(phase)]

#[phase(plugin, link)] extern crate itertools;

extern crate test;

use std::iter::order;
use std::iter::AdditiveIterator;
use itertools::Itertools;
use itertools::Interleave;

use itertools as it;

#[test]
fn product2() {
    let s = "αβ";

    let mut prod = iproduct!(s.chars(), range(0, 2i));
    assert!(prod.next() == Some(('α', 0)));
    assert!(prod.next() == Some(('α', 1)));
    assert!(prod.next() == Some(('β', 0)));
    assert!(prod.next() == Some(('β', 1)));
    assert!(prod.next() == None);
}

#[test]
fn product3() {
    let mut prod = iproduct!(range(0, 3i), range(0, 2i), range(0, 2i));
    assert_eq!(prod.size_hint(), (12, Some(12)));
    let v = prod.collect::<Vec<_>>();
    for i in range(0,3i) {
        for j in range(0, 2i) {
            for k in range(0, 2i) {
                assert!((i, j, k) == v[(i * 2 * 2 + j * 2 + k) as uint]);
            }
        }
    }
    for (a, b, c, d) in iproduct!(range(0, 3i), range(0, 2i), range(0, 2i), range(0, 3i)) {
        /* test compiles */
    }
}

#[test]
fn izip3() {
    let mut zip = izip!(range(0, 3u), range(0, 2i), range(0, 2i8));
    for i in range(0, 2i) {
        assert!((i as uint, i, i as i8) == zip.next().unwrap());
    }
    assert!(zip.next().is_none());

    let xs: [int, ..0] = [];
    let mut zip = izip!(range(0, 3u), range(0, 2i), range(0, 2i8), xs.iter());
    assert!(zip.next().is_none());

    for (a, b, c, d) in izip!(range(0, 3i), range(0, 2i), range(0, 2i), range(0, 3i)) {
        /* test compiles */
    }
}

#[test]
fn fn_map() {
    let xs = [0, 1, 2i];
    fn mapper(x: &int) -> String { x.to_string() }
    let it = xs.iter().fn_map(mapper);
    let jt = it.clone();
    assert!(it.zip(jt).all(|(x,y)| x == y));
}

#[test]
fn write_to() {
    let xs = [7i, 9, 8];
    let mut ys = [0i, ..5];
    let cnt = it::write(ys.iter_mut(), xs.iter().map(|x| *x));
    assert!(cnt == xs.len());
    assert!(ys == [7i, 9, 8, 0, 0]);

    let cnt = it::write(ys.iter_mut(), range(0,10i));
    assert!(cnt == ys.len());
    assert!(ys == [0, 1, 2, 3, 4]);
}

#[test]
fn interleave() {
    let xs: [u8, ..0]  = [];
    let ys = [7u8, 9, 8, 10];
    let zs = [2u8, 77];
    let it = Interleave::new(xs.iter(), ys.iter());
    assert!(order::eq(it, ys.iter()));

    let rs = [7u8, 2, 9, 77, 8, 10];
    let it = Interleave::new(ys.iter(), zs.iter());
    assert!(order::eq(it, rs.iter()));
}

#[test]
fn times() {
    assert!(it::times(0).count() == 0);
    assert!(it::times(5).count() == 5);
}

#[test]
fn drain() {
    let xs = [1i,2,3];
    let mut sum = 0;
    xs.iter().map(|elt| sum += *elt).drain();
    assert!(sum == 6);
}

#[test]
fn apply() {
    let xs = [1i, 2, 3];
    let mut sum = 0;
    xs.iter().apply(|elt| sum += *elt);
    assert!(sum == 6);
}

#[test]
fn dropn() {
    let xs = [1i, 2, 3];
    let mut it = xs.iter();
    assert!(it.dropn(2) == 2);
    assert!(it.next().is_some());
    assert!(it.next().is_none());
    let mut it = xs.iter();
    assert!(it.dropn(5) == 3);
    assert!(it.next().is_none());
}

#[test]
fn intersperse() {
    let xs = ["a", "", "b", "c"];
    let v: Vec<&str> = xs.iter().map(|x| x.clone()).intersperse(", ").collect();
    let text = v.concat();
    assert_eq!(text, "a, , b, c".to_string());

    let ys = [0, 1, 2, 3i];
    let mut it = ys.slice_to(0).iter().map(|x| *x).intersperse(1i);
    assert!(it.next() == None);
}

#[test]
fn linspace() {
    let mut iter = it::linspace::<f32>(0., 2., 3);
    assert_eq!(iter.next(), Some(0.0));
    assert_eq!(iter.next(), Some(1.0));
    assert_eq!(iter.next(), Some(2.0));
    assert_eq!(iter.next(), None);

    let mut iter = it::linspace::<f32>(0., -2., 4);
    assert_eq!(iter.next(), Some(0.));
    assert_eq!(iter.next(), Some(-0.666666666667));
    assert_eq!(iter.next(), Some(-1.333333333333));
    assert_eq!(iter.next(), Some(-2.));
    assert_eq!(iter.next(), None);

    let mut iter = it::linspace::<f32>(0., 1., 1);
    assert_eq!(iter.next(), Some(0.));
    assert_eq!(iter.next(), None);

    let mut iter = it::linspace::<f32>(0., 1., 0);
    assert_eq!(iter.next(), None);
}
<commit_msg>tests: Fix warnings<commit_after>//! Licensed under the Apache License, Version 2.0
//! http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
//! http://opensource.org/licenses/MIT, at your
//! option. This file may not be copied, modified, or distributed
//! except according to those terms.

#![feature(phase)]

#[phase(plugin, link)] extern crate itertools;

extern crate test;

use std::iter::order;
use itertools::Itertools;
use itertools::Interleave;

use itertools as it;

#[test]
fn product2() {
    let s = "αβ";

    let mut prod = iproduct!(s.chars(), range(0, 2i));
    assert!(prod.next() == Some(('α', 0)));
    assert!(prod.next() == Some(('α', 1)));
    assert!(prod.next() == Some(('β', 0)));
    assert!(prod.next() == Some(('β', 1)));
    assert!(prod.next() == None);
}

#[test]
fn product3() {
    let prod = iproduct!(range(0, 3i), range(0, 2i), range(0, 2i));
    assert_eq!(prod.size_hint(), (12, Some(12)));
    let v = prod.collect::<Vec<_>>();
    for i in range(0,3i) {
        for j in range(0, 2i) {
            for k in range(0, 2i) {
                assert!((i, j, k) == v[(i * 2 * 2 + j * 2 + k) as uint]);
            }
        }
    }
    for (_, _, _, _) in iproduct!(range(0, 3i), range(0, 2i), range(0, 2i), range(0, 3i)) {
        /* test compiles */
    }
}

#[test]
fn izip3() {
    let mut zip = izip!(range(0, 3u), range(0, 2i), range(0, 2i8));
    for i in range(0, 2i) {
        assert!((i as uint, i, i as i8) == zip.next().unwrap());
    }
    assert!(zip.next().is_none());

    let xs: [int, ..0] = [];
    let mut zip = izip!(range(0, 3u), range(0, 2i), range(0, 2i8), xs.iter());
    assert!(zip.next().is_none());

    for (_, _, _, _) in izip!(range(0, 3i), range(0, 2i), range(0, 2i), range(0, 3i)) {
        /* test compiles */
    }
}

#[test]
fn fn_map() {
    let xs = [0, 1, 2i];
    fn mapper(x: &int) -> String { x.to_string() }
    let it = xs.iter().fn_map(mapper);
    let jt = it.clone();
    assert!(it.zip(jt).all(|(x,y)| x == y));
}

#[test]
fn write_to() {
    let xs = [7i, 9, 8];
    let mut ys = [0i, ..5];
    let cnt = it::write(ys.iter_mut(), xs.iter().map(|x| *x));
    assert!(cnt == xs.len());
    assert!(ys == [7i, 9, 8, 0, 0]);

    let cnt = it::write(ys.iter_mut(), range(0,10i));
    assert!(cnt == ys.len());
    assert!(ys == [0, 1, 2, 3, 4]);
}

#[test]
fn interleave() {
    let xs: [u8, ..0]  = [];
    let ys = [7u8, 9, 8, 10];
    let zs = [2u8, 77];
    let it = Interleave::new(xs.iter(), ys.iter());
    assert!(order::eq(it, ys.iter()));

    let rs = [7u8, 2, 9, 77, 8, 10];
    let it = Interleave::new(ys.iter(), zs.iter());
    assert!(order::eq(it, rs.iter()));
}

#[test]
fn times() {
    assert!(it::times(0).count() == 0);
    assert!(it::times(5).count() == 5);
}

#[test]
fn drain() {
    let xs = [1i,2,3];
    let mut sum = 0;
    xs.iter().map(|elt| sum += *elt).drain();
    assert!(sum == 6);
}

#[test]
fn apply() {
    let xs = [1i, 2, 3];
    let mut sum = 0;
    xs.iter().apply(|elt| sum += *elt);
    assert!(sum == 6);
}

#[test]
fn dropn() {
    let xs = [1i, 2, 3];
    let mut it = xs.iter();
    assert!(it.dropn(2) == 2);
    assert!(it.next().is_some());
    assert!(it.next().is_none());
    let mut it = xs.iter();
    assert!(it.dropn(5) == 3);
    assert!(it.next().is_none());
}

#[test]
fn intersperse() {
    let xs = ["a", "", "b", "c"];
    let v: Vec<&str> = xs.iter().map(|x| x.clone()).intersperse(", ").collect();
    let text = v.concat();
    assert_eq!(text, "a, , b, c".to_string());

    let ys = [0, 1, 2, 3i];
    let mut it = ys.slice_to(0).iter().map(|x| *x).intersperse(1i);
    assert!(it.next() == None);
}

#[test]
fn linspace() {
    let mut iter = it::linspace::<f32>(0., 2., 3);
    assert_eq!(iter.next(), Some(0.0));
    assert_eq!(iter.next(), Some(1.0));
    assert_eq!(iter.next(), Some(2.0));
    assert_eq!(iter.next(), None);

    let mut iter = it::linspace::<f32>(0., -2., 4);
    assert_eq!(iter.next(), Some(0.));
    assert_eq!(iter.next(), Some(-0.666666666667));
    assert_eq!(iter.next(), Some(-1.333333333333));
    assert_eq!(iter.next(), Some(-2.));
    assert_eq!(iter.next(), None);

    let mut iter = it::linspace::<f32>(0., 1., 1);
    assert_eq!(iter.next(), Some(0.));
    assert_eq!(iter.next(), None);

    let mut iter = it::linspace::<f32>(0., 1., 0);
    assert_eq!(iter.next(), None);
}
<|endoftext|>


<commit_before>// This code is heavily inspired by hoedown.

//
// Performance observations:
//
// Note that buf.head() == Some(&ch) is much faster than buf[0] == ch.
//

#[cfg(test)] extern crate extra;
#[cfg(test)] use extra::test::BenchHarness;

static SP: u8 = ' ' as u8;
static NL: u8 = '\n' as u8;
static CR: u8 = '\r' as u8;
static TAB: u8 = '\t' as u8;
static STAR: u8 = '*' as u8;
static DASH: u8 = '-' as u8;
static UNDERSCORE: u8 = '_' as u8;

//
// Skip up to three leading spaces.
//
// Up to three leading spaces are allowed for many elements.
//
// We don't need to care about a TAB here as in this position it is equivalent
// to 4 spaces, which means that when we find a TAB here we would not parse the
// corresponding element.
//
fn skip_initial_three_spaces<'a>(buf: &'a[u8])-> &'a[u8] {
    let mut buf = buf;
    if buf.head() == Some(&SP) { buf = buf.tail(); }
    if buf.head() == Some(&SP) { buf = buf.tail(); }
    if buf.head() == Some(&SP) { buf = buf.tail(); }
    return buf;
}

//
// Return Some(`rem`) if the line is a horizontal rule, with `rem` being the
// buf after the hrule. Otherwise return None.
//
fn is_hrule<'a>(buf: &'a[u8]) -> Option<&'a[u8]> {
    let buf = skip_initial_three_spaces(buf);

    let item = match buf.head() {
        Some(&c) if c == STAR ||
                    c == DASH ||
                    c == UNDERSCORE => c,
        _                           => return None
    };

    // The count of '*', '-' or '_'
    let mut cnt: uint = 0;

    // Counts the consumed spaces (and the final NL)
    let mut spc: uint = 0;

    for &ch in buf.iter() {
        if      ch == item { cnt += 1; }
        else if ch == NL   { spc += 1; break; }
        else if ch == SP   { spc += 1; }
        else               { return None; }
    }

    if cnt >= 3 {
        Some(buf.slice_from(cnt + spc))
    } else {
        None
    }
}

#[test]
fn test_is_hrule() {
    // examples as given on the markdown homepage
    assert!(is_hrule(bytes!("* * *\n")).is_some());
    assert!(is_hrule(bytes!("***\n")).is_some());
    assert!(is_hrule(bytes!("*****\n")).is_some());
    assert!(is_hrule(bytes!("- - -\n")).is_some());
    assert!(is_hrule(bytes!("---------------------------------------\n")).is_some());

    // up to three spaces ignored
    assert!(is_hrule(bytes!(" ***\n")).is_some());
    assert!(is_hrule(bytes!("  ***\n")).is_some());
    assert!(is_hrule(bytes!("   ***\n")).is_some());

    // but not four, or a tab which is equivalent to four spaces
    assert!(is_hrule(bytes!("    ***\n")).is_none());
    assert!(is_hrule(bytes!("\t***\n")).is_none());

    // need at least three
    assert!(is_hrule(bytes!("*\n")).is_none());
    assert!(is_hrule(bytes!("**\n")).is_none());
    assert!(is_hrule(bytes!("* *\n")).is_none());
    assert!(is_hrule(bytes!("   * *\n")).is_none());

    // Also works without newline at the end
    assert!(is_hrule(bytes!("* * *")).is_some());

    // And underscores also supported
    assert!(is_hrule(bytes!("___")).is_some());
    assert!(is_hrule(bytes!("______________")).is_some());
    assert!(is_hrule(bytes!(" ______________")).is_some());

    // Test if the remaining buf actually works.
    let s = bytes!("   * * *\nremaining");
    let res = is_hrule(s);
    assert!(res.is_some());
    assert_eq!(res.unwrap(), bytes!("remaining"));
}

#[bench]
fn bench_is_hrule(b: &mut BenchHarness) {
    let s = bytes!("   * * * * * * * * * * * * * * * *\n");
    b.iter(|| is_hrule(s));
}

//
// Return Some(`rem`) if the line is an empty line, with `rem` being the buf
// after the empty line. Otherwise return None.
//
fn is_empty<'a>(buf: &'a[u8]) -> Option<&'a[u8]> {
    let mut cnt: uint = 0;

    for &ch in buf.iter() {
        if      ch == NL  { cnt += 1; break; }
        else if ch == CR  { cnt += 1; }
        else if ch == SP  { cnt += 1; }
        else if ch == TAB { cnt += 1; }
        else              { return None; }
    }

    if cnt > 0 {
        Some(buf.slice_from(cnt))
    } else {
        None
    }
}

#[test]
fn test_is_empty() {
    assert!(is_empty(bytes!("\n")).is_some());
    assert!(is_empty(bytes!("    \n")).is_some());
    assert!(is_empty(bytes!("  \t  \n")).is_some());
    assert!(is_empty(bytes!("  \t  \r\n")).is_some());
    assert!(is_empty(bytes!("  \t  \nabc")).is_some());
    assert!(is_empty(bytes!("  \t  ")).is_some());

    assert!(is_empty(bytes!("a")).is_none());
    assert!(is_empty(bytes!(" a")).is_none());
    assert!(is_empty(bytes!(" a\n")).is_none());
    assert!(is_empty(bytes!(" \ta\n")).is_none());

    // Test if the remaining buf actually works.
    let s = bytes!("   \t\r\nremaining");
    let res = is_empty(s);
    assert!(res.is_some());
    assert_eq!(res.unwrap(), bytes!("remaining"));
}
<commit_msg>Use nested if's<commit_after>// This code is heavily inspired by hoedown.

//
// Performance observations:
//
// Note that buf.head() == Some(&ch) is much faster than buf[0] == ch.
//

#[cfg(test)] extern crate extra;
#[cfg(test)] use extra::test::BenchHarness;

static SP: u8 = ' ' as u8;
static NL: u8 = '\n' as u8;
static CR: u8 = '\r' as u8;
static TAB: u8 = '\t' as u8;
static STAR: u8 = '*' as u8;
static DASH: u8 = '-' as u8;
static UNDERSCORE: u8 = '_' as u8;

//
// Skip up to three leading spaces.
//
// Up to three leading spaces are allowed for many elements.
//
// We don't need to care about a TAB here as in this position it is equivalent
// to 4 spaces, which means that when we find a TAB here we would not parse the
// corresponding element.
//
fn skip_initial_three_spaces<'a>(buf: &'a[u8])-> &'a[u8] {
    let mut buf = buf;
    if buf.head() == Some(&SP) { buf = buf.tail();
    if buf.head() == Some(&SP) { buf = buf.tail();
    if buf.head() == Some(&SP) { buf = buf.tail(); } } }
    return buf;
}

//
// Return Some(`rem`) if the line is a horizontal rule, with `rem` being the
// buf after the hrule. Otherwise return None.
//
fn is_hrule<'a>(buf: &'a[u8]) -> Option<&'a[u8]> {
    let buf = skip_initial_three_spaces(buf);

    let item = match buf.head() {
        Some(&c) if c == STAR ||
                    c == DASH ||
                    c == UNDERSCORE => c,
        _                           => return None
    };

    // The count of '*', '-' or '_'
    let mut cnt: uint = 0;

    // Counts the consumed spaces (and the final NL)
    let mut spc: uint = 0;

    for &ch in buf.iter() {
        if      ch == item { cnt += 1; }
        else if ch == NL   { spc += 1; break; }
        else if ch == SP   { spc += 1; }
        else               { return None; }
    }

    if cnt >= 3 {
        Some(buf.slice_from(cnt + spc))
    } else {
        None
    }
}

#[test]
fn test_is_hrule() {
    // examples as given on the markdown homepage
    assert!(is_hrule(bytes!("* * *\n")).is_some());
    assert!(is_hrule(bytes!("***\n")).is_some());
    assert!(is_hrule(bytes!("*****\n")).is_some());
    assert!(is_hrule(bytes!("- - -\n")).is_some());
    assert!(is_hrule(bytes!("---------------------------------------\n")).is_some());

    // up to three spaces ignored
    assert!(is_hrule(bytes!(" ***\n")).is_some());
    assert!(is_hrule(bytes!("  ***\n")).is_some());
    assert!(is_hrule(bytes!("   ***\n")).is_some());

    // but not four, or a tab which is equivalent to four spaces
    assert!(is_hrule(bytes!("    ***\n")).is_none());
    assert!(is_hrule(bytes!("\t***\n")).is_none());

    // need at least three
    assert!(is_hrule(bytes!("*\n")).is_none());
    assert!(is_hrule(bytes!("**\n")).is_none());
    assert!(is_hrule(bytes!("* *\n")).is_none());
    assert!(is_hrule(bytes!("   * *\n")).is_none());

    // Also works without newline at the end
    assert!(is_hrule(bytes!("* * *")).is_some());

    // And underscores also supported
    assert!(is_hrule(bytes!("___")).is_some());
    assert!(is_hrule(bytes!("______________")).is_some());
    assert!(is_hrule(bytes!(" ______________")).is_some());

    // Test if the remaining buf actually works.
    let s = bytes!("   * * *\nremaining");
    let res = is_hrule(s);
    assert!(res.is_some());
    assert_eq!(res.unwrap(), bytes!("remaining"));
}

#[bench]
fn bench_is_hrule(b: &mut BenchHarness) {
    let s = bytes!("   * * * * * * * * * * * * * * * *\n");
    b.iter(|| is_hrule(s));
}

//
// Return Some(`rem`) if the line is an empty line, with `rem` being the buf
// after the empty line. Otherwise return None.
//
fn is_empty<'a>(buf: &'a[u8]) -> Option<&'a[u8]> {
    let mut cnt: uint = 0;

    for &ch in buf.iter() {
        if      ch == NL  { cnt += 1; break; }
        else if ch == CR  { cnt += 1; }
        else if ch == SP  { cnt += 1; }
        else if ch == TAB { cnt += 1; }
        else              { return None; }
    }

    if cnt > 0 {
        Some(buf.slice_from(cnt))
    } else {
        None
    }
}

#[test]
fn test_is_empty() {
    assert!(is_empty(bytes!("\n")).is_some());
    assert!(is_empty(bytes!("    \n")).is_some());
    assert!(is_empty(bytes!("  \t  \n")).is_some());
    assert!(is_empty(bytes!("  \t  \r\n")).is_some());
    assert!(is_empty(bytes!("  \t  \nabc")).is_some());
    assert!(is_empty(bytes!("  \t  ")).is_some());

    assert!(is_empty(bytes!("a")).is_none());
    assert!(is_empty(bytes!(" a")).is_none());
    assert!(is_empty(bytes!(" a\n")).is_none());
    assert!(is_empty(bytes!(" \ta\n")).is_none());

    // Test if the remaining buf actually works.
    let s = bytes!("   \t\r\nremaining");
    let res = is_empty(s);
    assert!(res.is_some());
    assert_eq!(res.unwrap(), bytes!("remaining"));
}
<|endoftext|>


<commit_before>fn main() {
    // Increment via closures and functions.
    fn  function            (i: i32) -> i32 { i + 1 }

    // Annotation is identical to function annotation but is optional
    // as are the `{}` wrapping the body. These nameless functions
    // are assigned to appropriately named variables.
    let closure_annotated = |i: i32| -> i32 { i + 1 };
    let closure_inferred  = |i     |          i + 1  ;

    let i = 1;
    // Call the function and closures.
    println!("function: {}", function(i));
    println!("closure_annotated: {}", closure_annotated(i));
    println!("closure_inferred: {}", closure_inferred(i));

    // A closure taking no arguments which returns an `i32`.
    // The return type is inferred.
    let one = || 1;
    println!("closure returning one: {}", one());

}
<commit_msg>Add more context<commit_after>fn main() {
    // Increment via closures and functions.
    fn  function            (i: i32) -> i32 { i + 1 }

    // Closures are anonymous, here we are binding them to references
    // Annotation is identical to function annotation but is optional
    // as are the `{}` wrapping the body. These nameless functions
    // are assigned to appropriately named variables.
    let closure_annotated = |i: i32| -> i32 { i + 1 };
    let closure_inferred  = |i     |          i + 1  ;

    let i = 1;
    // Call the function and closures.
    println!("function: {}", function(i));
    println!("closure_annotated: {}", closure_annotated(i));
    println!("closure_inferred: {}", closure_inferred(i));

    // A closure taking no arguments which returns an `i32`.
    // The return type is inferred.
    let one = || 1;
    println!("closure returning one: {}", one());

}
<|endoftext|>