<commit_before>extern crate openssl;
extern crate openssl_verify;

use std::io;
use std::fmt;
use std::error;
use self::openssl::ssl::{self, SslContext, SslMethod, SSL_VERIFY_PEER, IntoSsl, SSL_OP_NO_SSLV2,
                         SSL_OP_NO_SSLV3, SSL_OP_NO_COMPRESSION, MidHandshakeSslStream};
use self::openssl::error::ErrorStack;
use self::openssl_verify::verify_callback;

pub struct Error(ssl::Error);

impl error::Error for Error {
    fn description(&self) -> &str {
        error::Error::description(&self.0)
    }

    fn cause(&self) -> Option<&error::Error> {
        error::Error::cause(&self.0)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, fmt)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl From<ssl::Error> for Error {
    fn from(err: ssl::Error) -> Error {
        Error(err)
    }
}

impl From<ErrorStack> for Error {
    fn from(err: ErrorStack) -> Error {
        ssl::Error::Ssl(err).into()
    }
}

pub struct MidHandshakeTlsStream<S>(MidHandshakeSslStream<S>);

impl<S> fmt::Debug for MidHandshakeTlsStream<S>
    where S: fmt::Debug
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl<S> MidHandshakeTlsStream<S> {
    pub fn get_ref(&self) -> &S {
        self.0.get_ref()
    }

    pub fn get_mut(&mut self) -> &mut S {
        self.0.get_mut()
    }
}

impl<S> MidHandshakeTlsStream<S>
    where S: io::Read + io::Write
{
    pub fn handshake(self) -> Result<TlsStream<S>, HandshakeError<S>> {
        match self.0.handshake() {
            Ok(s) => Ok(TlsStream(s)),
            Err(e) => Err(e.into()),
        }
    }
}

pub enum HandshakeError<S> {
    Failure(Error),
    Interrupted(MidHandshakeTlsStream<S>),
}

impl<S> From<ssl::HandshakeError<S>> for HandshakeError<S> {
    fn from(e: ssl::HandshakeError<S>) -> HandshakeError<S> {
        match e {
            ssl::HandshakeError::Failure(e) => HandshakeError::Failure(Error(e)),
            ssl::HandshakeError::Interrupted(s) => {
                HandshakeError::Interrupted(MidHandshakeTlsStream(s))
            }
        }
    }
}

impl<S> From<ErrorStack> for HandshakeError<S> {
    fn from(e: ErrorStack) -> HandshakeError<S> {
        HandshakeError::Failure(e.into())
    }
}

pub struct ClientBuilder(SslContext);

impl ClientBuilder {
    pub fn new() -> Result<ClientBuilder, Error> {
        let mut ctx = try!(SslContext::new(SslMethod::Sslv23));
        ctx.set_options(SSL_OP_NO_SSLV2 | SSL_OP_NO_SSLV3 | SSL_OP_NO_COMPRESSION);
        try!(ctx.set_default_verify_paths());
        try!(ctx.set_cipher_list("ALL!EXPORT!EXPORT40!EXPORT56!aNULL!LOW!RC4@STRENGTH"));
        Ok(ClientBuilder(ctx))
    }

    pub fn handshake<S>(&mut self,
                        domain: &str,
                        stream: S)
                        -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        let mut ssl = try!(self.0.into_ssl());
        try!(ssl.set_hostname(domain));
        let domain = domain.to_owned();
        ssl.set_verify_callback(SSL_VERIFY_PEER, move |p, x| verify_callback(&domain, p, x));

        let s = try!(ssl::SslStream::connect(ssl, stream));
        Ok(TlsStream(s))
    }
}

pub struct TlsStream<S>(ssl::SslStream<S>);

impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl<S: io::Read + io::Write> TlsStream<S> {
    pub fn buffered_read_size(&self) -> Result<usize, Error> {
        Ok(self.0.pending())
    }

    pub fn get_ref(&self) -> &S {
        self.0.get_ref()
    }

    pub fn get_mut(&mut self) -> &mut S {
        self.0.get_mut()
    }
}

impl<S: io::Read + io::Write> io::Read for TlsStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl<S: io::Read + io::Write> io::Write for TlsStream<S> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

/// OpenSSL-specific extensions to `TlsStream`.
pub trait TlsStreamExt<S> {
    /// Returns a shared reference to the OpenSSL `SslStream`.
    fn raw_stream(&self) -> &ssl::SslStream<S>;

    /// Returns a mutable reference to the OpenSSL `SslStream`.
    fn raw_stream_mut(&mut self) -> &mut ssl::SslStream<S>;
}

impl<S> TlsStreamExt<S> for ::TlsStream<S> {
    fn raw_stream(&self) -> &ssl::SslStream<S> {
        &(self.0).0
    }

    fn raw_stream_mut(&mut self) -> &mut ssl::SslStream<S> {
        &mut (self.0).0
    }
}
<commit_msg>Fix openssl<commit_after>extern crate openssl;
extern crate openssl_verify;

use std::io;
use std::fmt;
use std::error;
use self::openssl::ssl::{self, SslContext, SslMethod, SSL_VERIFY_PEER, IntoSsl, SSL_OP_NO_SSLV2,
                         SSL_OP_NO_SSLV3, SSL_OP_NO_COMPRESSION, MidHandshakeSslStream};
use self::openssl::error::ErrorStack;
use self::openssl_verify::verify_callback;

pub struct Error(ssl::Error);

impl error::Error for Error {
    fn description(&self) -> &str {
        error::Error::description(&self.0)
    }

    fn cause(&self) -> Option<&error::Error> {
        error::Error::cause(&self.0)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, fmt)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl From<ssl::Error> for Error {
    fn from(err: ssl::Error) -> Error {
        Error(err)
    }
}

impl From<ErrorStack> for Error {
    fn from(err: ErrorStack) -> Error {
        ssl::Error::Ssl(err).into()
    }
}

pub struct MidHandshakeTlsStream<S>(MidHandshakeSslStream<S>);

impl<S> fmt::Debug for MidHandshakeTlsStream<S>
    where S: fmt::Debug
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl<S> MidHandshakeTlsStream<S> {
    pub fn get_ref(&self) -> &S {
        self.0.get_ref()
    }

    pub fn get_mut(&mut self) -> &mut S {
        self.0.get_mut()
    }
}

impl<S> MidHandshakeTlsStream<S>
    where S: io::Read + io::Write
{
    pub fn handshake(self) -> Result<TlsStream<S>, HandshakeError<S>> {
        match self.0.handshake() {
            Ok(s) => Ok(TlsStream(s)),
            Err(e) => Err(e.into()),
        }
    }
}

pub enum HandshakeError<S> {
    Failure(Error),
    Interrupted(MidHandshakeTlsStream<S>),
}

impl<S> From<ssl::HandshakeError<S>> for HandshakeError<S> {
    fn from(e: ssl::HandshakeError<S>) -> HandshakeError<S> {
        match e {
            ssl::HandshakeError::Failure(e) => HandshakeError::Failure(Error(e)),
            ssl::HandshakeError::Interrupted(s) => {
                HandshakeError::Interrupted(MidHandshakeTlsStream(s))
            }
        }
    }
}

impl<S> From<ErrorStack> for HandshakeError<S> {
    fn from(e: ErrorStack) -> HandshakeError<S> {
        HandshakeError::Failure(e.into())
    }
}

pub struct ClientBuilder(SslContext);

impl ClientBuilder {
    pub fn new() -> Result<ClientBuilder, Error> {
        let mut ctx = try!(SslContext::new(SslMethod::Sslv23));
        ctx.set_options(SSL_OP_NO_SSLV2 | SSL_OP_NO_SSLV3 | SSL_OP_NO_COMPRESSION);
        try!(ctx.set_default_verify_paths());
        try!(ctx.set_cipher_list("ALL!EXPORT!EXPORT40!EXPORT56!aNULL!LOW!RC4@STRENGTH"));
        Ok(ClientBuilder(ctx))
    }

    pub fn handshake<S>(&mut self,
                        domain: &str,
                        stream: S)
                        -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        let mut ssl = try!(self.0.into_ssl());
        try!(ssl.set_hostname(domain));
        let domain = domain.to_owned();
        ssl.set_verify_callback(SSL_VERIFY_PEER, move |p, x| verify_callback(&domain, p, x));

        let s = try!(ssl::SslStream::connect(ssl, stream));
        Ok(TlsStream(s))
    }
}

pub struct TlsStream<S>(ssl::SslStream<S>);

impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl<S: io::Read + io::Write> TlsStream<S> {
    pub fn buffered_read_size(&self) -> Result<usize, Error> {
        Ok(self.0.ssl().pending())
    }

    pub fn get_ref(&self) -> &S {
        self.0.get_ref()
    }

    pub fn get_mut(&mut self) -> &mut S {
        self.0.get_mut()
    }
}

impl<S: io::Read + io::Write> io::Read for TlsStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl<S: io::Read + io::Write> io::Write for TlsStream<S> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

/// OpenSSL-specific extensions to `TlsStream`.
pub trait TlsStreamExt<S> {
    /// Returns a shared reference to the OpenSSL `SslStream`.
    fn raw_stream(&self) -> &ssl::SslStream<S>;

    /// Returns a mutable reference to the OpenSSL `SslStream`.
    fn raw_stream_mut(&mut self) -> &mut ssl::SslStream<S>;
}

impl<S> TlsStreamExt<S> for ::TlsStream<S> {
    fn raw_stream(&self) -> &ssl::SslStream<S> {
        &(self.0).0
    }

    fn raw_stream_mut(&mut self) -> &mut ssl::SslStream<S> {
        &mut (self.0).0
    }
}
<|endoftext|>


<commit_before>use nalgebra::Point2;
use std::collections::HashSet;

use event::{ElementState, Event, MouseButton, Reactor};
use super::state::{Element, InputState, InputStateSnapshot};

impl Element for MouseButton {
    type State = ElementState;
}

#[derive(Clone, Copy)]
pub struct MouseProximity;

impl Element for MouseProximity {
    type State = bool;
}

pub struct Mouse {
    position: Point2<u32>,
    state: MouseState,
    snapshot: MouseState,
}

