<commit_before>
extern crate rs6502;

#[test]
fn INTEGRATION_can_assemble_disassemble_basic_opcodes() {
    let asm = "LDA $4400";

    let mut assembler = rs6502::Assembler::new();
    let disassembler = rs6502::Disassembler::with_code_only();

    let bytecode = assembler.assemble_string(asm).unwrap();
    let disassembled = rs6502::Disassembler::clean_asm(disassembler.disassemble(&bytecode));

    assert_eq!(asm, disassembled.join("\n"));
}

#[test]
fn INTEGRATION_can_assemble_disassemble_clearmem_implementation() {
    let asm = "
            CLRMEM  LDA #$00
                    TAY
            CLRM1   STA ($FF),Y
                    INY
                    DEX
                    BNE CLRM1
                    RTS
    ";

    let mut assembler = rs6502::Assembler::new();
    let disassembler = rs6502::Disassembler::with_code_only();

    let bytecode = assembler.assemble_string(asm).unwrap();
    let disassembled = rs6502::Disassembler::clean_asm(disassembler.disassemble(&bytecode));

    let clean_disassembled = disassembled.join("\n");

    assert_eq!(rs6502::Disassembler::clean_asm("
        LDA #$00
        TAY
        STA ($FF),Y
        INY
        DEX
        BNE $0003
        RTS
    ")
                   .join("\n"),
               clean_disassembled);
}

#[test]
fn INTEGRATION_can_add_basic_numbers_in_accumulator() {
    let asm = "
        LDA #$20
        ADC #$10    ; A register should equal 48
    ";

    let mut cpu = rs6502::Cpu::new();
    let mut assembler = rs6502::Assembler::new();

    let bytecode = assembler.assemble_string(asm).unwrap();
    cpu.load(&bytecode[..], None);

    cpu.step();
    cpu.step();

    assert_eq!(0x30, cpu.registers.A);
}

#[test]
fn INTEGRATION_can_add_binary_coded_decimal_numbers_in_accumulator() {
    let asm = "
        SED
        LDA #$20
        ADC #$05    ; A register should equal 0x25
    ";

    let mut cpu = rs6502::Cpu::new();
    let mut assembler = rs6502::Assembler::new();
    let disassembler = rs6502::Disassembler::with_code_only();

    let bytecode = assembler.assemble_string(asm).unwrap();
    cpu.load(&bytecode[..], None);

    cpu.step();
    cpu.step();
    cpu.step();

    assert_eq!(0x25, cpu.registers.A);
}<commit_msg>Add test for mixed mode number addition<commit_after>
extern crate rs6502;

#[test]
fn INTEGRATION_can_assemble_disassemble_basic_opcodes() {
    let asm = "LDA $4400";

    let mut assembler = rs6502::Assembler::new();
    let disassembler = rs6502::Disassembler::with_code_only();

    let bytecode = assembler.assemble_string(asm).unwrap();
    let disassembled = rs6502::Disassembler::clean_asm(disassembler.disassemble(&bytecode));

    assert_eq!(asm, disassembled.join("\n"));
}

#[test]
fn INTEGRATION_can_assemble_disassemble_clearmem_implementation() {
    let asm = "
            CLRMEM  LDA #$00
                    TAY
            CLRM1   STA ($FF),Y
                    INY
                    DEX
                    BNE CLRM1
                    RTS
    ";

    let mut assembler = rs6502::Assembler::new();
    let disassembler = rs6502::Disassembler::with_code_only();

    let bytecode = assembler.assemble_string(asm).unwrap();
    let disassembled = rs6502::Disassembler::clean_asm(disassembler.disassemble(&bytecode));

    let clean_disassembled = disassembled.join("\n");

    assert_eq!(rs6502::Disassembler::clean_asm("
        LDA #$00
        TAY
        STA ($FF),Y
        INY
        DEX
        BNE $0003
        RTS
    ")
                   .join("\n"),
               clean_disassembled);
}

#[test]
fn INTEGRATION_can_add_basic_numbers_in_accumulator() {
    let asm = "
        LDA #$20
        ADC #$10    ; A register should equal 48
    ";

    let mut cpu = rs6502::Cpu::new();
    let mut assembler = rs6502::Assembler::new();

    let bytecode = assembler.assemble_string(asm).unwrap();
    cpu.load(&bytecode[..], None);

    cpu.step();
    cpu.step();

    assert_eq!(0x30, cpu.registers.A);
}

#[test]
fn INTEGRATION_can_add_binary_coded_decimal_numbers_in_accumulator() {
    let asm = "
        SED
        LDA #$20
        ADC #$05    ; A register should equal 0x25
    ";

    let mut cpu = rs6502::Cpu::new();
    let mut assembler = rs6502::Assembler::new();
    let disassembler = rs6502::Disassembler::with_code_only();

    let bytecode = assembler.assemble_string(asm).unwrap();
    cpu.load(&bytecode[..], None);

    cpu.step();
    cpu.step();
    cpu.step();

    assert_eq!(0x25, cpu.registers.A);
}

#[test]
fn INTEGRATION_can_add_mixed_mode_numbers_in_accumulator() {
    let asm = "
        LDA #$20
        ADC #10    ; A register should equal 0x2A
    ";

    let mut cpu = rs6502::Cpu::new();
    let mut assembler = rs6502::Assembler::new();
    let disassembler = rs6502::Disassembler::with_code_only();

    let bytecode = assembler.assemble_string(asm).unwrap();
    cpu.load(&bytecode[..], None);

    cpu.step();
    cpu.step();

    assert_eq!(0x2A, cpu.registers.A);
}<|endoftext|>


<commit_before>// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

#![feature(fnbox)]
#![feature(slice_patterns)]
#![feature(box_syntax)]
#![feature(test)]
#![cfg_attr(feature = "dev", feature(plugin))]
#![cfg_attr(feature = "dev", plugin(clippy))]
#![cfg_attr(not(feature = "dev"), allow(unknown_lints))]
#![cfg_attr(feature = "no-fail", allow(dead_code))]
#![recursion_limit = "100"]
#![allow(module_inception)]
#![allow(should_implement_trait)]
#![allow(large_enum_variant)]
#![allow(needless_pass_by_value)]
#![allow(unreadable_literal)]
#![allow(new_without_default_derive)]
#![allow(verbose_bit_mask)]

#[macro_use]
extern crate log;
extern crate protobuf;
extern crate test;
#[macro_use]
extern crate tikv;
extern crate rand;
extern crate rocksdb;
extern crate tempdir;
extern crate kvproto;
extern crate tipb;
extern crate grpcio as grpc;
extern crate futures;
extern crate futures_cpupool;
extern crate toml;
extern crate fail;
#[macro_use]
extern crate lazy_static;

#[allow(dead_code)]
mod raftstore;
#[allow(dead_code)]
mod storage;
#[cfg(not(feature = "no-fail"))]
mod failpoints_cases;

use std::sync::*;

lazy_static! {
    /// Failpoints are global structs, hence rules set in different cases
    /// may affect each other. So use a global lock to synchronize them.
    static ref LOCK: Mutex<()> = Mutex::new(());
}

fn setup<'a>() -> MutexGuard<'a, ()> {
    let guard = LOCK.lock().unwrap();
    fail::teardown();
    fail::setup();
    guard
}
<commit_msg>tests: make failpoints tests more stable (#2621)<commit_after>// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

#![feature(fnbox)]
#![feature(slice_patterns)]
#![feature(box_syntax)]
#![feature(test)]
#![cfg_attr(feature = "dev", feature(plugin))]
#![cfg_attr(feature = "dev", plugin(clippy))]
#![cfg_attr(not(feature = "dev"), allow(unknown_lints))]
#![cfg_attr(feature = "no-fail", allow(dead_code))]
#![recursion_limit = "100"]
#![allow(module_inception)]
#![allow(should_implement_trait)]
#![allow(large_enum_variant)]
#![allow(needless_pass_by_value)]
#![allow(unreadable_literal)]
#![allow(new_without_default_derive)]
#![allow(verbose_bit_mask)]

#[macro_use]
extern crate log;
extern crate protobuf;
extern crate test;
#[macro_use]
extern crate tikv;
extern crate rand;
extern crate rocksdb;
extern crate tempdir;
extern crate kvproto;
extern crate tipb;
extern crate grpcio as grpc;
extern crate futures;
extern crate futures_cpupool;
extern crate toml;
extern crate fail;
#[macro_use]
extern crate lazy_static;

#[allow(dead_code)]
mod raftstore;
#[allow(dead_code)]
mod storage;
#[cfg(not(feature = "no-fail"))]
mod failpoints_cases;

use std::sync::*;
use std::thread;

use tikv::util::panic_hook;

lazy_static! {
    /// Failpoints are global structs, hence rules set in different cases
    /// may affect each other. So use a global lock to synchronize them.
    static ref LOCK: Mutex<()> = Mutex::new(());
}

fn setup<'a>() -> MutexGuard<'a, ()> {
    // We don't want a failed test breaks others.
    let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
    fail::teardown();
    fail::setup();
    guard
}

#[test]
fn test_setup() {
    let _ = thread::spawn(move || {
        panic_hook::mute();
        let _g = setup();
        panic!("Poison!");
    }).join();

    let _g = setup();
}
<|endoftext|>


<commit_before>#![feature(prelude_import)]
#![doc = " Test"]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std;
#[doc = " Test"]
pub fn test() {}
<commit_msg>Update expected output with normalize_doc_attributes = true<commit_after>#![feature(prelude_import)]
//! Test
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std;
/// Test
pub fn test() {}
<|endoftext|>


<commit_before>use bits;
use consts;

/// Yields a series of scaled impulses vs time corresponding to given dibits.
pub struct C4FMImpulses<T> {
    /// The dibit source to iterate over.
    src: T,
    /// Current global sample index.
    sample: usize,
}

impl<T: Iterator<Item = bits::Dibit>> C4FMImpulses<T> {
    /// Construct a new `C4FMImpulses<T>` from the given source and sample rate.
    pub fn new(src: T) -> C4FMImpulses<T> {
        C4FMImpulses {
            src: src,
            sample: 0,
        }
    }
}

impl<T: Iterator<Item = bits::Dibit>> Iterator for C4FMImpulses<T> {
    type Item = f32;

    fn next(&mut self) -> Option<Self::Item> {
        // Store current sample and move to the next.
        let s = self.sample;
        self.sample += 1;

        // Impulse is only output at the beginning of a symbol period.
        if s % consts::PERIOD != 0 {
            return Some(0.0);
        }

        // Map the current dibit to a scaled impulse.
        if let Some(dibit) = self.src.next() {
            match dibit.bits() {
                0b01 => Some(0.18),
                0b00 => Some(0.06),
                0b10 => Some(-0.06),
                0b11 => Some(-0.18),
                _ => unreachable!(),
            }
        } else {
            None
        }
    }
}

/// Generates the alternating series of dibits used for the C4FM deviation test. The
/// resulting filtered waveform approximates a 1200Hz sine wave.
pub struct C4FMDeviationDibits {
    /// Used to alternate dibits.
    idx: usize,
}

impl C4FMDeviationDibits {
    /// Construct a new `C4FMDeviationDibits`.
    pub fn new() -> C4FMDeviationDibits {
        C4FMDeviationDibits {
            idx: 0,
        }
    }
}

impl Iterator for C4FMDeviationDibits {
    type Item = bits::Dibit;

    fn next(&mut self) -> Option<Self::Item> {
        let idx = self.idx;

        self.idx += 1;
        self.idx %= 4;

        Some(if idx < 2 {
            bits::Dibit::new(0b01)
        } else {
            bits::Dibit::new(0b11)
        })
    }
}

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

    #[test]
    fn test_impulses() {
        const BITS: &'static [u8] = &[
            0b00011011,
        ];

        let d = bits::Dibits::new(BITS.iter().cloned());
        let mut imp = C4FMImpulses::new(d);

        assert!(imp.next().unwrap() == 0.06);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.18);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == -0.06);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == -0.18);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().is_none());
    }

    #[test]
    fn test_deviation() {
        let mut d = C4FMDeviationDibits::new();

        assert!(d.next().unwrap().bits() == 0b01);
        assert!(d.next().unwrap().bits() == 0b01);
        assert!(d.next().unwrap().bits() == 0b11);
        assert!(d.next().unwrap().bits() == 0b11);
        assert!(d.next().unwrap().bits() == 0b01);
        assert!(d.next().unwrap().bits() == 0b01);
        assert!(d.next().unwrap().bits() == 0b11);
        assert!(d.next().unwrap().bits() == 0b11);
    }
}
<commit_msg>Add header doc to baseband::encode module<commit_after>//! Utilities for encoding symbols as a C4FM signal.

