<commit_before>// Support code for rustc's built in test runner generator. Currently,
// none of this is meant for users. It is intended to support the
// simplest interface possible for representing and running tests
// while providing a base that other test frameworks may build off of.

import generic_os::getenv;
import task::task;

export test_name;
export test_fn;
export default_test_fn;
export test_desc;
export test_main;
export test_result;
export test_opts;
export tr_ok;
export tr_failed;
export tr_ignored;
export run_tests_console;
export run_tests_console_;
export run_test;
export filter_tests;
export parse_opts;
export test_to_task;
export default_test_to_task;
export configure_test_task;
export joinable;

native "rust" mod rustrt {
    fn sched_threads() -> uint;
}

// The name of a test. By convention this follows the rules for rust
// paths; i.e. it should be a series of identifiers seperated by double
// colons. This way if some test runner wants to arrange the tests
// hierarchically it may.
type test_name = str;

// A function that runs a test. If the function returns successfully,
// the test succeeds; if the function fails then the test fails. We
// may need to come up with a more clever definition of test in order
// to support isolation of tests into tasks.
type test_fn<@T> = T;

type default_test_fn = test_fn<fn()>;

// The definition of a single test. A test runner will run a list of
// these.
type test_desc<@T> = {
    name: test_name,
    fn: test_fn<T>,
    ignore: bool
};

// The default console test runner. It accepts the command line
// arguments and a vector of test_descs (generated at compile time).
fn test_main(args: [str], tests: [test_desc<default_test_fn>]) {
    check (vec::is_not_empty(args));
    let opts =
        alt parse_opts(args) {
          either::left(o) { o }
          either::right(m) { fail m }
        };
    if !run_tests_console(opts, tests) { fail "Some tests failed"; }
}

type test_opts = {filter: option::t<str>, run_ignored: bool};

type opt_res = either::t<test_opts, str>;

// Parses command line arguments into test options
fn parse_opts(args: [str]) : vec::is_not_empty(args) -> opt_res {

    let args_ = vec::tail(args);
    let opts = [getopts::optflag("ignored")];
    let match =
        alt getopts::getopts(args_, opts) {
          getopts::success(m) { m }
          getopts::failure(f) { ret either::right(getopts::fail_str(f)) }
        };

    let filter =
        if vec::len(match.free) > 0u {
            option::some(match.free[0])
        } else { option::none };

    let run_ignored = getopts::opt_present(match, "ignored");

    let test_opts = {filter: filter, run_ignored: run_ignored};

    ret either::left(test_opts);
}

tag test_result { tr_ok; tr_failed; tr_ignored; }

type joinable = (task, comm::port<task::task_notification>);

// To get isolation and concurrency tests have to be run in their own tasks.
// In cases where test functions are closures it is not ok to just dump them
// into a task and run them, so this transformation gives the caller a chance
// to create the test task.
type test_to_task<@T> = fn@(test_fn<T>) -> joinable;

// A simple console test runner
fn run_tests_console(opts: test_opts,
                         tests: [test_desc<default_test_fn>]) -> bool {
    run_tests_console_(opts, tests, default_test_to_task)
}