impl Mouse {
    pub fn new() -> Self {
        Mouse {
            position: Point2::origin(),
            state: MouseState::new(),
            snapshot: MouseState::new(),
        }
    }

    pub fn position(&self) -> &Point2<u32> {
        &self.position
    }
}

impl InputState<MouseButton> for Mouse {
    fn state(&self, button: MouseButton) -> ElementState {
        self.state.state(button)
    }
}

impl InputState<MouseProximity> for Mouse {
    fn state(&self, proximity: MouseProximity) -> bool {
        self.state.state(proximity)
    }
}

impl Reactor for Mouse {
    fn react(&mut self, event: &Event) {
        match *event {
            Event::MouseEntered => {
                self.state.proximity = true;
            }
            Event::MouseInput(ElementState::Pressed, button) => {
                self.state.buttons.insert(button);
            }
            Event::MouseInput(ElementState::Released, button) => {
                self.state.buttons.remove(&button);
            }
            Event::MouseLeft => {
                self.state.proximity = false;
            }
            Event::MouseMoved(x, y) => {
                self.position = Point2::new(x as u32, y as u32);
            }
            _ => {}
        }
    }
}

impl InputStateSnapshot for Mouse {
    type Snapshot = MouseState;

    fn snapshot(&mut self) {
        self.snapshot = self.state.clone();
    }

    fn as_snapshot(&self) -> &Self::Snapshot {
        &self.snapshot
    }
}

#[derive(Clone)]
pub struct MouseState {
    buttons: HashSet<MouseButton>,
    proximity: bool,
}

impl MouseState {
    pub fn new() -> Self {
        MouseState {
            buttons: HashSet::new(),
            proximity: false,
        }
    }
}

impl InputState<MouseButton> for MouseState {
    fn state(&self, button: MouseButton) -> ElementState {
        if self.buttons.contains(&button) {
            ElementState::Pressed
        }
        else {
            ElementState::Released
        }
    }
}

impl InputState<MouseProximity> for MouseState {
    fn state(&self, _: MouseProximity) -> bool {
        self.proximity
    }
}
<commit_msg>Make `MouseState::new` private.<commit_after>use nalgebra::Point2;
use std::collections::HashSet;

use event::{ElementState, Event, MouseButton, Reactor};
use super::state::{Element, InputState, InputStateSnapshot};

impl Element for MouseButton {
    type State = ElementState;
}

#[derive(Clone, Copy)]
pub struct MouseProximity;

impl Element for MouseProximity {
    type State = bool;
}

pub struct Mouse {
    position: Point2<u32>,
    state: MouseState,
    snapshot: MouseState,
}

impl Mouse {
    pub fn new() -> Self {
        Mouse {
            position: Point2::origin(),
            state: MouseState::new(),
            snapshot: MouseState::new(),
        }
    }

    pub fn position(&self) -> &Point2<u32> {
        &self.position
    }
}

impl InputState<MouseButton> for Mouse {
    fn state(&self, button: MouseButton) -> ElementState {
        self.state.state(button)
    }
}

impl InputState<MouseProximity> for Mouse {
    fn state(&self, proximity: MouseProximity) -> bool {
        self.state.state(proximity)
    }
}

impl Reactor for Mouse {
    fn react(&mut self, event: &Event) {
        match *event {
            Event::MouseEntered => {
                self.state.proximity = true;
            }
            Event::MouseInput(ElementState::Pressed, button) => {
                self.state.buttons.insert(button);
            }
            Event::MouseInput(ElementState::Released, button) => {
                self.state.buttons.remove(&button);
            }
            Event::MouseLeft => {
                self.state.proximity = false;
            }
            Event::MouseMoved(x, y) => {
                self.position = Point2::new(x as u32, y as u32);
            }
            _ => {}
        }
    }
}

impl InputStateSnapshot for Mouse {
    type Snapshot = MouseState;

    fn snapshot(&mut self) {
        self.snapshot = self.state.clone();
    }

    fn as_snapshot(&self) -> &Self::Snapshot {
        &self.snapshot
    }
}

#[derive(Clone)]
pub struct MouseState {
    buttons: HashSet<MouseButton>,
    proximity: bool,
}

impl MouseState {
    fn new() -> Self {
        MouseState {
            buttons: HashSet::new(),
            proximity: false,
        }
    }
}

impl InputState<MouseButton> for MouseState {
    fn state(&self, button: MouseButton) -> ElementState {
        if self.buttons.contains(&button) {
            ElementState::Pressed
        }
        else {
            ElementState::Released
        }
    }
}

impl InputState<MouseProximity> for MouseState {
    fn state(&self, _: MouseProximity) -> bool {
        self.proximity
    }
}
<|endoftext|>


<commit_before>use register::Reg;
use condition::Condition;
use enum_set::EnumSet;

#[allow(non_camel_case_types)]
pub enum Op {
    MOV { rd: Reg, rm: Reg },
    MOV_imm8 { rd: Reg, imm8: u8 },
    LSL,
    LSR,
    ASR,
    AND,
    EOR,
    ADC,
    SBC,
    ROR,
    TST,
    RSB,
    CMP { rm: Reg, rn: Reg },
    CMP_imm8 { rn: Reg, imm8: u8 },
    CMN,
    ORR,
    MUL,
    BIC,
    MVN,
    ADDS { rm: Reg, rn: Reg, rd: Reg },
    ADD { rm: Reg, rdn: Reg },
    ADDS_imm { rn: Reg, rd: Reg, imm32: i32 },
    SUB,
    SUB_imm3,
    SUB_imm8,
    BX { rm: Reg },
    BLX { rm: Reg },
    BL { imm32: i32 },
    B_imm8 { cond: Condition, imm8: u8 },
    B_imm11 { imm11: u16 },
    SVC,
    UDF,
    PUSH { registers: EnumSet<Reg> },
    POP { registers: EnumSet<Reg> },
    LDR { rt: Reg, imm8: u8 },
}
<commit_msg>list all thumb-v6m instructions alphabetically<commit_after>use register::Reg;
use condition::Condition;
use enum_set::EnumSet;

#[allow(non_camel_case_types)]
pub enum Op {
    ADC,
    ADDS { rm: Reg, rn: Reg, rd: Reg },
    ADD { rm: Reg, rdn: Reg },
    ADDS_imm { rn: Reg, rd: Reg, imm32: u32 },
    ADR,
    AND,
    ASR,
    B { cond: Condition, imm32: i32 },
    BIC,
    BKPT,
    BL { imm32: i32 },
    BLX { rm: Reg },
    BX { rm: Reg },
    CMN,
    CMP_imm { rn: Reg, imm32: u32 },
    CMP { rm: Reg, rn: Reg },
    CPS,
    CPY,
    DMB,
    DSB,
    EOR,
    ISB,
    LDM,
    LDMIA,
    LDMFD,
    LDR_imm { rt: Reg, rn: Reg, imm32: u32 },
    LDR_lit { rt: Reg, imm32: u32 },
    LDR_reg { rt: Reg, rn: Reg, rm: Reg },
    LDRB_imm,
    LDRB_reg,
    LDRH_imm,
    LDRH_reg,
    LDRSB_reg,
    LDRSH_reg,
    LSL_imm,
    LSL_reg,
    LSR_imm,
    LSR_reg,
    MOV_reg { rd: Reg, rm: Reg, setflags: bool},
    MOV_imm { rd: Reg, imm32: u32 },
    MRS,
    MRS_reg,
    MUL,
    MVN_reg,
    NOP,
    ORR,
    POP { registers: EnumSet<Reg> },
    PUSH { registers: EnumSet<Reg> },
    REV,
    REV16,
    REVSH,
    ROR,
    RSB,
    SBC,
    SEV,
    STM,
    STMIA,
    STMEA,
    STR_imm,
    STR_reg,
    STRB_imm,
    STRB_reg,
    STRH_imm,
    STRH_reg,
    SUBS_imm { rd: Reg, rn: Reg, imm32: i32 },
    SUBS_reg { rm: Reg, rn: Reg, rd: Reg },
    SUB_SP_imm,
    SVC,
    SXTB,
    SXTH,
    TST,
    UDF,
    UXTB,
    UXTH,
    WFE,
    WFI,
    YIELD,
}
<|endoftext|>


<commit_before>extern crate serde;
extern crate serde_json;

use hyper::Client;
use hyper::client::{Body, Response};
use hyper::header::Headers;
use hyper::status::StatusCode;
use jira_request::*;
use std::io::Read;

pub fn send<R: JIRARequest, T: serde::de::Deserialize>(request: R) -> Result<T, String> {
    let client = Client::new();
    let mut res: Response = client.request(request.method(),
                                           &format!("{}{}", &request.base_url(), &request.path()))
        .headers(request.headers().unwrap_or(Headers::new()))
        .body(&request.body().unwrap_or("".to_string()))
        .send()
        .map_err(|e| e.to_string())?;

    match res.status {
        StatusCode::Ok => {
            let mut body = String::new();
            res.read_to_string(&mut body).map_err(|e| e.to_string())?;
            serde_json::from_str::<T>(&body).map_err(|e| e.to_string())
        },
        _ => Err("".to_string())// TODO　ステータスコードと説明を返す
    }
}<commit_msg>:art: Improve structure of JIRA Client<commit_after>extern crate serde;
extern crate serde_json;

use hyper::Client;
use hyper::client::{Body, Response};
use hyper::header::Headers;
use hyper::status::StatusCode;
use jira_request::*;
use std::io::Read;

pub fn send<R: JIRARequest, T: serde::de::Deserialize>(request: R) -> Result<T, String> {
    let client = Client::new();
    let url = format!("{}{}", &request.base_url(), &request.path());

    let mut res: Response = client.request(request.method(), &url)
        .headers(request.headers().unwrap_or(Headers::new()))
        .body(&request.body().unwrap_or("".to_string()))
        .send()
        .map_err(|e| e.to_string())?;

    let mut body = String::new();
    res.read_to_string(&mut body).map_err(|e| e.to_string())?;
    match res.status {
        StatusCode::Ok => serde_json::from_str::<T>(&body).map_err(|e| e.to_string()),
        _ => Err(body)
    }
}<|endoftext|>


