<commit_before>extern crate libc;
extern crate neovim;

use std::old_io::{File, FileMode, FileAccess};
use libc::{c_int, c_uchar, c_void};
use libc::funcs::posix88::unistd::{pipe, read, write};
use libc::types::os::arch::c95::size_t;

fn send_message(fd: c_int, command: &str) {
    let mut arr = neovim::Array::new();
    arr.add_string(command);
    let msg = neovim::serialize_message(1, "vim_command", &arr);
    let msg_ptr = msg.as_slice().as_ptr() as *const c_void;
    unsafe { write(fd, msg_ptr, msg.len() as size_t) };
}

fn recv_message(fd: c_int) -> Option<neovim::Array> {
    let mut buf : [c_uchar; 1024] = [0; 1024];
    let n = unsafe { read(fd, buf.as_mut_ptr() as *mut c_void, 1024) };
    if n < 0 {
        return None;
    }
    unsafe {
        let v = Vec::from_raw_buf(buf.as_ptr(), n as usize);
        let s = String::from_utf8_unchecked(v);
        Some(neovim::deserialize_message(&s))
    }
}

fn main() {
    // two anonymous pipes for msgpack-rpc between the logger and nvim
    let mut nvim_log : [c_int; 2] = [0; 2]; // to nvim from logger
    let mut log_nvim : [c_int; 2] = [0; 2]; // to logger from nvim
    unsafe {
        pipe(nvim_log.as_mut_ptr());
        pipe(log_nvim.as_mut_ptr());
    };

    // listen for events in a separate thread and log them
    ::std::thread::Thread::spawn(move || {
        // listen for bufenter events
        send_message(nvim_log[1], "au BufEnter * call rpcnotify(1, 'bufenter', fnamemodify(bufname(''), ':p'))");

        // receive messages
        let mut file = File::open_mode(&Path::new("events.log"), FileMode::Append, FileAccess::Write);
        while let Some(recv_arr) = recv_message(log_nvim[0]) {
            if recv_arr.len() > 0 {
                file.write_all(format!("{:?}\n", recv_arr).into_bytes().as_slice()).ok();
            }
        }
    });

    // start nvim
    let args : Vec<String> = ::std::env::args().collect();
    neovim::main_setup(&args);
    neovim::channel_from_fds(nvim_log[0], log_nvim[1]);
    neovim::main_loop();
}
<commit_msg>Use new io APIs in example<commit_after>#![feature(collections, core, libc)]

extern crate libc;
extern crate neovim;

use std::io::Write;
use std::fs::OpenOptions;
use std::path::Path;
use libc::{c_int, c_uchar, c_void};
use libc::funcs::posix88::unistd::{pipe, read, write};
use libc::types::os::arch::c95::size_t;

fn send_message(fd: c_int, command: &str) {
    let mut arr = neovim::Array::new();
    arr.add_string(command);
    let msg = neovim::serialize_message(1, "vim_command", &arr);
    let msg_ptr = msg.as_slice().as_ptr() as *const c_void;
    unsafe { write(fd, msg_ptr, msg.len() as size_t) };
}

fn recv_message(fd: c_int) -> Option<neovim::Array> {
    let mut buf : [c_uchar; 1024] = [0; 1024];
    let n = unsafe { read(fd, buf.as_mut_ptr() as *mut c_void, 1024) };
    if n < 0 {
        return None;
    }
    unsafe {
        let v = Vec::from_raw_buf(buf.as_ptr(), n as usize);
        let s = String::from_utf8_unchecked(v);
        Some(neovim::deserialize_message(&s))
    }
}

fn main() {
    // two anonymous pipes for msgpack-rpc between the logger and nvim
    let mut nvim_log : [c_int; 2] = [0; 2]; // to nvim from logger
    let mut log_nvim : [c_int; 2] = [0; 2]; // to logger from nvim
    unsafe {
        pipe(nvim_log.as_mut_ptr());
        pipe(log_nvim.as_mut_ptr());
    };

    // open log file
    let mut opts = OpenOptions::new();
    opts.create(true);
    opts.write(true);
    opts.append(true);
    let mut file = opts.open(&Path::new("events.log")).unwrap();

    // listen for events in a separate thread and log them
    ::std::thread::spawn(move || {
        // listen for bufenter events
        send_message(nvim_log[1], "au BufEnter * call rpcnotify(1, 'bufenter', fnamemodify(bufname(''), ':p'))");

        // receive messages
        while let Some(recv_arr) = recv_message(log_nvim[0]) {
            if recv_arr.len() > 0 {
                file.write_all(format!("{:?}\n", recv_arr).into_bytes().as_slice()).ok();
            }
        }
    });

    // start nvim
    let args : Vec<String> = ::std::env::args().collect();
    neovim::main_setup(&args);
    neovim::channel_from_fds(nvim_log[0], log_nvim[1]);
    neovim::main_loop();
}
<|endoftext|>


<commit_before>#![allow(unused_variables)]

extern crate glutin_window;
extern crate graphics;
extern crate rebind;
extern crate piston;
extern crate opengl_graphics;
extern crate viewport;

use glutin_window::GlutinWindow;
use graphics::*;
use opengl_graphics::{GlGraphics, OpenGL};
use piston::event_loop::{EventMap, Events};
use piston::input::{
    Event,
    Input,
    Motion,
    RenderArgs,
    RenderEvent,
    UpdateArgs,
    UpdateEvent
};
use piston::input::keyboard::Key;
use piston::input::Button::Keyboard;
use piston::window::WindowSettings;
use rebind::{Action, InputTranslator, RebindBuilder, Translated};
use std::cell::RefCell;
use std::rc::Rc;

struct App {
    window: Rc<RefCell<GlutinWindow>>,
    graphics: Rc<RefCell<GlGraphics>>,
    translator: InputTranslator<CharacterAction>,
    character: Character,
    cursor_pos: [f64; 2],
    bg_color: [f32; 4]
}

impl App {
    fn input(&mut self, input: &Input) {
        if let Some(t) = self.translator.translate(input) {
            match t {
                Translated::Press(action) => {
                    match action {
                        CharacterAction::Jump => {
                            println!("You jumped! Yay!");
                        },
                        CharacterAction::MoveLeft => {
                            self.character.current_velocity[0] += 0.5;
                        },
                        CharacterAction::MoveRight => {
                            self.character.current_velocity[0] -= 0.5;
                        }
                    }
                },
                Translated::Release(_) => {
                    self.character.current_velocity = [0.0, 0.0];
                },
                Translated::Move(Motion::MouseCursor(x, y)) => {
                    self.cursor_pos = [x, y];
                },
                _ => { }
            }
        }
    }

    fn update(&mut self, args: &UpdateArgs) {

    }

    fn render(&mut self, args: &RenderArgs) {
        let mut gl_graphics = self.graphics.borrow_mut();

        // draw the background color
        {
            gl_graphics.draw(args.viewport(), |_, gl| clear(self.bg_color, gl));
        }

        // draw the character
        {
            let square = rectangle::square(self.character.topleft[0],
                                           self.character.topleft[1],
                                           self.character.size);

            let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64);

            gl_graphics.draw(args.viewport(), |c, gl| {
                let transform = c.transform.trans(x, y);
                rectangle(self.character.color, square, transform, gl);
            });
        }

        // draw the cursor dot
        {
            let dot = ellipse::circle(self.cursor_pos[0], self.cursor_pos[1], 5.0);
            gl_graphics.draw(args.viewport(), |c, gl| ellipse([0.0, 1.0, 0.0, 1.0], dot, c.transform, gl));
        }
    }
}

struct Character {
    color: [f32; 4],
    topleft: [f64; 2],
    current_velocity: [f64; 2],
    size: f64
}

impl Character {
    fn new(col: [f32; 4], tl: [f64; 2], sz: f64) -> Self {
        Character {
            color: col,
            topleft: tl,
            current_velocity: [0.0f64, 0.0],
            size: sz
        }
    }
}

#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum CharacterAction {
    Jump,
    MoveLeft,
    MoveRight
}

impl Action for CharacterAction { }

fn main() {
    const WINDOW_SIZE: (u32, u32)  = (800, 600);
    const OPENGL: OpenGL = OpenGL::V3_2;

    let window = WindowSettings::new("calaxite", WINDOW_SIZE)
        .exit_on_esc(true)
        .fullscreen(false)
        .opengl(OPENGL)
        .vsync(true)
        .build()
        .unwrap_or_else(|e| panic!("Could not create window: {}", e));

    let gl_graphics = GlGraphics::new(OPENGL);

    let translator = RebindBuilder::new(WINDOW_SIZE.into())
        .with_action_mapping(Keyboard(Key::Space), CharacterAction::Jump)
        .with_action_mapping(Keyboard(Key::Left),  CharacterAction::MoveLeft)
        .with_action_mapping(Keyboard(Key::A),     CharacterAction::MoveLeft)
        .with_action_mapping(Keyboard(Key::Right), CharacterAction::MoveRight)
        .with_action_mapping(Keyboard(Key::D),     CharacterAction::MoveRight)
        .build_translator();

    let character = Character::new([1.0, 0.0, 0.0, 1.0],
                                   [30.0, 30.0],
                                   50.0);

    let mut app = App {
        window: Rc::new(RefCell::new(window)),
        graphics: Rc::new(RefCell::new(gl_graphics)),
        translator: translator,
        character: character,
        cursor_pos: [0.0, 0.0],
        bg_color: [0.0, 0.0, 0.0, 1.0] // black background
    };

    for e in app.window.clone().events() {
        match e {
            Event::Render(r) => { app.render(&r); },
            Event::Update(u) => { app.update(&u); },
            Event::Input(i)  => { app.input(&i); },
            _ => { }
        }
    }
}
<commit_msg>Remove trailing spaces<commit_after>#![allow(unused_variables)]

extern crate glutin_window;
extern crate graphics;
extern crate rebind;
extern crate piston;
extern crate opengl_graphics;
extern crate viewport;

use glutin_window::GlutinWindow;
use graphics::*;
use opengl_graphics::{GlGraphics, OpenGL};
use piston::event_loop::{EventMap, Events};
use piston::input::{
    Event,
    Input,
    Motion,
    RenderArgs,
    RenderEvent,
    UpdateArgs,
    UpdateEvent
};
use piston::input::keyboard::Key;
use piston::input::Button::Keyboard;
use piston::window::WindowSettings;
use rebind::{Action, InputTranslator, RebindBuilder, Translated};
use std::cell::RefCell;
use std::rc::Rc;

struct App {
    window: Rc<RefCell<GlutinWindow>>,
    graphics: Rc<RefCell<GlGraphics>>,
    translator: InputTranslator<CharacterAction>,
    character: Character,
    cursor_pos: [f64; 2],
    bg_color: [f32; 4]
}

impl App {
    fn input(&mut self, input: &Input) {
        if let Some(t) = self.translator.translate(input) {
            match t {
                Translated::Press(action) => {
                    match action {
                        CharacterAction::Jump => {
                            println!("You jumped! Yay!");
                        },
                        CharacterAction::MoveLeft => {
                            self.character.current_velocity[0] += 0.5;
                        },
                        CharacterAction::MoveRight => {
                            self.character.current_velocity[0] -= 0.5;
                        }
                    }
                },
                Translated::Release(_) => {
                    self.character.current_velocity = [0.0, 0.0];
                },
                Translated::Move(Motion::MouseCursor(x, y)) => {
                    self.cursor_pos = [x, y];
                },
                _ => { }
            }
        }
    }

    fn update(&mut self, args: &UpdateArgs) {

    }

    fn render(&mut self, args: &RenderArgs) {
        let mut gl_graphics = self.graphics.borrow_mut();

        // draw the background color
        {
            gl_graphics.draw(args.viewport(), |_, gl| clear(self.bg_color, gl));
        }

        // draw the character
        {
            let square = rectangle::square(self.character.topleft[0],
                                           self.character.topleft[1],
                                           self.character.size);

            let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64);

            gl_graphics.draw(args.viewport(), |c, gl| {
                let transform = c.transform.trans(x, y);
                rectangle(self.character.color, square, transform, gl);
            });
        }