fn run_tests_console_<@T>(opts: test_opts, tests: [test_desc<T>],
                          to_task: test_to_task<T>) -> bool {

    type test_state =
        @{out: io::writer,
          use_color: bool,
          mutable total: uint,
          mutable passed: uint,
          mutable failed: uint,
          mutable ignored: uint,
          mutable failures: [test_desc<T>]};

    fn callback<@T>(event: testevent<T>, st: test_state) {
        alt event {
          te_filtered(filtered_tests) {
            st.total = vec::len(filtered_tests);
            st.out.write_line(#fmt["\nrunning %u tests", st.total]);
          }
          te_wait(test) { st.out.write_str(#fmt["test %s ... ", test.name]); }
          te_result(test, result) {
            alt result {
              tr_ok. {
                st.passed += 1u;
                write_ok(st.out, st.use_color);
                st.out.write_line("");
              }
              tr_failed. {
                st.failed += 1u;
                write_failed(st.out, st.use_color);
                st.out.write_line("");
                st.failures += [test];
              }
              tr_ignored. {
                st.ignored += 1u;
                write_ignored(st.out, st.use_color);
                st.out.write_line("");
              }
            }
          }
        }
    }

    let st =
        @{out: io::stdout(),
          use_color: use_color(),
          mutable total: 0u,
          mutable passed: 0u,
          mutable failed: 0u,
          mutable ignored: 0u,
          mutable failures: []};

    run_tests(opts, tests, to_task, bind callback(_, st));

    assert (st.passed + st.failed + st.ignored == st.total);
    let success = st.failed == 0u;

    if !success {
        st.out.write_line("\nfailures:");
        for test: test_desc<T> in st.failures {
            let testname = test.name; // Satisfy alias analysis
            st.out.write_line(#fmt["    %s", testname]);
        }
    }

    st.out.write_str(#fmt["\nresult: "]);
    if success {
        // There's no parallelism at this point so it's safe to use color
        write_ok(st.out, true);
    } else { write_failed(st.out, true); }
    st.out.write_str(#fmt[". %u passed; %u failed; %u ignored\n\n", st.passed,
                          st.failed, st.ignored]);

    ret success;

    fn write_ok(out: io::writer, use_color: bool) {
        write_pretty(out, "ok", term::color_green, use_color);
    }

    fn write_failed(out: io::writer, use_color: bool) {
        write_pretty(out, "FAILED", term::color_red, use_color);
    }

    fn write_ignored(out: io::writer, use_color: bool) {
        write_pretty(out, "ignored", term::color_yellow, use_color);
    }

    fn write_pretty(out: io::writer, word: str, color: u8, use_color: bool) {
        if use_color && term::color_supported() {
            term::fg(out.get_buf_writer(), color);
        }
        out.write_str(word);
        if use_color && term::color_supported() {
            term::reset(out.get_buf_writer());
        }
    }
}

fn use_color() -> bool { ret get_concurrency() == 1u; }

tag testevent<@T> {
    te_filtered([test_desc<T>]);
    te_wait(test_desc<T>);
    te_result(test_desc<T>, test_result);
}

fn run_tests<@T>(opts: test_opts, tests: [test_desc<T>],
                 to_task: test_to_task<T>,
                 callback: fn@(testevent<T>)) {

    let filtered_tests = filter_tests(opts, tests);

    callback(te_filtered(filtered_tests));

    // It's tempting to just spawn all the tests at once but that doesn't
    // provide a great user experience because you might sit waiting for the
    // result of a particular test for an unusually long amount of time.
    let concurrency = get_concurrency();
    log #fmt["using %u test tasks", concurrency];
    let total = vec::len(filtered_tests);
    let run_idx = 0u;
    let wait_idx = 0u;
    let futures = [];

    while wait_idx < total {
        while vec::len(futures) < concurrency && run_idx < total {
            futures += [run_test(filtered_tests[run_idx], to_task)];
            run_idx += 1u;
        }

        let future = futures[0];
        callback(te_wait(future.test));
        let result = future.wait();
        callback(te_result(future.test, result));
        futures = vec::slice(futures, 1u, vec::len(futures));
        wait_idx += 1u;
    }
}

fn get_concurrency() -> uint { rustrt::sched_threads() }

fn filter_tests<@T>(opts: test_opts,
                    tests: [test_desc<T>]) -> [test_desc<T>] {
    let filtered = tests;

    // Remove tests that don't match the test filter
    filtered = if option::is_none(opts.filter) {
        filtered
    } else {
        let filter_str =
            alt opts.filter {
          option::some(f) { f }
          option::none. { "" }
        };

        fn filter_fn<@T>(test: test_desc<T>, filter_str: str) ->
            option::t<test_desc<T>> {
            if str::find(test.name, filter_str) >= 0 {
                ret option::some(test);
            } else { ret option::none; }
        }

        let filter = bind filter_fn(_, filter_str);

        vec::filter_map(filter, filtered)
    };

    // Maybe pull out the ignored test and unignore them
    filtered = if !opts.run_ignored {
        filtered
    } else {
        fn filter<@T>(test: test_desc<T>) -> option::t<test_desc<T>> {
            if test.ignore {
                ret option::some({name: test.name,
                                  fn: test.fn,
                                  ignore: false});
            } else { ret option::none; }
        };

        vec::filter_map(bind filter(_), filtered)
    };

    // Sort the tests alphabetically
    filtered =
        {
            fn lteq<@T>(t1: test_desc<T>, t2: test_desc<T>) -> bool {
                str::lteq(t1.name, t2.name)
            }
            sort::merge_sort(bind lteq(_, _), filtered)
        };

    ret filtered;
}

type test_future<@T> = {test: test_desc<T>, wait: fn@() -> test_result};

fn run_test<@T>(test: test_desc<T>,
                to_task: test_to_task<T>) -> test_future<T> {
    if !test.ignore {
        let test_task = to_task(test.fn);
        ret {test: test,
             wait:
                 bind fn (test_task: joinable) -> test_result {
                          alt task::join(test_task) {
                            task::tr_success. { tr_ok }
                            task::tr_failure. { tr_failed }
                          }
                      }(test_task)};
    } else { ret {test: test, wait: fn () -> test_result { tr_ignored }}; }
}

// We need to run our tests in another task in order to trap test failures.
// This function only works with functions that don't contain closures.
fn default_test_to_task(&&f: default_test_fn) -> joinable {
    fn run_task(f: default_test_fn) {
        configure_test_task();
        f();
    }
    ret task::spawn_joinable(f, run_task);
}

// Call from within a test task to make sure it's set up correctly
fn configure_test_task() {
    // If this task fails we don't want that failure to propagate to the
    // test runner or else we couldn't keep running tests
    task::unsupervise();
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>migrate sched_threads call<commit_after>// Support code for rustc's built in test runner generator. Currently,
// none of this is meant for users. It is intended to support the
// simplest interface possible for representing and running tests
// while providing a base that other test frameworks may build off of.

import generic_os::getenv;
import task::task;

export test_name;
export test_fn;
export default_test_fn;
export test_desc;
export test_main;
export test_result;
export test_opts;
export tr_ok;
export tr_failed;
export tr_ignored;
export run_tests_console;
export run_tests_console_;
export run_test;
export filter_tests;
export parse_opts;
export test_to_task;
export default_test_to_task;
export configure_test_task;
export joinable;

native "c-stack-cdecl" mod rustrt {
    fn sched_threads() -> uint;
}

// The name of a test. By convention this follows the rules for rust
// paths; i.e. it should be a series of identifiers seperated by double
// colons. This way if some test runner wants to arrange the tests
// hierarchically it may.
type test_name = str;

// A function that runs a test. If the function returns successfully,
// the test succeeds; if the function fails then the test fails. We
// may need to come up with a more clever definition of test in order
// to support isolation of tests into tasks.
type test_fn<@T> = T;

type default_test_fn = test_fn<fn()>;

// The definition of a single test. A test runner will run a list of
// these.
type test_desc<@T> = {
    name: test_name,
    fn: test_fn<T>,
    ignore: bool
};

// The default console test runner. It accepts the command line
// arguments and a vector of test_descs (generated at compile time).
fn test_main(args: [str], tests: [test_desc<default_test_fn>]) {
    check (vec::is_not_empty(args));
    let opts =
        alt parse_opts(args) {
          either::left(o) { o }
          either::right(m) { fail m }
        };
    if !run_tests_console(opts, tests) { fail "Some tests failed"; }
}

type test_opts = {filter: option::t<str>, run_ignored: bool};

type opt_res = either::t<test_opts, str>;

// Parses command line arguments into test options
fn parse_opts(args: [str]) : vec::is_not_empty(args) -> opt_res {

    let args_ = vec::tail(args);
    let opts = [getopts::optflag("ignored")];
    let match =
        alt getopts::getopts(args_, opts) {
          getopts::success(m) { m }
          getopts::failure(f) { ret either::right(getopts::fail_str(f)) }
        };

    let filter =
        if vec::len(match.free) > 0u {
            option::some(match.free[0])
        } else { option::none };

    let run_ignored = getopts::opt_present(match, "ignored");

    let test_opts = {filter: filter, run_ignored: run_ignored};

    ret either::left(test_opts);
}

tag test_result { tr_ok; tr_failed; tr_ignored; }

type joinable = (task, comm::port<task::task_notification>);

// To get isolation and concurrency tests have to be run in their own tasks.
// In cases where test functions are closures it is not ok to just dump them
// into a task and run them, so this transformation gives the caller a chance
// to create the test task.
type test_to_task<@T> = fn@(test_fn<T>) -> joinable;

// A simple console test runner
fn run_tests_console(opts: test_opts,
                         tests: [test_desc<default_test_fn>]) -> bool {
    run_tests_console_(opts, tests, default_test_to_task)
}

fn run_tests_console_<@T>(opts: test_opts, tests: [test_desc<T>],
                          to_task: test_to_task<T>) -> bool {

    type test_state =
        @{out: io::writer,
          use_color: bool,
          mutable total: uint,
          mutable passed: uint,
          mutable failed: uint,
          mutable ignored: uint,
          mutable failures: [test_desc<T>]};

    fn callback<@T>(event: testevent<T>, st: test_state) {
        alt event {
          te_filtered(filtered_tests) {
            st.total = vec::len(filtered_tests);
            st.out.write_line(#fmt["\nrunning %u tests", st.total]);
          }
          te_wait(test) { st.out.write_str(#fmt["test %s ... ", test.name]); }
          te_result(test, result) {
            alt result {
              tr_ok. {
                st.passed += 1u;
                write_ok(st.out, st.use_color);
                st.out.write_line("");
              }
              tr_failed. {
                st.failed += 1u;
                write_failed(st.out, st.use_color);
                st.out.write_line("");
                st.failures += [test];
              }
              tr_ignored. {
                st.ignored += 1u;
                write_ignored(st.out, st.use_color);
                st.out.write_line("");
              }
            }
          }
        }
    }

    let st =
        @{out: io::stdout(),
          use_color: use_color(),
          mutable total: 0u,
          mutable passed: 0u,
          mutable failed: 0u,
          mutable ignored: 0u,
          mutable failures: []};

    run_tests(opts, tests, to_task, bind callback(_, st));

    assert (st.passed + st.failed + st.ignored == st.total);
    let success = st.failed == 0u;

    if !success {
        st.out.write_line("\nfailures:");
        for test: test_desc<T> in st.failures {
            let testname = test.name; // Satisfy alias analysis
            st.out.write_line(#fmt["    %s", testname]);
        }
    }

    st.out.write_str(#fmt["\nresult: "]);
    if success {
        // There's no parallelism at this point so it's safe to use color
        write_ok(st.out, true);
    } else { write_failed(st.out, true); }
    st.out.write_str(#fmt[". %u passed; %u failed; %u ignored\n\n", st.passed,
                          st.failed, st.ignored]);

    ret success;

    fn write_ok(out: io::writer, use_color: bool) {
        write_pretty(out, "ok", term::color_green, use_color);
    }

    fn write_failed(out: io::writer, use_color: bool) {
        write_pretty(out, "FAILED", term::color_red, use_color);
    }

    fn write_ignored(out: io::writer, use_color: bool) {
        write_pretty(out, "ignored", term::color_yellow, use_color);
    }

    fn write_pretty(out: io::writer, word: str, color: u8, use_color: bool) {
        if use_color && term::color_supported() {
            term::fg(out.get_buf_writer(), color);
        }
        out.write_str(word);
        if use_color && term::color_supported() {
            term::reset(out.get_buf_writer());
        }
    }
}

fn use_color() -> bool { ret get_concurrency() == 1u; }

tag testevent<@T> {
    te_filtered([test_desc<T>]);
    te_wait(test_desc<T>);
    te_result(test_desc<T>, test_result);
}

fn run_tests<@T>(opts: test_opts, tests: [test_desc<T>],
                 to_task: test_to_task<T>,
                 callback: fn@(testevent<T>)) {

    let filtered_tests = filter_tests(opts, tests);

    callback(te_filtered(filtered_tests));

    // It's tempting to just spawn all the tests at once but that doesn't
    // provide a great user experience because you might sit waiting for the
    // result of a particular test for an unusually long amount of time.
    let concurrency = get_concurrency();
    log #fmt["using %u test tasks", concurrency];
    let total = vec::len(filtered_tests);
    let run_idx = 0u;
    let wait_idx = 0u;
    let futures = [];

    while wait_idx < total {
        while vec::len(futures) < concurrency && run_idx < total {
            futures += [run_test(filtered_tests[run_idx], to_task)];
            run_idx += 1u;
        }

        let future = futures[0];
        callback(te_wait(future.test));
        let result = future.wait();
        callback(te_result(future.test, result));
        futures = vec::slice(futures, 1u, vec::len(futures));
        wait_idx += 1u;
    }
}

fn get_concurrency() -> uint { rustrt::sched_threads() }

fn filter_tests<@T>(opts: test_opts,
                    tests: [test_desc<T>]) -> [test_desc<T>] {
    let filtered = tests;

    // Remove tests that don't match the test filter
    filtered = if option::is_none(opts.filter) {
        filtered
    } else {
        let filter_str =
            alt opts.filter {
          option::some(f) { f }
          option::none. { "" }
        };

        fn filter_fn<@T>(test: test_desc<T>, filter_str: str) ->
            option::t<test_desc<T>> {
            if str::find(test.name, filter_str) >= 0 {
                ret option::some(test);
            } else { ret option::none; }
        }

        let filter = bind filter_fn(_, filter_str);

        vec::filter_map(filter, filtered)
    };

    // Maybe pull out the ignored test and unignore them
    filtered = if !opts.run_ignored {
        filtered
    } else {
        fn filter<@T>(test: test_desc<T>) -> option::t<test_desc<T>> {
            if test.ignore {
                ret option::some({name: test.name,
                                  fn: test.fn,
                                  ignore: false});
            } else { ret option::none; }
        };

        vec::filter_map(bind filter(_), filtered)
    };

    // Sort the tests alphabetically
    filtered =
        {
            fn lteq<@T>(t1: test_desc<T>, t2: test_desc<T>) -> bool {
                str::lteq(t1.name, t2.name)
            }
            sort::merge_sort(bind lteq(_, _), filtered)
        };

    ret filtered;
}

type test_future<@T> = {test: test_desc<T>, wait: fn@() -> test_result};

fn run_test<@T>(test: test_desc<T>,
                to_task: test_to_task<T>) -> test_future<T> {
    if !test.ignore {
        let test_task = to_task(test.fn);
        ret {test: test,
             wait:
                 bind fn (test_task: joinable) -> test_result {
                          alt task::join(test_task) {
                            task::tr_success. { tr_ok }
                            task::tr_failure. { tr_failed }
                          }
                      }(test_task)};
    } else { ret {test: test, wait: fn () -> test_result { tr_ignored }}; }
}

// We need to run our tests in another task in order to trap test failures.
// This function only works with functions that don't contain closures.
fn default_test_to_task(&&f: default_test_fn) -> joinable {
    fn run_task(f: default_test_fn) {
        configure_test_task();
        f();
    }
    ret task::spawn_joinable(f, run_task);
}

// Call from within a test task to make sure it's set up correctly
fn configure_test_task() {
    // If this task fails we don't want that failure to propagate to the
    // test runner or else we couldn't keep running tests
    task::unsupervise();
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before>//! Data producers
//!
//! The goal of data producers is to parse data as soon as it is generated.
//!
//! # Example
//!
//! ```ignore
//!  use std::str;
//!  fn local_print<'a,T: Debug>(input: T) -> IResult<T, ()> {
//!    println!("{:?}", input);
//!    Done(input, ())
//!  }
//!  // create a data producer from a file
//!  FileProducer::new("links.txt", 20).map(|producer: FileProducer| {
//!    let mut p = producer;
//!
//!    // create the parsing function
//!    fn parser(par: IResult<(),&[u8]>) -> IResult<&[u8],()> {
//!      par.map_res(str::from_utf8).flat_map(local_print);
//!      Done("".as_bytes(), ())
//!    }
//!
//!    // adapt the parsing function to the producer
//!    pusher!(push, parser);
//!    // get started
//!    push(&mut p);
//!  });
//! ```

use internal::*;
use self::ProducerState::*;

use std::io::fs::File;
use std::io::{IoResult, IoErrorKind};

/// Holds the data producer's current state
///
/// * Eof indicates all data has been parsed, and contains the parser's result
///
/// * Continue indicates that more data is needed and should be available,
/// but not right now. Parsing should resume at some point.
///
/// * Data contains already parsed data
///
/// * ProducerError indicates something went wrong
#[derive(Debug,PartialEq,Eq)]
pub enum ProducerState<O> {
  Eof(O),
  Continue,
  Data(O),
  ProducerError(Err),
}

/// A producer implements the produce method, currently working with u8 arrays
pub trait Producer {
  fn produce(&mut self) -> ProducerState<&[u8]>;
}

/// Can produce data from a file
///
/// the size field is the size of v, the internal buffer
pub struct FileProducer {
  size: usize,
  file: File,
  v:    Vec<u8>
}

impl FileProducer {
  pub fn new(filename: &str, buffer_size: usize) -> IoResult<FileProducer> {
    File::open(&Path::new(filename)).map(|f| {
      FileProducer {size: buffer_size, file: f, v: Vec::with_capacity(buffer_size)}
    })
  }
}

impl Producer for FileProducer {
  fn produce(&mut self) -> ProducerState<&[u8]> {
    //let mut v = Vec::with_capacity(self.size);
    self.v.clear();
    match self.file.push(self.size, &mut self.v) {
      Err(e) => {
        match e.kind {
          IoErrorKind::NoProgress => Continue,
          IoErrorKind::EndOfFile  => Eof(self.v.as_slice()),
          _          => ProducerError(0)
        }
      },
      Ok(i)  => {
        println!("read {:?} bytes: {:?}", i, self.v);
        Data(self.v.as_slice())
      }
    }
  }
}

/// Can parse data from an already in memory byte array
///
/// * buffer holds the reference to the data that must be parsed
///
/// * length is the length of that buffer
///
/// * index is the position in the buffer
///
/// * chunk_size is the quantity of data sent at once
pub struct MemProducer<'x> {
  buffer: &'x [u8],
  chunk_size: usize,
  length: usize,
  index: usize
}

impl<'x> MemProducer<'x> {
  pub fn new(buffer: &'x[u8], chunk_size: usize) -> MemProducer {
    MemProducer {
      buffer:     buffer,
      chunk_size: chunk_size,
      length:     buffer.len(),
      index:      0
    }
  }
}

impl<'x> Producer for MemProducer<'x> {
  fn produce(&mut self) -> ProducerState<&[u8]> {
    if self.index + self.chunk_size < self.length {
      println!("self.index + {} < self.length", self.chunk_size);
      let new_index = self.index+self.chunk_size;
      let res = Data(self.buffer.slice(self.index, new_index));
      self.index = new_index;
      res
    } else if self.index < self.length {
      println!("self.index < self.length - 1");
      let res = Eof(self.buffer.slice(self.index, self.length));
      self.index = self.length;
      res
    } else {
      ProducerError(0)
    }
  }
}

/// Prepares a parser function for a push pipeline
///
/// It creates a function that accepts a producer and immediately starts parsing the data sent
///
/// # Example
///
/// ```ignore
/// fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],()> {
///   par.flat_map(local_print)
/// }
/// let mut p = MemProducer::new("abcdefgh".as_bytes(), 8);
///
/// pusher!(ps, pr);
/// ps(&mut p);
/// ```
#[macro_export]
macro_rules! pusher (
  ($name:ident, $f:expr) => (
    fn $name(producer: &mut Producer) {
      let mut acc: Vec<u8> = Vec::new();
      loop {
        let state = producer.produce();
        match state {
          ProducerState::Data(v) => {
            println!("got data");
            acc.push_all(v)
          },
          ProducerState::Eof([])  => {
            println!("eof empty");
            break;
          }
          ProducerState::Eof(v) => {
            println!("eof with {} bytes", v.len());
            acc.push_all(v)
          }
          _ => {break;}
        }
        let mut v2: Vec<u8>  = Vec::new();
        v2.push_all(acc.as_slice());
        let p = IResult::Done((), v2.as_slice());
        match $f(p) {
          IResult::Error(e)      => {
            println!("error, stopping: {}", e);
            break;
          },
          IResult::Incomplete(_) => {
            println!("incomplete");
          },
          IResult::Done(i, _)    => {
            println!("data, done");
            acc.clear();
            acc.push_all(i);
          }
        }
      }
    }
  );
);

#[cfg(test)]
mod tests {
  use super::*;
  use internal::IResult;
  use internal::IResult::*;
  use std::fmt::Debug;
  use std::str;
  use map::*;

  fn local_print<'a,T: Debug>(input: T) -> IResult<T, ()> {
    println!("{:?}", input);
    Done(input, ())
  }
  #[test]
  fn mem_producer() {
    let mut p = MemProducer::new("abcdefgh".as_bytes(), 4);
    assert_eq!(p.produce(), ProducerState::Data("abcd".as_bytes()));
  }

  #[test]
  fn mem_producer_2() {
    let mut p = MemProducer::new("abcdefgh".as_bytes(), 8);
    fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],()> {
      par.flat_map(local_print)
    }
    pusher!(ps, pr);
    ps(&mut p);
    //let mut iterations: uint = 0;
    //let mut p = MemProducer::new("abcdefghi".as_bytes(), 4);
    //p.push(|par| {iterations = iterations + 1; par.flat_map(print)});
    //assert_eq!(iterations, 3);
  }

  #[test]
  #[allow(unused_must_use)]
  fn file() {
    FileProducer::new("links.txt", 20).map(|producer: FileProducer| {
      let mut p = producer;
      //p.push(|par| {println!("parsed file: {}", par); par});
      //p.push(|par| par.flat_map(print));
      fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],()> {
        par.map_res(str::from_utf8).flat_map(local_print);
        Done("".as_bytes(), ())
      }
      pusher!(ps, pr);
      ps(&mut p);
      //assert!(false);
    });
  }

  #[test]
  fn accu() {
    fn f(input:&[u8]) -> IResult<&[u8],&[u8]> {
      if input.len() <= 4 {
        Incomplete(0)
      } else {
        Done("".as_bytes(), input)
      }
    }

    let mut p = MemProducer::new("abcdefgh".as_bytes(), 4);
    fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],&[u8]> {
      let r = par.flat_map(f);
      println!("f: {:?}", r);
      r
    }
    pusher!(ps, pr );
    ps(&mut p);
    //assert!(false);
  }

  #[test]
  fn accu_2() {
    fn f(input:&[u8]) -> IResult<&[u8],&[u8]> {
      if input.len() <= 4 || input.slice(0,5) != "abcde".as_bytes() {
        Incomplete(0)
      } else {
        Done(input.slice_from(5), input.slice(0,5))
      }
    }

    let mut p = MemProducer::new("abcdefgh".as_bytes(), 4);
    fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],&[u8]> {
      let r = par.flat_map(f);
      println!("f: {:?}", r);
      r
    }
    pusher!(ps, pr );
    ps(&mut p);
    //assert!(false);
  }
}
<commit_msg>rename io to old_io<commit_after>//! Data producers
//!
//! The goal of data producers is to parse data as soon as it is generated.
//!
//! # Example
//!
//! ```ignore
//!  use std::str;
//!  fn local_print<'a,T: Debug>(input: T) -> IResult<T, ()> {
//!    println!("{:?}", input);
//!    Done(input, ())
//!  }
//!  // create a data producer from a file
//!  FileProducer::new("links.txt", 20).map(|producer: FileProducer| {
//!    let mut p = producer;
//!
//!    // create the parsing function
//!    fn parser(par: IResult<(),&[u8]>) -> IResult<&[u8],()> {
//!      par.map_res(str::from_utf8).flat_map(local_print);
//!      Done("".as_bytes(), ())
//!    }
//!
//!    // adapt the parsing function to the producer
//!    pusher!(push, parser);
//!    // get started
//!    push(&mut p);
//!  });
//! ```

use internal::*;
use self::ProducerState::*;

use std::old_io::fs::File;
use std::old_io::{IoResult, IoErrorKind};

/// Holds the data producer's current state
///
/// * Eof indicates all data has been parsed, and contains the parser's result
///
/// * Continue indicates that more data is needed and should be available,
/// but not right now. Parsing should resume at some point.
///
/// * Data contains already parsed data
///
/// * ProducerError indicates something went wrong
#[derive(Debug,PartialEq,Eq)]
pub enum ProducerState<O> {
  Eof(O),
  Continue,
  Data(O),
  ProducerError(Err),
}

/// A producer implements the produce method, currently working with u8 arrays
pub trait Producer {
  fn produce(&mut self) -> ProducerState<&[u8]>;
}

/// Can produce data from a file
///
/// the size field is the size of v, the internal buffer
pub struct FileProducer {
  size: usize,
  file: File,
  v:    Vec<u8>
}

impl FileProducer {
  pub fn new(filename: &str, buffer_size: usize) -> IoResult<FileProducer> {
    File::open(&Path::new(filename)).map(|f| {
      FileProducer {size: buffer_size, file: f, v: Vec::with_capacity(buffer_size)}
    })
  }
}

impl Producer for FileProducer {
  fn produce(&mut self) -> ProducerState<&[u8]> {
    //let mut v = Vec::with_capacity(self.size);
    self.v.clear();
    match self.file.push(self.size, &mut self.v) {
      Err(e) => {
        match e.kind {
          IoErrorKind::NoProgress => Continue,
          IoErrorKind::EndOfFile  => Eof(self.v.as_slice()),
          _          => ProducerError(0)
        }
      },
      Ok(i)  => {
        println!("read {:?} bytes: {:?}", i, self.v);
        Data(self.v.as_slice())
      }
    }
  }
}

/// Can parse data from an already in memory byte array
///
/// * buffer holds the reference to the data that must be parsed
///
/// * length is the length of that buffer
///
/// * index is the position in the buffer
///
/// * chunk_size is the quantity of data sent at once
pub struct MemProducer<'x> {
  buffer: &'x [u8],
  chunk_size: usize,
  length: usize,
  index: usize
}

impl<'x> MemProducer<'x> {
  pub fn new(buffer: &'x[u8], chunk_size: usize) -> MemProducer {
    MemProducer {
      buffer:     buffer,
      chunk_size: chunk_size,
      length:     buffer.len(),
      index:      0
    }
  }
}

impl<'x> Producer for MemProducer<'x> {
  fn produce(&mut self) -> ProducerState<&[u8]> {
    if self.index + self.chunk_size < self.length {
      println!("self.index + {} < self.length", self.chunk_size);
      let new_index = self.index+self.chunk_size;
      let res = Data(self.buffer.slice(self.index, new_index));
      self.index = new_index;
      res
    } else if self.index < self.length {
      println!("self.index < self.length - 1");
      let res = Eof(self.buffer.slice(self.index, self.length));
      self.index = self.length;
      res
    } else {
      ProducerError(0)
    }
  }
}

/// Prepares a parser function for a push pipeline
///
/// It creates a function that accepts a producer and immediately starts parsing the data sent
///
/// # Example
///
/// ```ignore
/// fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],()> {
///   par.flat_map(local_print)
/// }
/// let mut p = MemProducer::new("abcdefgh".as_bytes(), 8);
///
/// pusher!(ps, pr);
/// ps(&mut p);
/// ```
#[macro_export]
macro_rules! pusher (
  ($name:ident, $f:expr) => (
    fn $name(producer: &mut Producer) {
      let mut acc: Vec<u8> = Vec::new();
      loop {
        let state = producer.produce();
        match state {
          ProducerState::Data(v) => {
            println!("got data");
            acc.push_all(v)
          },
          ProducerState::Eof([])  => {
            println!("eof empty");
            break;
          }
          ProducerState::Eof(v) => {
            println!("eof with {} bytes", v.len());
            acc.push_all(v)
          }
          _ => {break;}
        }
        let mut v2: Vec<u8>  = Vec::new();
        v2.push_all(acc.as_slice());
        let p = IResult::Done((), v2.as_slice());
        match $f(p) {
          IResult::Error(e)      => {
            println!("error, stopping: {}", e);
            break;
          },
          IResult::Incomplete(_) => {
            println!("incomplete");
          },
          IResult::Done(i, _)    => {
            println!("data, done");
            acc.clear();
            acc.push_all(i);
          }
        }
      }
    }
  );
);

#[cfg(test)]
mod tests {
  use super::*;
  use internal::IResult;
  use internal::IResult::*;
  use std::fmt::Debug;
  use std::str;
  use map::*;

  fn local_print<'a,T: Debug>(input: T) -> IResult<T, ()> {
    println!("{:?}", input);
    Done(input, ())
  }
  #[test]
  fn mem_producer() {
    let mut p = MemProducer::new("abcdefgh".as_bytes(), 4);
    assert_eq!(p.produce(), ProducerState::Data("abcd".as_bytes()));
  }

  #[test]
  fn mem_producer_2() {
    let mut p = MemProducer::new("abcdefgh".as_bytes(), 8);
    fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],()> {
      par.flat_map(local_print)
    }
    pusher!(ps, pr);
    ps(&mut p);
    //let mut iterations: uint = 0;
    //let mut p = MemProducer::new("abcdefghi".as_bytes(), 4);
    //p.push(|par| {iterations = iterations + 1; par.flat_map(print)});
    //assert_eq!(iterations, 3);
  }

  #[test]
  #[allow(unused_must_use)]
  fn file() {
    FileProducer::new("links.txt", 20).map(|producer: FileProducer| {
      let mut p = producer;
      //p.push(|par| {println!("parsed file: {}", par); par});
      //p.push(|par| par.flat_map(print));
      fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],()> {
        par.map_res(str::from_utf8).flat_map(local_print);
        Done("".as_bytes(), ())
      }
      pusher!(ps, pr);
      ps(&mut p);
      //assert!(false);
    });
  }

  #[test]
  fn accu() {
    fn f(input:&[u8]) -> IResult<&[u8],&[u8]> {
      if input.len() <= 4 {
        Incomplete(0)
      } else {
        Done("".as_bytes(), input)
      }
    }

    let mut p = MemProducer::new("abcdefgh".as_bytes(), 4);
    fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],&[u8]> {
      let r = par.flat_map(f);
      println!("f: {:?}", r);
      r
    }
    pusher!(ps, pr );
    ps(&mut p);
    //assert!(false);
  }

  #[test]
  fn accu_2() {
    fn f(input:&[u8]) -> IResult<&[u8],&[u8]> {
      if input.len() <= 4 || input.slice(0,5) != "abcde".as_bytes() {
        Incomplete(0)
      } else {
        Done(input.slice_from(5), input.slice(0,5))
      }
    }

    let mut p = MemProducer::new("abcdefgh".as_bytes(), 4);
    fn pr(par: IResult<(),&[u8]>) -> IResult<&[u8],&[u8]> {
      let r = par.flat_map(f);
      println!("f: {:?}", r);
      r
    }
    pusher!(ps, pr );
    ps(&mut p);
    //assert!(false);
  }
}
<|endoftext|>