<commit_before>// Copyright (c) 2019, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.

// Encode the same tiny blank frame 30 times
use rav1e::config::SpeedSettings;
use rav1e::*;

fn main() {
  let mut enc = EncoderConfig::default();

  enc.width = 64;
  enc.height = 96;

  enc.speed_settings = SpeedSettings::from_preset(9);

  let cfg = Config::new().with_encoder_config(enc);

  let mut ctx: Context<u16> = cfg.new_context().unwrap();

  let f = ctx.new_frame();

  let limit = 30;

  for i in 0..limit {
    println!("Sending frame {}", i);
    match ctx.send_frame(f.clone()) {
      Ok(_) => {}
      Err(e) => match e {
        EncoderStatus::EnoughData => {
          println!("Unable to append frame {} to the internal queue", i);
        }
        _ => {
          panic!("Unable to send frame {}", i);
        }
      },
    }
  }

  ctx.flush();

  // Test that we cleanly exit once we hit the limit
  let mut i = 0;
  while i < limit + 5 {
    match ctx.receive_packet() {
      Ok(pkt) => {
        println!("Packet {}", pkt.input_frameno);
        i += 1;
      }
      Err(e) => match e {
        EncoderStatus::LimitReached => {
          println!("Limit reached");
          break;
        }
        EncoderStatus::Encoded => println!("  Encoded"),
        EncoderStatus::NeedMoreData => println!("  Need more data"),
        _ => {
          panic!("Unable to receive packet {}", i);
        }
      },
    }
  }
}
<commit_msg>examples: Demonstrate filling a frame from raw pixels<commit_after>// Copyright (c) 2019, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.

// Encode the same tiny blank frame 30 times
use rav1e::config::SpeedSettings;
use rav1e::*;

fn main() {
  let mut enc = EncoderConfig::default();

  enc.width = 64;
  enc.height = 96;

  enc.speed_settings = SpeedSettings::from_preset(9);

  let cfg = Config::new().with_encoder_config(enc);

  let mut ctx: Context<u16> = cfg.new_context().unwrap();

  let mut f = ctx.new_frame();

  let pixels = vec![42; enc.width * enc.height];

  for p in &mut f.planes {
    let stride = (enc.width + p.cfg.xdec) >> p.cfg.xdec;
    p.copy_from_raw_u8(&pixels, stride, 1);
  }

  let limit = 30;

  for i in 0..limit {
    println!("Sending frame {}", i);
    match ctx.send_frame(f.clone()) {
      Ok(_) => {}
      Err(e) => match e {
        EncoderStatus::EnoughData => {
          println!("Unable to append frame {} to the internal queue", i);
        }
        _ => {
          panic!("Unable to send frame {}", i);
        }
      },
    }
  }

  ctx.flush();

  // Test that we cleanly exit once we hit the limit
  let mut i = 0;
  while i < limit + 5 {
    match ctx.receive_packet() {
      Ok(pkt) => {
        println!("Packet {}", pkt.input_frameno);
        i += 1;
      }
      Err(e) => match e {
        EncoderStatus::LimitReached => {
          println!("Limit reached");
          break;
        }
        EncoderStatus::Encoded => println!("  Encoded"),
        EncoderStatus::NeedMoreData => println!("  Need more data"),
        _ => {
          panic!("Unable to receive packet {}", i);
        }
      },
    }
  }
}
<|endoftext|>


<commit_before>use ra_syntax::{
    ast::{self, NameOwner, TypeAscriptionOwner, TypeParamsOwner},
    AstNode, SyntaxKind, TextRange, TextSize,
};
use rustc_hash::FxHashSet;

use crate::{assist_context::AssistBuilder, AssistContext, AssistId, Assists};

static ASSIST_NAME: &str = "introduce_named_lifetime";
static ASSIST_LABEL: &str = "Introduce named lifetime";

// Assist: introduce_named_lifetime
//
// Change an anonymous lifetime to a named lifetime.
//
// ```
// impl Cursor<'_<|>> {
//     fn node(self) -> &SyntaxNode {
//         match self {
//             Cursor::Replace(node) | Cursor::Before(node) => node,
//         }
//     }
// }
// ```
// ->
// ```
// impl<'a> Cursor<'a> {
//     fn node(self) -> &SyntaxNode {
//         match self {
//             Cursor::Replace(node) | Cursor::Before(node) => node,
//         }
//     }
// }
// ```
// FIXME: How can we handle renaming any one of multiple anonymous lifetimes?
// FIXME: should also add support for the case fun(f: &Foo) -> &<|>Foo
pub(crate) fn introduce_named_lifetime(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    let lifetime_token = ctx
        .find_token_at_offset(SyntaxKind::LIFETIME)
        .filter(|lifetime| lifetime.text() == "'_")?;
    if let Some(fn_def) = lifetime_token.ancestors().find_map(ast::FnDef::cast) {
        generate_fn_def_assist(acc, &fn_def, lifetime_token.text_range())
    } else if let Some(impl_def) = lifetime_token.ancestors().find_map(ast::ImplDef::cast) {
        // only allow naming the last anonymous lifetime
        lifetime_token.next_token().filter(|tok| tok.kind() == SyntaxKind::R_ANGLE)?;
        generate_impl_def_assist(acc, &impl_def, lifetime_token.text_range())
    } else {
        None
    }
}

/// Generate the assist for the fn def case
fn generate_fn_def_assist(
    acc: &mut Assists,
    fn_def: &ast::FnDef,
    lifetime_loc: TextRange,
) -> Option<()> {
    let param_list: ast::ParamList = fn_def.param_list()?;
    let new_lifetime_param = generate_unique_lifetime_param_name(&fn_def.type_param_list())?;
    let end_of_fn_ident = fn_def.name()?.ident_token()?.text_range().end();
    let self_param =
        // use the self if it's a reference and has no explicit lifetime
        param_list.self_param().filter(|p| p.lifetime_token().is_none() && p.amp_token().is_some());
    // compute the location which implicitly has the same lifetime as the anonymous lifetime
    let loc_needing_lifetime = if let Some(self_param) = self_param {
        // if we have a self reference, use that
        Some(self_param.self_token()?.text_range().start())
    } else {
        // otherwise, if there's a single reference parameter without a named liftime, use that
        let fn_params_without_lifetime: Vec<_> = param_list
            .params()
            .filter_map(|param| match param.ascribed_type() {
                Some(ast::TypeRef::ReferenceType(ascribed_type))
                    if ascribed_type.lifetime_token() == None =>
                {
                    Some(ascribed_type.amp_token()?.text_range().end())
                }
                _ => None,
            })
            .collect();
        match fn_params_without_lifetime.len() {
            1 => Some(fn_params_without_lifetime.into_iter().nth(0)?),
            0 => None,
            // multiple unnnamed is invalid. assist is not applicable
            _ => return None,
        }
    };
    acc.add(AssistId(ASSIST_NAME), ASSIST_LABEL, lifetime_loc, |builder| {
        add_lifetime_param(fn_def, builder, end_of_fn_ident, new_lifetime_param);
        builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
        loc_needing_lifetime.map(|loc| builder.insert(loc, format!("'{} ", new_lifetime_param)));
    })
}

/// Generate the assist for the impl def case
fn generate_impl_def_assist(
    acc: &mut Assists,
    impl_def: &ast::ImplDef,
    lifetime_loc: TextRange,
) -> Option<()> {
    let new_lifetime_param = generate_unique_lifetime_param_name(&impl_def.type_param_list())?;
    let end_of_impl_kw = impl_def.impl_token()?.text_range().end();
    acc.add(AssistId(ASSIST_NAME), ASSIST_LABEL, lifetime_loc, |builder| {
        add_lifetime_param(impl_def, builder, end_of_impl_kw, new_lifetime_param);
        builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
    })
}

/// Given a type parameter list, generate a unique lifetime parameter name
/// which is not in the list
fn generate_unique_lifetime_param_name(
    existing_type_param_list: &Option<ast::TypeParamList>,
) -> Option<char> {
    match existing_type_param_list {
        Some(type_params) => {
            let used_lifetime_params: FxHashSet<_> = type_params
                .lifetime_params()
                .map(|p| p.syntax().text().to_string()[1..].to_owned())
                .collect();
            (b'a'..=b'z').map(char::from).find(|c| !used_lifetime_params.contains(&c.to_string()))
        }
        None => Some('a'),
    }
}