        // draw the cursor dot
        {
            let dot = ellipse::circle(self.cursor_pos[0], self.cursor_pos[1], 5.0);
            gl_graphics.draw(args.viewport(), |c, gl| ellipse([0.0, 1.0, 0.0, 1.0], dot, c.transform, gl));
        }
    }
}

struct Character {
    color: [f32; 4],
    topleft: [f64; 2],
    current_velocity: [f64; 2],
    size: f64
}

impl Character {
    fn new(col: [f32; 4], tl: [f64; 2], sz: f64) -> Self {
        Character {
            color: col,
            topleft: tl,
            current_velocity: [0.0f64, 0.0],
            size: sz
        }
    }
}

#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum CharacterAction {
    Jump,
    MoveLeft,
    MoveRight
}

impl Action for CharacterAction { }

fn main() {
    const WINDOW_SIZE: (u32, u32)  = (800, 600);
    const OPENGL: OpenGL = OpenGL::V3_2;

    let window = WindowSettings::new("calaxite", WINDOW_SIZE)
        .exit_on_esc(true)
        .fullscreen(false)
        .opengl(OPENGL)
        .vsync(true)
        .build()
        .unwrap_or_else(|e| panic!("Could not create window: {}", e));

    let gl_graphics = GlGraphics::new(OPENGL);

    let translator = RebindBuilder::new(WINDOW_SIZE.into())
        .with_action_mapping(Keyboard(Key::Space), CharacterAction::Jump)
        .with_action_mapping(Keyboard(Key::Left),  CharacterAction::MoveLeft)
        .with_action_mapping(Keyboard(Key::A),     CharacterAction::MoveLeft)
        .with_action_mapping(Keyboard(Key::Right), CharacterAction::MoveRight)
        .with_action_mapping(Keyboard(Key::D),     CharacterAction::MoveRight)
        .build_translator();

    let character = Character::new([1.0, 0.0, 0.0, 1.0],
                                   [30.0, 30.0],
                                   50.0);

    let mut app = App {
        window: Rc::new(RefCell::new(window)),
        graphics: Rc::new(RefCell::new(gl_graphics)),
        translator: translator,
        character: character,
        cursor_pos: [0.0, 0.0],
        bg_color: [0.0, 0.0, 0.0, 1.0] // black background
    };

    for e in app.window.clone().events() {
        match e {
            Event::Render(r) => { app.render(&r); },
            Event::Update(u) => { app.update(&u); },
            Event::Input(i)  => { app.input(&i); },
            _ => { }
        }
    }
}
<|endoftext|>


<commit_before>#![feature(collections, libc)]

extern crate libc;
extern crate neovim;

use std::io::Write;
use std::fs::OpenOptions;
use std::path::Path;
use libc::{c_int, c_uchar, c_void};
use libc::funcs::posix88::unistd::{pipe, read, write};
use libc::types::os::arch::c95::size_t;

fn send_message(fd: c_int, command: &str) {
    let mut arr = neovim::Array::new();
    arr.add_string(command);
    let msg = neovim::serialize_message(1, "vim_command", &arr);
    let msg_ref: &str = msg.as_ref();
    let msg_ptr = msg_ref.as_ptr() as *const c_void;
    unsafe { write(fd, msg_ptr, msg.len() as size_t) };
}

fn recv_message(fd: c_int) -> Option<neovim::Array> {
    let mut buf : [c_uchar; 1024] = [0; 1024];
    let n = unsafe { read(fd, buf.as_mut_ptr() as *mut c_void, 1024) };
    if n < 0 {
        return None;
    }
    unsafe {
        let v = Vec::from_raw_buf(buf.as_ptr(), n as usize);
        let s = String::from_utf8_unchecked(v);
        Some(neovim::deserialize_message(&s))
    }
}

fn main() {
    // two anonymous pipes for msgpack-rpc between the logger and nvim
    let mut nvim_log : [c_int; 2] = [0; 2]; // to nvim from logger
    let mut log_nvim : [c_int; 2] = [0; 2]; // to logger from nvim
    unsafe {
        pipe(nvim_log.as_mut_ptr());
        pipe(log_nvim.as_mut_ptr());
    };

    // open log file
    let mut opts = OpenOptions::new();
    opts.create(true);
    opts.write(true);
    opts.append(true);
    let mut file = opts.open(&Path::new("events.log")).unwrap();

    // listen for events in a separate thread and log them
    ::std::thread::spawn(move || {
        // listen for bufenter events
        send_message(nvim_log[1], "au BufEnter * call rpcnotify(1, 'bufenter', fnamemodify(bufname(''), ':p'))");

        // receive messages
        while let Some(recv_arr) = recv_message(log_nvim[0]) {
            if recv_arr.len() > 0 {
                let recv_str = format!("{:?}\n", recv_arr).into_bytes();
                file.write_all(recv_str.as_ref()).ok();
            }
        }
    });

    // start nvim
    let args : Vec<String> = ::std::env::args().collect();
    neovim::main_setup(&args);
    neovim::channel_from_fds(nvim_log[0], log_nvim[1]);
    neovim::main_loop();
}
<commit_msg>Update example<commit_after>#![feature(libc)]

extern crate libc;
extern crate neovim;

use std::io::Write;
use std::fs::OpenOptions;
use std::path::Path;
use std::slice;
use libc::{c_int, c_uchar, c_void};
use libc::funcs::posix88::unistd::{pipe, read, write};
use libc::types::os::arch::c95::size_t;

fn send_message(fd: c_int, command: &str) {
    let mut arr = neovim::Array::new();
    arr.add_string(command);
    let msg = neovim::serialize_message(1, "vim_command", &arr);
    let msg_ref: &str = msg.as_ref();
    let msg_ptr = msg_ref.as_ptr() as *const c_void;
    unsafe { write(fd, msg_ptr, msg.len() as size_t) };
}

fn recv_message(fd: c_int) -> Option<neovim::Array> {
    let mut buf : [c_uchar; 1024] = [0; 1024];
    let n = unsafe { read(fd, buf.as_mut_ptr() as *mut c_void, 1024) };
    if n < 0 {
        return None;
    }
    unsafe {
        let v = slice::from_raw_parts(buf.as_ptr(), n as usize).to_vec();
        let s = String::from_utf8_unchecked(v);
        Some(neovim::deserialize_message(&s))
    }
}

fn main() {
    // two anonymous pipes for msgpack-rpc between the logger and nvim
    let mut nvim_log : [c_int; 2] = [0; 2]; // to nvim from logger
    let mut log_nvim : [c_int; 2] = [0; 2]; // to logger from nvim
    unsafe {
        pipe(nvim_log.as_mut_ptr());
        pipe(log_nvim.as_mut_ptr());
    };

    // open log file
    let mut opts = OpenOptions::new();
    opts.create(true);
    opts.write(true);
    opts.append(true);
    let mut file = opts.open(&Path::new("events.log")).unwrap();

    // listen for events in a separate thread and log them
    ::std::thread::spawn(move || {
        // listen for bufenter events
        send_message(nvim_log[1], "au BufEnter * call rpcnotify(1, 'bufenter', fnamemodify(bufname(''), ':p'))");

        // receive messages
        while let Some(recv_arr) = recv_message(log_nvim[0]) {
            if recv_arr.len() > 0 {
                let recv_str = format!("{:?}\n", recv_arr).into_bytes();
                file.write_all(recv_str.as_ref()).ok();
            }
        }
    });

    // start nvim
    let args : Vec<String> = ::std::env::args().collect();
    neovim::main_setup(&args);
    neovim::channel_from_fds(nvim_log[0], log_nvim[1]);
    neovim::main_loop();
}
<|endoftext|>


<commit_before>#![cfg(feature = "securityhub")]

extern crate env_logger;
extern crate rusoto_core;
extern crate rusoto_securityhub;

use rusoto_core::Region;
use rusoto_securityhub::{ListInvitationsRequest, SecurityHub, SecurityHubClient};

#[tokio::test]
async fn should_list_invitations() {
    let _ = env_logger::try_init();
    let client = SecurityHubClient::new(Region::UsWest2);
    let request = ListInvitationsRequest {
        ..Default::default()
    };

    let result = client.list_invitations(request).await;
    assert!(result.is_ok());
}
<commit_msg>Disable securityhub integ test<commit_after>#![cfg(feature = "securityhub")]

extern crate env_logger;
extern crate rusoto_core;
extern crate rusoto_securityhub;

use rusoto_core::Region;
use rusoto_securityhub::{ListInvitationsRequest, SecurityHub, SecurityHubClient};

#[tokio::test]
#[ignore]
async fn should_list_invitations() {
    let _ = env_logger::try_init();
    let client = SecurityHubClient::new(Region::UsWest2);
    let request = ListInvitationsRequest {
        ..Default::default()
    };

    client.list_invitations(request).await.unwrap();
}
<|endoftext|>


<commit_before>extern crate simple_csv;

use std::env;
use std::fs::File;
use std::io::BufReader;
use std::str::FromStr;
use simple_csv::{SimpleCsvWriter, SimpleCsvReader};

fn main(){
    let args : Vec<String> = env::args().collect();
    let threshold = f64::from_str(&args[1]).expect("first argument should be the threshold");

    let f = File::open("assets/brightness.csv").unwrap();
    let buf = BufReader::new(f);
    let reader = SimpleCsvReader::new(buf);

    let raw: Vec<(f64, f64)> = reader
        .map (|r| r.unwrap())
        .map(data)
        .collect();

    let mut result: Vec<(f64, f64)> = vec!();
    let mut current: Option<(f64, f64)> = None;
    for candidate in raw {
        match current {
            Some(previous) => {
                if (candidate.1 - previous.1).abs() <= threshold {
                    result.push(previous);
                    current = Some(candidate);
                }
            }

            None => {
                current = Some(candidate)
            }
        }
    }

    let o = File::create("assets/filter.csv").unwrap();
    let mut writer = SimpleCsvWriter::new(o);

    for (time, filtered) in result {
        writer.write(
            &vec!(time.to_string(), filtered.to_string())
        ).unwrap();
    }
}

fn data(row: Vec<String>) -> (f64, f64) {
    let iter = row.iter();

    let raw: Vec<f64> = iter
        .map(|s| f64::from_str(s).unwrap())
        .collect();

    (raw[0], raw[2])
}
<commit_msg>Simplify filtering of detrended data<commit_after>extern crate simple_csv;

use std::env;
use std::fs::File;
use std::io::BufReader;
use std::str::FromStr;
use simple_csv::{SimpleCsvWriter, SimpleCsvReader};

fn main(){
    let args : Vec<String> = env::args().collect();
    let threshold = f64::from_str(&args[1]).expect("first argument should be the threshold");

    let f = File::open("assets/detrend.csv").unwrap();
    let buf = BufReader::new(f);
    let reader = SimpleCsvReader::new(buf);

    let result: Vec<(f64, f64)> = reader
        .map (|r| r.unwrap())
        .map(data)
        .filter(|&(_,difference)| difference.abs() <= threshold)
        .collect();

    let o = File::create("assets/filter.csv").unwrap();
    let mut writer = SimpleCsvWriter::new(o);

    for (time, filtered) in result {
        writer.write(
            &vec!(time.to_string(), filtered.to_string())
        ).unwrap();
    }
}

fn data(row: Vec<String>) -> (f64, f64) {
    let iter = row.iter();

    let raw: Vec<f64> = iter
        .map(|s| f64::from_str(s).unwrap())
        .collect();

    (raw[0], raw[3])
}
<|endoftext|>


<commit_before>use std::mem;

fn main() {
  let v = [1u8, 0u8,0u8,1u8];
  let z : u32 = unsafe{ mem::transmute(v) };
  println!("{}", z);
}
<commit_msg>Drop test file<commit_after><|endoftext|>


<commit_before>use std::cell::RefCell;
use std::collections::hash_map::{Entry, HashMap};
use std::collections::hash_set::HashSet;
use std::rc::Rc;