use bits;
use consts;

/// Yields a series of scaled impulses vs time corresponding to given dibits.
pub struct C4FMImpulses<T> {
    /// The dibit source to iterate over.
    src: T,
    /// Current global sample index.
    sample: usize,
}

impl<T: Iterator<Item = bits::Dibit>> C4FMImpulses<T> {
    /// Construct a new `C4FMImpulses<T>` from the given source and sample rate.
    pub fn new(src: T) -> C4FMImpulses<T> {
        C4FMImpulses {
            src: src,
            sample: 0,
        }
    }
}

impl<T: Iterator<Item = bits::Dibit>> Iterator for C4FMImpulses<T> {
    type Item = f32;

    fn next(&mut self) -> Option<Self::Item> {
        // Store current sample and move to the next.
        let s = self.sample;
        self.sample += 1;

        // Impulse is only output at the beginning of a symbol period.
        if s % consts::PERIOD != 0 {
            return Some(0.0);
        }

        // Map the current dibit to a scaled impulse.
        if let Some(dibit) = self.src.next() {
            match dibit.bits() {
                0b01 => Some(0.18),
                0b00 => Some(0.06),
                0b10 => Some(-0.06),
                0b11 => Some(-0.18),
                _ => unreachable!(),
            }
        } else {
            None
        }
    }
}

/// Generates the alternating series of dibits used for the C4FM deviation test. The
/// resulting filtered waveform approximates a 1200Hz sine wave.
pub struct C4FMDeviationDibits {
    /// Used to alternate dibits.
    idx: usize,
}

impl C4FMDeviationDibits {
    /// Construct a new `C4FMDeviationDibits`.
    pub fn new() -> C4FMDeviationDibits {
        C4FMDeviationDibits {
            idx: 0,
        }
    }
}

impl Iterator for C4FMDeviationDibits {
    type Item = bits::Dibit;

    fn next(&mut self) -> Option<Self::Item> {
        let idx = self.idx;

        self.idx += 1;
        self.idx %= 4;

        Some(if idx < 2 {
            bits::Dibit::new(0b01)
        } else {
            bits::Dibit::new(0b11)
        })
    }
}

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

    #[test]
    fn test_impulses() {
        const BITS: &'static [u8] = &[
            0b00011011,
        ];

        let d = bits::Dibits::new(BITS.iter().cloned());
        let mut imp = C4FMImpulses::new(d);

        assert!(imp.next().unwrap() == 0.06);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.18);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == -0.06);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == -0.18);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().unwrap() == 0.0);
        assert!(imp.next().is_none());
    }

    #[test]
    fn test_deviation() {
        let mut d = C4FMDeviationDibits::new();

        assert!(d.next().unwrap().bits() == 0b01);
        assert!(d.next().unwrap().bits() == 0b01);
        assert!(d.next().unwrap().bits() == 0b11);
        assert!(d.next().unwrap().bits() == 0b11);
        assert!(d.next().unwrap().bits() == 0b01);
        assert!(d.next().unwrap().bits() == 0b01);
        assert!(d.next().unwrap().bits() == 0b11);
        assert!(d.next().unwrap().bits() == 0b11);
    }
}
<|endoftext|>


<commit_before>//! Command-line parsing and instruction assembly

pub mod configure;
pub mod serve;

use errors::*;

use clap::{App, AppSettings, Arg, ArgMatches};

pub fn main() {
    // Parse arguments
    let args = setup().get_matches();

    // Run command
    let result = call(&args);

    // Handle error, if necessary
    if let Err(err) = result {
        handle(&err);
    }
}

pub fn setup<'a, 'b>() -> App<'a, 'b> {
    App::new(crate_name!())
        .version(crate_version!())
        .author(crate_authors!("\n"))
        .about(crate_description!())

        .global_setting(AppSettings::ColoredHelp)
        .global_setting(AppSettings::GlobalVersion)
        .global_setting(AppSettings::DisableHelpSubcommand)

        .setting(AppSettings::SubcommandRequiredElseHelp)

        .arg(
            Arg::with_name("config")
                .short("c")
                .long("config")
                .alias("conf")
                .value_name("FILE")
                .help("Sets a custom config file")
                .takes_value(true)
                .default_value(
                    concat!(crate_name!(), ".conf")
                )
        )
        .arg(
            Arg::with_name("lock")
                .short("l")
                .long("lock")
                .value_name("FILE")
                .help("Sets a custom lock file")
                .takes_value(true)
                .default_value(
                    concat!(crate_name!(), ".lock")
                )
        )

        .subcommand(configure::setup())
        .subcommand(    serve::setup())
}

pub fn call(args: &ArgMatches) -> Result<()> {
    // Match and execute a subcommand
    match args.subcommand() {
        ("configure", Some(args)) => configure::call(args),
        ("serve",     Some(args)) =>     serve::call(args),
        _                         =>        unreachable!(),
    }
}
<commit_msg>Improve subcommand parsing (infer subcommands)<commit_after>//! Command-line parsing and instruction assembly

pub mod configure;
pub mod serve;

use errors::*;

use clap::{App, AppSettings, Arg, ArgMatches};

pub fn main() {
    // Parse arguments
    let args = setup().get_matches();

    // Run command
    let result = call(&args);

    // Handle error, if necessary
    if let Err(err) = result {
        handle(&err);
    }
}

pub fn setup<'a, 'b>() -> App<'a, 'b> {
    App::new(crate_name!())
        .version(crate_version!())
        .author(crate_authors!("\n"))
        .about(crate_description!())

        .global_setting(AppSettings::ColoredHelp)
        .global_setting(AppSettings::DisableHelpSubcommand)
        .global_setting(AppSettings::GlobalVersion)
        .global_setting(AppSettings::InferSubcommands)

        .setting(AppSettings::SubcommandRequiredElseHelp)

        .arg(
            Arg::with_name("config")
                .short("c")
                .long("config")
                .alias("conf")
                .value_name("FILE")
                .help("Sets a custom config file")
                .takes_value(true)
                .default_value(
                    concat!(crate_name!(), ".conf")
                )
        )
        .arg(
            Arg::with_name("lock")
                .short("l")
                .long("lock")
                .value_name("FILE")
                .help("Sets a custom lock file")
                .takes_value(true)
                .default_value(
                    concat!(crate_name!(), ".lock")
                )
        )

        .subcommand(configure::setup())
        .subcommand(    serve::setup())
}