/// Add the lifetime param to `builder`. If there are type parameters in `type_params_owner`, add it to the end. Otherwise
/// add new type params brackets with the lifetime parameter at `new_type_params_loc`.
fn add_lifetime_param<TypeParamsOwner: ast::TypeParamsOwner>(
    type_params_owner: &TypeParamsOwner,
    builder: &mut AssistBuilder,
    new_type_params_loc: TextSize,
    new_lifetime_param: char,
) {
    match type_params_owner.type_param_list() {
        // add the new lifetime parameter to an existing type param list
        Some(type_params) => {
            builder.insert(
                (u32::from(type_params.syntax().text_range().end()) - 1).into(),
                format!(", '{}", new_lifetime_param),
            );
        }
        // create a new type param list containing only the new lifetime parameter
        None => {
            builder.insert(new_type_params_loc, format!("<'{}>", new_lifetime_param));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::{check_assist, check_assist_not_applicable};

    #[test]
    fn test_example_case() {
        check_assist(
            introduce_named_lifetime,
            r#"impl Cursor<'_<|>> {
                fn node(self) -> &SyntaxNode {
                    match self {
                        Cursor::Replace(node) | Cursor::Before(node) => node,
                    }
                }
            }"#,
            r#"impl<'a> Cursor<'a> {
                fn node(self) -> &SyntaxNode {
                    match self {
                        Cursor::Replace(node) | Cursor::Before(node) => node,
                    }
                }
            }"#,
        );
    }

    #[test]
    fn test_example_case_simplified() {
        check_assist(
            introduce_named_lifetime,
            r#"impl Cursor<'_<|>> {"#,
            r#"impl<'a> Cursor<'a> {"#,
        );
    }

    #[test]
    fn test_example_case_cursor_after_tick() {
        check_assist(
            introduce_named_lifetime,
            r#"impl Cursor<'<|>_> {"#,
            r#"impl<'a> Cursor<'a> {"#,
        );
    }

    #[test]
    fn test_example_case_cursor_before_tick() {
        check_assist(
            introduce_named_lifetime,
            r#"impl Cursor<<|>'_> {"#,
            r#"impl<'a> Cursor<'a> {"#,
        );
    }

    #[test]
    fn test_not_applicable_cursor_position() {
        check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'_><|> {"#);
        check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<|><'_> {"#);
    }

    #[test]
    fn test_not_applicable_lifetime_already_name() {
        check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'a<|>> {"#);
        check_assist_not_applicable(introduce_named_lifetime, r#"fn my_fun<'a>() -> X<'a<|>>"#);
    }

    #[test]
    fn test_with_type_parameter() {
        check_assist(
            introduce_named_lifetime,
            r#"impl<T> Cursor<T, '_<|>>"#,
            r#"impl<T, 'a> Cursor<T, 'a>"#,
        );
    }

    #[test]
    fn test_with_existing_lifetime_name_conflict() {
        check_assist(
            introduce_named_lifetime,
            r#"impl<'a, 'b> Cursor<'a, 'b, '_<|>>"#,
            r#"impl<'a, 'b, 'c> Cursor<'a, 'b, 'c>"#,
        );
    }

    #[test]
    fn test_function_return_value_anon_lifetime_param() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun() -> X<'_<|>>"#,
            r#"fn my_fun<'a>() -> X<'a>"#,
        );
    }

    #[test]
    fn test_function_return_value_anon_reference_lifetime() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun() -> &'_<|> X"#,
            r#"fn my_fun<'a>() -> &'a X"#,
        );
    }

    #[test]
    fn test_function_param_anon_lifetime() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun(x: X<'_<|>>)"#,
            r#"fn my_fun<'a>(x: X<'a>)"#,
        );
    }

    #[test]
    fn test_function_add_lifetime_to_params() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun(f: &Foo) -> X<'_<|>>"#,
            r#"fn my_fun<'a>(f: &'a Foo) -> X<'a>"#,
        );
    }

    #[test]
    fn test_function_add_lifetime_to_params_in_presence_of_other_lifetime() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun<'other>(f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
            r#"fn my_fun<'other, 'a>(f: &'a Foo, b: &'other Bar) -> X<'a>"#,
        );
    }

    #[test]
    fn test_function_not_applicable_without_self_and_multiple_unnamed_param_lifetimes() {
        // this is not permitted under lifetime elision rules
        check_assist_not_applicable(
            introduce_named_lifetime,
            r#"fn my_fun(f: &Foo, b: &Bar) -> X<'_<|>>"#,
        );
    }

    #[test]
    fn test_function_add_lifetime_to_self_ref_param() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun<'other>(&self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
            r#"fn my_fun<'other, 'a>(&'a self, f: &Foo, b: &'other Bar) -> X<'a>"#,
        );
    }

    #[test]
    fn test_function_add_lifetime_to_param_with_non_ref_self() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun<'other>(self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
            r#"fn my_fun<'other, 'a>(self, f: &'a Foo, b: &'other Bar) -> X<'a>"#,
        );
    }
}
<commit_msg>introduce_named_lifetime assist wasn't applicable when type parameter followed anonymous lifetime token<commit_after>use ra_syntax::{
    ast::{self, NameOwner, TypeAscriptionOwner, TypeParamsOwner},
    AstNode, SyntaxKind, TextRange, TextSize,
};
use rustc_hash::FxHashSet;

use crate::{assist_context::AssistBuilder, AssistContext, AssistId, Assists};

static ASSIST_NAME: &str = "introduce_named_lifetime";
static ASSIST_LABEL: &str = "Introduce named lifetime";

// Assist: introduce_named_lifetime
//
// Change an anonymous lifetime to a named lifetime.
//
// ```
// impl Cursor<'_<|>> {
//     fn node(self) -> &SyntaxNode {
//         match self {
//             Cursor::Replace(node) | Cursor::Before(node) => node,
//         }
//     }
// }
// ```
// ->
// ```
// impl<'a> Cursor<'a> {
//     fn node(self) -> &SyntaxNode {
//         match self {
//             Cursor::Replace(node) | Cursor::Before(node) => node,
//         }
//     }
// }
// ```
// FIXME: How can we handle renaming any one of multiple anonymous lifetimes?
// FIXME: should also add support for the case fun(f: &Foo) -> &<|>Foo
pub(crate) fn introduce_named_lifetime(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    let lifetime_token = ctx
        .find_token_at_offset(SyntaxKind::LIFETIME)
        .filter(|lifetime| lifetime.text() == "'_")?;
    if let Some(fn_def) = lifetime_token.ancestors().find_map(ast::FnDef::cast) {
        generate_fn_def_assist(acc, &fn_def, lifetime_token.text_range())
    } else if let Some(impl_def) = lifetime_token.ancestors().find_map(ast::ImplDef::cast) {
        generate_impl_def_assist(acc, &impl_def, lifetime_token.text_range())
    } else {
        None
    }
}

/// Generate the assist for the fn def case
fn generate_fn_def_assist(
    acc: &mut Assists,
    fn_def: &ast::FnDef,
    lifetime_loc: TextRange,
) -> Option<()> {
    let param_list: ast::ParamList = fn_def.param_list()?;
    let new_lifetime_param = generate_unique_lifetime_param_name(&fn_def.type_param_list())?;
    let end_of_fn_ident = fn_def.name()?.ident_token()?.text_range().end();
    let self_param =
        // use the self if it's a reference and has no explicit lifetime
        param_list.self_param().filter(|p| p.lifetime_token().is_none() && p.amp_token().is_some());
    // compute the location which implicitly has the same lifetime as the anonymous lifetime
    let loc_needing_lifetime = if let Some(self_param) = self_param {
        // if we have a self reference, use that
        Some(self_param.self_token()?.text_range().start())
    } else {
        // otherwise, if there's a single reference parameter without a named liftime, use that
        let fn_params_without_lifetime: Vec<_> = param_list
            .params()
            .filter_map(|param| match param.ascribed_type() {
                Some(ast::TypeRef::ReferenceType(ascribed_type))
                    if ascribed_type.lifetime_token() == None =>
                {
                    Some(ascribed_type.amp_token()?.text_range().end())
                }
                _ => None,
            })
            .collect();
        match fn_params_without_lifetime.len() {
            1 => Some(fn_params_without_lifetime.into_iter().nth(0)?),
            0 => None,
            // multiple unnnamed is invalid. assist is not applicable
            _ => return None,
        }
    };
    acc.add(AssistId(ASSIST_NAME), ASSIST_LABEL, lifetime_loc, |builder| {
        add_lifetime_param(fn_def, builder, end_of_fn_ident, new_lifetime_param);
        builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
        loc_needing_lifetime.map(|loc| builder.insert(loc, format!("'{} ", new_lifetime_param)));
    })
}

/// Generate the assist for the impl def case
fn generate_impl_def_assist(
    acc: &mut Assists,
    impl_def: &ast::ImplDef,
    lifetime_loc: TextRange,
) -> Option<()> {
    let new_lifetime_param = generate_unique_lifetime_param_name(&impl_def.type_param_list())?;
    let end_of_impl_kw = impl_def.impl_token()?.text_range().end();
    acc.add(AssistId(ASSIST_NAME), ASSIST_LABEL, lifetime_loc, |builder| {
        add_lifetime_param(impl_def, builder, end_of_impl_kw, new_lifetime_param);
        builder.replace(lifetime_loc, format!("'{}", new_lifetime_param));
    })
}

/// Given a type parameter list, generate a unique lifetime parameter name
/// which is not in the list
fn generate_unique_lifetime_param_name(
    existing_type_param_list: &Option<ast::TypeParamList>,
) -> Option<char> {
    match existing_type_param_list {
        Some(type_params) => {
            let used_lifetime_params: FxHashSet<_> = type_params
                .lifetime_params()
                .map(|p| p.syntax().text().to_string()[1..].to_owned())
                .collect();
            (b'a'..=b'z').map(char::from).find(|c| !used_lifetime_params.contains(&c.to_string()))
        }
        None => Some('a'),
    }
}