use uuid::Uuid;

use js_types::js_type::JsPtrEnum;

pub mod scope;

pub type Alloc<T> = Rc<RefCell<T>>;

pub struct AllocBox {
    black_set: HashMap<Uuid, Alloc<JsPtrEnum>>,
    grey_set: HashMap<Uuid, Alloc<JsPtrEnum>>,
    white_set: HashMap<Uuid, Alloc<JsPtrEnum>>,
}

impl AllocBox {
    pub fn new() -> AllocBox {
        AllocBox {
            black_set: HashMap::new(),
            grey_set: HashMap::new(),
            white_set: HashMap::new(),
        }
    }

    pub fn len(&self) -> usize {
        self.black_set.len() + self.grey_set.len() + self.white_set.len()
    }

    pub fn alloc(&mut self, uuid: Uuid, ptr: JsPtrEnum) -> Uuid {
        // TODO validate that `uuid` isn't already in the map
        self.white_set.insert(uuid, Rc::new(RefCell::new(ptr)));
        uuid
    }

    pub fn mark_roots(&mut self, marks: HashSet<Uuid>) {
        for mark in marks {
            if let Some(ptr) = self.white_set.remove(&mark) {
                // Get all child references
                let child_ids = AllocBox::get_ptr_children(&ptr);
                // Mark current ref as black
                self.black_set.insert(mark, ptr);
                // Mark child references as grey
                self.grey_children(child_ids);
            } else if let Some(ptr) = self.grey_set.remove(&mark) {
                // Get all child references
                let child_ids = AllocBox::get_ptr_children(&ptr);
                // Mark current ref as black
                self.black_set.insert(mark, ptr);
                // Mark child references as grey
                self.grey_children(child_ids);
            }
        }
    }

    pub fn mark_ptrs(&mut self) {
        // Mark any grey object as black, and mark all white objs it refs as grey
        let mut new_grey_set = HashMap::new();
        for (uuid, var) in self.grey_set.drain() {
            let child_ids = AllocBox::get_ptr_children(&var);
            self.black_set.insert(uuid, var);
            for child_id in child_ids {
                if let Some(var) = self.white_set.remove(&child_id) {
                    new_grey_set.insert(child_id, var);
                }
            }
        }
        self.grey_set = new_grey_set;
    }

    pub fn sweep_ptrs(&mut self) {
        // Delete all white pointers and reset the GC state.
        self.white_set = self.black_set.clone();
        self.grey_set = HashMap::new();
        self.black_set = HashMap::new();
    }

    pub fn find_id(&self, uuid: &Uuid) -> Option<&Alloc<JsPtrEnum>> {
        self.white_set.get(uuid).or(
            self.grey_set.get(uuid).or(
                self.black_set.get(uuid)))
    }

    pub fn update_ptr(&mut self, uuid: &Uuid, ptr: JsPtrEnum) -> bool {
        if let Entry::Occupied(mut view) = self.find_id_mut(&uuid) {
            let inner = view.get_mut();
            *inner.borrow_mut() = ptr;
            true
        } else { false }
    }

    fn grey_children(&mut self, child_ids: HashSet<Uuid>) {
        for child_id in child_ids.iter() {
            if let Some(var) = self.white_set.remove(child_id) {
                self.grey_set.insert(*child_id, var);
            }
        }
    }

    fn get_ptr_children(ptr: &Alloc<JsPtrEnum>) -> HashSet<Uuid> {
        if let JsPtrEnum::JsObj(ref obj) = *ptr.borrow() {
            obj.get_children()
        } else { HashSet::new() }
    }

    fn find_id_mut(&mut self, uuid: &Uuid) -> Entry<Uuid, Alloc<JsPtrEnum>> {
        if let e @ Entry::Occupied(_) = self.white_set.entry(*uuid) {
            e
        } else if let e @ Entry::Occupied(_) = self.grey_set.entry(*uuid) {
            e
        } else { self.black_set.entry(*uuid) }
    }
}
<commit_msg>Fix AllocBox tests<commit_after>use std::cell::RefCell;
use std::collections::hash_map::{Entry, HashMap};
use std::collections::hash_set::HashSet;
use std::rc::Rc;

use uuid::Uuid;

use js_types::js_type::JsPtrEnum;

pub mod scope;

pub type Alloc<T> = Rc<RefCell<T>>;

pub struct AllocBox {
    black_set: HashMap<Uuid, Alloc<JsPtrEnum>>,
    grey_set: HashMap<Uuid, Alloc<JsPtrEnum>>,
    white_set: HashMap<Uuid, Alloc<JsPtrEnum>>,
}

impl AllocBox {
    pub fn new() -> AllocBox {
        AllocBox {
            black_set: HashMap::new(),
            grey_set: HashMap::new(),
            white_set: HashMap::new(),
        }
    }

    pub fn len(&self) -> usize {
        self.black_set.len() + self.grey_set.len() + self.white_set.len()
    }

    pub fn alloc(&mut self, uuid: Uuid, ptr: JsPtrEnum) -> Uuid {
        // TODO validate that `uuid` isn't already in the map
        self.white_set.insert(uuid, Rc::new(RefCell::new(ptr)));
        uuid
    }

    pub fn mark_roots(&mut self, marks: HashSet<Uuid>) {
        for mark in marks {
            if let Some(ptr) = self.white_set.remove(&mark) {
                // Get all child references
                let child_ids = AllocBox::get_ptr_children(&ptr);
                // Mark current ref as black
                self.black_set.insert(mark, ptr);
                // Mark child references as grey
                self.grey_children(child_ids);
            } else if let Some(ptr) = self.grey_set.remove(&mark) {
                // Get all child references
                let child_ids = AllocBox::get_ptr_children(&ptr);
                // Mark current ref as black
                self.black_set.insert(mark, ptr);
                // Mark child references as grey
                self.grey_children(child_ids);
            }
        }
    }

    pub fn mark_ptrs(&mut self) {
        // Mark any grey object as black, and mark all white objs it refs as grey
        let mut new_grey_set = HashMap::new();
        for (uuid, var) in self.grey_set.drain() {
            let child_ids = AllocBox::get_ptr_children(&var);
            self.black_set.insert(uuid, var);
            for child_id in child_ids {
                if let Some(var) = self.white_set.remove(&child_id) {
                    new_grey_set.insert(child_id, var);
                }
            }
        }
        self.grey_set = new_grey_set;
    }

    pub fn sweep_ptrs(&mut self) {
        // Delete all white pointers and reset the GC state.
        self.white_set = self.black_set.clone();
        self.grey_set = HashMap::new();
        self.black_set = HashMap::new();
    }

    pub fn find_id(&self, uuid: &Uuid) -> Option<&Alloc<JsPtrEnum>> {
        self.white_set.get(uuid).or(
            self.grey_set.get(uuid).or(
                self.black_set.get(uuid)))
    }

    pub fn update_ptr(&mut self, uuid: &Uuid, ptr: JsPtrEnum) -> bool {
        if let Entry::Occupied(mut view) = self.find_id_mut(&uuid) {
            let inner = view.get_mut();
            *inner.borrow_mut() = ptr;
            true
        } else { false }
    }

    fn grey_children(&mut self, child_ids: HashSet<Uuid>) {
        for child_id in child_ids.iter() {
            if let Some(var) = self.white_set.remove(child_id) {
                self.grey_set.insert(*child_id, var);
            }
        }
    }

    fn get_ptr_children(ptr: &Alloc<JsPtrEnum>) -> HashSet<Uuid> {
        if let JsPtrEnum::JsObj(ref obj) = *ptr.borrow() {
            obj.get_children()
        } else { HashSet::new() }
    }