<commit_before><commit_msg>Update tests to use example.com instead of domain.com<commit_after><|endoftext|>


<commit_before><commit_msg>Syncfile: fix issue with truncated uuids<commit_after><|endoftext|>


<commit_before><commit_msg>fiber can determine its status<commit_after><|endoftext|>


<commit_before><commit_msg>2019: Day 3, part 2.<commit_after>use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::io::Read;

use nom::{
    character::complete as character, combinator::map, combinator::map_opt, combinator::map_res,
    combinator::opt, multi::many1, sequence::pair, sequence::terminated, sequence::tuple, IResult,
};

type WirePath = Vec<Movement>;

#[derive(Clone, Copy, Debug)]
struct Movement {
    direction: Direction,
    amount: Amount,
}

#[derive(Clone, Copy, Debug)]
enum Direction {
    Down,
    Left,
    Right,
    Up,
}

impl Direction {
    fn inc(&self, position: Coordinates) -> Coordinates {
        match self {
            Direction::Down => Coordinates {
                y: position.y - 1,
                ..position
            },
            Direction::Left => Coordinates {
                x: position.x - 1,
                ..position
            },
            Direction::Right => Coordinates {
                x: position.x + 1,
                ..position
            },
            Direction::Up => Coordinates {
                y: position.y + 1,
                ..position
            },
        }
    }
}