/// Add the lifetime param to `builder`. If there are type parameters in `type_params_owner`, add it to the end. Otherwise
/// add new type params brackets with the lifetime parameter at `new_type_params_loc`.
fn add_lifetime_param<TypeParamsOwner: ast::TypeParamsOwner>(
    type_params_owner: &TypeParamsOwner,
    builder: &mut AssistBuilder,
    new_type_params_loc: TextSize,
    new_lifetime_param: char,
) {
    match type_params_owner.type_param_list() {
        // add the new lifetime parameter to an existing type param list
        Some(type_params) => {
            builder.insert(
                (u32::from(type_params.syntax().text_range().end()) - 1).into(),
                format!(", '{}", new_lifetime_param),
            );
        }
        // create a new type param list containing only the new lifetime parameter
        None => {
            builder.insert(new_type_params_loc, format!("<'{}>", new_lifetime_param));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::{check_assist, check_assist_not_applicable};

    #[test]
    fn test_example_case() {
        check_assist(
            introduce_named_lifetime,
            r#"impl Cursor<'_<|>> {
                fn node(self) -> &SyntaxNode {
                    match self {
                        Cursor::Replace(node) | Cursor::Before(node) => node,
                    }
                }
            }"#,
            r#"impl<'a> Cursor<'a> {
                fn node(self) -> &SyntaxNode {
                    match self {
                        Cursor::Replace(node) | Cursor::Before(node) => node,
                    }
                }
            }"#,
        );
    }

    #[test]
    fn test_example_case_simplified() {
        check_assist(
            introduce_named_lifetime,
            r#"impl Cursor<'_<|>> {"#,
            r#"impl<'a> Cursor<'a> {"#,
        );
    }

    #[test]
    fn test_example_case_cursor_after_tick() {
        check_assist(
            introduce_named_lifetime,
            r#"impl Cursor<'<|>_> {"#,
            r#"impl<'a> Cursor<'a> {"#,
        );
    }

    #[test]
    fn test_impl_with_other_type_param() {
        check_assist(
            introduce_named_lifetime,
            "impl<I> fmt::Display for SepByBuilder<'_<|>, I>
        where
            I: Iterator,
            I::Item: fmt::Display,
        {",
            "impl<I, 'a> fmt::Display for SepByBuilder<'a, I>
        where
            I: Iterator,
            I::Item: fmt::Display,
        {",
        )
    }

    #[test]
    fn test_example_case_cursor_before_tick() {
        check_assist(
            introduce_named_lifetime,
            r#"impl Cursor<<|>'_> {"#,
            r#"impl<'a> Cursor<'a> {"#,
        );
    }

    #[test]
    fn test_not_applicable_cursor_position() {
        check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'_><|> {"#);
        check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<|><'_> {"#);
    }

    #[test]
    fn test_not_applicable_lifetime_already_name() {
        check_assist_not_applicable(introduce_named_lifetime, r#"impl Cursor<'a<|>> {"#);
        check_assist_not_applicable(introduce_named_lifetime, r#"fn my_fun<'a>() -> X<'a<|>>"#);
    }

    #[test]
    fn test_with_type_parameter() {
        check_assist(
            introduce_named_lifetime,
            r#"impl<T> Cursor<T, '_<|>>"#,
            r#"impl<T, 'a> Cursor<T, 'a>"#,
        );
    }

    #[test]
    fn test_with_existing_lifetime_name_conflict() {
        check_assist(
            introduce_named_lifetime,
            r#"impl<'a, 'b> Cursor<'a, 'b, '_<|>>"#,
            r#"impl<'a, 'b, 'c> Cursor<'a, 'b, 'c>"#,
        );
    }

    #[test]
    fn test_function_return_value_anon_lifetime_param() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun() -> X<'_<|>>"#,
            r#"fn my_fun<'a>() -> X<'a>"#,
        );
    }

    #[test]
    fn test_function_return_value_anon_reference_lifetime() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun() -> &'_<|> X"#,
            r#"fn my_fun<'a>() -> &'a X"#,
        );
    }

    #[test]
    fn test_function_param_anon_lifetime() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun(x: X<'_<|>>)"#,
            r#"fn my_fun<'a>(x: X<'a>)"#,
        );
    }

    #[test]
    fn test_function_add_lifetime_to_params() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun(f: &Foo) -> X<'_<|>>"#,
            r#"fn my_fun<'a>(f: &'a Foo) -> X<'a>"#,
        );
    }

    #[test]
    fn test_function_add_lifetime_to_params_in_presence_of_other_lifetime() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun<'other>(f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
            r#"fn my_fun<'other, 'a>(f: &'a Foo, b: &'other Bar) -> X<'a>"#,
        );
    }

    #[test]
    fn test_function_not_applicable_without_self_and_multiple_unnamed_param_lifetimes() {
        // this is not permitted under lifetime elision rules
        check_assist_not_applicable(
            introduce_named_lifetime,
            r#"fn my_fun(f: &Foo, b: &Bar) -> X<'_<|>>"#,
        );
    }

    #[test]
    fn test_function_add_lifetime_to_self_ref_param() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun<'other>(&self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
            r#"fn my_fun<'other, 'a>(&'a self, f: &Foo, b: &'other Bar) -> X<'a>"#,
        );
    }

    #[test]
    fn test_function_add_lifetime_to_param_with_non_ref_self() {
        check_assist(
            introduce_named_lifetime,
            r#"fn my_fun<'other>(self, f: &Foo, b: &'other Bar) -> X<'_<|>>"#,
            r#"fn my_fun<'other, 'a>(self, f: &'a Foo, b: &'other Bar) -> X<'a>"#,
        );
    }
}
<|endoftext|>


<commit_before>#![deny(rust_2018_idioms)]

use comparison::{
    c_xxhash::{hash32, hash64},
    hash_once,
};
use criterion::{
    criterion_group, criterion_main, AxisScale, Bencher, Criterion, ParameterizedBenchmark,
    PlotConfiguration, Throughput,
};
use fnv::FnvHasher;
use rand::{distributions::Standard, rngs::StdRng, Rng, SeedableRng};
use std::{collections::hash_map::DefaultHasher, env, fmt, hash::Hasher, ops};
use twox_hash::{XxHash32, XxHash64};

const INPUT_SIZES: &[usize] = &[0, 1, 4, 16, 32, 128, 256, 512, 1024, 1024 * 1024];

fn bench_hasher<H>(hasher: impl Fn() -> H) -> impl FnMut(&mut Bencher, &Data)
where
    H: Hasher,
{
    move |b, data| b.iter(|| hash_once(hasher(), data))
}

fn bench_c<R>(hasher: impl Fn(&[u8]) -> R) -> impl FnMut(&mut Bencher, &Data) {
    move |b, data| b.iter(|| hasher(data))
}

fn bench_everything(c: &mut Criterion) {
    let seed: u64 = env::var("RANDOM_SEED")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or_else(rand::random);
    eprintln!("Using RANDOM_SEED={}", seed);

    let data: Vec<_> = INPUT_SIZES.iter().map(|&l| Data::new(l, seed)).collect();

    let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Logarithmic);

    let bench =
        ParameterizedBenchmark::new("XxHash64", bench_hasher(|| XxHash64::with_seed(0)), data)
            .with_function("XxHash32", bench_hasher(|| XxHash32::with_seed(0)))
            .with_function("XxHash64 (C)", bench_c(|d| hash64(d, 0)))
            .with_function("XxHash32 (C)", bench_c(|d| hash32(d, 0)))
            .with_function("DefaultHasher", bench_hasher(|| DefaultHasher::new()))
            .with_function("FnvHasher", bench_hasher(|| FnvHasher::default()))
            .throughput(|data| Throughput::Elements(data.0.len() as u32))
            .plot_config(plot_config);

    c.bench("All Hashers", bench);
}

struct Data(Vec<u8>);

impl Data {
    fn new(len: usize, seed: u64) -> Self {
        let mut rng = StdRng::seed_from_u64(seed);
        let data = rng.sample_iter(&Standard).take(len).collect();
        Self(data)
    }

    fn len(&self) -> usize {
        self.0.len()
    }
}

impl ops::Deref for Data {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Debug for Data {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} bytes", self.len())
    }
}

criterion_group!(benches, bench_everything);
criterion_main!(benches);
<commit_msg>Add benchmark for unaligned input<commit_after>#![deny(rust_2018_idioms)]

use comparison::{
    c_xxhash::{hash32, hash64},
    hash_once,
};
use criterion::{
    criterion_group, criterion_main, AxisScale, Bencher, Criterion, ParameterizedBenchmark,
    PlotConfiguration, Throughput,
};
use fnv::FnvHasher;
use rand::{distributions::Standard, rngs::StdRng, Rng, SeedableRng};
use std::{collections::hash_map::DefaultHasher, env, fmt, hash::Hasher, ops};
use twox_hash::{XxHash32, XxHash64};

const INPUT_SIZES: &[usize] = &[0, 1, 4, 16, 23, 32, 47, 128, 256, 512, 1024, 1024 * 1024];
const OFFSETS: &[usize] = &[0, 1];

fn bench_hasher<H>(hasher: impl Fn() -> H) -> impl FnMut(&mut Bencher, &Data)
where
    H: Hasher,
{
    move |b, data| b.iter(|| hash_once(hasher(), data))
}

fn bench_c<R>(hasher: impl Fn(&[u8]) -> R) -> impl FnMut(&mut Bencher, &Data) {
    move |b, data| b.iter(|| hasher(data))
}

fn bench_everything(c: &mut Criterion) {
    let seed: u64 = env::var("RANDOM_SEED")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or_else(rand::random);
    eprintln!("Using RANDOM_SEED={}", seed);

    let data: Vec<_> = OFFSETS
        .iter()
        .flat_map(|&o| {
            INPUT_SIZES
                .iter()
                .map(|&l| Data::new(l, seed, o))
                .collect::<Vec<_>>()
        })
        .collect();

    let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Logarithmic);

    let bench =
        ParameterizedBenchmark::new("XxHash64", bench_hasher(|| XxHash64::with_seed(0)), data)
            .with_function("XxHash32", bench_hasher(|| XxHash32::with_seed(0)))
            .with_function("XxHash64 (C)", bench_c(|d| hash64(d, 0)))
            .with_function("XxHash32 (C)", bench_c(|d| hash32(d, 0)))
            .with_function("DefaultHasher", bench_hasher(|| DefaultHasher::new()))
            .with_function("FnvHasher", bench_hasher(|| FnvHasher::default()))
            .throughput(|data| Throughput::Elements(data.0.len() as u32))
            .plot_config(plot_config);

    c.bench("All Hashers", bench);
}

struct Data(Vec<u8>, usize);

impl Data {
    fn new(len: usize, seed: u64, offset: usize) -> Self {
        let mut rng = StdRng::seed_from_u64(seed);
        let data = rng.sample_iter(&Standard).take(len + offset).collect();
        Self(data, offset)
    }

    #[inline]
    fn len(&self) -> usize {
        self.0.len() - self.offset()
    }

    #[inline]
    fn offset(&self) -> usize {
        self.1
    }
}

impl ops::Deref for Data {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        &self.0[self.offset()..]
    }
}

impl fmt::Debug for Data {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} bytes/offset {}", self.len(), self.offset())
    }
}

criterion_group!(benches, bench_everything);
criterion_main!(benches);
<|endoftext|>


<commit_before>macro_rules! skip_bytes (
  ($input: expr, $length: expr, $offset: expr) => (
    {
      match take!($input, $length) {
        $crate::nom::IResult::Done(i, bytes)   => {
          let head        = bytes[0] << $offset;
          let tail        = &bytes[1..];
          let is_all_zero = tail.iter().all(|byte| *byte == 0);

          if head == 0 && is_all_zero {
            $crate::nom::IResult::Done(i, bytes)
          } else {
            $crate::nom::IResult::Error($crate::nom::Err::Position(
              $crate::nom::ErrorCode::Digit as u32, $input))
          }
        }
        $crate::nom::IResult::Error(error)     =>
          $crate::nom::IResult::Error(error),
        $crate::nom::IResult::Incomplete(need) =>
          $crate::nom::IResult::Incomplete(need),
      }
    }
  );
);