    fn find_id_mut(&mut self, uuid: &Uuid) -> Entry<Uuid, Alloc<JsPtrEnum>> {
        if let e @ Entry::Occupied(_) = self.white_set.entry(*uuid) {
            e
        } else if let e @ Entry::Occupied(_) = self.grey_set.entry(*uuid) {
            e
        } else { self.black_set.entry(*uuid) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use uuid::Uuid;
    use js_types::js_type::JsPtrEnum;
    use js_types::js_str::JsStrStruct;

    fn make_str(s: &str) -> JsPtrEnum {
        JsPtrEnum::JsStr(JsStrStruct::new(s))
    }

    #[test]
    fn test_len() {
        let mut ab = AllocBox::new();
        assert_eq!(ab.len(), 0);
        ab.alloc(Uuid::new_v4(), make_str(""));
        assert_eq!(ab.len(), 1);
    }

    fn test_alloc() {
        let mut ab = AllocBox::new();
        let id1 = Uuid::new_v4();
        let id2 = Uuid::new_v4();
        let id3 = Uuid::new_v4();
        let _id1 = ab.alloc(id1.clone(), make_str(""));
        let _id2 = ab.alloc(id2.clone(), make_str(""));
        let _id3 = ab.alloc(id3.clone(), make_str(""));

        assert_eq!(id1, _id1);
        assert_eq!(id2, _id2);
        assert_eq!(id3, _id3);
    }

    fn test_mark_roots() {
        let mut ab = AllocBox::new();
        let id1 = Uuid::new_v4();
        let id2 = Uuid::new_v4();
        let id3 = Uuid::new_v4();
        let id1 = ab.alloc(id1, make_str(""));
        let id2 = ab.alloc(id2, make_str(""));
        let id3 = ab.alloc(id3, make_str(""));

        let marks = HashSet::new();
        marks.insert(id1); marks.insert(id2);
        ab.mark_roots(marks);

    }
}
<|endoftext|>


<commit_before>//! Exposes the `Alloy` type, a flexible storage container
//! that `Ingots` may use to expose new APIs or public data
//! to other `Ingots`.

use anymap::AnyMap;

/// `Alloy` wraps an AnyMap, a map allowing storage keyed by type
/// to allow for persistent data across `Ingots`.
///
/// `Ingots` can be inserted into an `Alloy` and retrieved later. Data needing
/// exposure across `Ingots` and persistence (for example, a body parser's parsed data)
/// should be stored on the `Ingot` and retrieved later from the `Alloy`.
///
/// Only one instance of any type can be stored in the `Alloy` at a time.
/// Best practice is to store targeted data. For example, for a body parser
///
/// ```ignore
/// impl<Rq, Rs> Ingot for BodyParser {
///     fn enter(req: &mut Rq, res: &mut Rs, alloy: &mut Alloy) -> Status {
///         let parsed: Parsed = ...; // Parse the body
///         alloy.insert(Parsed);
///     }
/// }
/// ```
///
/// In most cases, the `Ingot` itself does not need to be exposed,
/// and should not be stored on the `Alloy`.
pub struct Alloy {
    map: AnyMap
}

impl Alloy {
    /// Create a new, empty alloy.
    pub fn new() -> Alloy {
        Alloy {
            map: AnyMap::new()
        }
    }
}

impl Alloy {
    /// Get a reference to the stored value of a given type.
    pub fn find<'a, T: 'static>(&'a self) -> Option<&'a T> {
        self.map.find::<T>()
    }

    /// Get a mutable reference to the stored value of a given type.
    pub fn find_mut<'a, T: 'static>(&'a mut self) -> Option<&'a mut T> {
        self.map.find_mut::<T>()
    }

    /// Add an value to the `Alloy`.
    pub fn insert<T: 'static>(&mut self, value: T) {
        self.map.insert::<T>(value)
    }

    /// Remove a value from the `Alloy`.
    pub fn remove<T: 'static>(&mut self) {
        self.remove::<T>()
    }
}

<commit_msg>(doc) Updated Alloy for Middleware.<commit_after>//! Exposes the `Alloy` type, a flexible storage container
//! that `Middleware` may use to expose new APIs or public data
//! to other `Middleware`.

use anymap::AnyMap;

/// `Alloy` wraps an AnyMap, a map allowing storage keyed by type
/// to allow for persistent data across `Middleware`.
///
/// `Middleware` can be inserted into an `Alloy` and retrieved later. Data needing
/// exposure across `Middleware` and persistence (for example, a body parser's parsed data)
/// should be stored and retrieved later from the `Alloy`.
///
/// Only one instance of any type can be stored in the `Alloy` at a time.
/// Best practice is to store targeted data. For example, for a body parser,
/// rather than store the `Middleware`, store a `Parsed` type:
///
/// ```ignore
/// impl<Rq, Rs> Middleware for BodyParser {
///     fn enter(req: &mut Rq, res: &mut Rs, alloy: &mut Alloy) -> Status {
///         let parsed: Parsed = ...; // Parse the body
///         alloy.insert::<Parsed>(Parsed);
///     }
/// }
/// ```
///
/// In most cases, the `Middleware` itself does not need to be exposed,
/// and should not be stored on the `Alloy`.
pub struct Alloy {
    map: AnyMap
}

impl Alloy {
    /// Create a new, empty alloy.
    pub fn new() -> Alloy {
        Alloy {
            map: AnyMap::new()
        }
    }
}

impl Alloy {
    /// Get a reference to the stored value of a given type.
    pub fn find<'a, T: 'static>(&'a self) -> Option<&'a T> {
        self.map.find::<T>()
    }

    /// Get a mutable reference to the stored value of a given type.
    pub fn find_mut<'a, T: 'static>(&'a mut self) -> Option<&'a mut T> {
        self.map.find_mut::<T>()
    }

    /// Add an value to the `Alloy`.
    pub fn insert<T: 'static>(&mut self, value: T) {
        self.map.insert::<T>(value)
    }

    /// Remove a value from the `Alloy`.
    pub fn remove<T: 'static>(&mut self) {
        self.remove::<T>()
    }
}

<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net>
 */

use serde_json::{self, Error};
use submission::Submission;

#[derive(Debug)]
pub struct SubmissionResult {
    pub status: SubmissionStatus,
    pub meta: SubmissionMeta,
}

impl SubmissionResult {
    pub fn new(status: SubmissionStatus) -> SubmissionResult {
        SubmissionResult {
            status,
            meta: SubmissionMeta::None,
        }
    }

    pub fn with_meta(status: SubmissionStatus, meta: SubmissionMeta) -> SubmissionResult {
        SubmissionResult { status, meta }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SubmissionStatus {
    Successful,
    FailedTests,
    BadCompile,
    Crashed,
    Timeout,
    InternalError,
}

#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum SubmissionMeta {
    None,
    GeneralFailure { stderr: String },
    TestFailures { pass: u8, fail: u8, diff: String },
    InternalError(String),
}

#[derive(Debug, Serialize)]
pub struct Response {
    id: u32,
    user: u32,
    problem: String,
    result: SubmissionStatus,
    meta: SubmissionMeta,
}

impl Response {
    pub fn new(sub: &Submission, result: SubmissionResult) -> Response {
        Response {
            id: sub.get_id(),
            user: sub.get_user(),
            problem: sub.get_problem_name(),
            result: result.status,
            meta: result.meta,
        }
    }

    pub fn new_error(msg: String) -> Response {
        Response {
            id: 0,
            user: 0,
            problem: String::new(),
            result: SubmissionStatus::InternalError,
            meta: SubmissionMeta::InternalError(msg),
        }
    }

    pub fn encode(&self) -> Result<String, Error> {
        serde_json::to_string(&self)
    }

    pub fn get_status(&self) -> &SubmissionStatus {
        &self.result
    }
}
<commit_msg>Limit stored stderr to 8kb<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net>
 */

use serde_json::{self, Error};
use submission::Submission;

#[derive(Debug)]
pub struct SubmissionResult {
    pub status: SubmissionStatus,
    pub meta: SubmissionMeta,
}

impl SubmissionResult {
    pub fn new(status: SubmissionStatus) -> SubmissionResult {
        SubmissionResult {
            status,
            meta: SubmissionMeta::None,
        }
    }

    pub fn with_meta(status: SubmissionStatus, meta: SubmissionMeta) -> SubmissionResult {
        SubmissionResult { status, meta }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SubmissionStatus {
    Successful,
    FailedTests,
    BadCompile,
    Crashed,
    Timeout,
    InternalError,
}

#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum SubmissionMeta {
    None,
    GeneralFailure { stderr: String },
    TestFailures { pass: u8, fail: u8, diff: String },
    InternalError(String),
}

#[derive(Debug, Serialize)]
pub struct Response {
    id: u32,
    user: u32,
    problem: String,
    result: SubmissionStatus,
    meta: SubmissionMeta,
}

impl Response {
    pub fn new(sub: &Submission, result: SubmissionResult) -> Response {
        let meta = match result.meta {
            SubmissionMeta::GeneralFailure { stderr } => {
                let mut trunc = stderr.clone();
                trunc.truncate(8000);
                SubmissionMeta::GeneralFailure { stderr: trunc }
            }
            _ => result.meta,
        };

        Response {
            id: sub.get_id(),
            user: sub.get_user(),
            problem: sub.get_problem_name(),
            result: result.status,
            meta,
        }
    }

    pub fn new_error(msg: String) -> Response {
        Response {
            id: 0,
            user: 0,
            problem: String::new(),
            result: SubmissionStatus::InternalError,
            meta: SubmissionMeta::InternalError(msg),
        }
    }

    pub fn encode(&self) -> Result<String, Error> {
        serde_json::to_string(&self)
    }

    pub fn get_status(&self) -> &SubmissionStatus {
        &self.result
    }
}
<|endoftext|>


<commit_before>use quote::Tokens;
use syn::{Body, Field, Ident, Variant, VariantData, MacroInput, Ty};

pub fn expand(input: &MacroInput) -> Tokens {
    let trait_name = "Add";
    let trait_ident = Ident::from(trait_name);
    let method_name = trait_name.to_lowercase();
    let method_ident = Ident::from(method_name.clone());
    let input_type = &input.ident;

    let (output_type, block) = match input.body {
        Body::Struct(VariantData::Tuple(ref fields)) => {
            (input_type, tuple_content(input_type, fields, &method_ident))
        },
        Body::Struct(VariantData::Struct(ref fields)) => {
            (input_type, struct_content(input_type, fields, &method_ident))
        },

        _ => panic!(format!("Only structs and enums can use dervie({})", trait_name))
    };

    quote!(
        impl std::ops::#trait_ident for #input_type {
            type Output = #output_type;
            fn #method_ident(self, rhs: #input_type) -> #output_type {
                #block
            }
        }
    )
}

fn tuple_content(input_type: &Ident, fields: &Vec<Field>, method_ident: &Ident) -> Tokens  {
    let mut exprs = vec![];

    for i in 0..fields.len() {
        let i = Ident::from(i.to_string());
        let expr = quote!(self.#i.#method_ident(rhs.#i));
        exprs.push(expr);
    }

    quote!(#input_type(#(#exprs),*))
}

fn struct_content(input_type: &Ident, fields: &Vec<Field>, method_ident: &Ident) -> Tokens  {
    let mut exprs = vec![];

    for field in fields {
        // It's safe to unwrap because struct fields always have an identifier
        let field_id = field.ident.clone().unwrap();
        let expr = quote!(#field_id: self.#field_id.#method_ident(rhs.#field_id));
        exprs.push(expr)
    }

    quote!(#input_type{#(#exprs),*})
}

<commit_msg>Macros 1.1: Add some comment for clarity<commit_after>use quote::Tokens;
use syn::{Body, Field, Ident, Variant, VariantData, MacroInput, Ty};

pub fn expand(input: &MacroInput) -> Tokens {
    let trait_name = "Add";
    let trait_ident = Ident::from(trait_name);
    let method_name = trait_name.to_lowercase();
    let method_ident = Ident::from(method_name.clone());
    let input_type = &input.ident;

    let (output_type, block) = match input.body {
        Body::Struct(VariantData::Tuple(ref fields)) => {
            (input_type, tuple_content(input_type, fields, &method_ident))
        },
        Body::Struct(VariantData::Struct(ref fields)) => {
            (input_type, struct_content(input_type, fields, &method_ident))
        },

        _ => panic!(format!("Only structs and enums can use dervie({})", trait_name))
    };

    quote!(
        impl std::ops::#trait_ident for #input_type {
            type Output = #output_type;
            fn #method_ident(self, rhs: #input_type) -> #output_type {
                #block
            }
        }
    )
}

fn tuple_content(input_type: &Ident, fields: &Vec<Field>, method_ident: &Ident) -> Tokens  {
    let mut exprs = vec![];

    for i in 0..fields.len() {
        let i = Ident::from(i.to_string());
        // generates `self.0.add(rhs.0)`
        let expr = quote!(self.#i.#method_ident(rhs.#i));
        exprs.push(expr);
    }

    quote!(#input_type(#(#exprs),*))
}

fn struct_content(input_type: &Ident, fields: &Vec<Field>, method_ident: &Ident) -> Tokens  {
    let mut exprs = vec![];

    for field in fields {
        // It's safe to unwrap because struct fields always have an identifier
        let field_id = field.ident.clone().unwrap();
        // generates `x: self.x.add(rhs.x)`
        let expr = quote!(#field_id: self.#field_id.#method_ident(rhs.#field_id));
        exprs.push(expr)
    }

    quote!(#input_type{#(#exprs),*})
}

<|endoftext|>


<commit_before>use crate::convert::*;
use core::hash::{Hasher};

/// A `Hasher` for hashing an arbitrary stream of bytes.
///
/// Instances of [`AHasher`] represent state that is updated while hashing data.
///
/// Each method updates the internal state based on the new data provided. Once
/// all of the data has been provided, the resulting hash can be obtained by calling
/// `finish()`
///
/// [Clone] is also provided in case you wish to calculate hashes for two different items that
/// start with the same data.
///
#[derive(Debug, Clone)]
pub struct AHasher {
    buffer: [u64; 2],
    key: [u64; 2],
}

impl AHasher {
    /// Creates a new hasher keyed to the provided keys.
    /// # Example
    ///
    /// ```
    /// use std::hash::Hasher;
    /// use ahash::AHasher;
    ///
    /// let mut hasher = AHasher::new_with_keys(123, 456);
    ///
    /// hasher.write_u32(1989);
    /// hasher.write_u8(11);
    /// hasher.write_u8(9);
    /// hasher.write(b"Huh?");
    ///
    /// println!("Hash is {:x}!", hasher.finish());
    /// ```
    #[inline]
    pub fn new_with_keys(key0: u64, key1: u64) -> Self {
        Self { buffer: [key0, key1], key: [key1, key0]  }
    }

    #[cfg(test)]
    pub(crate) fn test_with_keys(key1: u64, key2: u64) -> AHasher {
        use crate::scramble_keys;
        let (k1, k2) = scramble_keys(key1, key2);
        AHasher { buffer: [k1, k2], key: [k2, k1] }
    }
}

#[inline(never)]
#[no_mangle]
fn hash_test_aes(input: &[u8]) -> u64 {
    let mut a = AHasher::new_with_keys(67, 87);
    a.write(input);
    a.finish()
}

/// Provides methods to hash all of the primitive types.
impl Hasher for AHasher {
    #[inline]
    fn write_u8(&mut self, i: u8) {
        self.write_u128(i as u128);
    }

    #[inline]
    fn write_u16(&mut self, i: u16) {
        self.write_u128(i as u128);
    }

    #[inline]
    fn write_u32(&mut self, i: u32) {
        self.write_u128(i as u128);
    }

    #[inline]
    fn write_u128(&mut self, i: u128) {
        self.buffer = aeshashx2(self.buffer.convert(), i, self.key.convert()).convert();
    }

    #[inline]
    fn write_usize(&mut self, i: usize) {
        self.write_u64(i as u64);
    }

    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.write_u128(i as u128);
    }

    #[inline]
    fn write(&mut self, input: &[u8]) {
        let mut data = input;
        let length = data.len() as u64;
        //This will be scrambled by the first AES round in any branch.
        self.buffer[1] = self.buffer[1].wrapping_add(length);
        //A 'binary search' on sizes reduces the number of comparisons.
        if data.len() <= 8 {
            if data.len() >= 2 {
                if data.len() >= 4 {
                    //len 4-8
                    self.buffer = aeshash(self.buffer.convert(), data.read_u32().0 as u128).convert();
                    self.buffer = aeshash(self.buffer.convert(), data.read_last_u32() as u128).convert();
                } else {
                    //len 2-3
                    self.buffer = aeshash(self.buffer.convert(), data.read_u16().0 as u128).convert();
                    self.buffer = aeshash(self.buffer.convert(), data[data.len() - 1] as u128).convert();
                }
            } else {
                let value;
                if data.len() > 0 {
                    value = data[0]; //len 1
                } else {
                    value = 0;
                }
                self.buffer = aeshash(self.buffer.convert(), value as u128).convert();
            }
            self.buffer = aeshash(self.buffer.convert(), self.key.convert()).convert();
        } else {
            if data.len() > 32 {
                if data.len() > 64 {
                    let (_, tail) = data.split_at(data.len() - 32);
                    let mut par_block: u128 = self.buffer.convert();
                    while data.len() > 32 {
                        let (b1, rest) = data.read_u128();
                        self.buffer = aeshashx2(self.buffer.convert(), b1, self.key.convert()).convert();
                        data = rest;
                        let (b2, rest) = data.read_u128();
                        par_block = aeshashx2(par_block, b2, self.key.convert());
                        data = rest;
                    }
                    let (b1, rest) = tail.read_u128();
                    self.buffer = aeshashx2(self.buffer.convert(), b1, self.key.convert()).convert();
                    let (b2, _) = rest.read_u128();
                    par_block = aeshashx2(par_block, b2, self.key.convert());
                    self.buffer = aeshashx2(self.buffer.convert(), par_block, self.key.convert()).convert();
                } else {
                    //len 33-64
                    let (head, _) = data.split_at(32);
                    let (_, tail) = data.split_at(data.len() - 32);
                    self.buffer = aeshashx2(self.buffer.convert(), head.read_u128().0, self.key.convert()).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), head.read_last_u128(), self.key.convert()).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), tail.read_u128().0, self.key.convert()).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), tail.read_last_u128(), self.key.convert()).convert();
                }
            } else {
                if data.len() > 16 {
                    //len 17-32
                    self.buffer = aeshashx2(self.buffer.convert(), data.read_u128().0, self.key.convert()).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), data.read_last_u128(), self.key.convert()).convert();
                } else {
                    //len 9-16
                    self.buffer = aeshash(self.buffer.convert(), data.read_u64().0 as u128).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), data.read_last_u64() as u128, self.key.convert()).convert();
                }
            }
        }
    }
    #[inline]
    fn finish(&self) -> u64 {
        let result: [u64; 2] = aeshash(self.buffer.convert(), self.key.convert()).convert();
        result[0] //.wrapping_add(result[1])
    }
}