type Amount = u32;

type Distance = u32;

#[derive(Clone, Copy, Debug, Hash)]
struct Coordinates {
    x: i32,
    y: i32,
}

impl Coordinates {
    const ZERO: Coordinates = Coordinates { x: 0, y: 0 };
}

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

fn main() -> io::Result<()> {
    let mut input: String = String::new();
    io::stdin().read_to_string(&mut input)?;
    let (_, (wire_a, wire_b)) = parse_wire_paths(&input)
        .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{:?}", err)))?;

    let wire_a_locations_and_distances = all_locations_and_distances(&wire_a);
    let wire_b_locations_and_distances = all_locations_and_distances(&wire_b);
    let wire_a_locations = wire_a_locations_and_distances
        .keys()
        .collect::<HashSet<&Coordinates>>();
    let wire_b_locations = wire_b_locations_and_distances
        .keys()
        .collect::<HashSet<&Coordinates>>();
    let overlapping_locations = wire_a_locations.intersection(&wire_b_locations);
    let best = overlapping_locations
        .map(|c| wire_a_locations_and_distances[c] + wire_b_locations_and_distances[c])
        .min()
        .ok_or(io::ErrorKind::NotFound)?;
    println!("{}", best);

    Ok(())
}

fn all_locations_and_distances(wire_path: &WirePath) -> HashMap<Coordinates, Distance> {
    let mut locations = HashMap::new();
    let mut position = Coordinates::ZERO;
    let mut steps = 0;
    for movement in wire_path {
        for _ in 0..movement.amount {
            steps += 1;
            position = movement.direction.inc(position);
            if !locations.contains_key(&position) {
                locations.insert(position, steps);
            }
        }
    }
    locations
}

fn parse_wire_paths(input: &str) -> IResult<&str, (WirePath, WirePath)> {
    tuple((parse_wire_path, parse_wire_path))(input)
}

fn parse_wire_path(input: &str) -> IResult<&str, WirePath> {
    terminated(
        many1(terminated(parse_movement, opt(character::char(',')))),
        opt(character::line_ending),
    )(input)
}

fn parse_movement(input: &str) -> IResult<&str, Movement> {
    map(
        pair(parse_direction, parse_amount),
        |(direction, amount)| Movement { direction, amount },
    )(input)
}

fn parse_direction(input: &str) -> IResult<&str, Direction> {
    map_opt(character::anychar, |c| match c {
        'D' => Some(Direction::Down),
        'L' => Some(Direction::Left),
        'R' => Some(Direction::Right),
        'U' => Some(Direction::Up),
        _ => None,
    })(input)
}

fn parse_amount(input: &str) -> IResult<&str, Amount> {
    map_res(character::digit1, |digits: &str| digits.parse::<Amount>())(input)
}
<|endoftext|>


<commit_before><commit_msg>Fix missing #[ruma_api(body)]<commit_after><|endoftext|>


<commit_before><commit_msg>Added if else example<commit_after>fn main() {
    let n = 5;

    if n < 0 {
        print!("{} is negative", n);
    } else if n > 0 {
        print!("{} is positive", n);
    } else {
        print!("{} is zero", n);
    }

    let big_n =
        if n < 10 && n > -10 {
            println!(", and is a small number, increase ten-fold");

            // This expression returns an `i32`.
            10 * n
        } else {
            println!(", and is a big number, reduce by two");

            // This expression must return an `i32` as well.
            n / 2
            // TODO ^ Try suppressing this expression with a semicolon.
        };
    //   ^ Don't forget to put a semicolon here! All `let` bindings need it.

    println!("{} -> {}", n, big_n);
}
<|endoftext|>


<commit_before><commit_msg>Rename `BlockLevelKind` to `NonReplacedContents`<commit_after><|endoftext|>


<commit_before><commit_msg>add dummy.rs<commit_after>// Usually 'cargo test' tries to build everything in the examples directory.
// That doesn't work for our examples because they have their own Cargo.toml and build.rs files.
// We can override the default behavior of 'cargo test' by supplying a dummy file, like this,
// and pointing to it in our Cargo.toml's [[example]] section.

fn main() {}
<|endoftext|>


<commit_before><commit_msg>EULER: Multiples of 3 and 5<commit_after>// EULER: Multiples of 3 and 5
// https://projecteuler.net/problem=1
fn main() {
    let sum = range(1i, 1000i).filter(|&x| {x % 3 == 0 || x % 5 == 0}).fold(0i, |a, b| a + b);
    println!("{}", sum);
}
<|endoftext|>


<commit_before><commit_msg>Add a test for assignment of unique boxes of generics<commit_after>// Issue #976

fn f<@T>(x: ~T) {
    let _x2 = x;
}
fn main() { }
<|endoftext|>


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

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

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

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

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

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

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

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

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

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

// NV allocator framework
struct NvAllocOps;

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

struct NvAllocOps {
    int (*nv_ao_init)(nv_alloc_t *, __va_list);
    void (*nv_ao_fini)(nv_alloc_t *);
    void *(*nv_ao_alloc)(nv_alloc_t *, size_t);
    void (*nv_ao_free)(nv_alloc_t *, void *, size_t);
    void (*nv_ao_reset)(nv_alloc_t *);
}
<commit_msg>Forgot to comment out unrustified code<commit_after>enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String, // TODO: What to name this string type?
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    Hrtime,
    Nvlist, // TODO: What to name this ?
    NvlistArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array
}

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

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

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

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

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

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

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

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

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

// NV allocator framework
struct NvAllocOps;

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

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


<commit_before><commit_msg>add write_read tests<commit_after>extern crate quick_protobuf;

use quick_protobuf::{Reader, MessageRead, Writer, MessageWrite};

macro_rules! write_read_primitive {
    ($name:ident, $read:ident, $write:ident) => (write_read_primitive!($name, $read, $write, 145););
    ($name:ident, $read:ident, $write:ident, $def:expr) => (
#[test]
fn $name(){
    let v = $def;
    let mut buf = Vec::new();
    {
        let mut w = Writer::new(&mut buf);
        w.$write(v).unwrap();
    }
    let len = buf.len();
    let mut buf = &*buf;
    let mut r = Reader::from_reader(&mut buf, len);
    assert_eq!(v, r.$read().unwrap());
}
    );
}