pub fn call(args: &ArgMatches) -> Result<()> {
    // Match and execute a subcommand
    match args.subcommand() {
        ("configure", Some(args)) => configure::call(args),
        ("serve",     Some(args)) =>     serve::call(args),
        _                         =>        unreachable!(),
    }
}
<|endoftext|>


<commit_before>extern crate difference;
extern crate quickcheck;

use difference::{Changeset, Difference};
use quickcheck::{TestResult, quickcheck, QuickCheck};
use std::fmt;

const DEBUG: bool = false;

struct Check<'a> {
    old: &'a str,
    new: &'a str,
    changeset: Changeset,
}

impl<'a> fmt::Display for Check<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Changeset::new({:?}, {:?}, {:?}) -> [",
            self.old,
            self.new,
            self.changeset.split
        )?;

        let mut iter = self.changeset.diffs.iter();
        if let Some(d) = iter.next() {
            write!(f, "{:?}", d)?;
        }
        for d in iter {
            write!(f, " {:?}", d)?;
        }
        write!(f, "]")
    }
}

fn check_changeset(old: &str, new: &str, split: &str) -> TestResult {
    Check::new(old, new, split).check()
}

impl<'a> Check<'a> {
    fn new(old: &'a str, new: &'a str, split: &'a str) -> Check<'a> {
        Check {
            old: old,
            new: new,
            changeset: Changeset::new(old, new, split),
        }
    }

    fn check(&self) -> TestResult {
        let split = &self.changeset.split;

        let mut old: Vec<&str> = Vec::new();
        let mut new: Vec<&str> = Vec::new();

        for d in &self.changeset.diffs {
            if DEBUG {
                println!("assert `{:?}` (old: {:?}, new: {:?})", d, old, new);
            }

            match *d {
                Difference::Same(ref x) => {
                    old.push(x);
                    new.push(x);
                }
                Difference::Add(ref x) => {
                    new.push(x);
                }
                Difference::Rem(ref x) => {
                    old.push(x);
                }
            }
        }
        let got_old = old.join(split);
        let got_new = new.join(split);
        if got_old != self.old {
            return TestResult::error(format!("Diff output implies old=`{:?}`, not `{:?}` in {}",
                        got_old, self.old, self,
                ));
        }
        if got_new != self.new {
            return TestResult::error(format!("Diff output implies new=`{:?}`, not `{:?}` in {}",
                        got_new, self.new, self,
                ));
        }

        TestResult::passed()
    }
}

#[test]
fn simple() {
    quickcheck(check_changeset("a", "a a", " "));
}

#[test]
fn issue_19() {
    // https://github.com/johannhof/difference.rs/issues/19
    quickcheck(check_changeset("a b : g", "b a : b b : g g", " "));
}

#[test]
fn fuzzy() {
    fn prop(old: Vec<usize>, new: Vec<usize>, words: Vec<char>) -> TestResult {
        if words.is_empty() {
            return TestResult::discard();
        }

        fn map_to_words(input: &[usize], words: &[char]) -> String {
            input.iter().enumerate().fold(
                String::new(),
                |mut acc, (i, x)| {
                    if i > 0 {
                        acc.push(' ');
                    }
                    acc.push(words[x % words.len()]);
                    acc
                },
            )
        }
        let old = map_to_words(&old, &words);
        let new = map_to_words(&new, &words);

        check_changeset(&old, &new, " ")
    }

    QuickCheck::new()
        .tests(100) // max successful tests
        .max_tests(10000) // max attempts
        .quickcheck(prop as fn(Vec<usize>, Vec<usize>, Vec<char>) -> TestResult);
}
<commit_msg>Placate clippy<commit_after>extern crate difference;
extern crate quickcheck;

use difference::{Changeset, Difference};
use quickcheck::{TestResult, quickcheck, QuickCheck};
use std::fmt;

const DEBUG: bool = false;

struct Check<'a> {
    old: &'a str,
    new: &'a str,
    changeset: Changeset,
}

impl<'a> fmt::Display for Check<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Changeset::new({:?}, {:?}, {:?}) -> [",
            self.old,
            self.new,
            self.changeset.split
        )?;

        let mut iter = self.changeset.diffs.iter();
        if let Some(d) = iter.next() {
            write!(f, "{:?}", d)?;
        }
        for d in iter {
            write!(f, " {:?}", d)?;
        }
        write!(f, "]")
    }
}

fn check_changeset(old: &str, new: &str, split: &str) -> TestResult {
    Check::new(old, new, split).check()
}