#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes"))]
#[inline(always)]
fn aeshash(value: u128, xor: u128) -> u128 {
    #[cfg(target_arch = "x86")]
    use core::arch::x86::*;
    #[cfg(target_arch = "x86_64")]
    use core::arch::x86_64::*;
    use core::mem::transmute;
    unsafe {
        let value = transmute(value);
        transmute(_mm_aesdec_si128(value, transmute(xor)))
    }
}
#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes"))]
#[inline(always)]
fn aeshashx2(value: u128, k1: u128, k2: u128) -> u128 {
    #[cfg(target_arch = "x86")]
    use core::arch::x86::*;
    #[cfg(target_arch = "x86_64")]
    use core::arch::x86_64::*;
    use core::mem::transmute;
    unsafe {
        let value = transmute(value);
        let value = _mm_aesdec_si128(value, transmute(k1));
        transmute(_mm_aesdec_si128(value, transmute(k2)))
    }
}

#[cfg(test)]
mod tests {
    use crate::aes_hash::*;
    use crate::convert::Convert;
    use std::collections::HashMap;
    use std::hash::BuildHasherDefault;

    #[cfg(feature = "compile-time-rng")]
    #[test]
    fn test_builder() {
        let mut map = HashMap::<u32, u64, BuildHasherDefault<AHasher>>::default();
        map.insert(1, 3);
    }

    #[cfg(feature = "compile-time-rng")]
    #[test]
    fn test_default() {
        let hasher_a = AHasher::default();
        assert_ne!(0, hasher_a.buffer[0]);
        assert_ne!(0, hasher_a.buffer[1]);
        assert_ne!(hasher_a.buffer[0], hasher_a.buffer[1]);
        let hasher_b = AHasher::default();
        assert_eq!(hasher_a.buffer[0], hasher_b.buffer[0]);
        assert_eq!(hasher_a.buffer[1], hasher_b.buffer[1]);
    }

    #[test]
    fn test_hash() {
        let mut result: [u64; 2] = [0x6c62272e07bb0142, 0x62b821756295c58d];
        let value: [u64; 2] = [1 << 32, 0xFEDCBA9876543210];
        result = aeshash(value.convert(), result.convert()).convert();
        result = aeshash(result.convert(), result.convert()).convert();
        let mut result2: [u64; 2] = [0x6c62272e07bb0142, 0x62b821756295c58d];
        let value2: [u64; 2] = [1, 0xFEDCBA9876543210];
        result2 = aeshash(value2.convert(), result2.convert()).convert();
        result2 = aeshash(result2.convert(), result.convert()).convert();
        let result: [u8; 16] = result.convert();
        let result2: [u8; 16] = result2.convert();
        assert_ne!(hex::encode(result), hex::encode(result2));
    }

    #[test]
    fn test_conversion() {
        let input: &[u8] = "dddddddd".as_bytes();
        let bytes: u64 = as_array!(input, 8).convert();
        assert_eq!(bytes, 0x6464646464646464);
    }
}
<commit_msg>Remove some unneeded conversions<commit_after>use crate::convert::*;
use core::hash::{Hasher};

/// A `Hasher` for hashing an arbitrary stream of bytes.
///
/// Instances of [`AHasher`] represent state that is updated while hashing data.
///
/// Each method updates the internal state based on the new data provided. Once
/// all of the data has been provided, the resulting hash can be obtained by calling
/// `finish()`
///
/// [Clone] is also provided in case you wish to calculate hashes for two different items that
/// start with the same data.
///
#[derive(Debug, Clone)]
pub struct AHasher {
    buffer: [u64; 2],
    key: u128,
}

impl AHasher {
    /// Creates a new hasher keyed to the provided keys.
    /// # Example
    ///
    /// ```
    /// use std::hash::Hasher;
    /// use ahash::AHasher;
    ///
    /// let mut hasher = AHasher::new_with_keys(123, 456);
    ///
    /// hasher.write_u32(1989);
    /// hasher.write_u8(11);
    /// hasher.write_u8(9);
    /// hasher.write(b"Huh?");
    ///
    /// println!("Hash is {:x}!", hasher.finish());
    /// ```
    #[inline]
    pub fn new_with_keys(key0: u64, key1: u64) -> Self {
        Self { buffer: [key0, key1], key: [key1, key0].convert()  }
    }

    #[cfg(test)]
    pub(crate) fn test_with_keys(key1: u64, key2: u64) -> AHasher {
        use crate::scramble_keys;
        let (k1, k2) = scramble_keys(key1, key2);
        AHasher { buffer: [k1, k2], key: [k2, k1].convert() }
    }
}

#[inline(never)]
#[no_mangle]
fn hash_test_aes(input: &[u8]) -> u64 {
    let mut a = AHasher::new_with_keys(67, 87);
    a.write(input);
    a.finish()
}

/// Provides methods to hash all of the primitive types.
impl Hasher for AHasher {
    #[inline]
    fn write_u8(&mut self, i: u8) {
        self.write_u128(i as u128);
    }

    #[inline]
    fn write_u16(&mut self, i: u16) {
        self.write_u128(i as u128);
    }

    #[inline]
    fn write_u32(&mut self, i: u32) {
        self.write_u128(i as u128);
    }

    #[inline]
    fn write_u128(&mut self, i: u128) {
        self.buffer = aeshashx2(self.buffer.convert(), i, self.key).convert();
    }

    #[inline]
    fn write_usize(&mut self, i: usize) {
        self.write_u64(i as u64);
    }

    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.write_u128(i as u128);
    }

    #[inline]
    fn write(&mut self, input: &[u8]) {
        let mut data = input;
        let length = data.len() as u64;
        //This will be scrambled by the first AES round in any branch.
        self.buffer[1] = self.buffer[1].wrapping_add(length);
        //A 'binary search' on sizes reduces the number of comparisons.
        if data.len() <= 8 {
            if data.len() >= 2 {
                if data.len() >= 4 {
                    //len 4-8
                    self.buffer = aeshash(self.buffer.convert(), data.read_u32().0 as u128).convert();
                    self.buffer = aeshash(self.buffer.convert(), data.read_last_u32() as u128).convert();
                } else {
                    //len 2-3
                    self.buffer = aeshash(self.buffer.convert(), data.read_u16().0 as u128).convert();
                    self.buffer = aeshash(self.buffer.convert(), data[data.len() - 1] as u128).convert();
                }
            } else {
                let value;
                if data.len() > 0 {
                    value = data[0]; //len 1
                } else {
                    value = 0;
                }
                self.buffer = aeshash(self.buffer.convert(), value as u128).convert();
            }
            self.buffer = aeshash(self.buffer.convert(), self.key).convert();
        } else {
            if data.len() > 32 {
                if data.len() > 64 {
                    let (_, tail) = data.split_at(data.len() - 32);
                    let mut par_block: u128 = self.buffer.convert();
                    while data.len() > 32 {
                        let (b1, rest) = data.read_u128();
                        self.buffer = aeshashx2(self.buffer.convert(), b1, self.key).convert();
                        data = rest;
                        let (b2, rest) = data.read_u128();
                        par_block = aeshashx2(par_block, b2, self.key);
                        data = rest;
                    }
                    let (b1, rest) = tail.read_u128();
                    self.buffer = aeshashx2(self.buffer.convert(), b1, self.key).convert();
                    let (b2, _) = rest.read_u128();
                    par_block = aeshashx2(par_block, b2, self.key);
                    self.buffer = aeshashx2(self.buffer.convert(), par_block, self.key).convert();
                } else {
                    //len 33-64
                    let (head, _) = data.split_at(32);
                    let (_, tail) = data.split_at(data.len() - 32);
                    self.buffer = aeshashx2(self.buffer.convert(), head.read_u128().0, self.key).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), head.read_last_u128(), self.key).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), tail.read_u128().0, self.key).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), tail.read_last_u128(), self.key).convert();
                }
            } else {
                if data.len() > 16 {
                    //len 17-32
                    self.buffer = aeshashx2(self.buffer.convert(), data.read_u128().0, self.key).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), data.read_last_u128(), self.key).convert();
                } else {
                    //len 9-16
                    self.buffer = aeshash(self.buffer.convert(), data.read_u64().0 as u128).convert();
                    self.buffer = aeshashx2(self.buffer.convert(), data.read_last_u64() as u128, self.key).convert();
                }
            }
        }
    }
    #[inline]
    fn finish(&self) -> u64 {
        let result: [u64; 2] = aeshash(self.buffer.convert(), self.key).convert();
        result[0] //.wrapping_add(result[1])
    }
}

#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes"))]
#[inline(always)]
fn aeshash(value: u128, xor: u128) -> u128 {
    #[cfg(target_arch = "x86")]
    use core::arch::x86::*;
    #[cfg(target_arch = "x86_64")]
    use core::arch::x86_64::*;
    use core::mem::transmute;
    unsafe {
        let value = transmute(value);
        transmute(_mm_aesdec_si128(value, transmute(xor)))
    }
}
#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes"))]
#[inline(always)]
fn aeshashx2(value: u128, k1: u128, k2: u128) -> u128 {
    #[cfg(target_arch = "x86")]
    use core::arch::x86::*;
    #[cfg(target_arch = "x86_64")]
    use core::arch::x86_64::*;
    use core::mem::transmute;
    unsafe {
        let value = transmute(value);
        let value = _mm_aesdec_si128(value, transmute(k1));
        transmute(_mm_aesdec_si128(value, transmute(k2)))
    }
}