write_read_primitive!(wr_int32, read_int32, write_int32);
write_read_primitive!(wr_int64, read_int64, write_int64);
write_read_primitive!(wr_uint32, read_uint32, write_uint32);
write_read_primitive!(wr_uint64, read_uint64, write_uint64);
write_read_primitive!(wr_sint32, read_sint32, write_sint32);
write_read_primitive!(wr_sint64, read_sint64, write_sint64);
write_read_primitive!(wr_bool, read_bool, write_bool, true);
write_read_primitive!(wr_fixed32, read_fixed32, write_fixed32);
write_read_primitive!(wr_fixed64, read_fixed64, write_fixed64);
write_read_primitive!(wr_sfixed32, read_sfixed32, write_sfixed32);
write_read_primitive!(wr_sfixed64, read_sfixed64, write_sfixed64);
write_read_primitive!(wr_float, read_float, write_float, 5.8);
write_read_primitive!(wr_double, read_double, write_double, 5.8);

#[test]
fn wr_bytes(){
    let v = b"test_write_read";
    let mut buf = Vec::new();
    {
        let mut w = Writer::new(&mut buf);
        w.write_bytes(v).unwrap();
    }
    let len = buf.len();
    let mut buf = &*buf;
    let mut r = Reader::from_reader(&mut buf, len);
    assert_eq!(v, &*r.read_bytes().unwrap());
}

#[test]
fn wr_string(){
    let v = "test_write_read";
    let mut buf = Vec::new();
    {
        let mut w = Writer::new(&mut buf);
        w.write_string(v).unwrap();
    }
    let len = buf.len();
    let mut buf = &*buf;
    let mut r = Reader::from_reader(&mut buf, len);
    assert_eq!(v, &*r.read_string().unwrap());
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
enum TestEnum {
    A = 0,
    B = 1,
    C = 2,
}

impl From<i32> for TestEnum {
    fn from(v: i32) -> TestEnum {
        match v {
            0 => TestEnum::A,
            1 => TestEnum::B,
            2 => TestEnum::C,
            _ => unreachable!(),
        }
    }
}

#[test]
fn wr_enum(){

    let v = TestEnum::C;
    let mut buf = Vec::new();
    {
        let mut w = Writer::new(&mut buf);
        w.write_enum(v as i32).unwrap();
    }
    let len = buf.len();
    let mut buf = &*buf;
    let mut r = Reader::from_reader(&mut buf, len);
    assert_eq!(v, r.read_enum().unwrap());
}

<|endoftext|>


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

use core::prelude::*;

use ast;
use ast::{meta_item, item, expr, ident};
use codemap::span;
use ext::base::ExtCtxt;
use ext::build::{AstBuilder, Duplicate};
use ext::deriving::generic::*;

use core::vec;

pub fn expand_deriving_rand(cx: @ExtCtxt,
                            span: span,
                            mitem: @meta_item,
                            in_items: ~[@item])
    -> ~[@item] {
    let trait_def = TraitDef {
        path: Path::new(~["std", "rand", "Rand"]),
        additional_bounds: ~[],
        generics: LifetimeBounds::empty(),
        methods: ~[
            MethodDef {
                name: "rand",
                generics: LifetimeBounds {
                    lifetimes: ~[],
                    bounds: ~[("R",
                               ~[ Path::new(~["std", "rand", "Rng"]) ])]
                },
                explicit_self: None,
                args: ~[
                    Ptr(~Literal(Path::new_local("R")),
                        Borrowed(None, ast::m_mutbl))
                ],
                ret_ty: Self,
                const_nonmatching: false,
                combine_substructure: rand_substructure
            }
        ]
    };
    trait_def.expand(cx, span, mitem, in_items)
}

fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr {
    let rng = match substr.nonself_args {
        [rng] => ~[ rng ],
        _ => cx.bug("Incorrect number of arguments to `rand` in `deriving(Rand)`")
    };
    let rand_ident = ~[
        cx.ident_of("std"),
        cx.ident_of("rand"),
        cx.ident_of("Rand"),
        cx.ident_of("rand")
    ];
    let rand_call = || {
        cx.expr_call_global(span,
                            copy rand_ident,
                            ~[ rng[0].duplicate(cx) ])
    };

    return match *substr.fields {
        StaticStruct(_, ref summary) => {
            rand_thing(cx, span, substr.type_ident, summary, rand_call)
        }
        StaticEnum(_, ref variants) => {
            if variants.is_empty() {
                cx.span_fatal(span, "`Rand` cannot be derived for enums with no variants");
            }

            let variant_count = cx.expr_uint(span, variants.len());

            // need to specify the u32-ness of the random number
            let u32_ty = cx.ty_ident(span, cx.ident_of("u32"));
            let r_ty = cx.ty_ident(span, cx.ident_of("R"));
            let rand_name = cx.path_all(span, true, copy rand_ident, None, ~[ u32_ty, r_ty ]);
            let rand_name = cx.expr_path(rand_name);

            // ::std::rand::Rand::rand::<u32>(rng)
            let rv_call = cx.expr_call(span,
                                       rand_name,
                                       ~[ rng[0].duplicate(cx) ]);

            // rand() % variants.len()
            let rand_variant = cx.expr_binary(span, ast::rem,
                                              rv_call, variant_count);

            let mut arms = do variants.mapi |i, id_sum| {
                let i_expr = cx.expr_uint(span, i);
                let pat = cx.pat_lit(span, i_expr);

                match *id_sum {
                    (ident, ref summary) => {
                        cx.arm(span,
                               ~[ pat ],
                               rand_thing(cx, span, ident, summary, rand_call))
                    }
                }
            };

            // _ => {} at the end. Should never occur
            arms.push(cx.arm_unreachable(span));

            cx.expr_match(span, rand_variant, arms)
        }
        _ => cx.bug("Non-static method in `deriving(Rand)`")
    };

    fn rand_thing(cx: @ExtCtxt, span: span,
                  ctor_ident: ident,
                  summary: &Either<uint, ~[ident]>,
                  rand_call: &fn() -> @expr) -> @expr {
        match *summary {
            Left(count) => {
                if count == 0 {
                    cx.expr_ident(span, ctor_ident)
                } else {
                    let exprs = vec::from_fn(count, |_| rand_call());
                    cx.expr_call_ident(span, ctor_ident, exprs)
                }
            }
            Right(ref fields) => {
                let rand_fields = do fields.map |ident| {
                    cx.field_imm(span, *ident, rand_call())
                };
                cx.expr_struct_ident(span, ctor_ident, rand_fields)
            }
        }
    }
}
<commit_msg>syntax: revert the uint -> u32 "fix"; make the names/comment match.<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::prelude::*;

use ast;
use ast::{meta_item, item, expr, ident};
use codemap::span;
use ext::base::ExtCtxt;
use ext::build::{AstBuilder, Duplicate};
use ext::deriving::generic::*;

use core::vec;

pub fn expand_deriving_rand(cx: @ExtCtxt,
                            span: span,
                            mitem: @meta_item,
                            in_items: ~[@item])
    -> ~[@item] {
    let trait_def = TraitDef {
        path: Path::new(~["std", "rand", "Rand"]),
        additional_bounds: ~[],
        generics: LifetimeBounds::empty(),
        methods: ~[
            MethodDef {
                name: "rand",
                generics: LifetimeBounds {
                    lifetimes: ~[],
                    bounds: ~[("R",
                               ~[ Path::new(~["std", "rand", "Rng"]) ])]
                },
                explicit_self: None,
                args: ~[
                    Ptr(~Literal(Path::new_local("R")),
                        Borrowed(None, ast::m_mutbl))
                ],
                ret_ty: Self,
                const_nonmatching: false,
                combine_substructure: rand_substructure
            }
        ]
    };
    trait_def.expand(cx, span, mitem, in_items)
}

fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr {
    let rng = match substr.nonself_args {
        [rng] => ~[ rng ],
        _ => cx.bug("Incorrect number of arguments to `rand` in `deriving(Rand)`")
    };
    let rand_ident = ~[
        cx.ident_of("std"),
        cx.ident_of("rand"),
        cx.ident_of("Rand"),
        cx.ident_of("rand")
    ];
    let rand_call = || {
        cx.expr_call_global(span,
                            copy rand_ident,
                            ~[ rng[0].duplicate(cx) ])
    };

    return match *substr.fields {
        StaticStruct(_, ref summary) => {
            rand_thing(cx, span, substr.type_ident, summary, rand_call)
        }
        StaticEnum(_, ref variants) => {
            if variants.is_empty() {
                cx.span_fatal(span, "`Rand` cannot be derived for enums with no variants");
            }

            let variant_count = cx.expr_uint(span, variants.len());

            // need to specify the uint-ness of the random number
            let uint_ty = cx.ty_ident(span, cx.ident_of("uint"));
            let r_ty = cx.ty_ident(span, cx.ident_of("R"));
            let rand_name = cx.path_all(span, true, copy rand_ident, None, ~[ uint_ty, r_ty ]);
            let rand_name = cx.expr_path(rand_name);

            // ::std::rand::Rand::rand::<uint>(rng)
            let rv_call = cx.expr_call(span,
                                       rand_name,
                                       ~[ rng[0].duplicate(cx) ]);

            // rand() % variants.len()
            let rand_variant = cx.expr_binary(span, ast::rem,
                                              rv_call, variant_count);

            let mut arms = do variants.mapi |i, id_sum| {
                let i_expr = cx.expr_uint(span, i);
                let pat = cx.pat_lit(span, i_expr);

                match *id_sum {
                    (ident, ref summary) => {
                        cx.arm(span,
                               ~[ pat ],
                               rand_thing(cx, span, ident, summary, rand_call))
                    }
                }
            };

            // _ => {} at the end. Should never occur
            arms.push(cx.arm_unreachable(span));

            cx.expr_match(span, rand_variant, arms)
        }
        _ => cx.bug("Non-static method in `deriving(Rand)`")
    };

    fn rand_thing(cx: @ExtCtxt, span: span,
                  ctor_ident: ident,
                  summary: &Either<uint, ~[ident]>,
                  rand_call: &fn() -> @expr) -> @expr {
        match *summary {
            Left(count) => {
                if count == 0 {
                    cx.expr_ident(span, ctor_ident)
                } else {
                    let exprs = vec::from_fn(count, |_| rand_call());
                    cx.expr_call_ident(span, ctor_ident, exprs)
                }
            }
            Right(ref fields) => {
                let rand_fields = do fields.map |ident| {
                    cx.field_imm(span, *ident, rand_call())
                };
                cx.expr_struct_ident(span, ctor_ident, rand_fields)
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for generic iface methods<commit_after>iface to_str {
    fn to_str() -> str;
}
impl of to_str for int {
    fn to_str() -> str { int::str(self) }
}
impl of to_str for str {
    fn to_str() -> str { self }
}

iface map<T> {
    fn map<U>(f: block(T) -> U) -> [U];
}
impl <T> of map<T> for [T] {
    fn map<U>(f: block(T) -> U) -> [U] {
        let r = [];
        for x in self { r += [f(x)]; }
        r
    }
}

fn foo<U, T: map<U>>(x: T) -> [str] {
    x.map({|_e| "hi" })
}
fn bar<U: to_str, T: map<U>>(x: T) -> [str] {
    x.map({|_e| _e.to_str() })
}

fn main() {
    assert foo([1]) == ["hi"];
    assert bar::<int, [int]>([4, 5]) == ["4", "5"];
    assert bar::<str, [str]>(["x", "y"]) == ["x", "y"];
}
<|endoftext|>


<commit_before>fn on_osmain(f: fn~()) {
    let po = comm::Port();
    let ch = comm::Chan(po);
    do task::spawn_sched(task::PlatformThread) |copy f| {
        f();
        comm::send(ch, ());
    }
    comm::recv(po);
}

// FIXME: Needs additional cocoa setup on OS X. rust-cocoa should probably just
// be a dependency
#[test]
#[ignore(cfg(target_os = "macos"))]
fn test_everything() {

    on_osmain(|| {
        init(~[init_video, init_timer]);
        run_tests(~[
            general::test_was_init,
            general::test_set_error,
            general::test_error,
            general::test_clear_error,
            video::test_set_video_mode,
            // FIXME: Doesn't work when called from a directory that
            // doesn't contain the test image file
            //video::test_blit,
            test_event::test_poll_event_none
            // FIXME: This test is interactive
            //test_event::test_keyboard
        ]);
        quit();
    })
}

fn run_tests(tests: ~[fn()]) {
    vec::iter(tests, |test| test());
}

mod general {
    fn test_was_init() {
        assert init_timer == init_timer;
        //assert vec::contains(was_init(~[init_timer]), init_timer);
    }

    fn test_set_error() {
        set_error(~"test");
        assert get_error() == ~"test";
    }

    fn test_error() {
        clear_error();
        assert str::is_empty(get_error());
        error(enomem);
        assert str::is_not_empty(get_error());
    }

    fn test_clear_error() {
        set_error(~"test");
        clear_error();
        assert str::is_empty(get_error());
    }
}

mod test_event {
    fn test_poll_event_none() {
        ::event::poll_event(|event| assert event == ::event::no_event);
    }

    fn test_keyboard() {
        io::println(~"press a key in the window");
        let surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::swsurface], ~[::video::doublebuf, ::video::resizable]);
        let mut keydown = false;
        let mut keyup = false;
        while !keydown || !keyup {
            ::event::poll_event(|event| {
                match event {
                  event::keyup_event(_) => keyup = true,
                  event::keydown_event(_) => keydown = true,
                  _ => { }
                }
            })
        }
        ::video::free_surface(surface);
    }
}

mod video {

    fn test_set_video_mode() {
        let surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::hwsurface], ~[::video::doublebuf]);
        assert surface != ptr::null();
        ::video::free_surface(surface);
    }

    fn test_blit() {
        let screen = ::video::set_video_mode(320, 200, 32,
            ~[::video::swsurface], ~[::video::doublebuf]);
        assert screen != ptr::null();

        let image = {
            // FIXME: We need to load this from the crate instead of
            // off the filesystem
            let tmp = ::video::load_bmp(~"rust-logo-128x128-blk.bmp");
            assert tmp != ptr::null();
            let image = ::video::display_format(tmp);
            assert image != ptr::null();
            ::video::free_surface(tmp);
            image
        };

        for iter::repeat(1u) || {
            ::video::blit_surface(image, ptr::null(),
                                  screen, ptr::null());
            ::video::flip(screen);
            ::event::poll_event(|_event| {})
        };

        ::video::free_surface(image);
        ::video::free_surface(screen);
    }
}
<commit_msg>Silly me, I left the test code commented out! Uncommented, so all tests validly passing now.<commit_after>fn on_osmain(f: fn~()) {
    let po = comm::Port();
    let ch = comm::Chan(po);
    do task::spawn_sched(task::PlatformThread) |copy f| {
        f();
        comm::send(ch, ());
    }
    comm::recv(po);
}

// FIXME: Needs additional cocoa setup on OS X. rust-cocoa should probably just
// be a dependency
#[test]
#[ignore(cfg(target_os = "macos"))]
fn test_everything() {

    on_osmain(|| {
        init(~[init_video, init_timer]);
        run_tests(~[
            general::test_was_init,
            general::test_set_error,
            general::test_error,
            general::test_clear_error,
            video::test_set_video_mode,
            // FIXME: Doesn't work when called from a directory that
            // doesn't contain the test image file
            //video::test_blit,
            test_event::test_poll_event_none
            // FIXME: This test is interactive
            //test_event::test_keyboard
        ]);
        quit();
    })
}

fn run_tests(tests: ~[fn()]) {
    vec::iter(tests, |test| test());
}

mod general {
    fn test_was_init() {
        assert vec::contains(was_init(~[init_timer]), init_timer);
    }

    fn test_set_error() {
        set_error(~"test");
        assert get_error() == ~"test";
    }

    fn test_error() {
        clear_error();
        assert str::is_empty(get_error());
        error(enomem);
        assert str::is_not_empty(get_error());
    }

    fn test_clear_error() {
        set_error(~"test");
        clear_error();
        assert str::is_empty(get_error());
    }
}

mod test_event {
    fn test_poll_event_none() {
        ::event::poll_event(|event| assert event == ::event::no_event);
    }

    fn test_keyboard() {
        io::println(~"press a key in the window");
        let surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::swsurface], ~[::video::doublebuf, ::video::resizable]);
        let mut keydown = false;
        let mut keyup = false;
        while !keydown || !keyup {
            ::event::poll_event(|event| {
                match event {
                  event::keyup_event(_) => keyup = true,
                  event::keydown_event(_) => keydown = true,
                  _ => { }
                }
            })
        }
        ::video::free_surface(surface);
    }
}