macro_rules! count_slice (
  ($input: expr, $submac: ident!( $($args:tt)* ), $result: expr) => (
    {
      let mut input    = $input;
      let mut count    = 0;
      let mut is_error = false;

      for result in $result {
        match $submac!(input, $($args)*) {
          $crate::nom::IResult::Done(i, o)    => {
            *result = o;

            input   = i;
            count  += 1;
          }
          $crate::nom::IResult::Error(_)      => {
            is_error = true;
            break;
          }
          $crate::nom::IResult::Incomplete(_) => break,
        }
      }

      if is_error {
        $crate::nom::IResult::Error($crate::nom::Err::Position(
          $crate::nom::ErrorCode::Count as u32, $input.0))
      } else if count == $result.len() {
        $crate::nom::IResult::Done(input, ())
      } else {
        $crate::nom::IResult::Incomplete($crate::nom::Needed::Unknown)
      }
    }
  );
  ($i: expr, $f: expr, $count: expr) => (
    count_slice!($i, call!($f), $count);
  );
);

macro_rules! count_bits (
  ($input: expr, $submac: ident!( $($args:tt)* ), $count: expr) => (
    {
      let mut input    = $input;
      let mut count    = 0;
      let mut is_error = false;
      let mut result   = Vec::with_capacity($count);

      loop {
        if count == $count {
          break;
        }

        match $submac!(input, $($args)*) {
          $crate::nom::IResult::Done(i, o)    => {
            result.push(o);

            input  = i;
            count += 1;
          }
          $crate::nom::IResult::Error(_)      => {
            is_error = true;
            break;
          }
          $crate::nom::IResult::Incomplete(_) => break,
        }
      }

      if is_error {
        $crate::nom::IResult::Error($crate::nom::Err::Position(
          $crate::nom::ErrorCode::Count as u32, $input.0))
      } else if count == $count {
        $crate::nom::IResult::Done(input, result)
      } else {
        $crate::nom::IResult::Incomplete($crate::nom::Needed::Unknown)
      }
    }
  );
  ($i: expr, $f: expr, $count: expr) => (
    count_bits!($i, call!($f), $count);
  );
);

macro_rules! take_signed_bits (
  ($input: expr, $signed_type: ty, $count: expr) => (
    map!($input, take_bits!(u32, $count), |value| {
      let max_count = ::std::mem::size_of::<$signed_type>() * 8;

      if $count >= max_count || value < (1 << ($count - 1)) {
        value as $signed_type
      } else {
        (value as $signed_type).wrapping_sub(1 << $count)
      }
    });
  );
  ($input: expr, $count: expr) => (
    take_signed_bits!($input, i32, $count);
  );
);

#[cfg(test)]
mod tests {
  use super::*;
  use nom::{
    IResult,
    Err, ErrorCode
  };

  #[test]
  fn test_take_signed_bits() {
    let inputs      = [ (&[0b00100000][..], 2)
                      , (&[0b00011111][..], 2)
                      , (&[0b00001000, 0b00000000][..], 4)
                      , (&[0b00000111, 0b11111111][..], 4)
                      , (&[0b10000000, 0b00000000, 0b00000000][..], 0)
                      , (&[0b01111111, 0b11111111, 0b11111111][..], 0)
                      ];
    let results_i8  = [ IResult::Done((&[][..], 0), -32)
                      , IResult::Done((&[][..], 0), 31)
                      ];
    let results_i16 = [ IResult::Done((&[][..], 0), -2048)
                      , IResult::Done((&[][..], 0), 2047)
                      ];
    let results_i32 = [ IResult::Done((&[][..], 0), -8388608)
                      , IResult::Done((&[][..], 0), 8388607)
                      ];

    assert_eq!(take_signed_bits!(inputs[0], i8, 6), results_i8[0]);
    assert_eq!(take_signed_bits!(inputs[1], i8, 6), results_i8[1]);
    assert_eq!(take_signed_bits!(inputs[2], i16, 12), results_i16[0]);
    assert_eq!(take_signed_bits!(inputs[3], i16, 12), results_i16[1]);
    assert_eq!(take_signed_bits!(inputs[4], i32, 24), results_i32[0]);
    assert_eq!(take_signed_bits!(inputs[5], i32, 24), results_i32[1]);
  }
}
<commit_msg>Use `extend_sign` for the `take_signed_bits!` macro<commit_after>macro_rules! skip_bytes (
  ($input: expr, $length: expr, $offset: expr) => (
    {
      match take!($input, $length) {
        $crate::nom::IResult::Done(i, bytes)   => {
          let head        = bytes[0] << $offset;
          let tail        = &bytes[1..];
          let is_all_zero = tail.iter().all(|byte| *byte == 0);

          if head == 0 && is_all_zero {
            $crate::nom::IResult::Done(i, bytes)
          } else {
            $crate::nom::IResult::Error($crate::nom::Err::Position(
              $crate::nom::ErrorCode::Digit as u32, $input))
          }
        }
        $crate::nom::IResult::Error(error)     =>
          $crate::nom::IResult::Error(error),
        $crate::nom::IResult::Incomplete(need) =>
          $crate::nom::IResult::Incomplete(need),
      }
    }
  );
);

macro_rules! count_slice (
  ($input: expr, $submac: ident!( $($args:tt)* ), $result: expr) => (
    {
      let mut input    = $input;
      let mut count    = 0;
      let mut is_error = false;

      for result in $result {
        match $submac!(input, $($args)*) {
          $crate::nom::IResult::Done(i, o)    => {
            *result = o;

            input   = i;
            count  += 1;
          }
          $crate::nom::IResult::Error(_)      => {
            is_error = true;
            break;
          }
          $crate::nom::IResult::Incomplete(_) => break,
        }
      }

      if is_error {
        $crate::nom::IResult::Error($crate::nom::Err::Position(
          $crate::nom::ErrorCode::Count as u32, $input.0))
      } else if count == $result.len() {
        $crate::nom::IResult::Done(input, ())
      } else {
        $crate::nom::IResult::Incomplete($crate::nom::Needed::Unknown)
      }
    }
  );
  ($i: expr, $f: expr, $count: expr) => (
    count_slice!($i, call!($f), $count);
  );
);

macro_rules! count_bits (
  ($input: expr, $submac: ident!( $($args:tt)* ), $count: expr) => (
    {
      let mut input    = $input;
      let mut count    = 0;
      let mut is_error = false;
      let mut result   = Vec::with_capacity($count);

      loop {
        if count == $count {
          break;
        }

        match $submac!(input, $($args)*) {
          $crate::nom::IResult::Done(i, o)    => {
            result.push(o);

            input  = i;
            count += 1;
          }
          $crate::nom::IResult::Error(_)      => {
            is_error = true;
            break;
          }
          $crate::nom::IResult::Incomplete(_) => break,
        }
      }

      if is_error {
        $crate::nom::IResult::Error($crate::nom::Err::Position(
          $crate::nom::ErrorCode::Count as u32, $input.0))
      } else if count == $count {
        $crate::nom::IResult::Done(input, result)
      } else {
        $crate::nom::IResult::Incomplete($crate::nom::Needed::Unknown)
      }
    }
  );
  ($i: expr, $f: expr, $count: expr) => (
    count_bits!($i, call!($f), $count);
  );
);

macro_rules! take_signed_bits (
  ($input: expr, $signed_type: ty, $count: expr) => (
    map!($input, take_bits!(u32, $count), |value| {
      ::utility::extend_sign(value, $count) as $signed_type
    });
  );
  ($input: expr, $count: expr) => (
    take_signed_bits!($input, i32, $count);
  );
);

#[cfg(test)]
mod tests {
  use super::*;
  use nom::{
    IResult,
    Err, ErrorCode
  };

  #[test]
  fn test_take_signed_bits() {
    let inputs      = [ (&[0b00100000][..], 2)
                      , (&[0b00011111][..], 2)
                      , (&[0b00001000, 0b00000000][..], 4)
                      , (&[0b00000111, 0b11111111][..], 4)
                      , (&[0b10000000, 0b00000000, 0b00000000][..], 0)
                      , (&[0b01111111, 0b11111111, 0b11111111][..], 0)
                      ];
    let results_i8  = [ IResult::Done((&[][..], 0), -32)
                      , IResult::Done((&[][..], 0), 31)
                      ];
    let results_i16 = [ IResult::Done((&[][..], 0), -2048)
                      , IResult::Done((&[][..], 0), 2047)
                      ];
    let results_i32 = [ IResult::Done((&[][..], 0), -8388608)
                      , IResult::Done((&[][..], 0), 8388607)
                      ];

    assert_eq!(take_signed_bits!(inputs[0], i8, 6), results_i8[0]);
    assert_eq!(take_signed_bits!(inputs[1], i8, 6), results_i8[1]);
    assert_eq!(take_signed_bits!(inputs[2], i16, 12), results_i16[0]);
    assert_eq!(take_signed_bits!(inputs[3], i16, 12), results_i16[1]);
    assert_eq!(take_signed_bits!(inputs[4], i32, 24), results_i32[0]);
    assert_eq!(take_signed_bits!(inputs[5], i32, 24), results_i32[1]);
  }
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::fmt;

use serde::de::{MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Extensions(pub HashMap<String, serde_json::Value>);

impl Extensions {
    fn add(&mut self, ext_id: String, value: serde_json::Value) {
        self.0.insert(ext_id, value);
    }
}

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

impl<'de> Deserialize<'de> for Extensions {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ExtensionsVisitor;
        impl<'de> Visitor<'de> for ExtensionsVisitor {
            type Value = Extensions;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct Extensions")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Extensions, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut extensions = Extensions::default();
                while let Some(key) = map.next_key::<String>()? {
                    if key.starts_with("x-") {
                        extensions.add(key, map.next_value()?);
                    }
                }
                Ok(extensions)
            }
        }
        deserializer.deserialize_map(ExtensionsVisitor)
    }
}