#[cfg(test)]
mod tests {
    use crate::aes_hash::*;
    use crate::convert::Convert;
    use std::collections::HashMap;
    use std::hash::BuildHasherDefault;

    #[cfg(feature = "compile-time-rng")]
    #[test]
    fn test_builder() {
        let mut map = HashMap::<u32, u64, BuildHasherDefault<AHasher>>::default();
        map.insert(1, 3);
    }

    #[cfg(feature = "compile-time-rng")]
    #[test]
    fn test_default() {
        let hasher_a = AHasher::default();
        assert_ne!(0, hasher_a.buffer[0]);
        assert_ne!(0, hasher_a.buffer[1]);
        assert_ne!(hasher_a.buffer[0], hasher_a.buffer[1]);
        let hasher_b = AHasher::default();
        assert_eq!(hasher_a.buffer[0], hasher_b.buffer[0]);
        assert_eq!(hasher_a.buffer[1], hasher_b.buffer[1]);
    }

    #[test]
    fn test_hash() {
        let mut result: [u64; 2] = [0x6c62272e07bb0142, 0x62b821756295c58d];
        let value: [u64; 2] = [1 << 32, 0xFEDCBA9876543210];
        result = aeshash(value.convert(), result.convert()).convert();
        result = aeshash(result.convert(), result.convert()).convert();
        let mut result2: [u64; 2] = [0x6c62272e07bb0142, 0x62b821756295c58d];
        let value2: [u64; 2] = [1, 0xFEDCBA9876543210];
        result2 = aeshash(value2.convert(), result2.convert()).convert();
        result2 = aeshash(result2.convert(), result.convert()).convert();
        let result: [u8; 16] = result.convert();
        let result2: [u8; 16] = result2.convert();
        assert_ne!(hex::encode(result), hex::encode(result2));
    }

    #[test]
    fn test_conversion() {
        let input: &[u8] = "dddddddd".as_bytes();
        let bytes: u64 = as_array!(input, 8).convert();
        assert_eq!(bytes, 0x6464646464646464);
    }
}
<|endoftext|>


<commit_before>use euclid::{rect, TypedPoint2D, TypedRect};
use num::{Float, One, Zero};
use rand::distributions::{Distribution, Standard, Uniform};
use rand::Rng;
use seeded_rng;
use std::error::Error;
use std::fmt;
use std::hash::Hash;
use std::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign};

/// Clamp a value to range.
pub fn clamp<C: PartialOrd + Copy>(mn: C, mx: C, x: C) -> C {
    if x < mn {
        mn
    } else if x > mx {
        mx
    } else {
        x
    }
}

/// Deterministic noise.
///
/// Turns an input value into a noise value.
///
/// # Examples
///
/// ```
/// # extern crate rand;
/// # extern crate calx;
/// # fn main() {
/// use rand::distributions::Uniform;
/// use calx::Noise;
///
/// let depth = Uniform::new_inclusive(-1.0, 1.0);
/// let z: f32 = depth.noise(&(12, 34));
/// assert_eq!(z, -0.6524992);
/// let z: f32 = depth.noise(&(34, 12));
/// assert_eq!(z, -0.56852627);
/// # }
/// ```
pub trait Noise<T> {
    fn noise(&self, seed: &impl Hash) -> T;
}

impl<T: Distribution<U>, U> Noise<U> for T {
    fn noise(&self, seed: &impl Hash) -> U { self.sample(&mut seeded_rng(&seed)) }
}

/// A deciban unit log odds value.
///
/// Log odds correspond to the Bayesian probability for a hypothesis that
/// has decibans * 1/10 log_2(10) bits of evidence in favor of it. They're
/// a bit like rolling a d20 but better.
///
/// # Examples
///
/// ```
/// use calx::Deciban;
/// assert_eq!(0.0, Deciban::new(0.5).0);
/// assert_eq!(10, Deciban::new(0.909091).0 as i32);
///
/// assert_eq!(0.5, Deciban(0.0).to_p());
/// assert_eq!(24, (Deciban(-5.0).to_p() * 100.0) as i32);
/// ```
#[derive(Copy, Clone, PartialEq, PartialOrd, Default, Debug)]
pub struct Deciban(pub f32);

impl Deciban {
    /// Build a deciban value from a probability in [0, 1).
    pub fn new(p: f32) -> Deciban {
        debug_assert!(p >= 0.0 && p < 1.0);
        Deciban(10.0 * (p / (1.0 - p)).log(10.0))
    }

    /// Convert a deciban value to the corresponding probability in [0, 1).
    pub fn to_p(self) -> f32 { 1.0 - 1.0 / (1.0 + 10.0.powf(self.0 / 10.0)) }
}

impl Distribution<Deciban> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ::Deciban {
        Deciban::new(rng.gen_range(0.0, 1.0))
    }
}

impl Add for Deciban {
    type Output = Deciban;
    fn add(self, rhs: Deciban) -> Deciban { Deciban(self.0 + rhs.0) }
}

impl AddAssign for Deciban {
    fn add_assign(&mut self, rhs: Deciban) { self.0 += rhs.0; }
}

impl Sub for Deciban {
    type Output = Deciban;
    fn sub(self, rhs: Deciban) -> Deciban { Deciban(self.0 - rhs.0) }
}

impl SubAssign for Deciban {
    fn sub_assign(&mut self, rhs: Deciban) { self.0 -= rhs.0; }
}

/// Interpolate linearly between two values.
pub fn lerp<T, U, V, W>(a: U, b: U, t: T) -> W
where
    U: Add<V, Output = W> + Sub<U, Output = V> + Copy,
    V: Mul<T, Output = V>,
{
    a + (b - a) * t
}

/// Sequence of points for linearly interpolating between them.
pub struct LerpPath<T, U> {
    points: Vec<(T, U)>,
}

impl<T, U, V, W> LerpPath<T, U>
where
    U: Add<V, Output = W> + Sub<U, Output = V> + Copy,
    V: Mul<T, Output = V>,
    T: PartialOrd + Sub<T, Output = T> + Div<T, Output = T> + Copy + Zero,
{
    pub fn new(begin: (T, U), end: (T, U)) -> LerpPath<T, U> {
        let mut result = LerpPath {
            points: vec![begin],
        };
        result.add(end);
        result
    }

    pub fn add(&mut self, point: (T, U)) {
        for i in 0..self.points.len() {
            if point.0 == self.points[i].0 {
                // Avoid zero width intervals or we'll get division by zero down the road, just
                // replace the point if the position is exactly the same.
                self.points[i] = point;
                return;
            }
            if point.0 < self.points[i].0 {
                self.points.insert(i, point);
                return;
            }
        }

        self.points.push(point);
    }

    pub fn sample(&self, t: T) -> W {
        if t < self.points[0].0 {
            return lerp(self.points[0].1, self.points[0].1, T::zero());
        }

        for i in 1..self.points.len() {
            if t < self.points[i].0 {
                let scaled = (t - self.points[i - 1].0) / (self.points[i].0 - self.points[i - 1].0);
                return lerp(self.points[i - 1].1, self.points[i].1, scaled);
            }
        }

        lerp(
            self.points[self.points.len() - 1].1,
            self.points[self.points.len() - 1].1,
            T::zero(),
        )
    }
}

/// Single-pass weighted sample for iterations.
pub trait WeightedChoice {
    type Item;

    /// Choose an item from the iteration with probability weighted by item weight.
    fn weighted_choice<R: Rng, F>(self, rng: &mut R, weight_fn: F) -> Option<Self::Item>
    where
        F: Fn(&Self::Item) -> f32;
}

impl<T, I: IntoIterator<Item = T> + Sized> WeightedChoice for I {
    type Item = T;

    fn weighted_choice<R: Rng, F>(self, rng: &mut R, weight_fn: F) -> Option<Self::Item>
    where
        F: Fn(&Self::Item) -> f32,
    {
        let dist = Uniform::new(0.0, 1.0);
        let (_, ret) = self
            .into_iter()
            .fold((0.0, None), |(weight_sum, prev_item), item| {
                let item_weight = weight_fn(&item);
                debug_assert!(item_weight >= 0.0);
                let p = item_weight / (weight_sum + item_weight);
                let next_item = if dist.sample(rng) < p {
                    Some(item)
                } else {
                    prev_item
                };
                (weight_sum + item_weight, next_item)
            });
        ret
    }
}

/// Insert a 0 bit between the low 16 bits of a number.
///
/// Useful for <https://en.wikipedia.org/wiki/Z-order_curve>
#[inline(always)]
pub fn spread_bits_by_2(mut bits: u32) -> u32 {
    // from https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
    bits &= /* --------------- */ 0b0000_0000_0000_0000_1111_1111_1111_1111;
    bits = (bits ^ (bits << 8)) & 0b0000_0000_1111_1111_0000_0000_1111_1111;
    bits = (bits ^ (bits << 4)) & 0b0000_1111_0000_1111_0000_1111_0000_1111;
    bits = (bits ^ (bits << 2)) & 0b0011_0011_0011_0011_0011_0011_0011_0011;
    bits = (bits ^ (bits << 1)) & 0b0101_0101_0101_0101_0101_0101_0101_0101;
    bits
}

/// Remove every odd bit and compact the even bits into the lower half of the number.
///
/// Useful for <https://en.wikipedia.org/wiki/Z-order_curve>
#[inline(always)]
pub fn compact_bits_by_2(mut bits: u32) -> u32 {
    // from https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
    bits &= /* --------------- */ 0b0101_0101_0101_0101_0101_0101_0101_0101;
    bits = (bits ^ (bits >> 1)) & 0b0011_0011_0011_0011_0011_0011_0011_0011;
    bits = (bits ^ (bits >> 2)) & 0b0000_1111_0000_1111_0000_1111_0000_1111;
    bits = (bits ^ (bits >> 4)) & 0b0000_0000_1111_1111_0000_0000_1111_1111;
    bits = (bits ^ (bits >> 8)) & 0b0000_0000_0000_0000_1111_1111_1111_1111;
    bits
}

/// Repeatedly run a random generator that may fail until it succeeds.
pub fn retry_gen<R: Rng, T, E>(
    n_tries: usize,
    rng: &mut R,
    gen: impl Fn(&mut R) -> Result<T, E>,
) -> Result<T, E> {
    let mut ret = gen(rng);
    for _ in 0..(n_tries - 1) {
        if ret.is_ok() {
            return ret;
        }
        ret = gen(rng);
    }

    ret
}

/// Build an axis-aligned rectangle that contains the given points.
///
/// It will add unit distance to the right and bottom edges to make sure the resulting `TypedRect`
/// will contain all the points. It would beneath
///
/// # Examples
///
/// ```
/// # extern crate euclid;
/// # extern crate calx;
/// # fn main() {
/// use euclid::point2;
///
/// let points: Vec<euclid::Point2D<i32>> = vec![point2(2, 3), point2(4, 5), point2(6, 7)];
/// let rect = calx::bounding_rect(&points);
/// assert!(rect.contains(&point2(2, 3)));
/// assert!(rect.contains(&point2(6, 7)));
/// assert!(!rect.contains(&point2(7, 7)));
/// assert!(!rect.contains(&point2(2, 2)));
/// # }
/// ```
pub fn bounding_rect<'a, I, T, U>(points: I) -> TypedRect<T, U>
where
    I: IntoIterator<Item = &'a TypedPoint2D<T, U>>,
    T: Zero + One + Add + Sub<Output = T> + Ord + Copy + 'a,
    U: 'a,
{
    let mut iter = points.into_iter();
    if let Some(first) = iter.next() {
        let (mut min_x, mut min_y) = (first.x, first.y);
        let (mut max_x, mut max_y) = (first.x, first.y);

        for p in iter {
            min_x = min_x.min(p.x);
            min_y = min_y.min(p.y);
            max_x = max_x.max(p.x);
            max_y = max_y.max(p.y);
        }

        // Make the rect contain the edge points.
        max_x = max_x + T::one();
        max_y = max_y + T::one();

        rect(min_x, min_y, max_x - min_x, max_y - min_y)
    } else {
        TypedRect::zero()
    }
}