mod video {

    fn test_set_video_mode() {
        let surface = ::video::set_video_mode(320, 200, 32,
            ~[::video::hwsurface], ~[::video::doublebuf]);
        assert surface != ptr::null();
        ::video::free_surface(surface);
    }

    fn test_blit() {
        let screen = ::video::set_video_mode(320, 200, 32,
            ~[::video::swsurface], ~[::video::doublebuf]);
        assert screen != ptr::null();

        let image = {
            // FIXME: We need to load this from the crate instead of
            // off the filesystem
            let tmp = ::video::load_bmp(~"rust-logo-128x128-blk.bmp");
            assert tmp != ptr::null();
            let image = ::video::display_format(tmp);
            assert image != ptr::null();
            ::video::free_surface(tmp);
            image
        };

        for iter::repeat(1u) || {
            ::video::blit_surface(image, ptr::null(),
                                  screen, ptr::null());
            ::video::flip(screen);
            ::event::poll_event(|_event| {})
        };

        ::video::free_surface(image);
        ::video::free_surface(screen);
    }
}
<|endoftext|>


<commit_before>

// This is a test for issue #109.
use std;

fn slice[T](e: vec[T]) {
    let result: vec[T] = std::vec::alloc[T](1 as uint);
    log "alloced";
    result += e;
    log "appended";
}

fn main() { slice[str](["a"]); }<commit_msg>Remove run-pass/vec-alloc-append.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Fix #207 with unit test<commit_after>use ron::{de::from_str, ser::to_string};
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data")]
enum TestEnum {
    Name(String),
    Index(u32),
}

#[test]
fn test_adjacently_tagged() {
    let source = TestEnum::Index(1);

    let ron_string = to_string(&source).unwrap();

    assert_eq!(ron_string, "(type:\"Index\",data:1)");

    let deserialized = from_str::<TestEnum>(&ron_string).unwrap();

    assert_eq!(deserialized, source);
}
<|endoftext|>


<commit_before><commit_msg>Write buffer to stream<commit_after><|endoftext|>


<commit_before><commit_msg>Add menu example<commit_after>/*
 * Copyright (c) 2019 Boucher, Antoni <bouanto@zoho.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

use gtk::{
    GtkMenuItemExt,
    Inhibit,
    MenuShellExt,
    OrientableExt,
    WidgetExt,
};
use gtk::Orientation::Vertical;
use relm::{Relm, Widget, connect};
use relm_derive::{Msg, widget};

use self::Msg::*;

pub struct Model {
    relm: Relm<Win>,
}

#[derive(Msg)]
pub enum Msg {
    Quit,
}

#[widget]
impl Widget for Win {
    fn init_view(&mut self) {
        let file_menu = gtk::Menu::new();
        let file_item = gtk::MenuItem::new_with_label("File");
        file_item.set_submenu(Some(&file_menu));
        let quit_item = gtk::MenuItem::new_with_label("Quit");
        self.menubar.append(&file_item);
        file_menu.append(&quit_item);
        self.menubar.show_all();

        connect!(quit_item, connect_activate(_), self.model.relm, Quit);
    }

    fn model(relm: &Relm<Self>, _: ()) -> Model {
        Model {
            relm: relm.clone(),
        }
    }

    fn update(&mut self, event: Msg) {
        match event {
            Quit => gtk::main_quit(),
        }
    }

    view! {
        gtk::Window {
            gtk::Box {
                orientation: Vertical,
                #[name="menubar"]
                gtk::MenuBar {
                },
            },
            delete_event(_, _) => (Quit, Inhibit(false)),
        }
    }
}

fn main() {
    Win::run(()).expect("Win::run failed");
}
<|endoftext|>


<commit_before><commit_msg>Define a word<commit_after>pub mod components {

    pub struct word {
        val: [u8; 3],
    }

    impl word {
        pub fn new() -> Self {
            word { val: [0; 3] }
        }
    }

} /* components */
<|endoftext|>


<commit_before><commit_msg>build script<commit_after>use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("hello.rs");
    let mut f = File::create(&dest_path).unwrap();

    f.write_all(b"
        pub fn message() -> &'static str {
            \"Hello, World!\"
        }
    ").unwrap();
}
<|endoftext|>


<commit_before><commit_msg>CloneSlicePrelude is now in the prelude, import unnecessary ...<commit_after><|endoftext|>


<commit_before><commit_msg>test: enforce newlines in array format<commit_after>use ron::ser::{to_string_pretty, PrettyConfig};

#[test]
fn small_array() {
    let arr = &[(), (), ()][..];
    assert_eq!(
        to_string_pretty(&arr, PrettyConfig::new().with_new_line("\n".to_string())).unwrap(),
        "[
    (),
    (),
    (),
]"
    );
}
<|endoftext|>


<commit_before><commit_msg>rust kata<commit_after>use std::mem;