impl Serialize for Extensions {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(self.0.len()))?;
        for (k, v) in self.0.clone() {
            map.serialize_entry(&k, &v)?;
        }
        map.end()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::Value;
    use serde_test::{assert_tokens, Token};

    use crate::v3_0::extension::Extensions;

    #[test]
    fn test_serde_extensions() {
        let mut extensions = Extensions::default();
        extensions.add(String::from("x-test"), Value::from("val"));
        assert_tokens(
            &extensions,
            &[
                Token::Map { len: Some(1) },
                Token::String("x-test"),
                Token::String("val"),
                Token::MapEnd,
            ],
        )
    }
}
<commit_msg>feat(extensions): hide implementation details behind an API<commit_after>use std::collections::HashMap;
use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde::de::{MapAccess, Visitor};
use serde::ser::SerializeMap;

#[derive(Debug, Eq, PartialEq, Clone)]
/// Contains openapi specification extensions
/// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#specificationExtensions
pub struct Extensions(HashMap<String, serde_json::Value>);

impl Extensions {
    fn add(&mut self, ext_id: String, value: serde_json::Value) {
        self.0.insert(ext_id, value);
    }

    /// Fetch extension by name
    pub fn get(&self, ext_id: &str) -> Option<&serde_json::Value> {
        self.0.get(ext_id)
    }

    /// A reference to all the captured extensions
    pub fn all(&self) -> &HashMap<String, serde_json::Value> {
        &self.0
    }
}

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

impl<'de> Deserialize<'de> for Extensions {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
    {
        struct ExtensionsVisitor;
        impl<'de> Visitor<'de> for ExtensionsVisitor {
            type Value = Extensions;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct Extensions")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Extensions, V::Error>
                where
                    V: MapAccess<'de>,
            {
                let mut extensions = Extensions::default();
                while let Some(key) = map.next_key::<String>()? {
                    if key.starts_with("x-") {
                        extensions.add(key, map.next_value()?);
                    }
                }
                Ok(extensions)
            }
        }
        deserializer.deserialize_map(ExtensionsVisitor)
    }
}

impl Serialize for Extensions {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(self.0.len()))?;
        for (k, v) in self.0.clone() {
            map.serialize_entry(&k, &v)?;
        }
        map.end()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::Value;
    use serde_test::{assert_tokens, Token};

    use crate::v3_0::extension::Extensions;

    #[test]
    fn test_serde_extensions() {
        let mut extensions = Extensions::default();
        extensions.add(String::from("x-test"), Value::from("val"));
        assert_tokens(
            &extensions,
            &[
                Token::Map { len: Some(1) },
                Token::String("x-test"),
                Token::String("val"),
                Token::MapEnd,
            ],
        )
    }

    #[test]
    fn test_get_extension() {
        let value = Value::from("val");

        let mut extensions = Extensions::default();
        extensions.add(String::from("x-test"), value.clone());

        assert_eq!(extensions.get("x-test"), Some(&value));
    }

    #[test]
    fn test_all_extensions() {
        let value = Value::from("val");

        let mut extensions = Extensions::default();
        extensions.add(String::from("x-test"), value.clone());

        assert_eq!(
            extensions.all().get_key_value("x-test"),
            Some((&"x-test".to_string(), &value))
        );
    }
}
<|endoftext|>


<commit_before>use std::ops::{Index, IndexMut};
use std::iter::{Iterator, repeat};

use graph::{Edge, Graph};

pub struct AdjacencyMatrix {
    rows: Vec<Vec<u32>>,
}

impl AdjacencyMatrix {
    fn new(size: usize) -> AdjacencyMatrix {
        let row = vec![0; size];
        let rows = repeat(row).take(size).collect();

        AdjacencyMatrix { rows: rows }
    }

    pub fn from_graph(g: &Graph) -> AdjacencyMatrix {
        let mut m = AdjacencyMatrix::new(g.vertex_count);

        for &Edge { x, y } in &g.edges {
            m[x][y] = 1;
            if !g.directed {
                m[y][x] = 1;
            }
        }

        m
    }

    pub fn size(&self) -> usize {
        self.rows.len()
    }
}

// For convenience, enable writing matrix[x] instead of matrix.rows[x].

impl Index<usize> for AdjacencyMatrix {
    type Output = Vec<u32>;

    fn index<'a>(&'a self, _index: usize) -> &'a Vec<u32> {
        &self.rows[_index]
    }
}

impl IndexMut<usize> for AdjacencyMatrix {
    fn index_mut<'a>(&'a mut self, _index: usize) -> &'a mut Vec<u32> {
        &mut self.rows[_index]
    }
}

// Breadth-first search.

impl AdjacencyMatrix {
    pub fn breadth_first_search(&self, start: usize) -> BreadthFirstSearch {
        let mut visited = vec!(false; self.size());
        visited[start] = true;

        BreadthFirstSearch {
            matrix: self,
            visited: visited,
            queue: vec![start],
            y: 0
        }
    }
}

struct BreadthFirstSearch<'a> {
    matrix: &'a AdjacencyMatrix,
    visited: Vec<bool>,
    queue: Vec<usize>,
    y: usize,
}

impl<'a> Iterator for BreadthFirstSearch<'a> {
    type Item = Edge;

    fn next(&mut self) -> Option<Edge> {
        while !self.queue.is_empty() {
            let x = self.queue[0];

            for y in self.y..self.matrix.size() {
                if self.visited[y] || self.matrix[x][y] == 0 {
                    continue;
                }
                self.visited[y] = true;
                self.queue.push(y);
                self.y = y + 1;
                return Some(Edge { x: x, y: y });
            }

            // Process the next element in the queue.
            self.queue.remove(0);
            self.y = 0;
        }

        None
    }
}

// Breadth-first search using std::iter::Unfold. Unless I missed something, it's much more
// complicated than not using Unfold.

// struct BreadthFirstSearchState<'a> {
//     matrix: &'a AdjacencyMatrix,
//     visited: Vec<bool>,
//     queue: Vec<usize>,
//     y: usize,
// }

// struct BreadthFirstSearch<'a> {
//     unfold: Unfold<BreadthFirstSearchState<'a>,
//         fn(&mut BreadthFirstSearchState) -> Option<Edge>>,
// }

// impl<'a> Iterator for BreadthFirstSearch<'a> {
//     type Item = Edge;

//     fn next(&mut self) -> Option<Edge> {
//         self.unfold.next()
//     }
// }

// impl AdjacencyMatrix {
//     pub fn breadth_first_search(&self, start: usize) -> BreadthFirstSearch {
//         let mut visited = vec!(false; self.size());
//         visited[start] = true;

//         let state = BreadthFirstSearchState {
//             matrix: self,
//             visited: visited,
//             queue: vec![start],
//             y: 0
//         };

//         BreadthFirstSearch { unfold: Unfold::new(state, unfold_breadth_first_search) }
//     }
// }

// fn unfold_breadth_first_search(state: &mut BreadthFirstSearchState) -> Option<Edge> {
//     while !state.queue.is_empty() {
//         let x = state.queue[0];

//         for y in state.y..state.matrix.size() {
//             if state.visited[y] || state.matrix[x][y] == 0 {
//                 continue;
//             }

//             state.visited[y] = true;
//             state.queue.push(y);
//             state.y = y + 1;

//             return Some(Edge { x: x, y: y });
//         }

//         // Process the next element in the queue.
//         state.queue.remove(0);
//         state.y = 0;
//     }

//     None
// }

// Breadth-first search using a callback closure. The implementation is much simpler than the
// iterator-based BFS, however the external API is not as nice (forced to use a callback closure
// instead of a classic for loop).

// impl AdjacencyMatrix {
//     pub fn breadth_first_search<C>(&self, start: usize, mut callback: C)
//        where C: FnMut(Edge) -> bool {

//         let mut visited = vec!(false; self.size());
//         visited[start] = true;

//         let mut queue = vec![start];

//         while queue.len() > 0 {
//             // Dequeue first element.
//             let x = queue.remove(0);

//             for y in 0..self.size() {
//                 if visited[y] || self[x][y] == 0 {
//                     continue;
//                 }
//                 visited[y] = true;
//                 queue.push(y);
//                 // The edge callback can return true to abort the current graph traversal.
//                 if callback(Edge { x: x, y: y }) {
//                     return;
//                 }
//             }
//         }
//     }
// }
<commit_msg>[edge_connectivity/rust] Simplify Unfold-based BFS<commit_after>use std::ops::{Index, IndexMut};
use std::iter::{Iterator, repeat};

use graph::{Edge, Graph};

pub struct AdjacencyMatrix {
    rows: Vec<Vec<u32>>,
}

impl AdjacencyMatrix {
    fn new(size: usize) -> AdjacencyMatrix {
        let row = vec![0; size];
        let rows = repeat(row).take(size).collect();

        AdjacencyMatrix { rows: rows }
    }

    pub fn from_graph(g: &Graph) -> AdjacencyMatrix {
        let mut m = AdjacencyMatrix::new(g.vertex_count);

        for &Edge { x, y } in &g.edges {
            m[x][y] = 1;
            if !g.directed {
                m[y][x] = 1;
            }
        }

        m
    }

    pub fn size(&self) -> usize {
        self.rows.len()
    }
}

// For convenience, enable writing matrix[x] instead of matrix.rows[x].

impl Index<usize> for AdjacencyMatrix {
    type Output = Vec<u32>;

    fn index<'a>(&'a self, _index: usize) -> &'a Vec<u32> {
        &self.rows[_index]
    }
}

impl IndexMut<usize> for AdjacencyMatrix {
    fn index_mut<'a>(&'a mut self, _index: usize) -> &'a mut Vec<u32> {
        &mut self.rows[_index]
    }
}

// Breadth-first search.

struct BreadthFirstSearch<'a> {
    matrix: &'a AdjacencyMatrix,
    visited: Vec<bool>,
    queue: Vec<usize>,
    y: usize,
}