/// Error type for when you don't care about the type and just want to use a string message.
#[derive(Debug)]
pub struct GenericError(pub String);

impl Error for GenericError {}

impl fmt::Display for GenericError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) }
}

/// Construct a `GenericError`.
#[macro_export]
macro_rules! err {
    ($($arg:tt)*) => ($crate::GenericError(format!($($arg)*)));
}

/// Return a `Result<_, Box<Error>>` error with `GenericError` message.
#[macro_export]
macro_rules! die {
    ($($arg:tt)*) => (return Err(Box::new(err!($($arg)*))););
}
<commit_msg>Add sized constraint<commit_after>use euclid::{rect, TypedPoint2D, TypedRect};
use num::{Float, One, Zero};
use rand::distributions::{Distribution, Standard, Uniform};
use rand::Rng;
use seeded_rng;
use std::error::Error;
use std::fmt;
use std::hash::Hash;
use std::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign};

/// Clamp a value to range.
pub fn clamp<C: PartialOrd + Copy>(mn: C, mx: C, x: C) -> C {
    if x < mn {
        mn
    } else if x > mx {
        mx
    } else {
        x
    }
}

/// Deterministic noise.
///
/// Turns an input value into a noise value.
///
/// # Examples
///
/// ```
/// # extern crate rand;
/// # extern crate calx;
/// # fn main() {
/// use rand::distributions::Uniform;
/// use calx::Noise;
///
/// let depth = Uniform::new_inclusive(-1.0, 1.0);
/// let z: f32 = depth.noise(&(12, 34));
/// assert_eq!(z, -0.6524992);
/// let z: f32 = depth.noise(&(34, 12));
/// assert_eq!(z, -0.56852627);
/// # }
/// ```
pub trait Noise<T> {
    fn noise(&self, seed: &impl Hash) -> T;
}

impl<T: Distribution<U>, U> Noise<U> for T {
    fn noise(&self, seed: &impl Hash) -> U { self.sample(&mut seeded_rng(&seed)) }
}

/// A deciban unit log odds value.
///
/// Log odds correspond to the Bayesian probability for a hypothesis that
/// has decibans * 1/10 log_2(10) bits of evidence in favor of it. They're
/// a bit like rolling a d20 but better.
///
/// # Examples
///
/// ```
/// use calx::Deciban;
/// assert_eq!(0.0, Deciban::new(0.5).0);
/// assert_eq!(10, Deciban::new(0.909091).0 as i32);
///
/// assert_eq!(0.5, Deciban(0.0).to_p());
/// assert_eq!(24, (Deciban(-5.0).to_p() * 100.0) as i32);
/// ```
#[derive(Copy, Clone, PartialEq, PartialOrd, Default, Debug)]
pub struct Deciban(pub f32);

impl Deciban {
    /// Build a deciban value from a probability in [0, 1).
    pub fn new(p: f32) -> Deciban {
        debug_assert!(p >= 0.0 && p < 1.0);
        Deciban(10.0 * (p / (1.0 - p)).log(10.0))
    }

    /// Convert a deciban value to the corresponding probability in [0, 1).
    pub fn to_p(self) -> f32 { 1.0 - 1.0 / (1.0 + 10.0.powf(self.0 / 10.0)) }
}

impl Distribution<Deciban> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ::Deciban {
        Deciban::new(rng.gen_range(0.0, 1.0))
    }
}

impl Add for Deciban {
    type Output = Deciban;
    fn add(self, rhs: Deciban) -> Deciban { Deciban(self.0 + rhs.0) }
}

impl AddAssign for Deciban {
    fn add_assign(&mut self, rhs: Deciban) { self.0 += rhs.0; }
}

impl Sub for Deciban {
    type Output = Deciban;
    fn sub(self, rhs: Deciban) -> Deciban { Deciban(self.0 - rhs.0) }
}

impl SubAssign for Deciban {
    fn sub_assign(&mut self, rhs: Deciban) { self.0 -= rhs.0; }
}

/// Interpolate linearly between two values.
pub fn lerp<T, U, V, W>(a: U, b: U, t: T) -> W
where
    U: Add<V, Output = W> + Sub<U, Output = V> + Copy,
    V: Mul<T, Output = V>,
{
    a + (b - a) * t
}

/// Sequence of points for linearly interpolating between them.
pub struct LerpPath<T, U> {
    points: Vec<(T, U)>,
}

impl<T, U, V, W> LerpPath<T, U>
where
    U: Add<V, Output = W> + Sub<U, Output = V> + Copy,
    V: Mul<T, Output = V>,
    T: PartialOrd + Sub<T, Output = T> + Div<T, Output = T> + Copy + Zero,
{
    pub fn new(begin: (T, U), end: (T, U)) -> LerpPath<T, U> {
        let mut result = LerpPath {
            points: vec![begin],
        };
        result.add(end);
        result
    }

    pub fn add(&mut self, point: (T, U)) {
        for i in 0..self.points.len() {
            if point.0 == self.points[i].0 {
                // Avoid zero width intervals or we'll get division by zero down the road, just
                // replace the point if the position is exactly the same.
                self.points[i] = point;
                return;
            }
            if point.0 < self.points[i].0 {
                self.points.insert(i, point);
                return;
            }
        }

        self.points.push(point);
    }

    pub fn sample(&self, t: T) -> W {
        if t < self.points[0].0 {
            return lerp(self.points[0].1, self.points[0].1, T::zero());
        }

        for i in 1..self.points.len() {
            if t < self.points[i].0 {
                let scaled = (t - self.points[i - 1].0) / (self.points[i].0 - self.points[i - 1].0);
                return lerp(self.points[i - 1].1, self.points[i].1, scaled);
            }
        }

        lerp(
            self.points[self.points.len() - 1].1,
            self.points[self.points.len() - 1].1,
            T::zero(),
        )
    }
}

/// Single-pass weighted sample for iterations.
pub trait WeightedChoice {
    type Item;

    /// Choose an item from the iteration with probability weighted by item weight.
    fn weighted_choice<R: Rng, F>(self, rng: &mut R, weight_fn: F) -> Option<Self::Item>
    where
        F: Fn(&Self::Item) -> f32;
}

impl<T, I: IntoIterator<Item = T> + Sized> WeightedChoice for I {
    type Item = T;

    fn weighted_choice<R: Rng, F>(self, rng: &mut R, weight_fn: F) -> Option<Self::Item>
    where
        F: Fn(&Self::Item) -> f32,
    {
        let dist = Uniform::new(0.0, 1.0);
        let (_, ret) = self
            .into_iter()
            .fold((0.0, None), |(weight_sum, prev_item), item| {
                let item_weight = weight_fn(&item);
                debug_assert!(item_weight >= 0.0);
                let p = item_weight / (weight_sum + item_weight);
                let next_item = if dist.sample(rng) < p {
                    Some(item)
                } else {
                    prev_item
                };
                (weight_sum + item_weight, next_item)
            });
        ret
    }
}

/// Insert a 0 bit between the low 16 bits of a number.
///
/// Useful for <https://en.wikipedia.org/wiki/Z-order_curve>
#[inline(always)]
pub fn spread_bits_by_2(mut bits: u32) -> u32 {
    // from https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
    bits &= /* --------------- */ 0b0000_0000_0000_0000_1111_1111_1111_1111;
    bits = (bits ^ (bits << 8)) & 0b0000_0000_1111_1111_0000_0000_1111_1111;
    bits = (bits ^ (bits << 4)) & 0b0000_1111_0000_1111_0000_1111_0000_1111;
    bits = (bits ^ (bits << 2)) & 0b0011_0011_0011_0011_0011_0011_0011_0011;
    bits = (bits ^ (bits << 1)) & 0b0101_0101_0101_0101_0101_0101_0101_0101;
    bits
}

/// Remove every odd bit and compact the even bits into the lower half of the number.
///
/// Useful for <https://en.wikipedia.org/wiki/Z-order_curve>
#[inline(always)]
pub fn compact_bits_by_2(mut bits: u32) -> u32 {
    // from https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
    bits &= /* --------------- */ 0b0101_0101_0101_0101_0101_0101_0101_0101;
    bits = (bits ^ (bits >> 1)) & 0b0011_0011_0011_0011_0011_0011_0011_0011;
    bits = (bits ^ (bits >> 2)) & 0b0000_1111_0000_1111_0000_1111_0000_1111;
    bits = (bits ^ (bits >> 4)) & 0b0000_0000_1111_1111_0000_0000_1111_1111;
    bits = (bits ^ (bits >> 8)) & 0b0000_0000_0000_0000_1111_1111_1111_1111;
    bits
}

/// Repeatedly run a random generator that may fail until it succeeds.
pub fn retry_gen<R: Rng + ?Sized, T, E>(
    n_tries: usize,
    rng: &mut R,
    gen: impl Fn(&mut R) -> Result<T, E>,
) -> Result<T, E> {
    let mut ret = gen(rng);
    for _ in 0..(n_tries - 1) {
        if ret.is_ok() {
            return ret;
        }
        ret = gen(rng);
    }

    ret
}

/// Build an axis-aligned rectangle that contains the given points.
///
/// It will add unit distance to the right and bottom edges to make sure the resulting `TypedRect`
/// will contain all the points. It would beneath
///
/// # Examples
///
/// ```
/// # extern crate euclid;
/// # extern crate calx;
/// # fn main() {
/// use euclid::point2;
///
/// let points: Vec<euclid::Point2D<i32>> = vec![point2(2, 3), point2(4, 5), point2(6, 7)];
/// let rect = calx::bounding_rect(&points);
/// assert!(rect.contains(&point2(2, 3)));
/// assert!(rect.contains(&point2(6, 7)));
/// assert!(!rect.contains(&point2(7, 7)));
/// assert!(!rect.contains(&point2(2, 2)));
/// # }
/// ```
pub fn bounding_rect<'a, I, T, U>(points: I) -> TypedRect<T, U>
where
    I: IntoIterator<Item = &'a TypedPoint2D<T, U>>,
    T: Zero + One + Add + Sub<Output = T> + Ord + Copy + 'a,
    U: 'a,
{
    let mut iter = points.into_iter();
    if let Some(first) = iter.next() {
        let (mut min_x, mut min_y) = (first.x, first.y);
        let (mut max_x, mut max_y) = (first.x, first.y);

        for p in iter {
            min_x = min_x.min(p.x);
            min_y = min_y.min(p.y);
            max_x = max_x.max(p.x);
            max_y = max_y.max(p.y);
        }

        // Make the rect contain the edge points.
        max_x = max_x + T::one();
        max_y = max_y + T::one();

        rect(min_x, min_y, max_x - min_x, max_y - min_y)
    } else {
        TypedRect::zero()
    }
}

/// Error type for when you don't care about the type and just want to use a string message.
#[derive(Debug)]
pub struct GenericError(pub String);

impl Error for GenericError {}

impl fmt::Display for GenericError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) }
}

/// Construct a `GenericError`.
#[macro_export]
macro_rules! err {
    ($($arg:tt)*) => ($crate::GenericError(format!($($arg)*)));
}

/// Return a `Result<_, Box<Error>>` error with `GenericError` message.
#[macro_export]
macro_rules! die {
    ($($arg:tt)*) => (return Err(Box::new(err!($($arg)*))););
}
<|endoftext|>


<commit_before>//! Randomization of big integers

use rand::distributions::uniform::{SampleUniform, UniformSampler};
use rand::prelude::*;
use rand::AsByteSliceMut;

use BigInt;
use BigUint;
use Sign::*;

use big_digit::BigDigit;
use bigint::{into_magnitude, magnitude};