fn main() {
    let a: u8 = 123;
    println!("a = {}", a);

    let mut b: i8 = 0; //mutable
    println!("b = {}", b);
    b = 42;
    println!("b = {}", b);

    let mut c = 123456789;
    println!("c = {}, size = {}", c,  mem::size_of_val(&c));
    c = -1;
    println!("c = {}, size = {}", c,  mem::size_of_val(&c));

    let z: isize = 123; // isize/ usize
    let size_of_z = mem::size_of_val(&z);
    println!("z = {}, takes up {} bytes, {}-bit OS",
            z, size_of_z, size_of_z * 8);

    let d: char = 'x';
    println!("d = {}, size = {} bytes", d, mem::size_of_val(&d));

    let e: f64 = 2.5;
    println!("e = {}, size = {} bytes", e, mem::size_of_val(&e));

    let g = false;
    println!("g = {}, size = {} bytes", g, mem::size_of_val(&g));

    let f: bool = 4 > 0;
    println!("f = {}, size = {} bytes", f, mem::size_of_val(&f));

    println!("{}", i8::min_value());
}
<|endoftext|>


<commit_before><commit_msg>Add iterator extension for reporting from iterator<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2342<commit_after>// https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/
pub fn maximum_sum(nums: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", maximum_sum(vec![18, 43, 36, 13, 7])); // 54
    println!("{}", maximum_sum(vec![10, 12, 19, 14])); // -1
}
<|endoftext|>


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

trait Qiz {
  fn qiz();
}

struct Foo;
impl Qiz for Foo {
  fn qiz() {}
}

struct Bar {
  foos: &'static [&'static (Qiz + 'static)]
}

const FOO : Foo = Foo;
const BAR : Bar = Bar { foos: &[&FOO]};
//~^ ERROR: cannot convert to a trait object because trait `Qiz` is not object-safe [E0038]

fn main() { }
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #42160 - venkatagiri:issue_38821, r=Mark-Simulacrum<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.

pub struct Nullable<T: NotNull>(T);

pub trait NotNull {}

pub trait IntoNullable {
    type Nullable;
}

impl<T: NotNull> IntoNullable for T {
    type Nullable = Nullable<T>;
}

impl<T: NotNull> IntoNullable for Nullable<T> {
    type Nullable = Nullable<T>;
}

pub trait Expression {
    type SqlType;
}

pub trait Column: Expression {}

#[derive(Debug, Copy, Clone)]
//~^ ERROR the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied
pub enum ColumnInsertValue<Col, Expr> where
    Col: Column,
    Expr: Expression<SqlType=<Col::SqlType as IntoNullable>::Nullable>,
{
    Expression(Col, Expr),
    Default(Col),
}

fn main() {}
<|endoftext|>


<commit_before>//! Basic DOM data structures.

use std::collections::hashmap::{HashMap, HashSet};

pub type AttrMap = HashMap<String, String>;

#[deriving(Show)]
pub struct Node {
    // data common to all nodes:
    pub children: Vec<Node>,

    // data specific to each node type:
    pub node_type: NodeType,
}

#[deriving(Show)]
pub enum NodeType {
    Element(ElementData),
    Text(String),
}

#[deriving(Show)]
pub struct ElementData {
    pub tag_name: String,
    pub attributes: AttrMap,
}

// Constructor functions for convenience:

pub fn text(data: String) -> Node {
    Node::new(vec!(), Text(data))
}

pub fn elem(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {
    Node::new(children, Element(ElementData {
        tag_name: name,
        attributes: attrs,
    }))
}

// Node methods

impl Node {
    fn new(children: Vec<Node>, node_type: NodeType) -> Node {
        Node {
            children: children,
            node_type: node_type
        }
    }
}

// Element methods

impl ElementData {
    pub fn get_attribute<'a>(&'a self, key: &str) -> Option<&'a String> {
        self.attributes.find_equiv(&key)
    }

    pub fn id<'a>(&'a self) -> Option<&'a String> {
        self.get_attribute("id")
    }

    pub fn classes<'a>(&'a self) -> HashSet<&'a str> {
        self.get_attribute("class").iter().flat_map(|classlist| {
            classlist.as_slice().split(' ')
        }).collect()
    }
}
<commit_msg>Simplify DOM constructors<commit_after>//! Basic DOM data structures.

use std::collections::hashmap::{HashMap, HashSet};

pub type AttrMap = HashMap<String, String>;

#[deriving(Show)]
pub struct Node {
    // data common to all nodes:
    pub children: Vec<Node>,

    // data specific to each node type:
    pub node_type: NodeType,
}

#[deriving(Show)]
pub enum NodeType {
    Element(ElementData),
    Text(String),
}

#[deriving(Show)]
pub struct ElementData {
    pub tag_name: String,
    pub attributes: AttrMap,
}

// Constructor functions for convenience:

pub fn text(data: String) -> Node {
    Node { children: vec![], node_type: Text(data) }
}

pub fn elem(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {
    Node {
        children: children,
        node_type: Element(ElementData {
            tag_name: name,
            attributes: attrs,
        })
    }
}

// Element methods

impl ElementData {
    pub fn get_attribute<'a>(&'a self, key: &str) -> Option<&'a String> {
        self.attributes.find_equiv(&key)
    }

    pub fn id<'a>(&'a self) -> Option<&'a String> {
        self.get_attribute("id")
    }

    pub fn classes<'a>(&'a self) -> HashSet<&'a str> {
        self.get_attribute("class").iter().flat_map(|classlist| {
            classlist.as_slice().split(' ')
        }).collect()
    }
}
<|endoftext|>


<commit_before>//! Basic DOM data structures.

use std::collections::{HashMap,HashSet};

pub type AttrMap = HashMap<String, String>;

#[deriving(Show)]
pub struct Node {
    // data common to all nodes:
    pub children: Vec<Node>,

    // data specific to each node type:
    pub node_type: NodeType,
}

#[deriving(Show)]
pub enum NodeType {
    Element(ElementData),
    Text(String),
}

#[deriving(Show)]
pub struct ElementData {
    pub tag_name: String,
    pub attributes: AttrMap,
}

// Constructor functions for convenience:

pub fn text(data: String) -> Node {
    Node { children: vec![], node_type: NodeType::Text(data) }
}

pub fn elem(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {
    Node {
        children: children,
        node_type: NodeType::Element(ElementData {
            tag_name: name,
            attributes: attrs,
        })
    }
}

// Element methods

impl ElementData {
    pub fn get_attribute(&self, key: &str) -> Option<&String> {
        self.attributes.get(key)
    }

    pub fn id(&self) -> Option<&String> {
        self.get_attribute("id")
    }

    pub fn classes(&self) -> HashSet<&str> {
        match self.get_attribute("class") {
            Some(classlist) => classlist.as_slice().split(' ').collect(),
            None => HashSet::new()
        }
    }
}
<commit_msg>Simplify attribute lookup methods<commit_after>//! Basic DOM data structures.

use std::collections::{HashMap,HashSet};

pub type AttrMap = HashMap<String, String>;

#[deriving(Show)]
pub struct Node {
    // data common to all nodes:
    pub children: Vec<Node>,

    // data specific to each node type:
    pub node_type: NodeType,
}

#[deriving(Show)]
pub enum NodeType {
    Element(ElementData),
    Text(String),
}

#[deriving(Show)]
pub struct ElementData {
    pub tag_name: String,
    pub attributes: AttrMap,
}

// Constructor functions for convenience:

pub fn text(data: String) -> Node {
    Node { children: vec![], node_type: NodeType::Text(data) }
}

pub fn elem(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {
    Node {
        children: children,
        node_type: NodeType::Element(ElementData {
            tag_name: name,
            attributes: attrs,
        })
    }
}

// Element methods

impl ElementData {
    pub fn id(&self) -> Option<&String> {
        self.attributes.get("id")
    }

    pub fn classes(&self) -> HashSet<&str> {
        match self.attributes.get("class") {
            Some(classlist) => classlist.as_slice().split(' ').collect(),
            None => HashSet::new()
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add as_bytes method to MaybeUtf8<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor domain_match to be easier to read.<commit_after><|endoftext|>


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

#![feature(duration)]

extern crate libc;

use std::io;
use std::ops::Neg;
use std::net::{ToSocketAddrs, SocketAddr};

use utils::{One, NetInt};

mod tcp;
mod udp;
mod socket;
mod ext;
mod utils;

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

pub use tcp::TcpBuilder;
pub use udp::UdpBuilder;
pub use ext::{TcpStreamExt, TcpListenerExt, UdpSocketExt};

fn one_addr<T: ToSocketAddrs>(tsa: T) -> io::Result<SocketAddr> {
    let mut addrs = try!(tsa.to_socket_addrs());
    let addr = match addrs.next() {
        Some(addr) => addr,
        None => return Err(io::Error::new(io::ErrorKind::Other,
                                          "no socket addresses could be resolved"))
    };
    if addrs.next().is_none() {
        Ok(addr)
    } else {
        Err(io::Error::new(io::ErrorKind::Other,
                           "more than one address resolved"))
    }
}

fn cvt<T: One + PartialEq + Neg<Output=T>>(t: T) -> io::Result<T> {
    let one: T = T::one();
    if t == -one {
        Err(io::Error::last_os_error())
    } else {
        Ok(t)
    }
}

fn hton<I: NetInt>(i: I) -> I { i.to_be() }

trait AsInner {
    type Inner;
    fn as_inner(&self) -> &Self::Inner;
}

trait FromInner {
    type Inner;
    fn from_inner(inner: Self::Inner) -> Self;
}

trait IntoInner {
    type Inner;
    fn into_inner(self) -> Self::Inner;
}
<commit_msg>Reexport *BuilderExt<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(duration)]

extern crate libc;

use std::io;
use std::ops::Neg;
use std::net::{ToSocketAddrs, SocketAddr};

use utils::{One, NetInt};

mod tcp;
mod udp;
mod socket;
mod ext;
mod utils;

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

pub use tcp::TcpBuilder;
pub use udp::UdpBuilder;
pub use ext::{TcpStreamExt, TcpListenerExt, UdpSocketExt};
pub use ext::{TcpBuilderExt, UdpBuilderExt};

fn one_addr<T: ToSocketAddrs>(tsa: T) -> io::Result<SocketAddr> {
    let mut addrs = try!(tsa.to_socket_addrs());
    let addr = match addrs.next() {
        Some(addr) => addr,
        None => return Err(io::Error::new(io::ErrorKind::Other,
                                          "no socket addresses could be resolved"))
    };
    if addrs.next().is_none() {
        Ok(addr)
    } else {
        Err(io::Error::new(io::ErrorKind::Other,
                           "more than one address resolved"))
    }
}

fn cvt<T: One + PartialEq + Neg<Output=T>>(t: T) -> io::Result<T> {
    let one: T = T::one();
    if t == -one {
        Err(io::Error::last_os_error())
    } else {
        Ok(t)
    }
}

fn hton<I: NetInt>(i: I) -> I { i.to_be() }

trait AsInner {
    type Inner;
    fn as_inner(&self) -> &Self::Inner;
}

trait FromInner {
    type Inner;
    fn from_inner(inner: Self::Inner) -> Self;
}

trait IntoInner {
    type Inner;
    fn into_inner(self) -> Self::Inner;
}
<|endoftext|>


<commit_before><commit_msg>Demonstrated rotation works for line collison, I'm just stupid<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unecessary feature gate 'io'<commit_after><|endoftext|>


<commit_before><commit_msg>:hammer: Fix stub<commit_after><|endoftext|>


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

use rustc::infer::canonical::{Canonical, QueryResult};
use rustc::traits::{self, FulfillmentContext, ObligationCause, SelectionContext};
use rustc::traits::query::{CanonicalProjectionGoal, NoSolution, normalize::NormalizationResult};
use rustc::ty::{ParamEnvAnd, TyCtxt};
use rustc_data_structures::sync::Lrc;
use syntax::ast::DUMMY_NODE_ID;
use syntax_pos::DUMMY_SP;
use std::sync::atomic::Ordering;

crate fn normalize_projection_ty<'tcx>(
    tcx: TyCtxt<'_, 'tcx, 'tcx>,
    goal: CanonicalProjectionGoal<'tcx>,
) -> Result<Lrc<Canonical<'tcx, QueryResult<'tcx, NormalizationResult<'tcx>>>>, NoSolution> {
    debug!("normalize_provider(goal={:#?})", goal);

    tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed);
    tcx.infer_ctxt().enter(|ref infcx| {
        let (
            ParamEnvAnd {
                param_env,
                value: goal,
            },
            canonical_inference_vars,
        ) = infcx.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &goal);
        let fulfill_cx = &mut FulfillmentContext::new();
        let selcx = &mut SelectionContext::new(infcx);
        let cause = ObligationCause::misc(DUMMY_SP, DUMMY_NODE_ID);
        let mut obligations = vec![];
        let answer =
            traits::normalize_projection_type(selcx, param_env, goal, cause, 0, &mut obligations);
        fulfill_cx.register_predicate_obligations(infcx, obligations);

        // Now that we have fulfilled as much as we can, create a solution
        // from what we've learned.
        infcx.make_canonicalized_query_result(
            canonical_inference_vars,
            NormalizationResult { normalized_ty: answer },
            fulfill_cx,
        )
    })
}
<commit_msg>use query boiler plate for `normalize_projection_ty` too<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use rustc::infer::canonical::{Canonical, QueryResult};
use rustc::infer::InferOk;
use rustc::traits::query::{normalize::NormalizationResult, CanonicalProjectionGoal, NoSolution};
use rustc::traits::{self, ObligationCause, SelectionContext};
use rustc::ty::{ParamEnvAnd, TyCtxt};
use rustc_data_structures::sync::Lrc;
use std::sync::atomic::Ordering;
use syntax::ast::DUMMY_NODE_ID;
use syntax_pos::DUMMY_SP;