impl<'a> Check<'a> {
    fn new(old: &'a str, new: &'a str, split: &'a str) -> Check<'a> {
        Check {
            old: old,
            new: new,
            changeset: Changeset::new(old, new, split),
        }
    }

    fn check(&self) -> TestResult {
        let split = &self.changeset.split;

        let mut old: Vec<&str> = Vec::new();
        let mut new: Vec<&str> = Vec::new();

        for d in &self.changeset.diffs {
            if DEBUG {
                println!("assert `{:?}` (old: {:?}, new: {:?})", d, old, new);
            }

            match *d {
                Difference::Same(ref x) => {
                    old.push(x);
                    new.push(x);
                }
                Difference::Add(ref x) => {
                    new.push(x);
                }
                Difference::Rem(ref x) => {
                    old.push(x);
                }
            }
        }
        let got_old = old.join(split);
        let got_new = new.join(split);
        if got_old != self.old {
            return TestResult::error(format!("Diff output implies old=`{:?}`, not `{:?}` in {}",
                        got_old, self.old, self,
                ));
        }
        if got_new != self.new {
            return TestResult::error(format!("Diff output implies new=`{:?}`, not `{:?}` in {}",
                        got_new, self.new, self,
                ));
        }

        TestResult::passed()
    }
}

#[test]
fn simple() {
    quickcheck(check_changeset("a", "a a", " "));
}

#[test]
fn issue_19() {
    // https://github.com/johannhof/difference.rs/issues/19
    quickcheck(check_changeset("a b : g", "b a : b b : g g", " "));
}

#[test]
#[allow(needless_pass_by_value)]
fn fuzzy() {
    fn prop(old: Vec<usize>, new: Vec<usize>, words: Vec<char>) -> TestResult {
        if words.is_empty() {
            return TestResult::discard();
        }

        fn map_to_words(input: &[usize], words: &[char]) -> String {
            input.iter().enumerate().fold(
                String::new(),
                |mut acc, (i, x)| {
                    if i > 0 {
                        acc.push(' ');
                    }
                    acc.push(words[x % words.len()]);
                    acc
                },
            )
        }
        let old = map_to_words(&old, &words);
        let new = map_to_words(&new, &words);

        check_changeset(&old, &new, " ")
    }

    QuickCheck::new()
        .tests(100) // max successful tests
        .max_tests(10_000) // max attempts
        .quickcheck(prop as fn(Vec<usize>, Vec<usize>, Vec<char>) -> TestResult);
}
<|endoftext|>


<commit_before>use async_trait::async_trait;
use cucumber::{t, StepContext, Steps};
use snafu::ResultExt;

use crate::error::{self, Error};
use crate::state::{State, Step, StepStatus};
use crate::steps::download::DownloadNTFS;
use mimir2::adapters::secondary::elasticsearch::ElasticsearchStorage;
use tests::ntfs;

pub fn steps() -> Steps<State> {
    let mut steps: Steps<State> = Steps::new();

    steps.given_regex_async(
        r#"ntfs file has been indexed for (.*) as (.*)"#,
        t!(|mut state, ctx| {
            let region = ctx.matches[1].clone();
            let dataset = ctx.matches[2].clone();

            state
                .execute(IndexNTFS { region, dataset }, &ctx)
                .await
                .expect("failed to index NTFS file");

            state
        }),
    );

    // download and index ntfs
    steps.given_regex_async(
        "stops have been indexed for (.*) as (.*)",
        t!(|mut state, ctx| {
            let region = ctx.matches[1].clone();
            let dataset = ctx.matches[2].clone();

            state
                .execute(
                    DownloadNTFS {
                        region: region.clone(),
                    },
                    &ctx,
                )
                .await
                .expect("failed to download NTFS file");

            state
                .execute(IndexNTFS { region, dataset }, &ctx)
                .await
                .expect("failed to index NTFS file");

            state
        }),
    );

    steps
}

/// Index an NTFS file for a given region into Elasticsearch.
///
/// This will require to import admins first.
#[derive(Debug, PartialEq)]
pub struct IndexNtfs {
    pub region: String,
    pub dataset: String,
}

#[async_trait(?Send)]
impl Step for IndexNTFS {
    async fn execute(&mut self, _state: &State, ctx: &StepContext) -> Result<StepStatus, Error> {
        let Self { region, dataset } = self;
        let client: &ElasticsearchStorage = ctx.get().expect("could not get ES client");

        state
            .status_of(&IndexCosmogony {
                region: region.to_string(),
                dataset: dataset.to_string(),
            })
            .expect("You must index admins before indexing stops");

        ntfs::index_stops(client, region, dataset, false)
            .await
            .map(|status| status.into())
            .context(error::IndexNtfs)
    }
}
<commit_msg>Fix case on indexntfs<commit_after>use async_trait::async_trait;
use cucumber::{t, StepContext, Steps};
use snafu::ResultExt;

use crate::error::{self, Error};
use crate::state::{State, Step, StepStatus};
use crate::steps::admin::IndexCosmogony;
use crate::steps::download::DownloadNTFS;
use mimir2::adapters::secondary::elasticsearch::ElasticsearchStorage;
use tests::ntfs;

pub fn steps() -> Steps<State> {
    let mut steps: Steps<State> = Steps::new();

    steps.given_regex_async(
        r#"ntfs file has been indexed for (.*) as (.*)"#,
        t!(|mut state, ctx| {
            let region = ctx.matches[1].clone();
            let dataset = ctx.matches[2].clone();

            state
                .execute(IndexNTFS { region, dataset }, &ctx)
                .await
                .expect("failed to index NTFS file");

            state
        }),
    );

    // download and index ntfs
    steps.given_regex_async(
        "stops have been indexed for (.*) as (.*)",
        t!(|mut state, ctx| {
            let region = ctx.matches[1].clone();
            let dataset = ctx.matches[2].clone();

            state
                .execute(
                    DownloadNTFS {
                        region: region.clone(),
                    },
                    &ctx,
                )
                .await
                .expect("failed to download NTFS file");

            state
                .execute(IndexNTFS { region, dataset }, &ctx)
                .await
                .expect("failed to index NTFS file");

            state
        }),
    );

    steps
}

/// Index an NTFS file for a given region into Elasticsearch.
///
/// This will require to import admins first.
#[derive(Debug, PartialEq)]
pub struct IndexNTFS {
    pub region: String,
    pub dataset: String,
}

#[async_trait(?Send)]
impl Step for IndexNTFS {
    async fn execute(&mut self, state: &State, ctx: &StepContext) -> Result<StepStatus, Error> {
        let Self { region, dataset } = self;
        let client: &ElasticsearchStorage = ctx.get().expect("could not get ES client");

        state
            .status_of(&IndexCosmogony {
                region: region.to_string(),
                dataset: dataset.to_string(),
            })
            .expect("You must index admins before indexing stops");

        ntfs::index_stops(client, region, dataset, false)
            .await
            .map(|status| status.into())
            .context(error::IndexNTFS)
    }
}
<|endoftext|>


<commit_before>use shell_command::ShellCommand;
use nom::IResult;
use std::process::Command;
use std::env;
use std::env::VarError;

fn token_char(ch: char) -> bool {
    match ch {
        ch if ch as u8 <= 32 || 127 <= ch as u8 => false,
        '"' | '\'' | '>' | '<' | '|' | ';' | '{' | '}' | '$' => false,
        _ => true,
    }
}

fn var_char(ch: char) -> bool {
    match ch {
        'a' ... 'z' => true,
        'A' ... 'Z' => true,
        '0' ... '9' => true,
        '_' => true,
        _ => false,
    }
}

enum TokenPart {
    Bare(String),
    Placeholder,
    EnvVariable(String),
}

struct Token(Vec<TokenPart>);

impl Token {
    fn into_string(self, args: &mut Iterator<Item = &str>)
            -> Result<String, VarError> {
        let mut token = String::from("");
        for part in self.0 {
            match part {
                TokenPart::Bare(s) => token += &s,
                TokenPart::Placeholder =>
                    token += args.next().expect("Too many placeholders"),
                TokenPart::EnvVariable(name) => {
                    debug!("Environment variable {}", name);
                    token += &env::var(name)?
                }
            }
        }
        Ok(token)
    }
}

named!(bare_token<&str, TokenPart>,
       map!(take_while1_s!(token_char), |s| TokenPart::Bare(String::from(s))));
named!(quoted_token<&str, TokenPart>,
       map!(delimited!(tag_s!("\""), take_until_s!("\""), tag_s!("\"")),
            |s| TokenPart::Bare(String::from(s))));
named!(place_holder<&str, TokenPart>,
       map!(tag_s!("{}"), |_| TokenPart::Placeholder));
named!(env_var<&str, TokenPart>,
       map!(preceded!(tag!("$"), take_while1_s!(var_char)),
            |name| TokenPart::EnvVariable(String::from(name))));
named!(command_token<&str, Token>,
       map!(many1!(alt!(bare_token | quoted_token | place_holder | env_var)),
            |vec| Token(vec)));

named!(command< &str, Vec<Token> >,
       terminated!(ws!(many1!(command_token)), eof!()));

#[macro_export]
macro_rules! cmd {
    ($format:expr) => ($crate::command::new_command($format, &[]).unwrap());
    ($format:expr, $($arg:expr),+) =>
        ($crate::command::new_command($format, &[$($arg),+]).unwrap());
}

fn parse_cmd<'a>(format: &'a str, args: &'a [&str])
        -> Result<Vec<String>, VarError> {
    let tokens = match command(format) {
        IResult::Done(_, result) => result,
        IResult::Error(error) => panic!("Error {:?}", error),
        IResult::Incomplete(needed) => panic!("Needed {:?}", needed)
    };
    let args = args.iter().map(|a| *a).collect::<Vec<_>>();
    let mut args = args.into_iter();
    tokens.into_iter().map(|token| token.into_string(&mut args))
        .collect::<Result<Vec<_>, _>>()
}

pub fn new_command(format: &str, args: &[&str])
        -> Result<ShellCommand, VarError> {
    let vec = parse_cmd(format, args)?;
    let mut command = Command::new(&vec[0]);
    if vec.len() > 1 {
        command.args(&vec[1..]);
    }
    let line = vec.join(" ");
    Ok(ShellCommand::new(line, command))
}

#[test]
fn test_parse_cmd() {
    let tokens = parse_cmd(r#"cmd 1 2
                              3 "
  4" {}"#, &["5"]).unwrap();
    assert_eq!("cmd", tokens[0]);
    assert_eq!("1", tokens[1]);
    assert_eq!("2", tokens[2]);
    assert_eq!("3", tokens[3]);
    assert_eq!("\n  4", tokens[4]);
    assert_eq!("5", tokens[5]);
}

#[test]
fn test_parse_cmd_env() {
    use env_logger;
    env_logger::init().unwrap();
    env::set_var("MY_VAR", "VALUE");
    let tokens = parse_cmd("echo $MY_VAR/dir", &[]).unwrap();
    assert_eq!("VALUE/dir", tokens[1]);
}
<commit_msg>Use range<commit_after>use shell_command::ShellCommand;
use nom::IResult;
use std::process::Command;
use std::env;
use std::env::VarError;

fn token_char(ch: char) -> bool {
    match ch {
        '\x00' ... '\x20' => false,
        '\x7f' | '"' | '\'' | '>' | '<' | '|' | ';' | '{' | '}' | '$' => false,
        _ => true,
    }
}

fn var_char(ch: char) -> bool {
    match ch {
        'a' ... 'z' => true,
        'A' ... 'Z' => true,
        '0' ... '9' => true,
        '_' => true,
        _ => false,
    }
}

enum TokenPart {
    Bare(String),
    Placeholder,
    EnvVariable(String),
}

struct Token(Vec<TokenPart>);

impl Token {
    fn into_string(self, args: &mut Iterator<Item = &str>)
            -> Result<String, VarError> {
        let mut token = String::from("");
        for part in self.0 {
            match part {
                TokenPart::Bare(s) => token += &s,
                TokenPart::Placeholder =>
                    token += args.next().expect("Too many placeholders"),
                TokenPart::EnvVariable(name) => {
                    debug!("Environment variable {}", name);
                    token += &env::var(name)?
                }
            }
        }
        Ok(token)
    }
}

named!(bare_token<&str, TokenPart>,
       map!(take_while1_s!(token_char), |s| TokenPart::Bare(String::from(s))));
named!(quoted_token<&str, TokenPart>,
       map!(delimited!(tag_s!("\""), take_until_s!("\""), tag_s!("\"")),
            |s| TokenPart::Bare(String::from(s))));
named!(place_holder<&str, TokenPart>,
       map!(tag_s!("{}"), |_| TokenPart::Placeholder));
named!(env_var<&str, TokenPart>,
       map!(preceded!(tag!("$"), take_while1_s!(var_char)),
            |name| TokenPart::EnvVariable(String::from(name))));
named!(command_token<&str, Token>,
       map!(many1!(alt!(bare_token | quoted_token | place_holder | env_var)),
            |vec| Token(vec)));

named!(command< &str, Vec<Token> >,
       terminated!(ws!(many1!(command_token)), eof!()));

#[macro_export]
macro_rules! cmd {
    ($format:expr) => ($crate::command::new_command($format, &[]).unwrap());
    ($format:expr, $($arg:expr),+) =>
        ($crate::command::new_command($format, &[$($arg),+]).unwrap());
}

fn parse_cmd<'a>(format: &'a str, args: &'a [&str])
        -> Result<Vec<String>, VarError> {
    let tokens = match command(format) {
        IResult::Done(_, result) => result,
        IResult::Error(error) => panic!("Error {:?}", error),
        IResult::Incomplete(needed) => panic!("Needed {:?}", needed)
    };
    let args = args.iter().map(|a| *a).collect::<Vec<_>>();
    let mut args = args.into_iter();
    tokens.into_iter().map(|token| token.into_string(&mut args))
        .collect::<Result<Vec<_>, _>>()
}

pub fn new_command(format: &str, args: &[&str])
        -> Result<ShellCommand, VarError> {
    let vec = parse_cmd(format, args)?;
    let mut command = Command::new(&vec[0]);
    if vec.len() > 1 {
        command.args(&vec[1..]);
    }
    let line = vec.join(" ");
    Ok(ShellCommand::new(line, command))
}

#[test]
fn test_parse_cmd() {
    let tokens = parse_cmd(r#"cmd 1 2
                              3 "
  4" {}"#, &["5"]).unwrap();
    assert_eq!("cmd", tokens[0]);
    assert_eq!("1", tokens[1]);
    assert_eq!("2", tokens[2]);
    assert_eq!("3", tokens[3]);
    assert_eq!("\n  4", tokens[4]);
    assert_eq!("5", tokens[5]);
}

#[test]
fn test_parse_cmd_env() {
    use env_logger;
    env_logger::init().unwrap();
    env::set_var("MY_VAR", "VALUE");
    let tokens = parse_cmd("echo $MY_VAR/dir", &[]).unwrap();
    assert_eq!("VALUE/dir", tokens[1]);
}
<|endoftext|>


<commit_before>use constants::*;
use std::ffi::OsString;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};

pub fn initialize() {
    println!("Initialize ...");

    let dir_name    = ".kic";
    let path_to_dir = Path::new(dir_name);
    if path_to_dir.exists() && path_to_dir.is_dir() {
        println!("  OK: \"{}\" directory has already exist.", dir_name);
    } else {
        match fs::create_dir(path_to_dir) {
            Ok(_)    => println!("  OK: Created \"{}\" directory.", dir_name),
            Err(why) => panic!("{:?}", why),
        }
    }

    let config_file    = "config";
    let path_to_config = path_to_dir.clone().join(config_file);
    create_setting_file(&path_to_config, DEFAULT_CONFIG);
}

fn create_setting_file(path_to_file: &PathBuf, contents: &'static str) {
    if path_to_file.exists() && path_to_file.is_file() {
        println!("  OK: \"{:?}\" file has already exist.", path_to_file);
    } else {
        match File::create(path_to_file) {
            Ok(mut fp) => {
                println!("  OK: Created {:?} file.", path_to_file);
                match fp.write(contents.as_bytes()) {
                    Ok(_)    => {},
                    Err(why) => panic!("{:?}", why),
                }
            },
            Err(why) => panic!("{:?}", why),
        }
    }
}

// You will be enable to use std::fs::walk_dir instead of this function in rust 1.6.0 or later
fn walk_dir<P: AsRef<Path>>(p: P) -> Vec<OsString> {
    let dirs = match fs::read_dir(p) {
        Ok(ds)   => ds,
        Err(why) => panic!("{:?}", why),
    };
    let dirs = dirs.filter(|d| d.is_ok())
        .flat_map(|d| {
            let p = d.unwrap().path();
            if IGNORED_NAMES.iter().any(|name| p.ends_with(name)) {
                Vec::new()
            } else if p.is_file() {
                vec![p.into_os_string()]
            } else {
                walk_dir(&p)
            }
        })
        .collect::<Vec<OsString>>();
    dirs
}

pub fn set_params() {
    println!("set parameters");
}

pub fn sweep() {
    println!("sweep");
}

pub fn burn() {
    println!("burn");
}

pub fn register_with_cron() {
    println!("register");
}

pub fn unregister_cron() {
    println!("unregister");
}

pub fn destroy() {
    println!("destroy");
}
<commit_msg>Create "ignore" file<commit_after>use constants::*;
use std::ffi::OsString;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};

pub fn initialize() {
    println!("Initialize ...");

    let dir_name    = ".kic";
    let path_to_dir = Path::new(dir_name);
    if path_to_dir.exists() && path_to_dir.is_dir() {
        println!("  OK: \"{}\" directory has already exist.", dir_name);
    } else {
        match fs::create_dir(path_to_dir) {
            Ok(_)    => println!("  OK: Created \"{}\" directory.", dir_name),
            Err(why) => panic!("{:?}", why),
        }
    }

    let config_file    = "config";
    let path_to_config = path_to_dir.clone().join(config_file);
    create_setting_file(path_to_config, DEFAULT_CONFIG);

    let ignore_file    = "ignore";
    let path_to_ignore = path_to_dir.clone().join(ignore_file);
    let ignore_contents = walk_dir(".").iter()
        .map(|f| f.clone().into_string())
        .filter(|f| f.is_ok())
        .fold("".to_string(), |c, f| c + &(f.unwrap()) + "\n");
    create_setting_file(path_to_ignore, ignore_contents);
}

fn create_setting_file<S: AsRef<str>>(path_to_file: PathBuf, contents: S) {
    if path_to_file.exists() && path_to_file.is_file() {
        println!("  OK: \"{:?}\" file has already exist.", path_to_file);
    } else {
        match File::create(&path_to_file) {
            Ok(mut fp) => {
                println!("  OK: Created {:?} file.", path_to_file);
                match fp.write(contents.as_ref().as_bytes()) {
                    Ok(_)    => {},
                    Err(why) => panic!("{:?}", why),
                }
            },
            Err(why) => panic!("{:?}", why),
        }
    }
}

// You will be enable to use std::fs::walk_dir instead of this function in rust 1.6.0 or later
fn walk_dir<P: AsRef<Path>>(p: P) -> Vec<OsString> {
    let dirs = match fs::read_dir(p) {
        Ok(ds)   => ds,
        Err(why) => panic!("{:?}", why),
    };
    let dirs = dirs.filter(|d| d.is_ok())
        .flat_map(|d| {
            let p = d.unwrap().path();
            if IGNORED_NAMES.iter().any(|name| p.ends_with(name)) {
                Vec::new()
            } else if p.is_file() {
                vec![p.into_os_string()]
            } else {
                walk_dir(&p)
            }
        })
        .collect::<Vec<OsString>>();
    dirs
}

pub fn set_params() {
    println!("set parameters");
}

pub fn sweep() {
    println!("sweep");
}

pub fn burn() {
    println!("burn");
}

pub fn register_with_cron() {
    println!("register");
}

pub fn unregister_cron() {
    println!("unregister");
}

pub fn destroy() {
    println!("destroy");
}
<|endoftext|>


<commit_before>// The implementation is based on:
// http://www.librow.com/articles/article-10

use num_complex::Complex;
use num_traits::Float;

use {Operation, Plan, Transform};

impl<T> Transform<T> for [Complex<T>] where T: Float {
    fn transform(&mut self, plan: &Plan<T>) {
        let n = self.len();
        assert!(n <= plan.n);
        rearrange(self, n);
        calculate(self, n, &plan.factors);
        if let Operation::Inverse = plan.operation {
            scale(self, n);
        }
    }
}

impl<T> Transform<T> for Vec<Complex<T>> where T: Float {
    #[inline(always)]
    fn transform(&mut self, plan: &Plan<T>) {
        Transform::transform(&mut self[..], plan)
    }
}

#[inline(always)]
fn calculate<T>(data: &mut [Complex<T>], n: usize, factors: &[Complex<T>]) where T: Float {
    let mut k = 0;
    let mut step = 1;
    while step < n {
        let jump = step << 1;
        for mut i in 0..step {
            while i < n {
                let j = i + step;
                let product = factors[k] * data[j];
                data[j] = data[i] - product;
                data[i] = data[i] + product;
                i += jump;
            }
            k += 1;
        }
        step <<= 1;
    }
}

#[inline(always)]
fn rearrange<T>(data: &mut [Complex<T>], n: usize) {
    let mut j = 0;
    for i in 0..n {
        if j > i {
            data.swap(i, j);
        }
        let mut mask = n >> 1;
        while j & mask != 0 {
            j &= !mask;
            mask >>= 1;
        }
        j |= mask;
    }
}

#[inline(always)]
fn scale<T>(data: &mut [Complex<T>], n: usize) where T: Float {
    let factor = T::from(n).unwrap().recip();
    for i in 0..n {
        data[i] = data[i].scale(factor);
    }
}
<commit_msg>Use more idiomatic Rust loop in scale()<commit_after>// The implementation is based on:
// http://www.librow.com/articles/article-10

use num_complex::Complex;
use num_traits::Float;

use {Operation, Plan, Transform};

impl<T> Transform<T> for [Complex<T>] where T: Float {
    fn transform(&mut self, plan: &Plan<T>) {
        let n = self.len();
        assert!(n <= plan.n);
        rearrange(self, n);
        calculate(self, n, &plan.factors);
        if let Operation::Inverse = plan.operation {
            scale(self, n);
        }
    }
}

impl<T> Transform<T> for Vec<Complex<T>> where T: Float {
    #[inline(always)]
    fn transform(&mut self, plan: &Plan<T>) {
        Transform::transform(&mut self[..], plan)
    }
}

#[inline(always)]
fn calculate<T>(data: &mut [Complex<T>], n: usize, factors: &[Complex<T>]) where T: Float {
    let mut k = 0;
    let mut step = 1;
    while step < n {
        let jump = step << 1;
        for mut i in 0..step {
            while i < n {
                let j = i + step;
                let product = factors[k] * data[j];
                data[j] = data[i] - product;
                data[i] = data[i] + product;
                i += jump;
            }
            k += 1;
        }
        step <<= 1;
    }
}

#[inline(always)]
fn rearrange<T>(data: &mut [Complex<T>], n: usize) {
    let mut j = 0;
    for i in 0..n {
        if j > i {
            data.swap(i, j);
        }
        let mut mask = n >> 1;
        while j & mask != 0 {
            j &= !mask;
            mask >>= 1;
        }
        j |= mask;
    }
}

#[inline(always)]
fn scale<T>(data: &mut [Complex<T>], n: usize) where T: Float {
    let factor = T::from(n).unwrap().recip();
    for value in data {
        *value = value.scale(factor);
    }
}
<|endoftext|>


<commit_before>use serialize::json::{Json, ToJson};
use regex::Regex;
use std::iter::IteratorExt;
use std::collections::RingBuf;

pub struct Context {
    data: Json
}

static NULL_VALUE: Json = Json::Null;
static ARRAY_INDEX_MATCHER: Regex = regex!(r"\[\d+\]$");

impl Context {
    pub fn null() -> Context {
        Context {
            data: NULL_VALUE.clone()
        }
    }