use integer::Integer;
use traits::Zero;

pub trait RandBigInt {
    /// Generate a random `BigUint` of the given bit size.
    fn gen_biguint(&mut self, bit_size: usize) -> BigUint;

    /// Generate a random BigInt of the given bit size.
    fn gen_bigint(&mut self, bit_size: usize) -> BigInt;

    /// Generate a random `BigUint` less than the given bound. Fails
    /// when the bound is zero.
    fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;

    /// Generate a random `BigUint` within the given range. The lower
    /// bound is inclusive; the upper bound is exclusive. Fails when
    /// the upper bound is not greater than the lower bound.
    fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;

    /// Generate a random `BigInt` within the given range. The lower
    /// bound is inclusive; the upper bound is exclusive. Fails when
    /// the upper bound is not greater than the lower bound.
    fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
}

impl<R: Rng + ?Sized> RandBigInt for R {
    fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
        use super::big_digit::BITS;
        let (digits, rem) = bit_size.div_rem(&BITS);
        let mut data = vec![BigDigit::default(); digits + (rem > 0) as usize];
        // `fill_bytes` is faster than many `gen::<u32>` calls
        self.fill_bytes(data[..].as_byte_slice_mut());
        // Swap bytes per the `Rng::fill` source. This might be
        // unnecessary if reproducibility across architectures is not
        // desired.
        data.to_le();
        if rem > 0 {
            data[digits] >>= BITS - rem;
        }
        BigUint::new_native(data)
    }

    fn gen_bigint(&mut self, bit_size: usize) -> BigInt {
        loop {
            // Generate a random BigUint...
            let biguint = self.gen_biguint(bit_size);
            // ...and then randomly assign it a Sign...
            let sign = if biguint.is_zero() {
                // ...except that if the BigUint is zero, we need to try
                // again with probability 0.5. This is because otherwise,
                // the probability of generating a zero BigInt would be
                // double that of any other number.
                if self.gen() {
                    continue;
                } else {
                    NoSign
                }
            } else if self.gen() {
                Plus
            } else {
                Minus
            };
            return BigInt::from_biguint(sign, biguint);
        }
    }

    fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
        assert!(!bound.is_zero());
        let bits = bound.bits();
        loop {
            let n = self.gen_biguint(bits);
            if n < *bound {
                return n;
            }
        }
    }

    fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint {
        assert!(*lbound < *ubound);
        if lbound.is_zero() {
            self.gen_biguint_below(ubound)
        } else {
            lbound + self.gen_biguint_below(&(ubound - lbound))
        }
    }

    fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt {
        assert!(*lbound < *ubound);
        if lbound.is_zero() {
            BigInt::from(self.gen_biguint_below(magnitude(&ubound)))
        } else if ubound.is_zero() {
            lbound + BigInt::from(self.gen_biguint_below(magnitude(&lbound)))
        } else {
            let delta = ubound - lbound;
            lbound + BigInt::from(self.gen_biguint_below(magnitude(&delta)))
        }
    }
}

/// The back-end implementing rand's `UniformSampler` for `BigUint`.
#[derive(Clone, Debug)]
pub struct UniformBigUint {
    base: BigUint,
    len: BigUint,
}

impl UniformSampler for UniformBigUint {
    type X = BigUint;

    #[inline]
    fn new(low: Self::X, high: Self::X) -> Self {
        assert!(low < high);
        UniformBigUint {
            len: high - &low,
            base: low,
        }
    }

    #[inline]
    fn new_inclusive(low: Self::X, high: Self::X) -> Self {
        assert!(low <= high);
        Self::new(low, high + 1u32)
    }

    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
        &self.base + rng.gen_biguint_below(&self.len)
    }

    #[inline]
    fn sample_single<R: Rng + ?Sized>(low: Self::X, high: Self::X, rng: &mut R) -> Self::X {
        rng.gen_biguint_range(&low, &high)
    }
}

impl SampleUniform for BigUint {
    type Sampler = UniformBigUint;
}

/// The back-end implementing rand's `UniformSampler` for `BigInt`.
#[derive(Clone, Debug)]
pub struct UniformBigInt {
    base: BigInt,
    len: BigUint,
}

impl UniformSampler for UniformBigInt {
    type X = BigInt;

    #[inline]
    fn new(low: Self::X, high: Self::X) -> Self {
        assert!(low < high);
        UniformBigInt {
            len: into_magnitude(high - &low),
            base: low,
        }
    }

    #[inline]
    fn new_inclusive(low: Self::X, high: Self::X) -> Self {
        assert!(low <= high);
        Self::new(low, high + 1u32)
    }

    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
        &self.base + BigInt::from(rng.gen_biguint_below(&self.len))
    }

    #[inline]
    fn sample_single<R: Rng + ?Sized>(low: Self::X, high: Self::X, rng: &mut R) -> Self::X {
        rng.gen_bigint_range(&low, &high)
    }
}

impl SampleUniform for BigInt {
    type Sampler = UniformBigInt;
}

/// A random distribution for `BigUint` and `BigInt` values of a particular bit size.
#[derive(Clone, Copy, Debug)]
pub struct RandomBits {
    bits: usize,
}

impl RandomBits {
    #[inline]
    pub fn new(bits: usize) -> RandomBits {
        RandomBits { bits }
    }
}

impl Distribution<BigUint> for RandomBits {
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigUint {
        rng.gen_biguint(self.bits)
    }
}

impl Distribution<BigInt> for RandomBits {
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigInt {
        rng.gen_bigint(self.bits)
    }
}
<commit_msg>Fix rand value stability for u64_digit<commit_after>//! Randomization of big integers

use rand::distributions::uniform::{SampleUniform, UniformSampler};
use rand::prelude::*;

use BigInt;
use BigUint;
use Sign::*;

use bigint::{into_magnitude, magnitude};

use integer::Integer;
use traits::Zero;

pub trait RandBigInt {
    /// Generate a random `BigUint` of the given bit size.
    fn gen_biguint(&mut self, bit_size: usize) -> BigUint;

    /// Generate a random BigInt of the given bit size.
    fn gen_bigint(&mut self, bit_size: usize) -> BigInt;

    /// Generate a random `BigUint` less than the given bound. Fails
    /// when the bound is zero.
    fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;

    /// Generate a random `BigUint` within the given range. The lower
    /// bound is inclusive; the upper bound is exclusive. Fails when
    /// the upper bound is not greater than the lower bound.
    fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;

    /// Generate a random `BigInt` within the given range. The lower
    /// bound is inclusive; the upper bound is exclusive. Fails when
    /// the upper bound is not greater than the lower bound.
    fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
}

fn gen_bits<R: Rng + ?Sized>(rng: &mut R, data: &mut [u32], rem: usize) {
    // `fill` is faster than many `gen::<u32>` calls
    rng.fill(data);
    if rem > 0 {
        let last = data.len() - 1;
        data[last] >>= 32 - rem;
    }
}

impl<R: Rng + ?Sized> RandBigInt for R {
    #[cfg(not(feature = "u64_digit"))]
    fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
        let (digits, rem) = bit_size.div_rem(&32);
        let mut data = vec![0u32; digits + (rem > 0) as usize];
        gen_bits(self, &mut data, rem);
        BigUint::new_native(data)
    }

    #[cfg(feature = "u64_digit")]
    fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
        let (digits, rem) = bit_size.div_rem(&32);
        let native_digits = bit_size.div_ceil(&64);
        let mut data = vec![0u64; native_digits];
        unsafe {
            // Generate bits in a `&mut [u32]` slice for value stability
            let ptr = data.as_mut_ptr() as *mut u32;
            let len = digits + (rem > 0) as usize;
            debug_assert!(native_digits * 2 >= len);
            let data = std::slice::from_raw_parts_mut(ptr, len);
            gen_bits(self, data, rem);
        }
        #[cfg(target_endian = "big")]
        for digit in &mut data {
            // swap u32 digits into u64 endianness
            *digit = (*digit << 32) | (*digit >> 32);
        }
        BigUint::new_native(data)
    }

    fn gen_bigint(&mut self, bit_size: usize) -> BigInt {
        loop {
            // Generate a random BigUint...
            let biguint = self.gen_biguint(bit_size);
            // ...and then randomly assign it a Sign...
            let sign = if biguint.is_zero() {
                // ...except that if the BigUint is zero, we need to try
                // again with probability 0.5. This is because otherwise,
                // the probability of generating a zero BigInt would be
                // double that of any other number.
                if self.gen() {
                    continue;
                } else {
                    NoSign
                }
            } else if self.gen() {
                Plus
            } else {
                Minus
            };
            return BigInt::from_biguint(sign, biguint);
        }
    }

    fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
        assert!(!bound.is_zero());
        let bits = bound.bits();
        loop {
            let n = self.gen_biguint(bits);
            if n < *bound {
                return n;
            }
        }
    }

    fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint {
        assert!(*lbound < *ubound);
        if lbound.is_zero() {
            self.gen_biguint_below(ubound)
        } else {
            lbound + self.gen_biguint_below(&(ubound - lbound))
        }
    }

    fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt {
        assert!(*lbound < *ubound);
        if lbound.is_zero() {
            BigInt::from(self.gen_biguint_below(magnitude(&ubound)))
        } else if ubound.is_zero() {
            lbound + BigInt::from(self.gen_biguint_below(magnitude(&lbound)))
        } else {
            let delta = ubound - lbound;
            lbound + BigInt::from(self.gen_biguint_below(magnitude(&delta)))
        }
    }
}

/// The back-end implementing rand's `UniformSampler` for `BigUint`.
#[derive(Clone, Debug)]
pub struct UniformBigUint {
    base: BigUint,
    len: BigUint,
}

impl UniformSampler for UniformBigUint {
    type X = BigUint;

    #[inline]
    fn new(low: Self::X, high: Self::X) -> Self {
        assert!(low < high);
        UniformBigUint {
            len: high - &low,
            base: low,
        }
    }

    #[inline]
    fn new_inclusive(low: Self::X, high: Self::X) -> Self {
        assert!(low <= high);
        Self::new(low, high + 1u32)
    }

    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
        &self.base + rng.gen_biguint_below(&self.len)
    }

    #[inline]
    fn sample_single<R: Rng + ?Sized>(low: Self::X, high: Self::X, rng: &mut R) -> Self::X {
        rng.gen_biguint_range(&low, &high)
    }
}

impl SampleUniform for BigUint {
    type Sampler = UniformBigUint;
}

/// The back-end implementing rand's `UniformSampler` for `BigInt`.
#[derive(Clone, Debug)]
pub struct UniformBigInt {
    base: BigInt,
    len: BigUint,
}

impl UniformSampler for UniformBigInt {
    type X = BigInt;

    #[inline]
    fn new(low: Self::X, high: Self::X) -> Self {
        assert!(low < high);
        UniformBigInt {
            len: into_magnitude(high - &low),
            base: low,
        }
    }

    #[inline]
    fn new_inclusive(low: Self::X, high: Self::X) -> Self {
        assert!(low <= high);
        Self::new(low, high + 1u32)
    }

    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
        &self.base + BigInt::from(rng.gen_biguint_below(&self.len))
    }

    #[inline]
    fn sample_single<R: Rng + ?Sized>(low: Self::X, high: Self::X, rng: &mut R) -> Self::X {
        rng.gen_bigint_range(&low, &high)
    }
}

impl SampleUniform for BigInt {
    type Sampler = UniformBigInt;
}

/// A random distribution for `BigUint` and `BigInt` values of a particular bit size.
#[derive(Clone, Copy, Debug)]
pub struct RandomBits {
    bits: usize,
}

impl RandomBits {
    #[inline]
    pub fn new(bits: usize) -> RandomBits {
        RandomBits { bits }
    }
}

impl Distribution<BigUint> for RandomBits {
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigUint {
        rng.gen_biguint(self.bits)
    }
}

impl Distribution<BigInt> for RandomBits {
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigInt {
        rng.gen_bigint(self.bits)
    }
}
<|endoftext|>