crate fn normalize_projection_ty<'tcx>(
    tcx: TyCtxt<'_, 'tcx, 'tcx>,
    goal: CanonicalProjectionGoal<'tcx>,
) -> Result<Lrc<Canonical<'tcx, QueryResult<'tcx, NormalizationResult<'tcx>>>>, NoSolution> {
    debug!("normalize_provider(goal={:#?})", goal);

    tcx.sess
        .perf_stats
        .normalize_projection_ty
        .fetch_add(1, Ordering::Relaxed);
    tcx.infer_ctxt().enter_canonical_trait_query(
        &goal,
        |infcx,
         ParamEnvAnd {
             param_env,
             value: goal,
         }| {
            let selcx = &mut SelectionContext::new(infcx);
            let cause = ObligationCause::misc(DUMMY_SP, DUMMY_NODE_ID);
            let mut obligations = vec![];
            let answer = traits::normalize_projection_type(
                selcx,
                param_env,
                goal,
                cause,
                0,
                &mut obligations,
            );
            Ok(InferOk {
                value: NormalizationResult {
                    normalized_ty: answer,
                },
                obligations,
            })
        },
    )
}
<|endoftext|>


<commit_before><commit_msg>Remove unused file<commit_after><|endoftext|>


<commit_before><commit_msg>Unused constant<commit_after><|endoftext|>


<commit_before><commit_msg>object safety implemented<commit_after><|endoftext|>


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

// Test that we give the generic E0495 when one of the free regions is
// bound in a closure (rather than suggesting a change to the signature
// of the closure, which is not specified in `foo` but rather in `invoke`).

// FIXME - This might be better as a UI test, but the finer details
// of the error seem to vary on different machines.
fn invoke<'a, F>(x: &'a i32, f: F) -> &'a i32
where F: FnOnce(&'a i32, &i32) -> &'a i32
{
    let y = 22;
    f(x, &y)
}

fn foo<'a>(x: &'a i32) { //~ ERROR E0495
    invoke(&x, |a, b| if a > b { a } else { b });
}

fn main() {}
<commit_msg>move ERROR line<commit_after>// Copyright 2016 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.

// Test that we give the generic E0495 when one of the free regions is
// bound in a closure (rather than suggesting a change to the signature
// of the closure, which is not specified in `foo` but rather in `invoke`).

// FIXME - This might be better as a UI test, but the finer details
// of the error seem to vary on different machines.
fn invoke<'a, F>(x: &'a i32, f: F) -> &'a i32
where F: FnOnce(&'a i32, &i32) -> &'a i32
{
    let y = 22;
    f(x, &y)
}

fn foo<'a>(x: &'a i32) {
    invoke(&x, |a, b| if a > b { a } else { b }); //~ ERROR E0495
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Added a test case for #506<commit_after>/*
  A reduced test case for Issue #506, provided by Rob Arnold.
*/

native "rust" mod rustrt {
  fn task_yield();
}

fn main() {
  spawn rustrt::task_yield();
}

<|endoftext|>


<commit_before><commit_msg>Complete the parser. Remove tests for parsing attributes.<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Deny non-absolut import pathes"<commit_after><|endoftext|>


<commit_before><commit_msg>Add RethinkDB errors to module `errors`<commit_after><|endoftext|>


<commit_before><commit_msg>Use the connection module in RethinkDb<commit_after><|endoftext|>


<commit_before><commit_msg>Add code for low-power-embedded-game<commit_after>pub fn divmod(dividend: i16, divisor: i16) -> (i16, i16) {
    (dividend / divisor, dividend % divisor)
}

pub fn evens<T>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T> {
    iter.step_by(2)
}

pub struct Position(pub i16, pub i16);
impl Position {
    pub fn manhattan(&self) -> i16 {
        self.0.abs() + self.1.abs()
    }
}
<|endoftext|>


<commit_before><commit_msg>difference between functions and closures<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test case for conditional drop<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.

#![feature(generators, generator_trait)]

use std::ops::Generator;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};

static A: AtomicUsize = ATOMIC_USIZE_INIT;

struct B;

impl Drop for B {
    fn drop(&mut self) {
        A.fetch_add(1, Ordering::SeqCst);
    }
}

fn test() -> bool { true }
fn test2() -> bool { false }

fn main() {
    t1();
    t2();
}

fn t1() {
    let mut a = || {
        let b = B;
        if test() {
            drop(b);
        }
        yield;
    };

    let n = A.load(Ordering::SeqCst);
    a.resume();
    assert_eq!(A.load(Ordering::SeqCst), n + 1);
    a.resume();
    assert_eq!(A.load(Ordering::SeqCst), n + 1);
}

fn t2() {
    let mut a = || {
        let b = B;
        if test2() {
            drop(b);
        }
        yield;
    };

    let n = A.load(Ordering::SeqCst);
    a.resume();
    assert_eq!(A.load(Ordering::SeqCst), n);
    a.resume();
    assert_eq!(A.load(Ordering::SeqCst), n + 1);
}
<|endoftext|>


<commit_before><commit_msg>:art: Refactor the Slack Client<commit_after><|endoftext|>


<commit_before><commit_msg>Add test: check with imag-ids whether no entries exist after init<commit_after><|endoftext|>


<commit_before><commit_msg>add `volatile_load` and `volatile_store`<commit_after><|endoftext|>


<commit_before><commit_msg>"Morden" as chain name produces incorrect rlp of transaction Added proper handling for 'morden' inside utils<commit_after><|endoftext|>


<commit_before><commit_msg>Moved test utils into `util` module<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests for `minimum_packet_size`<commit_after>// Copyright (c) 2015 Robert Clipsham <robert@octarineparrot.com>
//
// 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.

#![feature(core, collections, custom_attribute, plugin)]
#![plugin(pnet_macros)]

extern crate pnet;
extern crate pnet_macros;

use pnet_macros::types::*;

#[packet]
pub struct ByteAligned {
    banana: u8,
    #[payload]
    payload: Vec<u8>
}

#[packet]
pub struct ByteAlignedWithVariableLength {
    banana: u16,
    #[length_fn = "length_fn1"]
    #[payload]
    payload: Vec<u8>
}

fn length_fn1(_: &ByteAlignedWithVariableLengthPacket) -> usize {
    unimplemented!()
}

#[packet]
pub struct ByteAlignedWithVariableLengthAndPayload {
    banana: u32,
    #[length_fn = "length_fn2"]
    var_length: Vec<u8>,
    #[payload]
    payload: Vec<u8>
}

fn length_fn2(_: &ByteAlignedWithVariableLengthAndPayloadPacket) -> usize {
    unimplemented!()
}

#[packet]
pub struct NonByteAligned {
    banana: u3,
    tomato: u5,
    #[payload]
    payload: Vec<u8>
}

#[packet]
pub struct NonByteAlignedWithVariableLength {
    banana: u11be,
    tomato: u21be,
    #[length_fn = "length_fn3"]
    #[payload]
    payload: Vec<u8>
}

fn length_fn3(_: &NonByteAlignedWithVariableLengthPacket) -> usize {
    unimplemented!()
}

#[packet]
pub struct NonByteAlignedWithVariableLengthAndPayload {
    banana: u7,
    tomato: u9be,
    #[length_fn = "length_fn4"]
    var_length: Vec<u8>,
    #[payload]
    payload: Vec<u8>
}

fn length_fn4(_: &NonByteAlignedWithVariableLengthAndPayloadPacket) -> usize {
    unimplemented!()
}

fn main() {
    assert_eq!(ByteAlignedPacket::minimum_packet_size(), 1);
    assert_eq!(ByteAlignedWithVariableLengthPacket::minimum_packet_size(), 2);
    assert_eq!(ByteAlignedWithVariableLengthAndPayloadPacket::minimum_packet_size(), 4);
    assert_eq!(NonByteAlignedPacket::minimum_packet_size(), 1);
    assert_eq!(NonByteAlignedWithVariableLengthPacket::minimum_packet_size(), 4);
    assert_eq!(NonByteAlignedWithVariableLengthAndPayloadPacket::minimum_packet_size(), 2);
}
<|endoftext|>


<commit_before><commit_msg>Update create_media_content to r0.4.0<commit_after><|endoftext|>


<commit_before><commit_msg>Add option to override ref data in contact entries<commit_after><|endoftext|>