impl AdjacencyMatrix {
    pub fn breadth_first_search(&self, start: usize) -> BreadthFirstSearch {
        let mut visited = vec!(false; self.size());
        visited[start] = true;

        BreadthFirstSearch {
            matrix: self,
            visited: visited,
            queue: vec![start],
            y: 0
        }
    }
}

impl<'a> Iterator for BreadthFirstSearch<'a> {
    type Item = Edge;

    fn next(&mut self) -> Option<Edge> {
        while !self.queue.is_empty() {
            let x = self.queue[0];

            for y in self.y..self.matrix.size() {
                if self.visited[y] || self.matrix[x][y] == 0 {
                    continue;
                }
                self.visited[y] = true;
                self.queue.push(y);
                self.y = y + 1;
                return Some(Edge { x: x, y: y });
            }

            // Process the next element in the queue.
            self.queue.remove(0);
            self.y = 0;
        }

        None
    }
}

// Breadth-first search using std::iter::Unfold. In this situation there's no reason to use it over
// implementing Iterator directly. Unfold seems to shine in situations where we can just pass it a
// closure, but here we cannot use a closure because we need to return an iterator (see
// http://is.gd/2MDM1r).

// struct BFS<'a> {
//     matrix: &'a AdjacencyMatrix,
//     visited: Vec<bool>,
//     queue: Vec<usize>,
//     y: usize,
// }

// impl AdjacencyMatrix {
//     pub fn breadth_first_search(&self, start: usize) ->
//         Unfold<BFS, fn(&mut BFS) -> Option<Edge>> {

//         let mut visited = vec!(false; self.size());
//         visited[start] = true;

//         let state = BFS {
//             matrix: self,
//             visited: visited,
//             queue: vec![start],
//             y: 0
//         };

//         Unfold::new(state, unfold_breadth_first_search)
//     }
// }

// fn unfold_breadth_first_search(state: &mut BFS) -> Option<Edge> {
//     while !state.queue.is_empty() {
//         let x = state.queue[0];

//         for y in state.y..state.matrix.size() {
//             if state.visited[y] || state.matrix[x][y] == 0 {
//                 continue;
//             }

//             state.visited[y] = true;
//             state.queue.push(y);
//             state.y = y + 1;

//             return Some(Edge { x: x, y: y });
//         }

//         // Process the next element in the queue.
//         state.queue.remove(0);
//         state.y = 0;
//     }

//     None
// }

// Breadth-first search using a callback closure. The implementation is much simpler than the
// iterator-based BFS, however the external API is not as nice (forced to use a callback closure
// instead of a classic for loop).

// impl AdjacencyMatrix {
//     pub fn breadth_first_search<C>(&self, start: usize, mut callback: C)
//        where C: FnMut(Edge) -> bool {

//         let mut visited = vec!(false; self.size());
//         visited[start] = true;

//         let mut queue = vec![start];

//         while queue.len() > 0 {
//             // Dequeue first element.
//             let x = queue.remove(0);

//             for y in 0..self.size() {
//                 if visited[y] || self[x][y] == 0 {
//                     continue;
//                 }
//                 visited[y] = true;
//                 queue.push(y);
//                 // The edge callback can return true to abort the current graph traversal.
//                 if callback(Edge { x: x, y: y }) {
//                     return;
//                 }
//             }
//         }
//     }
// }
<|endoftext|>


<commit_before>use std::sync::Arc;
use std::collections::HashMap;
use std::result::Result;
use serde_json::*;

use super::super::tool::*;
use super::super::environment::*;
use super::toolset::*;

///
/// A static environment just contains a set of tools
///
pub struct StaticEnvironment {
    /// The tools in this environment
    tools: HashMap<String, Arc<Box<NamedTool>>>
}

///
/// Wrapper for a tool from a static environment
///
struct StaticEnvironmentTool {
    /// Reference to the tool within the environment
    tool: Arc<Box<NamedTool>>
}

impl Tool for StaticEnvironmentTool {
    fn invoke_json(&self, input: Value, environment: &Environment) -> Result<Value, Value> {
        (**self.tool).invoke_json(input, environment)
    }
}

impl Environment for StaticEnvironment {
    ///
    /// Retrieves a tool using a JSON interface by name
    ///
    fn get_json_tool(&self, name: &str) -> Result<Box<Tool>, RetrieveToolError> {
        let tool = self.tools.get(&String::from(name));

        match tool {
            Some(tool)  => Ok(Box::new(StaticEnvironmentTool { tool: tool.clone() })),
            None        => Err(RetrieveToolError::not_found())
        }
    }
}

impl StaticEnvironment {
    ///
    /// Creates a new static environment from a toolset
    ///
    pub fn from_toolset<T: ToolSet>(set: T, environment: &Environment) -> StaticEnvironment {
        let tools       = set.create_tools(environment);
        let mut tool_hash   = HashMap::new();

        for tool in tools {
            let name = String::from(tool.get_name());

            tool_hash.insert(name, Arc::new(tool));
        }

        StaticEnvironment { tools: tool_hash }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use super::super::functional_tool::*;
    use super::super::empty_environment::*;
    use super::super::basic_toolset::*;

    #[test]
    fn can_get_tool_by_name() {
        let toolset = BasicToolSet::from(vec![
            ("add-1", make_pure_tool(|x: i32| { x+1 })),
            ("add-2", make_pure_tool(|x: i32| { x+2 }))
        ]);
        let environment = StaticEnvironment::from_toolset(toolset, &EmptyEnvironment::new());

        assert!(environment.get_json_tool("add-1").is_ok());
        assert!(environment.get_json_tool("add-2").is_ok());
    }

    #[test]
    fn error_for_missing_tool() {
        let toolset = BasicToolSet::from(vec![
            ("add-1", make_pure_tool(|x: i32| { x+1 })),
            ("add-2", make_pure_tool(|x: i32| { x+2 }))
        ]);
        let environment = StaticEnvironment::from_toolset(toolset, &EmptyEnvironment::new());

        assert!(environment.get_json_tool("add-3").is_err());
    }

    #[test]
    fn tools_are_right() {
        let toolset = BasicToolSet::from(vec![
            ("add-1", make_pure_tool(|x: i32| { x+1 })),
            ("add-2", make_pure_tool(|x: i32| { x+2 }))
        ]);
        let environment = StaticEnvironment::from_toolset(toolset, &EmptyEnvironment::new());

        let add1 = environment.get_json_tool("add-1").unwrap();
        let add2 = environment.get_json_tool("add-2").unwrap();

        assert!(add1.invoke_json(json![ 2 ], &environment) == Ok(json![ 3 ]));
        assert!(add2.invoke_json(json![ 2 ], &environment) == Ok(json![ 4 ]));
    }
}
<commit_msg>Update comments<commit_after>//!
//! A static environment is used to store a fixed set of tools.
//!

use std::sync::Arc;
use std::collections::HashMap;
use std::result::Result;
use serde_json::*;

use super::super::tool::*;
use super::super::environment::*;
use super::toolset::*;

///
/// A static environment just contains a fixed set of tools
///
pub struct StaticEnvironment {
    /// The tools in this environment
    tools: HashMap<String, Arc<Box<NamedTool>>>
}

///
/// Wrapper for a tool from a static environment
///
struct StaticEnvironmentTool {
    /// Reference to the tool within the environment
    tool: Arc<Box<NamedTool>>
}

impl Tool for StaticEnvironmentTool {
    fn invoke_json(&self, input: Value, environment: &Environment) -> Result<Value, Value> {
        (**self.tool).invoke_json(input, environment)
    }
}

impl Environment for StaticEnvironment {
    ///
    /// Retrieves a tool using a JSON interface by name
    ///
    fn get_json_tool(&self, name: &str) -> Result<Box<Tool>, RetrieveToolError> {
        let tool = self.tools.get(&String::from(name));

        match tool {
            Some(tool)  => Ok(Box::new(StaticEnvironmentTool { tool: tool.clone() })),
            None        => Err(RetrieveToolError::not_found())
        }
    }
}

impl StaticEnvironment {
    ///
    /// Creates a new static environment from a toolset
    ///
    pub fn from_toolset<T: ToolSet>(set: T, environment: &Environment) -> StaticEnvironment {
        let tools       = set.create_tools(environment);
        let mut tool_hash   = HashMap::new();

        for tool in tools {
            let name = String::from(tool.get_name());

            tool_hash.insert(name, Arc::new(tool));
        }

        StaticEnvironment { tools: tool_hash }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use super::super::functional_tool::*;
    use super::super::empty_environment::*;
    use super::super::basic_toolset::*;

    #[test]
    fn can_get_tool_by_name() {
        let toolset = BasicToolSet::from(vec![
            ("add-1", make_pure_tool(|x: i32| { x+1 })),
            ("add-2", make_pure_tool(|x: i32| { x+2 }))
        ]);
        let environment = StaticEnvironment::from_toolset(toolset, &EmptyEnvironment::new());

        assert!(environment.get_json_tool("add-1").is_ok());
        assert!(environment.get_json_tool("add-2").is_ok());
    }

    #[test]
    fn error_for_missing_tool() {
        let toolset = BasicToolSet::from(vec![
            ("add-1", make_pure_tool(|x: i32| { x+1 })),
            ("add-2", make_pure_tool(|x: i32| { x+2 }))
        ]);
        let environment = StaticEnvironment::from_toolset(toolset, &EmptyEnvironment::new());

        assert!(environment.get_json_tool("add-3").is_err());
    }

    #[test]
    fn tools_are_right() {
        let toolset = BasicToolSet::from(vec![
            ("add-1", make_pure_tool(|x: i32| { x+1 })),
            ("add-2", make_pure_tool(|x: i32| { x+2 }))
        ]);
        let environment = StaticEnvironment::from_toolset(toolset, &EmptyEnvironment::new());

        let add1 = environment.get_json_tool("add-1").unwrap();
        let add2 = environment.get_json_tool("add-2").unwrap();

        assert!(add1.invoke_json(json![ 2 ], &environment) == Ok(json![ 3 ]));
        assert!(add2.invoke_json(json![ 2 ], &environment) == Ok(json![ 4 ]));
    }
}
<|endoftext|>