    pub fn wraps<'a, T: ToJson>(e: &T) -> Context {
        Context {
            data: e.to_json()
        }
    }

    pub fn navigate(&self, path: &String, relative_path: &String) -> &Json {
        let mut path_stack :RingBuf<&str> = RingBuf::new();
        for p in (*path).split('/') {
            match p {
                "this" | "." | "" => {
                    continue;
                }
                ".." => {
                    path_stack.pop_back();
                }
                _ => {
                    for dot_p in p.split('.') {
                        match ARRAY_INDEX_MATCHER.find(dot_p) {
                            Some((s, _)) => {
                                let arr = dot_p.slice_to(s);
                                if arr != "this" {
                                    path_stack.push_back(dot_p.slice_to(s));
                                }
                                path_stack.push_back(dot_p.slice_from(s));
                            },
                            None => {
                                if dot_p != "this" {
                                    path_stack.push_back(dot_p);
                                }
                            }
                        }
                    }
                }
            }
        }

        for p in (*relative_path).split('/') {
            match p {
                "this" | "." | "" => {
                    continue;
                }
                ".." => {
                    path_stack.pop_back();
                }
                _ => {
                    for dot_p in p.split('.') {
                        match ARRAY_INDEX_MATCHER.find(dot_p) {
                            Some((s, _)) => {
                                let arr = dot_p.slice_to(s);
                                if arr != "this" {
                                    path_stack.push_back(dot_p.slice_to(s));
                                }
                                path_stack.push_back(dot_p.slice_from(s));
                            },
                            None => {
                                if dot_p != "this" {
                                    path_stack.push_back(dot_p);
                                }
                            }
                        }
                    }
                }
            }
        }

        let paths :Vec<&str> = path_stack.iter().map(|x| *x).collect();
        let mut data: &Json = &self.data;
        for p in paths.iter() {
            if ARRAY_INDEX_MATCHER.is_match(*p) {
                data = match *data {
                    Json::Array(ref a) => {
                        let index = p.slice_chars(1, p.len()-1);
//                        println!("========== {}", index);
                        let index_u: Option<uint> = from_str(index);
                        match index_u {
                            Some(i) => a.get(i).unwrap(),
                            None => &NULL_VALUE
                        }
                    },
                    _ => {
                        &NULL_VALUE
                    }
                }
            } else {
                data = match data.find(*p) {
                    Some(d) => d,
                    None => &NULL_VALUE
                }
            }
        }
        data
    }
}

pub trait JsonRender {
    fn render(&self) -> String;
}

impl JsonRender for Json {
    fn render(&self) -> String {
        match *self {
            Json::String(_) => {
                let s = format!("{}", *self);
                s.slice_chars(1, s.char_len()-1).to_string()
            },
            _ => {
                format!("{}", *self)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use context::{JsonRender, Context};
    use std::collections::BTreeMap;
    use serialize::json::{Json, ToJson};

    struct Address {
        city: String,
        country: String
    }

    impl ToJson for Address {
        fn to_json(&self) -> Json {
            let mut m = BTreeMap::new();
            m.insert("city".to_string(), self.city.to_json());
            m.insert("country".to_string(), self.country.to_json());
            Json::Object(m)
        }
    }

    struct Person {
        name: String,
        age: i16,
        addr: Address,
        titles: Vec<String>
    }

    impl ToJson for Person {
        fn to_json(&self) -> Json {
            let mut m = BTreeMap::new();
            m.insert("name".to_string(), self.name.to_json());
            m.insert("age".to_string(), self.age.to_json());
            m.insert("addr".to_string(), self.addr.to_json());
            m.insert("titles".to_string(), self.titles.to_json());
            Json::Object(m)
        }
    }

    #[test]
    fn test_render() {
        let v = "hello";
        let ctx = Context::wraps(&v.to_string());
        let this = "this".to_string();
        assert_eq!(ctx.navigate(&this, &this).render(), v.to_string());
    }

    #[test]
    fn test_navigation() {
        let addr = Address {
            city: "Beijing".to_string(),
            country: "China".to_string()
        };

        let person = Person {
            name: "Ning Sun".to_string(),
            age: 27,
            addr: addr,
            titles: vec!["programmer".to_string(),
                         "cartographier".to_string()]
        };

        let ctx = Context::wraps(&person);
        let this = "this".to_string();
        let that = "./name/../addr/country".to_string();

        assert_eq!(ctx.navigate(&this, &that).render(), "China".to_string());

        let v = true;
        let ctx2 = Context::wraps(&v);
        assert_eq!(ctx2.navigate(&"this".to_string(), &"this".to_string()).render(), "true".to_string());

        let this2 = "this".to_string();
        let that2 = "titles[0]".to_string();
        assert_eq!(ctx.navigate(&this2, &that2).render(), "programmer".to_string());
    }
}
<commit_msg>refactor: remove duplicate code<commit_after>use serialize::json::{Json, ToJson};
use regex::Regex;
use std::iter::IteratorExt;
use std::collections::RingBuf;

pub struct Context {
    data: Json
}

static NULL_VALUE: Json = Json::Null;
static ARRAY_INDEX_MATCHER: Regex = regex!(r"\[\d+\]$");

fn parse_json_visitor<'a>(path_stack: &mut RingBuf<&'a str>, path: &'a String) {
    for p in (*path).split('/') {
        match p {
            "this" | "." | "" => {
                continue;
            }
            ".." => {
                path_stack.pop_back();
            }
            _ => {
                for dot_p in p.split('.') {
                    match ARRAY_INDEX_MATCHER.find(dot_p) {
                        Some((s, _)) => {
                            let arr = dot_p.slice_to(s);
                            if arr != "this" {
                                path_stack.push_back(dot_p.slice_to(s));
                            }
                            path_stack.push_back(dot_p.slice_from(s));
                        },
                        None => {
                            if dot_p != "this" {
                                path_stack.push_back(dot_p);
                            }
                        }
                    }
                }
            }
        }
    }
}

impl Context {
    pub fn null() -> Context {
        Context {
            data: NULL_VALUE.clone()
        }
    }

    pub fn wraps<'a, T: ToJson>(e: &T) -> Context {
        Context {
            data: e.to_json()
        }
    }

    pub fn navigate(&self, path: &String, relative_path: &String) -> &Json {
        let mut path_stack :RingBuf<&str> = RingBuf::new();
        parse_json_visitor(&mut path_stack, path);
        parse_json_visitor(&mut path_stack, relative_path);

        let paths :Vec<&str> = path_stack.iter().map(|x| *x).collect();
        let mut data: &Json = &self.data;
        for p in paths.iter() {
            if ARRAY_INDEX_MATCHER.is_match(*p) {
                data = match *data {
                    Json::Array(ref a) => {
                        let index = p.slice_chars(1, p.len()-1);
//                        println!("========== {}", index);
                        let index_u: Option<uint> = from_str(index);
                        match index_u {
                            Some(i) => a.get(i).unwrap(),
                            None => &NULL_VALUE
                        }
                    },
                    _ => {
                        &NULL_VALUE
                    }
                }
            } else {
                data = match data.find(*p) {
                    Some(d) => d,
                    None => &NULL_VALUE
                }
            }
        }
        data
    }
}

pub trait JsonRender {
    fn render(&self) -> String;
}

impl JsonRender for Json {
    fn render(&self) -> String {
        match *self {
            Json::String(_) => {
                let s = format!("{}", *self);
                s.slice_chars(1, s.char_len()-1).to_string()
            },
            _ => {
                format!("{}", *self)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use context::{JsonRender, Context};
    use std::collections::BTreeMap;
    use serialize::json::{Json, ToJson};

    struct Address {
        city: String,
        country: String
    }

    impl ToJson for Address {
        fn to_json(&self) -> Json {
            let mut m = BTreeMap::new();
            m.insert("city".to_string(), self.city.to_json());
            m.insert("country".to_string(), self.country.to_json());
            Json::Object(m)
        }
    }

    struct Person {
        name: String,
        age: i16,
        addr: Address,
        titles: Vec<String>
    }

    impl ToJson for Person {
        fn to_json(&self) -> Json {
            let mut m = BTreeMap::new();
            m.insert("name".to_string(), self.name.to_json());
            m.insert("age".to_string(), self.age.to_json());
            m.insert("addr".to_string(), self.addr.to_json());
            m.insert("titles".to_string(), self.titles.to_json());
            Json::Object(m)
        }
    }

    #[test]
    fn test_render() {
        let v = "hello";
        let ctx = Context::wraps(&v.to_string());
        let this = "this".to_string();
        assert_eq!(ctx.navigate(&this, &this).render(), v.to_string());
    }

    #[test]
    fn test_navigation() {
        let addr = Address {
            city: "Beijing".to_string(),
            country: "China".to_string()
        };

        let person = Person {
            name: "Ning Sun".to_string(),
            age: 27,
            addr: addr,
            titles: vec!["programmer".to_string(),
                         "cartographier".to_string()]
        };

        let ctx = Context::wraps(&person);
        let this = "this".to_string();
        let that = "./name/../addr/country".to_string();

        assert_eq!(ctx.navigate(&this, &that).render(), "China".to_string());

        let v = true;
        let ctx2 = Context::wraps(&v);
        assert_eq!(ctx2.navigate(&"this".to_string(), &"this".to_string()).render(), "true".to_string());

        let this2 = "this".to_string();
        let that2 = "titles[0]".to_string();
        assert_eq!(ctx.navigate(&this2, &that2).render(), "programmer".to_string());
    }
}
<|endoftext|>


<commit_before>use std::{
    clone::Clone,
    fmt::{self, Debug, Formatter},
    marker::PhantomData,
};

use serde::{
    de::{Deserialize, DeserializeOwned, Deserializer, IgnoredAny, MapAccess, Visitor},
    ser::{Serialize, Serializer},
};
use serde_json::value::RawValue;

use crate::cow::MyCowStr;

/// A wrapper around `Box<RawValue>`, to be used in place of any type in the Matrix endpoint
/// definition to allow request and response types to contain that said type represented by
/// the generic argument `Ev`.
///
/// Ruma offers the `Raw` wrapper to enable passing around JSON text that is only partially
/// validated. This is useful when a client receives events that do not follow the spec perfectly
/// or a server needs to generate reference hashes with the original canonical JSON string.
/// All event structs and enums implement `Serialize` / `Deserialize`, `Raw` should be used
/// to pass around events in a lossless way.
///
/// ```no_run
/// # use serde::Deserialize;
/// # use ruma_serde::Raw;
/// # #[derive(Deserialize)]
/// # struct AnyRoomEvent;
///
/// let json = r#"{ "type": "imagine a full event", "content": {...} }"#;
///
/// let deser = serde_json::from_str::<Raw<AnyRoomEvent>>(json)
///     .unwrap() // the first Result from serde_json::from_str, will not fail
///     .deserialize() // deserialize to the inner type
///     .unwrap(); // finally get to the AnyRoomEvent
/// ```
pub struct Raw<T> {
    json: Box<RawValue>,
    _ev: PhantomData<T>,
}

impl<T> Raw<T> {
    fn new(json: Box<RawValue>) -> Self {
        Self { json, _ev: PhantomData }
    }

    /// Create a `Raw` from a boxed `RawValue`.
    pub fn from_json(raw: Box<RawValue>) -> Self {
        Self::new(raw)
    }

    /// Access the underlying json value.
    pub fn json(&self) -> &RawValue {
        &self.json
    }

    /// Convert `self` into the underlying json value.
    pub fn into_json(self) -> Box<RawValue> {
        self.json
    }

    /// Try to access a given field inside this `Raw`, assuming it contains an
    /// object.
    ///
    /// Returns `Err(_)` when the contained value is not an object, or the field
    /// exists but is fails to deserialize to the expected type.
    ///
    /// Returns `Ok(None)` when the field doesn't exist or is `null`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # type CustomMatrixEvent = ();
    /// # fn foo() -> serde_json::Result<()> {
    /// # let raw_event: ruma_serde::Raw<()> = todo!();
    /// if raw_event.get_field::<String>("type")?.as_deref() == Some("org.custom.matrix.event") {
    ///     let event = raw_event.deserialize_as::<CustomMatrixEvent>()?;
    ///     // ...
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_field<'a, U>(&'a self, field_name: &str) -> serde_json::Result<Option<U>>
    where
        U: Deserialize<'a>,
    {
        struct SingleFieldVisitor<'b, T> {
            field_name: &'b str,
            _phantom: PhantomData<T>,
        }

        impl<'b, T> SingleFieldVisitor<'b, T> {
            fn new(field_name: &'b str) -> Self {
                Self { field_name, _phantom: PhantomData }
            }
        }

        impl<'b, 'de, T> Visitor<'de> for SingleFieldVisitor<'b, T>
        where
            T: Deserialize<'de>,
        {
            type Value = Option<T>;

            fn expecting(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("a string")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut res = None;
                while let Some(key) = map.next_key::<MyCowStr<'_>>()? {
                    if key.get() == self.field_name {
                        res = Some(map.next_value()?);
                    } else {
                        map.next_value::<IgnoredAny>()?;
                    }
                }

                Ok(res)
            }
        }

        let mut deserializer = serde_json::Deserializer::from_str(self.json().get());
        deserializer.deserialize_map(SingleFieldVisitor::new(field_name))
    }
}

impl<T> Raw<T>
where
    T: DeserializeOwned,
{
    /// Try to deserialize the JSON as the expected type.
    pub fn deserialize(&self) -> serde_json::Result<T> {
        serde_json::from_str(self.json.get())
    }

    /// Try to deserialize the JSON as a custom type.
    pub fn deserialize_as<U>(&self) -> serde_json::Result<U>
    where
        U: DeserializeOwned,
    {
        serde_json::from_str(self.json.get())
    }
}

impl<T: Serialize> From<&T> for Raw<T> {
    fn from(val: &T) -> Self {
        Self::new(serde_json::value::to_raw_value(val).unwrap())
    }
}

// With specialization a fast path from impl for `impl<T> From<Box<RawValue...`
// could be used. Until then there is a special constructor `from_json` for this.
impl<T: Serialize> From<T> for Raw<T> {
    fn from(val: T) -> Self {
        Self::from(&val)
    }
}

impl<T> Clone for Raw<T> {
    fn clone(&self) -> Self {
        Self::new(self.json.clone())
    }
}

impl<T> Debug for Raw<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        use std::any::type_name;
        f.debug_struct(&format!("Raw::<{}>", type_name::<T>())).field("json", &self.json).finish()
    }
}

impl<'de, T> Deserialize<'de> for Raw<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Box::<RawValue>::deserialize(deserializer).map(Self::new)
    }
}

impl<T> Serialize for Raw<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.json.serialize(serializer)
    }
}
<commit_msg>serde: Relax bounds on Raw::deserialize_as<commit_after>use std::{
    clone::Clone,
    fmt::{self, Debug, Formatter},
    marker::PhantomData,
};

use serde::{
    de::{Deserialize, DeserializeOwned, Deserializer, IgnoredAny, MapAccess, Visitor},
    ser::{Serialize, Serializer},
};
use serde_json::value::RawValue;

use crate::cow::MyCowStr;

/// A wrapper around `Box<RawValue>`, to be used in place of any type in the Matrix endpoint
/// definition to allow request and response types to contain that said type represented by
/// the generic argument `Ev`.
///
/// Ruma offers the `Raw` wrapper to enable passing around JSON text that is only partially
/// validated. This is useful when a client receives events that do not follow the spec perfectly
/// or a server needs to generate reference hashes with the original canonical JSON string.
/// All event structs and enums implement `Serialize` / `Deserialize`, `Raw` should be used
/// to pass around events in a lossless way.
///
/// ```no_run
/// # use serde::Deserialize;
/// # use ruma_serde::Raw;
/// # #[derive(Deserialize)]
/// # struct AnyRoomEvent;
///
/// let json = r#"{ "type": "imagine a full event", "content": {...} }"#;
///
/// let deser = serde_json::from_str::<Raw<AnyRoomEvent>>(json)
///     .unwrap() // the first Result from serde_json::from_str, will not fail
///     .deserialize() // deserialize to the inner type
///     .unwrap(); // finally get to the AnyRoomEvent
/// ```
pub struct Raw<T> {
    json: Box<RawValue>,
    _ev: PhantomData<T>,
}

impl<T> Raw<T> {
    fn new(json: Box<RawValue>) -> Self {
        Self { json, _ev: PhantomData }
    }

    /// Create a `Raw` from a boxed `RawValue`.
    pub fn from_json(raw: Box<RawValue>) -> Self {
        Self::new(raw)
    }

    /// Access the underlying json value.
    pub fn json(&self) -> &RawValue {
        &self.json
    }

    /// Convert `self` into the underlying json value.
    pub fn into_json(self) -> Box<RawValue> {
        self.json
    }

    /// Try to access a given field inside this `Raw`, assuming it contains an
    /// object.
    ///
    /// Returns `Err(_)` when the contained value is not an object, or the field
    /// exists but is fails to deserialize to the expected type.
    ///
    /// Returns `Ok(None)` when the field doesn't exist or is `null`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # type CustomMatrixEvent = ();
    /// # fn foo() -> serde_json::Result<()> {
    /// # let raw_event: ruma_serde::Raw<()> = todo!();
    /// if raw_event.get_field::<String>("type")?.as_deref() == Some("org.custom.matrix.event") {
    ///     let event = raw_event.deserialize_as::<CustomMatrixEvent>()?;
    ///     // ...
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_field<'a, U>(&'a self, field_name: &str) -> serde_json::Result<Option<U>>
    where
        U: Deserialize<'a>,
    {
        struct SingleFieldVisitor<'b, T> {
            field_name: &'b str,
            _phantom: PhantomData<T>,
        }

        impl<'b, T> SingleFieldVisitor<'b, T> {
            fn new(field_name: &'b str) -> Self {
                Self { field_name, _phantom: PhantomData }
            }
        }

        impl<'b, 'de, T> Visitor<'de> for SingleFieldVisitor<'b, T>
        where
            T: Deserialize<'de>,
        {
            type Value = Option<T>;

            fn expecting(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("a string")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut res = None;
                while let Some(key) = map.next_key::<MyCowStr<'_>>()? {
                    if key.get() == self.field_name {
                        res = Some(map.next_value()?);
                    } else {
                        map.next_value::<IgnoredAny>()?;
                    }
                }

                Ok(res)
            }
        }

        let mut deserializer = serde_json::Deserializer::from_str(self.json().get());
        deserializer.deserialize_map(SingleFieldVisitor::new(field_name))
    }

    /// Try to deserialize the JSON as a custom type.
    pub fn deserialize_as<U>(&self) -> serde_json::Result<U>
    where
        U: DeserializeOwned,
    {
        serde_json::from_str(self.json.get())
    }
}

impl<T> Raw<T>
where
    T: DeserializeOwned,
{
    /// Try to deserialize the JSON as the expected type.
    pub fn deserialize(&self) -> serde_json::Result<T> {
        serde_json::from_str(self.json.get())
    }
}

impl<T: Serialize> From<&T> for Raw<T> {
    fn from(val: &T) -> Self {
        Self::new(serde_json::value::to_raw_value(val).unwrap())
    }
}

// With specialization a fast path from impl for `impl<T> From<Box<RawValue...`
// could be used. Until then there is a special constructor `from_json` for this.
impl<T: Serialize> From<T> for Raw<T> {
    fn from(val: T) -> Self {
        Self::from(&val)
    }
}

impl<T> Clone for Raw<T> {
    fn clone(&self) -> Self {
        Self::new(self.json.clone())
    }
}

impl<T> Debug for Raw<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        use std::any::type_name;
        f.debug_struct(&format!("Raw::<{}>", type_name::<T>())).field("json", &self.json).finish()
    }
}

impl<'de, T> Deserialize<'de> for Raw<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Box::<RawValue>::deserialize(deserializer).map(Self::new)
    }
}

impl<T> Serialize for Raw<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.json.serialize(serializer)
    }
}
<|endoftext|>


<commit_before>pub struct StdCounter {
    pub value: i64
}

pub trait Counter {
    fn clear(&mut self);
    fn dec(&mut self, value: i64);
    fn inc(&mut self, value: i64);
    fn snapshot(&self) -> Self;
}

impl Counter for StdCounter {
    fn clear(&mut self) {
        self.value = 0;
    }

    fn dec(&mut self, value: i64) {
        self.value -= value;
    }

    fn inc(&mut self, value: i64) {
        self.value += value;
    }

    fn snapshot(&self) ->  StdCounter {
        return StdCounter { value: self.value }
    }
}

#[cfg(test)]
mod test {
    use counter::StdCounter;
    use counter::Counter;

    #[test]
    fn increment_by_1() {
        let mut c = StdCounter{ value: 0 };
        c.inc(1);
        assert!(c.value == 1);
    }

    #[test]
    fn snapshot() {
        let c = StdCounter{value: 0};
        let mut c_snapshot = c.snapshot();

        c_snapshot.inc(1);

        assert!(c.value == 0);
        assert!(c_snapshot.value == 1);
    }
}<commit_msg>Use metric and cleanup a bit<commit_after>use metric::Metric;

pub struct StdCounter {
    pub value: i64
}

pub trait Counter : Metric {
    fn clear(&mut self);

    fn dec(&mut self, value: i64);

    fn inc(&mut self, value: i64);

    fn snapshot(&self) -> Self;

    fn new() -> Self;
}

impl Counter for StdCounter {
    fn clear(&mut self) {
        self.value = 0;
    }

    fn dec(&mut self, value: i64) {
        self.value -= value;
    }

    fn inc(&mut self, value: i64) {
        self.value += value;
    }

    fn snapshot(&self) ->  StdCounter {
        StdCounter { value: self.value }
    }

    fn new() -> StdCounter {
        StdCounter{ value: 0i64 }
    }
}

impl Metric for StdCounter {
}

#[cfg(test)]
mod test {
    use counter::StdCounter;
    use counter::Counter;

    #[test]
    fn increment_by_1() {
        let mut c = StdCounter{ value: 0 };
        c.inc(1);
        assert!(c.value == 1);
    }

    #[test]
    fn snapshot() {
        let c = StdCounter{value: 0};
        let mut c_snapshot = c.snapshot();

        c_snapshot.inc(1);

        assert!(c.value == 0);
        assert!(c_snapshot.value == 1);
    }
}<|endoftext|>


<commit_before>use super::{Document, Object, ObjectId};

impl Document {
	/// Create an object ID.
	pub fn new_object_id(&mut self) -> ObjectId {
		self.max_id += 1;
		(self.max_id, 0)
	}

	/// Add PDF object into document's object list.
	pub fn add_object<T: Into<Object>>(&mut self, object: T) -> ObjectId {
		self.max_id += 1;
		let id = (self.max_id, 0);
		self.objects.insert(id, object.into());
		id
	}
}

#[test]
fn create_document() {
	use super::{Dictionary, Stream, StringFormat};
	use super::content::*;
	use Object::Reference;
	use std::iter::FromIterator;
	use chrono::prelude::Local;

	let mut doc = Document::new();
	doc.version = "1.5".to_string();
	let info_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Title", Object::String(b"Create PDF document example".to_vec(), StringFormat::Literal)),
			("Creator", Object::String(b"https://crates.io/crates/lopdf".to_vec(), StringFormat::Literal)),
			("CreationDate", Local::now().into()),
		])
	);
	let pages_id = doc.new_object_id();
	let font_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Type", "Font".into()),
			("Subtype", "Type1".into()),
			("BaseFont", "Courier".into()),
		])
	);
	let resources_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Font", Dictionary::from_iter(vec![
				("F1", Reference(font_id)),
			]).into()),
		])
	);
	let content = Content{operations: vec![
		Operation::new("BT", vec![]),
		Operation::new("Tf", vec!["F1".into(), 48.into()]),
		Operation::new("Td", vec![100.into(), 600.into()]),
		Operation::new("Tj", vec![Object::String(b"Hello World!".to_vec(), StringFormat::Literal)]),
		Operation::new("ET", vec![]),
	]};
	let content_id = doc.add_object(Stream::new(Dictionary::new(), content.encode().unwrap()));
	let page_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Type", "Page".into()),
			("Parent", Reference(pages_id)),
			("Contents", vec![Reference(content_id)].into()),
		])
	);
	let pages = Dictionary::from_iter(vec![
		("Type", "Pages".into()),
		("Kids", vec![Reference(page_id)].into()),
		("Count", 1.into()),
		("Resources", Reference(resources_id)),
		("MediaBox", vec![0.into(), 0.into(), 595.into(), 842.into()].into()),
	]);
	doc.objects.insert(pages_id, Object::Dictionary(pages));
	let catalog_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Type", "Catalog".into()),
			("Pages", Reference(pages_id)),
		])
	);
	doc.trailer.set("Root", Reference(catalog_id));
	doc.trailer.set("Info", Reference(info_id));
	doc.compress();

	doc.save("test_1_create.pdf").unwrap();
}
<commit_msg>Added unit test for load_from() and save_to()<commit_after>use super::{Document, Object, ObjectId};

impl Document {
	/// Create an object ID.
	pub fn new_object_id(&mut self) -> ObjectId {
		self.max_id += 1;
		(self.max_id, 0)
	}

	/// Add PDF object into document's object list.
	pub fn add_object<T: Into<Object>>(&mut self, object: T) -> ObjectId {
		self.max_id += 1;
		let id = (self.max_id, 0);
		self.objects.insert(id, object.into());
		id
	}
}

#[test]
fn create_document() {
	use super::{Dictionary, Stream, StringFormat};
	use super::content::*;
	use Object::Reference;
	use std::iter::FromIterator;
	use chrono::prelude::Local;

	let mut doc = Document::new();
	doc.version = "1.5".to_string();
	let info_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Title", Object::String(b"Create PDF document example".to_vec(), StringFormat::Literal)),
			("Creator", Object::String(b"https://crates.io/crates/lopdf".to_vec(), StringFormat::Literal)),
			("CreationDate", Local::now().into()),
		])
	);
	let pages_id = doc.new_object_id();
	let font_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Type", "Font".into()),
			("Subtype", "Type1".into()),
			("BaseFont", "Courier".into()),
		])
	);
	let resources_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Font", Dictionary::from_iter(vec![
				("F1", Reference(font_id)),
			]).into()),
		])
	);
	let content = Content{operations: vec![
		Operation::new("BT", vec![]),
		Operation::new("Tf", vec!["F1".into(), 48.into()]),
		Operation::new("Td", vec![100.into(), 600.into()]),
		Operation::new("Tj", vec![Object::String(b"Hello World!".to_vec(), StringFormat::Literal)]),
		Operation::new("ET", vec![]),
	]};
	let content_id = doc.add_object(Stream::new(Dictionary::new(), content.encode().unwrap()));
	let page_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Type", "Page".into()),
			("Parent", Reference(pages_id)),
			("Contents", vec![Reference(content_id)].into()),
		])
	);
	let pages = Dictionary::from_iter(vec![
		("Type", "Pages".into()),
		("Kids", vec![Reference(page_id)].into()),
		("Count", 1.into()),
		("Resources", Reference(resources_id)),
		("MediaBox", vec![0.into(), 0.into(), 595.into(), 842.into()].into()),
	]);
	doc.objects.insert(pages_id, Object::Dictionary(pages));
	let catalog_id = doc.add_object(
		Dictionary::from_iter(vec![
			("Type", "Catalog".into()),
			("Pages", Reference(pages_id)),
		])
	);
	doc.trailer.set("Root", Reference(catalog_id));
	doc.trailer.set("Info", Reference(info_id));
	doc.compress();

	doc.save("test_1_create.pdf").unwrap();

	// test load_from() and save_to()
	use std::fs::File;
	use std::io::Cursor;

	let in_file = File::open("test_1_create.pdf").unwrap();
	let mut in_doc = Document::load_from(in_file).unwrap();

	let out_buf = Vec::<u8>::new();
	let mut memory_cursor = Cursor::new(out_buf);
	in_doc.save_to(&mut memory_cursor).unwrap();
	assert!(!memory_cursor.get_ref().is_empty());
}
<|endoftext|>