<commit_before>// A port of the simplistic benchmark from
//
//    http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.

extern crate extra;
extern crate native;
extern crate zmq;

use std::comm;
use std::os;

fn server(mut pull_socket: zmq::Socket, mut push_socket: zmq::Socket, mut workers: uint) {
    let mut count = 0u;
    let mut msg = zmq::Message::new();

    while workers != 0 {
        match pull_socket.recv(&mut msg, 0) {
            Err(e) => fail!(e.to_str()),
            Ok(()) => {
                msg.with_str(|s| {
                    if s == "" {
                        workers -= 1;
                    } else {
                        count += from_str::<uint>(s).unwrap();
                    }
                })
            }
        }
    }

    match push_socket.send_str(count.to_str(), 0) {
        Ok(()) => { }
        Err(e) => fail!(e.to_str()),
    }
}

fn spawn_server(ctx: &mut zmq::Context, workers: uint) -> comm::Chan<()> {
    let mut pull_socket = ctx.socket(zmq::PULL).unwrap();
    let mut push_socket = ctx.socket(zmq::PUSH).unwrap();

    pull_socket.bind("inproc://server-pull").unwrap();
    push_socket.bind("inproc://server-push").unwrap();

    // Spawn the server.
    let (ready_po, ready_ch) = comm::Chan::new();
    let (start_po, start_ch) = comm::Chan::new();

    // Mutable sockets cannot be implicitly captured.
    let pull_socket = pull_socket;
    let push_socket = push_socket;

    native::task::spawn(proc() {
        // Let the main thread know we're ready.
        ready_ch.send(());

        // Wait until we need to start.
        start_po.recv();

        server(pull_socket, push_socket, workers);
    });

    // Wait for the server to start.
    ready_po.recv();

    start_ch
}

fn worker(mut push_socket: zmq::Socket, count: uint) {
    for _ in range(0, count) {
        push_socket.send_str(100u.to_str(), 0).unwrap();
    }

    // Let the server know we're done.
    push_socket.send_str("", 0).unwrap();
}

fn spawn_worker(ctx: &mut zmq::Context, count: uint) -> comm::Port<()> {
    let mut push_socket = ctx.socket(zmq::PUSH).unwrap();

    push_socket.connect("inproc://server-pull").unwrap();
    //push_socket.connect("tcp://127.0.0.1:3456").unwrap();

    // Mutable sockets cannot be implicitly captured.
    let push_socket = push_socket;

    // Spawn the worker.
    let (po, ch) = comm::Chan::new();
    native::task::spawn(proc() {
        // Let the main thread we're ready.
        ch.send(());

        worker(push_socket, count);

        ch.send(());
    });

    // Wait for the worker to start.
    po.recv();

    po
}

fn run(ctx: &mut zmq::Context, size: uint, workers: uint) {
    let start_ch = spawn_server(ctx, workers);

    // Create some command/control sockets.
    let mut push_socket = ctx.socket(zmq::PUSH).unwrap();
    let mut pull_socket = ctx.socket(zmq::PULL).unwrap();

    push_socket.connect("inproc://server-pull").unwrap();
    pull_socket.connect("inproc://server-push").unwrap();
    //push_socket.connect("tcp://127.0.0.1:3456").unwrap();
    //pull_socket.connect("tcp://127.0.0.1:3457").unwrap();

    // Spawn all the workers.
    let mut worker_results = ~[];
    for _ in range(0, workers) {
        worker_results.push(spawn_worker(ctx, size / workers));
    }

    let start = extra::time::precise_time_s();

    start_ch.send(());

    // Block until all the workers finish.
    for po in worker_results.iter() {
        po.recv();
    }

    // Receive the final count.
    let result = match pull_socket.recv_msg(0) {
        Ok(msg) => msg.with_str(|s| from_str::<uint>(s).unwrap()),
        Err(e) => fail!(e.to_str()),
    };

    let end = extra::time::precise_time_s();
    let elapsed = end - start;

    println!("Count is {}", result);
    println!("Test took {} seconds", elapsed);
    let thruput = ((size / workers * workers) as f64) / elapsed;
    println!("Throughput={:f} per sec", thruput);
}

fn main() {
    let args = os::args();

    let args = if os::getenv("RUST_BENCH").is_some() {
        ~[~"", ~"1000000", ~"10000"]
    } else if args.len() <= 1u {
        ~[~"", ~"10000", ~"4"]
    } else {
        args
    };

    let size = from_str::<uint>(args[1]).unwrap();
    let workers = from_str::<uint>(args[2]).unwrap();

    let mut ctx = zmq::Context::new();

    run(&mut ctx, size, workers);
}
<commit_msg>changed from libextra::time to libtime, based on rust-nightly 201402240406~7cc6b5e~saucy<commit_after>// A port of the simplistic benchmark from
//
//    http://github.com/PaulKeeble/ScalaVErlangAgents
//
// I *think* it's the same, more or less.

extern crate extra;
extern crate native;
extern crate zmq;
extern crate time;

use std::comm;
use std::os;

fn server(mut pull_socket: zmq::Socket, mut push_socket: zmq::Socket, mut workers: uint) {
    let mut count = 0u;
    let mut msg = zmq::Message::new();

    while workers != 0 {
        match pull_socket.recv(&mut msg, 0) {
            Err(e) => fail!(e.to_str()),
            Ok(()) => {
                msg.with_str(|s| {
                    if s == "" {
                        workers -= 1;
                    } else {
                        count += from_str::<uint>(s).unwrap();
                    }
                })
            }
        }
    }

    match push_socket.send_str(count.to_str(), 0) {
        Ok(()) => { }
        Err(e) => fail!(e.to_str()),
    }
}

fn spawn_server(ctx: &mut zmq::Context, workers: uint) -> comm::Chan<()> {
    let mut pull_socket = ctx.socket(zmq::PULL).unwrap();
    let mut push_socket = ctx.socket(zmq::PUSH).unwrap();

    pull_socket.bind("inproc://server-pull").unwrap();
    push_socket.bind("inproc://server-push").unwrap();

    // Spawn the server.
    let (ready_po, ready_ch) = comm::Chan::new();
    let (start_po, start_ch) = comm::Chan::new();

    // Mutable sockets cannot be implicitly captured.
    let pull_socket = pull_socket;
    let push_socket = push_socket;

    native::task::spawn(proc() {
        // Let the main thread know we're ready.
        ready_ch.send(());

        // Wait until we need to start.
        start_po.recv();

        server(pull_socket, push_socket, workers);
    });

    // Wait for the server to start.
    ready_po.recv();

    start_ch
}

fn worker(mut push_socket: zmq::Socket, count: uint) {
    for _ in range(0, count) {
        push_socket.send_str(100u.to_str(), 0).unwrap();
    }

    // Let the server know we're done.
    push_socket.send_str("", 0).unwrap();
}

fn spawn_worker(ctx: &mut zmq::Context, count: uint) -> comm::Port<()> {
    let mut push_socket = ctx.socket(zmq::PUSH).unwrap();

    push_socket.connect("inproc://server-pull").unwrap();
    //push_socket.connect("tcp://127.0.0.1:3456").unwrap();

    // Mutable sockets cannot be implicitly captured.
    let push_socket = push_socket;

    // Spawn the worker.
    let (po, ch) = comm::Chan::new();
    native::task::spawn(proc() {
        // Let the main thread we're ready.
        ch.send(());

        worker(push_socket, count);

        ch.send(());
    });

    // Wait for the worker to start.
    po.recv();

    po
}

fn run(ctx: &mut zmq::Context, size: uint, workers: uint) {
    let start_ch = spawn_server(ctx, workers);

    // Create some command/control sockets.
    let mut push_socket = ctx.socket(zmq::PUSH).unwrap();
    let mut pull_socket = ctx.socket(zmq::PULL).unwrap();

    push_socket.connect("inproc://server-pull").unwrap();
    pull_socket.connect("inproc://server-push").unwrap();
    //push_socket.connect("tcp://127.0.0.1:3456").unwrap();
    //pull_socket.connect("tcp://127.0.0.1:3457").unwrap();

    // Spawn all the workers.
    let mut worker_results = ~[];
    for _ in range(0, workers) {
        worker_results.push(spawn_worker(ctx, size / workers));
    }

    let start = time::precise_time_s();

    start_ch.send(());

    // Block until all the workers finish.
    for po in worker_results.iter() {
        po.recv();
    }

    // Receive the final count.
    let result = match pull_socket.recv_msg(0) {
        Ok(msg) => msg.with_str(|s| from_str::<uint>(s).unwrap()),
        Err(e) => fail!(e.to_str()),
    };

    let end = time::precise_time_s();
    let elapsed = end - start;

    println!("Count is {}", result);
    println!("Test took {} seconds", elapsed);
    let thruput = ((size / workers * workers) as f64) / elapsed;
    println!("Throughput={:f} per sec", thruput);
}

fn main() {
    let args = os::args();

    let args = if os::getenv("RUST_BENCH").is_some() {
        ~[~"", ~"1000000", ~"10000"]
    } else if args.len() <= 1u {
        ~[~"", ~"10000", ~"4"]
    } else {
        args
    };

    let size = from_str::<uint>(args[1]).unwrap();
    let workers = from_str::<uint>(args[2]).unwrap();

    let mut ctx = zmq::Context::new();

    run(&mut ctx, size, workers);
}
<|endoftext|>


<commit_before>use conrod::{self, event, widget, Colorable, Positionable, Widget};
use conrod::widget::primitive::text::Style;
use std::io;
use super::{Error, Screen, theme};
use super::conrod_gfx;
use core::resource::ResourceLoader;
use gfx::{Encoder, Factory, Resources, CommandBuffer};
use gfx::handle::{ShaderResourceView, RenderTargetView};
use frontend::render::formats;

#[derive(Clone, Debug)]
pub struct WidgetIdGroup {
	panel_id: widget::Id,
	label_id: widget::Id,
	value_id: widget::Id,
}

#[derive(Clone, Debug)]
pub struct Ids {
	help_canvas: widget::Id,
	help_text: widget::Id,

	hud_canvas: widget::Id,
	hud_labels: Vec<WidgetIdGroup>,
}

pub struct Ui<'f, R, F>
	where
		R: Resources,
		F: Factory<R> + 'f,
{
	factory: &'f mut F,
	renderer: conrod_gfx::Renderer<R>,
	ui: Box<conrod::Ui>,
	image_map: conrod::image::Map<(ShaderResourceView<R, [f32; 4]>, (u32, u32))>,
	hidpi_factor: f64,
	style_label: Style,
	style_value: Style,
	ids: Ids,
	events: Vec<event::Input>,
}

impl From<conrod::text::font::Error> for Error {
	fn from(_: conrod::text::font::Error) -> Error {
		Error::FontLoader
	}
}

impl From<io::Error> for Error {
	fn from(_: io::Error) -> Error {
		Error::ResourceLoader
	}
}

impl Screen {
	fn draw_widgets<'e>(&self,
	                    ui: &'e mut conrod::Ui,
	                    root_window_id: widget::Id,
	                    style_label: Style,
	                    style_value: Style,
	                    ids: &Ids) -> conrod::UiCell<'e> {
		let mut widgets = ui.set_widgets();

		match self {
			&Screen::Help => {
				let help_text = "Text help";
				widget::Canvas::new()
					.pad(10.0)
					.color(conrod::color::CHARCOAL.alpha(0.4))
					.middle_of(root_window_id)
					.scroll_kids_vertically()
					.set(ids.help_canvas, &mut widgets);

				widget::Text::new(&help_text)
					.middle_of(ids.help_canvas)
					.with_style(style_label)
					.set(ids.help_text, &mut widgets);
			}
			&Screen::Main(ref frame_update) => {
				let mut ids_iter = ids.hud_labels.iter();
				let mut txt_with_label = |label: &str, value: &str| {
					let WidgetIdGroup { panel_id, label_id, value_id } = ids_iter.next().unwrap().clone();
					widget::Canvas::new()
						.pad(10.0)
						.color(conrod::color::CHARCOAL.alpha(0.4))
						.middle_of(root_window_id)
						.set(panel_id, &mut widgets);

					widget::Text::new(label)
						.mid_left_of(panel_id)
						.with_style(style_label)
						.set(label_id, &mut widgets);

					widget::Text::new(value)
						.mid_right_of(panel_id)
						.with_style(style_value)
						.set(value_id, &mut widgets);
				};

				txt_with_label("Sim Frames", &format!("{}", frame_update.simulation.count));
				txt_with_label("Vid Frames", &format!("{}", frame_update.count));
				txt_with_label("Elapsed", &format!("{:.3}", frame_update.elapsed));
				txt_with_label("Sim dt", &format!("{:.3}", frame_update.simulation.dt));
				txt_with_label("Vid dt", &format!("{:.3}", frame_update.dt));
				txt_with_label(">>", &format!("x{}", frame_update.speed_factor));
				txt_with_label("Avg dt", &format!("{:.3}", frame_update.duration_smooth));
				txt_with_label("FPS", &format!("{:.1}", frame_update.fps));
				txt_with_label("Population", &format!("{}", frame_update.simulation.population));
				txt_with_label("Extinctions", &format!("{}", frame_update.simulation.extinctions));
			}
		};
		widgets
	}
}

impl<'f, R, F> Ui<'f, R, F> where
	R: Resources,
	F: Factory<R> + 'f, {
	pub fn new<'e, L>(res: &L,
	                  factory: &'e mut F,
	                  frame_buffer: &RenderTargetView<R, formats::ScreenColorFormat>,
	                  hidpi_factor: f64) -> Result<Ui<'f, R, F>, Error>
		where L: ResourceLoader<u8>, 'e: 'f {
		let renderer = conrod_gfx::Renderer::new(factory, frame_buffer, hidpi_factor).unwrap();
		let image_map = conrod::image::Map::new();
		let (w, h, _, _) = frame_buffer.get_dimensions();
		let mut ui = conrod::UiBuilder::new([w as f64, h as f64]).theme(theme::default_theme()).build();

		Self::load_font(res, &mut ui.fonts, "fonts/FreeSans.ttf")?;

		let style_label = Style {
			color: Some(conrod::color::WHITE),
			font_size: Some(20),
			..Default::default()
		};
		let style_value = Style {
			color: Some(conrod::color::WHITE),
			font_size: Some(20),
			..Default::default()
		};

		let ids = Ids {
			help_canvas: ui.widget_id_generator().next(),
			help_text: ui.widget_id_generator().next(),

			hud_canvas: ui.widget_id_generator().next(),
			hud_labels: (0..10)
				.map(|_| {
					WidgetIdGroup {
						panel_id: ui.widget_id_generator().next(),
						label_id: ui.widget_id_generator().next(),
						value_id: ui.widget_id_generator().next(),
					}
				})
				.collect()
		};

		Ok(Ui {
			factory,
			renderer,
			ui: Box::new(ui),
			image_map,
			hidpi_factor,
			style_label,
			style_value,
			ids,
			events: Vec::new(),
		})
	}

	pub fn resize_to(&mut self,
	                 frame_buffer: &RenderTargetView<R, formats::ScreenColorFormat>)
	                 -> Result<(), Error> {
		let hidpi_factor = self.hidpi_factor;
		self.renderer = conrod_gfx::Renderer::new(self.factory, frame_buffer, hidpi_factor).unwrap();
		Ok(())
	}

	fn load_font<L>(res: &L, map: &mut conrod::text::font::Map, key: &str) ->
	Result<conrod::text::font::Id, Error>
		where L: ResourceLoader<u8> {
		let font_bytes = res.load(key)?;
		let font_collection = conrod::text::FontCollection::from_bytes(font_bytes);
		let default_font = font_collection.into_font().ok_or(Error::FontLoader)?;
		let id = map.insert(default_font);
		Ok(id)
	}

	pub fn draw_screen<C>(&mut self, screen: &Screen, encoder: &mut Encoder<R, C>)
		where C: CommandBuffer<R> {
		let dims = (self.ui.win_w as f32, self.ui.win_h as f32);
		let window_id = self.ui.window.clone();
		let widgets = screen.draw_widgets(&mut self.ui,
		                                  window_id,
		                                  self.style_label.clone(),
		                                  self.style_value.clone(),
		                                  &self.ids.clone());
		let primitives = widgets.draw();
		self.renderer.fill(encoder, dims, primitives, &self.image_map);
		self.renderer.draw(self.factory, encoder, &self.image_map);
	}

	pub fn push_event(&mut self, event: event::Input) {
		self.events.push(event);
	}

	pub fn handle_events(&mut self) {
		for event in &self.events {
			self.ui.handle_event(event.clone())
		}
		self.events.clear();
	}
}<commit_msg>Widget simple table layout<commit_after>use conrod::{self, event, widget, Colorable, Positionable, Sizeable, Widget};
use conrod::widget::primitive::text::Style;
use std::io;
use super::{Error, Screen, theme};
use super::conrod_gfx;
use core::resource::ResourceLoader;
use gfx::{Encoder, Factory, Resources, CommandBuffer};
use gfx::handle::{ShaderResourceView, RenderTargetView};
use frontend::render::formats;

#[derive(Clone, Debug)]
pub struct WidgetIdGroup {
	panel_row_id: widget::Id,
	panel_id: widget::Id,
	label_id: widget::Id,
	value_id: widget::Id,
}

#[derive(Clone, Debug)]
pub struct Ids {
	help_canvas: widget::Id,
	help_text: widget::Id,

	hud_canvas: widget::Id,
	hud_labels: Vec<WidgetIdGroup>,
}

pub struct Ui<'f, R, F>
	where
		R: Resources,
		F: Factory<R> + 'f,
{
	factory: &'f mut F,
	renderer: conrod_gfx::Renderer<R>,
	ui: Box<conrod::Ui>,
	image_map: conrod::image::Map<(ShaderResourceView<R, [f32; 4]>, (u32, u32))>,
	hidpi_factor: f64,
	style_label: Style,
	style_value: Style,
	ids: Ids,
	events: Vec<event::Input>,
}

impl From<conrod::text::font::Error> for Error {
	fn from(_: conrod::text::font::Error) -> Error {
		Error::FontLoader
	}
}

impl From<io::Error> for Error {
	fn from(_: io::Error) -> Error {
		Error::ResourceLoader
	}
}

impl Screen {
	fn draw_widgets<'e>(&self,
						ui: &'e mut conrod::Ui,
						root_window_id: widget::Id,
						style_label: Style,
						style_value: Style,
						ids: &Ids) -> conrod::UiCell<'e> {
		let mut widgets = ui.set_widgets();

		match self {
			&Screen::Help => {
				let help_text = "Text help";
				widget::Canvas::new()
					.pad(10.0)
					.color(conrod::color::CHARCOAL.alpha(0.4))
					.middle_of(root_window_id)
					.scroll_kids_vertically()
					.set(ids.help_canvas, &mut widgets);

				widget::Text::new(&help_text)
					.middle_of(ids.help_canvas)
					.with_style(style_label)
					.set(ids.help_text, &mut widgets);
			}
			&Screen::Main(ref frame_update) => {
				let splits = ids.hud_labels.iter()
					.map(|&WidgetIdGroup { panel_row_id, .. }|
						(panel_row_id, widget::Canvas::new().color(conrod::color::TRANSPARENT)))
					.collect::<Vec<_>>();
				;
				widget::Canvas::new()
					.pad(50.0)
					.color(conrod::color::TRANSPARENT)
					.kid_area_w_of(root_window_id)
					.mid_top()
					.flow_down(&splits)
					.set(ids.hud_canvas, &mut widgets);
				let mut ids_iter = ids.hud_labels.iter();
				let mut txt_with_label = |label: &str, value: &str| {
					let WidgetIdGroup { panel_id, label_id, value_id, panel_row_id } = ids_iter.next().unwrap().clone();

					widget::Canvas::new()
						.mid_left_of(panel_row_id)
						.pad(10.0)
						.color(conrod::color::CHARCOAL.alpha(0.4))
						.w(300.0)
						.h(60.0)
						.set(panel_id, &mut widgets);

					widget::Text::new(label)
						.mid_left_of(panel_id)
						.with_style(style_label)
						.set(label_id, &mut widgets);

					widget::Text::new(value)
						.mid_right_of(panel_id)
						.with_style(style_value)
						.set(value_id, &mut widgets);
				};

				txt_with_label("Sim Frames", &format!("{}", frame_update.simulation.count));
				txt_with_label("Vid Frames", &format!("{}", frame_update.count));
				txt_with_label("Elapsed", &format!("{:.3}", frame_update.elapsed));
				txt_with_label("Sim dt", &format!("{:.3}", frame_update.simulation.dt));
				txt_with_label("Vid dt", &format!("{:.3}", frame_update.dt));
				txt_with_label(">>", &format!("x{}", frame_update.speed_factor));
				txt_with_label("Avg dt", &format!("{:.3}", frame_update.duration_smooth));
				txt_with_label("FPS", &format!("{:.1}", frame_update.fps));
				txt_with_label("Population", &format!("{}", frame_update.simulation.population));
				txt_with_label("Extinctions", &format!("{}", frame_update.simulation.extinctions));
			}
		};
		widgets
	}
}

impl<'f, R, F> Ui<'f, R, F> where
	R: Resources,
	F: Factory<R> + 'f, {
	pub fn new<'e, L>(res: &L,
					  factory: &'e mut F,
					  frame_buffer: &RenderTargetView<R, formats::ScreenColorFormat>,
					  hidpi_factor: f64) -> Result<Ui<'f, R, F>, Error>
		where L: ResourceLoader<u8>, 'e: 'f {
		let renderer = conrod_gfx::Renderer::new(factory, frame_buffer, hidpi_factor).unwrap();
		let image_map = conrod::image::Map::new();
		let (w, h, _, _) = frame_buffer.get_dimensions();
		let mut ui = conrod::UiBuilder::new([w as f64, h as f64]).theme(theme::default_theme()).build();

		Self::load_font(res, &mut ui.fonts, "fonts/FreeSans.ttf")?;

		let style_label = Style {
			color: Some(conrod::color::LIGHT_GRAY),
			font_size: Some(14),
			..Default::default()
		};
		let style_value = Style {
			color: Some(conrod::color::GREEN),
			font_size: Some(14),
			..Default::default()
		};

		let ids = Ids {
			help_canvas: ui.widget_id_generator().next(),
			help_text: ui.widget_id_generator().next(),

			hud_canvas: ui.widget_id_generator().next(),
			hud_labels: (0..10)
				.map(|_| {
					WidgetIdGroup {
						panel_row_id: ui.widget_id_generator().next(),
						panel_id: ui.widget_id_generator().next(),
						label_id: ui.widget_id_generator().next(),
						value_id: ui.widget_id_generator().next(),
					}
				})
				.collect()
		};

		Ok(Ui {
			factory,
			renderer,
			ui: Box::new(ui),
			image_map,
			hidpi_factor,
			style_label,
			style_value,
			ids,
			events: Vec::new(),
		})
	}

	pub fn resize_to(&mut self,
					 frame_buffer: &RenderTargetView<R, formats::ScreenColorFormat>)
					 -> Result<(), Error> {
		let hidpi_factor = self.hidpi_factor;
		self.renderer = conrod_gfx::Renderer::new(self.factory, frame_buffer, hidpi_factor).unwrap();
		Ok(())
	}

	fn load_font<L>(res: &L, map: &mut conrod::text::font::Map, key: &str) ->
	Result<conrod::text::font::Id, Error>
		where L: ResourceLoader<u8> {
		let font_bytes = res.load(key)?;
		let font_collection = conrod::text::FontCollection::from_bytes(font_bytes);
		let default_font = font_collection.into_font().ok_or(Error::FontLoader)?;
		let id = map.insert(default_font);
		Ok(id)
	}

	pub fn draw_screen<C>(&mut self, screen: &Screen, encoder: &mut Encoder<R, C>)
		where C: CommandBuffer<R> {
		let dims = (self.ui.win_w as f32, self.ui.win_h as f32);
		let window_id = self.ui.window.clone();
		let widgets = screen.draw_widgets(&mut self.ui,
										  window_id,
										  self.style_label.clone(),
										  self.style_value.clone(),
										  &self.ids.clone());
		let primitives = widgets.draw();
		self.renderer.fill(encoder, dims, primitives, &self.image_map);
		self.renderer.draw(self.factory, encoder, &self.image_map);
	}

	pub fn push_event(&mut self, event: event::Input) {
		self.events.push(event);
	}

	pub fn handle_events(&mut self) {
		for event in &self.events {
			self.ui.handle_event(event.clone())
		}
		self.events.clear();
	}
}<|endoftext|>


<commit_before>use std::collections::HashSet;
use super::bls::{
    AggregateSignature,
    AggregatePublicKey,
};
use super::db::ClientDB;
use super::db::stores::{
    ValidatorStore,
    ValidatorStoreError,
};
use super::utils::types::Bitfield;

#[derive(Debug, PartialEq)]
pub enum SignatureVerificationError {
    BadValidatorIndex,
    PublicKeyCorrupt,
    NoPublicKeyForValidator,
    DBError(String),
}

fn verify_aggregate_signature_for_indices<T>(message: &[u8],
                                             agg_sig: &AggregateSignature,
                                             attestation_indices: &[usize],
                                             bitfield: &Bitfield,
                                             validator_store: &ValidatorStore<T>)
    -> Result<(bool, Option<HashSet<usize>>), SignatureVerificationError>
    where T: ClientDB + Sized
{
    let mut voters = HashSet::new();
    let mut agg_pub_key = AggregatePublicKey::new();

    for i in 0..attestation_indices.len() {
        let voted = bitfield.get_bit(i);
        if voted {
            let validator = attestation_indices[i];
            let pub_key = validator_store.get_public_key_by_index(i)?
                .ok_or(SignatureVerificationError::NoPublicKeyForValidator)?;
            agg_pub_key.add(&pub_key);
            voters.insert(validator);
        }
    }
    if agg_sig.verify(&message, &agg_pub_key) {
        Ok((true, Some(voters)))
    } else {
        Ok((false, None))
    }
}

impl From<ValidatorStoreError> for SignatureVerificationError {
    fn from(error: ValidatorStoreError) -> Self {
        match error {
            ValidatorStoreError::DBError(s) =>
                SignatureVerificationError::DBError(s),
            ValidatorStoreError::DecodeError =>
                SignatureVerificationError::PublicKeyCorrupt,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::bls::{
        Keypair,
        Signature,
    };
    use super::super::db::MemoryDB;
    use std::sync::Arc;

    #[test]
    fn test_signature_verification() {
        let message = "cats".as_bytes();
        let signing_keypairs = vec![
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
        ];
        let non_signing_keypairs = vec![
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
        ];
        /*
         * Signing keypairs first, then non-signing
         */
        let mut all_keypairs = signing_keypairs.clone();
        all_keypairs.append(&mut non_signing_keypairs.clone());

        let attestation_indices: Vec<usize> = (0..all_keypairs.len())
            .collect();
        let mut bitfield = Bitfield::new();
        for i in 0..signing_keypairs.len() {
            bitfield.set_bit(i, true);
        }

        let db = Arc::new(MemoryDB::open());
        let store = ValidatorStore::new(db);

        for (i, keypair) in all_keypairs.iter().enumerate() {
            store.put_public_key_by_index(i, &keypair.pk).unwrap();
        }

        let mut agg_sig = AggregateSignature::new();
        for keypair in &signing_keypairs {
            let sig = Signature::new(&message, &keypair.sk);
            agg_sig.add(&sig);
        }

        /*
         * Test using all valid parameters.
         */
        let (is_valid, voters) = verify_aggregate_signature_for_indices(
            &message,
            &agg_sig,
            &attestation_indices,
            &bitfield,
            &store).unwrap();

        let voters = voters.unwrap();
        assert_eq!(is_valid, true);
        (0..signing_keypairs.len())
            .for_each(|i| assert!(voters.contains(&i)));
        (signing_keypairs.len()..non_signing_keypairs.len())
            .for_each(|i| assert!(!voters.contains(&i)));

        /*
         * Add another validator to the bitfield, run validation will all other
         * parameters the same and assert that it fails.
         */
        bitfield.set_bit(signing_keypairs.len() + 1, true);
        let (is_valid, voters) = verify_aggregate_signature_for_indices(
            &message,
            &agg_sig,
            &attestation_indices,
            &bitfield,
            &store).unwrap();

        assert_eq!(is_valid, false);
        assert_eq!(voters, None);
    }
}
<commit_msg>Tidy validation signatures<commit_after>use std::collections::HashSet;
use super::bls::{
    AggregateSignature,
    AggregatePublicKey,
};
use super::db::ClientDB;
use super::db::stores::{
    ValidatorStore,
    ValidatorStoreError,
};
use super::utils::types::Bitfield;

#[derive(Debug, PartialEq)]
pub enum SignatureVerificationError {
    BadValidatorIndex,
    PublicKeyCorrupt,
    NoPublicKeyForValidator,
    DBError(String),
}

pub fn verify_aggregate_signature_for_indices<T>(
    message: &[u8],
    agg_sig: &AggregateSignature,
    attestation_indices: &[usize],
    bitfield: &Bitfield,
    validator_store: &ValidatorStore<T>)
    -> Result<(bool, Option<HashSet<usize>>), SignatureVerificationError>
    where T: ClientDB + Sized
{
    let mut voters = HashSet::new();
    let mut agg_pub_key = AggregatePublicKey::new();

    for i in 0..attestation_indices.len() {
        let voted = bitfield.get_bit(i);
        if voted {
            let validator = attestation_indices[i];
            let pub_key = validator_store.get_public_key_by_index(i)?
                .ok_or(SignatureVerificationError::NoPublicKeyForValidator)?;
            agg_pub_key.add(&pub_key);
            voters.insert(validator);
        }
    }
    if agg_sig.verify(&message, &agg_pub_key) {
        Ok((true, Some(voters)))
    } else {
        Ok((false, None))
    }
}

impl From<ValidatorStoreError> for SignatureVerificationError {
    fn from(error: ValidatorStoreError) -> Self {
        match error {
            ValidatorStoreError::DBError(s) =>
                SignatureVerificationError::DBError(s),
            ValidatorStoreError::DecodeError =>
                SignatureVerificationError::PublicKeyCorrupt,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::bls::{
        Keypair,
        Signature,
    };
    use super::super::db::MemoryDB;
    use std::sync::Arc;

    /*
     * Cases that still need testing:
     *
     * - No signatures.
     * - Database failure.
     * - Unknown validator index.
     * - Extra validator on signature.
     */

    #[test]
    fn test_signature_verification() {
        let message = "cats".as_bytes();
        let signing_keypairs = vec![
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
        ];
        let non_signing_keypairs = vec![
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
            Keypair::random(),
        ];
        /*
         * Signing keypairs first, then non-signing
         */
        let mut all_keypairs = signing_keypairs.clone();
        all_keypairs.append(&mut non_signing_keypairs.clone());

        let attestation_indices: Vec<usize> = (0..all_keypairs.len())
            .collect();
        let mut bitfield = Bitfield::new();
        for i in 0..signing_keypairs.len() {
            bitfield.set_bit(i, true);
        }

        let db = Arc::new(MemoryDB::open());
        let store = ValidatorStore::new(db);

        for (i, keypair) in all_keypairs.iter().enumerate() {
            store.put_public_key_by_index(i, &keypair.pk).unwrap();
        }

        let mut agg_sig = AggregateSignature::new();
        for keypair in &signing_keypairs {
            let sig = Signature::new(&message, &keypair.sk);
            agg_sig.add(&sig);
        }

        /*
         * Test using all valid parameters.
         */
        let (is_valid, voters) = verify_aggregate_signature_for_indices(
            &message,
            &agg_sig,
            &attestation_indices,
            &bitfield,
            &store).unwrap();

        let voters = voters.unwrap();
        assert_eq!(is_valid, true);
        (0..signing_keypairs.len())
            .for_each(|i| assert!(voters.contains(&i)));
        (signing_keypairs.len()..non_signing_keypairs.len())
            .for_each(|i| assert!(!voters.contains(&i)));

        /*
         * Add another validator to the bitfield, run validation will all other
         * parameters the same and assert that it fails.
         */
        bitfield.set_bit(signing_keypairs.len() + 1, true);
        let (is_valid, voters) = verify_aggregate_signature_for_indices(
            &message,
            &agg_sig,
            &attestation_indices,
            &bitfield,
            &store).unwrap();

        assert_eq!(is_valid, false);
        assert_eq!(voters, None);
    }
}
<|endoftext|>


<commit_before>use json_flex;
use json_flex::JFObject;

#[derive(Clone)]
pub struct Rows {
    data: Option<Vec<JFObject>>
}

/// A result rows representing type.
/// This type is usually generated by [`ResultParser#into_raw()`](struct.ResultParser.html#method.into_row).
impl Rows {
    pub fn new(data: Option<Vec<JFObject>>) -> Rows {
        Rows { data: data }
    }

    /// Get columns in `Rows`.
    pub fn columns(&mut self) -> Option<Vec<JFObject>> {
        let popable = match self.data.clone() {
            Some(v) => v,
            None => return None
        };
        let pop = match popable.clone().pop() {
            Some(v) => v,
            None => return None
        };
        match pop.into_vec().clone() {
            Some(v) => return Some(v.clone()),
            None => return None
        }
    }
}

#[derive(Clone, Debug)]
pub struct ResultParser {
    result: Box<JFObject>
}

/// ResultParser
///
/// Groonga returns following array json:
///
/// success response:
/// `[[status, start_time, elapsed_time],
///   [[[matched_columns], [Array([column1, type1], ...)],
///     [Array([result1, result2, ...])]]]]`
///
/// error response:
/// `[[status, start_time, elapsed_time, error_information, ...]]`
impl ResultParser {
    pub fn new(json: String) -> ResultParser {
        ResultParser{result: json_flex::decode(json)}
    }

    /// Get raw response result.
    pub fn get_raw_object(&mut self) -> Box<JFObject> {
        self.result.clone()
    }

    /// Return header elements in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn get_header(&mut self) -> JFObject {
        self.result[0].clone()
    }

    /// Return status in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn status(&mut self) -> Option<&i64> {
        self.result[0][0].into_i64()
    }

    /// Return start time in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn start_time(&mut self) -> Option<&f64> {
        self.result[0][1].into_f64()
    }

    /// Return elapsed time in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn elapsed_time(&mut self) -> Option<&f64> {
        self.result[0][2].into_f64()
    }

    /// [nodoc]
    #[inline]
    fn matched_columns_num(&mut self) -> Option<i64> {
        let vectoizable = match self.result[1][0][0].into_vec().clone() {
            Some(elem) => elem,
            None => return None
        };
        let pop = match vectoizable.clone().pop() {
            Some(pop) => pop,
            None => return None
        };
        match pop.into_i64().clone() {
            Some(v) => return Some(v.clone()),
            None => return None
        }
    }

    /// Return a number of matched columns in response.
    pub fn matched_columns(&mut self) -> Option<i64> {
        match self.status() {
            Some(&0) => self.matched_columns_num(),
            Some(_) => None,
            None    => None
        }
    }

    /// Get result in response.
    ///
    /// If request succeeded, it can get matched result array.
    /// Otherwise, one can get error messages.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn result(&mut self) -> Option<Vec<JFObject>> {
        match self.status() {
            Some(&0) => Some(vec![self.result[1][0].clone()]),
            Some(_) => Some(vec![self.result[0][3].clone()]),
            None    => None
        }
    }

    /// Convert to `Rows` type and return its type values.
    pub fn into_row(&mut self) -> Rows {
        Rows::new(self.result())
    }
}

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

    const RESPONSE: &'static str = "
    [[0,1452348610.39281,0.000101566314697266],
    [[[9],
     [[\"_id\",\"UInt32\"],[\"_key\",\"ShortText\"],[\"title\",\"ShortText\"]],
     [1,\"http://example.org/\",\"This is test record 1!\"],
     [2,\"http://example.net/\",\"test record 2.\"],
     [3,\"http://example.com/\",\"test test record three.\"],
     [4,\"http://example.net/afr\",\"test record four.\"],
     [5,\"http://example.org/aba\",\"test test test record five.\"],
     [6,\"http://example.com/rab\",\"test test test test record six.\"],
     [7,\"http://example.net/atv\",\"test test test record seven.\"],
     [8,\"http://example.org/gat\",\"test test record eight.\"],
     [9,\"http://example.com/vdw\",\"test test record nine.\"]]]]";

    #[test]
    fn parse_result() {
        let mut decode = ResultParser::new(RESPONSE.to_string());
        assert_eq!(&0, decode.status().unwrap());
        assert_eq!(&1452348610.39281, decode.start_time().unwrap());
        assert_eq!(&0.000101566314697266, decode.elapsed_time().unwrap());
        assert_eq!(9, decode.matched_columns().unwrap());
        let vec = decode.result().unwrap().pop().unwrap().unwrap_vec().clone();
        let expected = r#"Array([Integer(1), String("http://example.org/"), String("This is test record 1!")])"#.to_owned();
        assert_eq!(expected, format!("{:?}", vec[2]))
    }

    #[test]
    fn row_columns() {
        let mut decode = ResultParser::new(RESPONSE.to_string());
        let vec = decode.into_row().columns().unwrap();
        let expected = r#"Array([Integer(1), String("http://example.org/"), String("This is test record 1!")])"#.to_owned();
        assert_eq!(expected, format!("{:?}", vec[2]))
    }
}
<commit_msg>Remove needless return<commit_after>use json_flex;
use json_flex::JFObject;

#[derive(Clone)]
pub struct Rows {
    data: Option<Vec<JFObject>>
}

/// A result rows representing type.
/// This type is usually generated by [`ResultParser#into_raw()`](struct.ResultParser.html#method.into_row).
impl Rows {
    pub fn new(data: Option<Vec<JFObject>>) -> Rows {
        Rows { data: data }
    }

    /// Get columns in `Rows`.
    pub fn columns(&mut self) -> Option<Vec<JFObject>> {
        let popable = match self.data.clone() {
            Some(v) => v,
            None => return None
        };
        let pop = match popable.clone().pop() {
            Some(v) => v,
            None => return None
        };
        match pop.into_vec().clone() {
            Some(v) => Some(v.clone()),
            None => None
        }
    }
}

#[derive(Clone, Debug)]
pub struct ResultParser {
    result: Box<JFObject>
}

/// ResultParser
///
/// Groonga returns following array json:
///
/// success response:
/// `[[status, start_time, elapsed_time],
///   [[[matched_columns], [Array([column1, type1], ...)],
///     [Array([result1, result2, ...])]]]]`
///
/// error response:
/// `[[status, start_time, elapsed_time, error_information, ...]]`
impl ResultParser {
    pub fn new(json: String) -> ResultParser {
        ResultParser{result: json_flex::decode(json)}
    }

    /// Get raw response result.
    pub fn get_raw_object(&mut self) -> Box<JFObject> {
        self.result.clone()
    }

    /// Return header elements in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn get_header(&mut self) -> JFObject {
        self.result[0].clone()
    }

    /// Return status in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn status(&mut self) -> Option<&i64> {
        self.result[0][0].into_i64()
    }

    /// Return start time in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn start_time(&mut self) -> Option<&f64> {
        self.result[0][1].into_f64()
    }

    /// Return elapsed time in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn elapsed_time(&mut self) -> Option<&f64> {
        self.result[0][2].into_f64()
    }

    /// [nodoc]
    #[inline]
    fn matched_columns_num(&mut self) -> Option<i64> {
        let vectoizable = match self.result[1][0][0].into_vec().clone() {
            Some(elem) => elem,
            None => return None
        };
        let pop = match vectoizable.clone().pop() {
            Some(pop) => pop,
            None => return None
        };
        match pop.into_i64().clone() {
            Some(v) => Some(v.clone()),
            None => None
        }
    }

    /// Return a number of matched columns in response.
    pub fn matched_columns(&mut self) -> Option<i64> {
        match self.status() {
            Some(&0) => self.matched_columns_num(),
            Some(_) => None,
            None    => None
        }
    }

    /// Get result in response.
    ///
    /// If request succeeded, it can get matched result array.
    /// Otherwise, one can get error messages.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn result(&mut self) -> Option<Vec<JFObject>> {
        match self.status() {
            Some(&0) => Some(vec![self.result[1][0].clone()]),
            Some(_) => Some(vec![self.result[0][3].clone()]),
            None    => None
        }
    }

    /// Convert to `Rows` type and return its type values.
    pub fn into_row(&mut self) -> Rows {
        Rows::new(self.result())
    }
}

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

    const RESPONSE: &'static str = "
    [[0,1452348610.39281,0.000101566314697266],
    [[[9],
     [[\"_id\",\"UInt32\"],[\"_key\",\"ShortText\"],[\"title\",\"ShortText\"]],
     [1,\"http://example.org/\",\"This is test record 1!\"],
     [2,\"http://example.net/\",\"test record 2.\"],
     [3,\"http://example.com/\",\"test test record three.\"],
     [4,\"http://example.net/afr\",\"test record four.\"],
     [5,\"http://example.org/aba\",\"test test test record five.\"],
     [6,\"http://example.com/rab\",\"test test test test record six.\"],
     [7,\"http://example.net/atv\",\"test test test record seven.\"],
     [8,\"http://example.org/gat\",\"test test record eight.\"],
     [9,\"http://example.com/vdw\",\"test test record nine.\"]]]]";

    #[test]
    fn parse_result() {
        let mut decode = ResultParser::new(RESPONSE.to_string());
        assert_eq!(&0, decode.status().unwrap());
        assert_eq!(&1452348610.39281, decode.start_time().unwrap());
        assert_eq!(&0.000101566314697266, decode.elapsed_time().unwrap());
        assert_eq!(9, decode.matched_columns().unwrap());
        let vec = decode.result().unwrap().pop().unwrap().unwrap_vec().clone();
        let expected = r#"Array([Integer(1), String("http://example.org/"), String("This is test record 1!")])"#.to_owned();
        assert_eq!(expected, format!("{:?}", vec[2]))
    }

    #[test]
    fn row_columns() {
        let mut decode = ResultParser::new(RESPONSE.to_string());
        let vec = decode.into_row().columns().unwrap();
        let expected = r#"Array([Integer(1), String("http://example.org/"), String("This is test record 1!")])"#.to_owned();
        assert_eq!(expected, format!("{:?}", vec[2]))
    }
}
<|endoftext|>


<commit_before>use json_flex;
use json_flex::JFObject;

#[derive(Clone)]
pub struct Rows {
    data: Option<Vec<JFObject>>
}

/// A result rows representing type.
/// This type is usually generated by [`ResultParser#into_raw()`](struct.ResultParser.html#method.into_row).
impl Rows {
    pub fn new(data: Option<Vec<JFObject>>) -> Rows {
        Rows { data: data }
    }

    /// Get columns in `Rows`.
    pub fn columns(&mut self) -> Option<Vec<JFObject>> {
        let popable = match self.data.clone() {
            Some(v) => v,
            None => return None
        };
        let pop = match popable.clone().pop() {
            Some(v) => v,
            None => return None
        };
        match pop.into_vec().clone() {
            Some(v) => return Some(v.clone()),
            None => return None
        }
    }
}

#[derive(Clone, Debug)]
pub struct ResultParser {
    result: Box<JFObject>
}

/// ResultParser
///
/// Groonga returns following array json:
///
/// success response:
/// `[[status,start_time, elapsed_time],
///   [[[matched_columns],[Array([column1,type1], ...)],
///     [Array([result1, result2, ...])]]]]`
///
/// error response:
/// `[[status,start_time, elapsed_time, error_information, ...]]`
impl ResultParser {
    pub fn new(json: String) -> ResultParser {
        ResultParser{result: json_flex::decode(json)}
    }

    /// Get raw response result.
    pub fn get_raw_object(&mut self) -> Box<JFObject> {
        self.result.clone()
    }

    /// Return header elements in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn get_header(&mut self) -> JFObject {
        self.result[0].clone()
    }

    /// Return status in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn status(&mut self) -> Option<&i64> {
        self.result[0][0].into_i64()
    }

    /// Return start time in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn start_time(&mut self) -> Option<&f64> {
        self.result[0][1].into_f64()
    }

    /// Return elapsed time in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn elapsed_time(&mut self) -> Option<&f64> {
        self.result[0][2].into_f64()
    }

    /// [nodoc]
    #[inline]
    fn matched_columns_num(&mut self) -> Option<i64> {
        let vectoizable = match self.result[1][0][0].into_vec().clone() {
            Some(elem) => elem,
            None => return None
        };
        let pop = match vectoizable.clone().pop() {
            Some(pop) => pop,
            None => return None
        };
        match pop.into_i64().clone() {
            Some(v) => return Some(v.clone()),
            None => return None
        }
    }

    /// Return a number of matched columns in response.
    pub fn matched_columns(&mut self) -> Option<i64> {
        match self.status() {
            Some(&0) => self.matched_columns_num(),
            Some(_) => None,
            None    => None
        }
    }

    /// Get result in response.
    ///
    /// If request succeeded, it can get matched result array.
    /// Otherwise, one can get error messages.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn result(&mut self) -> Option<Vec<JFObject>> {
        match self.status() {
            Some(&0) => Some(vec![self.result[1][0].clone()]),
            Some(_) => Some(vec![self.result[0][3].clone()]),
            None    => None
        }
    }

    /// Convert to `Rows` type and return its type values.
    pub fn into_row(&mut self) -> Rows {
        Rows::new(self.result())
    }
}

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

    const RESPONSE: &'static str = "
    [[0,1452348610.39281,0.000101566314697266],
    [[[9],
     [[\"_id\",\"UInt32\"],[\"_key\",\"ShortText\"],[\"title\",\"ShortText\"]],
     [1,\"http://example.org/\",\"This is test record 1!\"],
     [2,\"http://example.net/\",\"test record 2.\"],
     [3,\"http://example.com/\",\"test test record three.\"],
     [4,\"http://example.net/afr\",\"test record four.\"],
     [5,\"http://example.org/aba\",\"test test test record five.\"],
     [6,\"http://example.com/rab\",\"test test test test record six.\"],
     [7,\"http://example.net/atv\",\"test test test record seven.\"],
     [8,\"http://example.org/gat\",\"test test record eight.\"],
     [9,\"http://example.com/vdw\",\"test test record nine.\"]]]]";

    #[test]
    fn parse_result() {
        let mut decode = ResultParser::new(RESPONSE.to_string());
        assert_eq!(&0, decode.status().unwrap());
        assert_eq!(&1452348610.39281, decode.start_time().unwrap());
        assert_eq!(&0.000101566314697266, decode.elapsed_time().unwrap());
        assert_eq!(9, decode.matched_columns().unwrap());
        let vec = decode.result().unwrap().pop().unwrap().unwrap_vec().clone();
        let expected = r#"Array([Integer(1), String("http://example.org/"), String("This is test record 1!")])"#.to_owned();
        assert_eq!(expected, format!("{:?}", vec[2]))
    }
}
<commit_msg>test: Add Rows type into_row() test<commit_after>use json_flex;
use json_flex::JFObject;

#[derive(Clone)]
pub struct Rows {
    data: Option<Vec<JFObject>>
}

/// A result rows representing type.
/// This type is usually generated by [`ResultParser#into_raw()`](struct.ResultParser.html#method.into_row).
impl Rows {
    pub fn new(data: Option<Vec<JFObject>>) -> Rows {
        Rows { data: data }
    }

    /// Get columns in `Rows`.
    pub fn columns(&mut self) -> Option<Vec<JFObject>> {
        let popable = match self.data.clone() {
            Some(v) => v,
            None => return None
        };
        let pop = match popable.clone().pop() {
            Some(v) => v,
            None => return None
        };
        match pop.into_vec().clone() {
            Some(v) => return Some(v.clone()),
            None => return None
        }
    }
}

#[derive(Clone, Debug)]
pub struct ResultParser {
    result: Box<JFObject>
}

/// ResultParser
///
/// Groonga returns following array json:
///
/// success response:
/// `[[status,start_time, elapsed_time],
///   [[[matched_columns],[Array([column1,type1], ...)],
///     [Array([result1, result2, ...])]]]]`
///
/// error response:
/// `[[status,start_time, elapsed_time, error_information, ...]]`
impl ResultParser {
    pub fn new(json: String) -> ResultParser {
        ResultParser{result: json_flex::decode(json)}
    }

    /// Get raw response result.
    pub fn get_raw_object(&mut self) -> Box<JFObject> {
        self.result.clone()
    }

    /// Return header elements in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn get_header(&mut self) -> JFObject {
        self.result[0].clone()
    }

    /// Return status in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn status(&mut self) -> Option<&i64> {
        self.result[0][0].into_i64()
    }

    /// Return start time in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn start_time(&mut self) -> Option<&f64> {
        self.result[0][1].into_f64()
    }

    /// Return elapsed time in response.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn elapsed_time(&mut self) -> Option<&f64> {
        self.result[0][2].into_f64()
    }

    /// [nodoc]
    #[inline]
    fn matched_columns_num(&mut self) -> Option<i64> {
        let vectoizable = match self.result[1][0][0].into_vec().clone() {
            Some(elem) => elem,
            None => return None
        };
        let pop = match vectoizable.clone().pop() {
            Some(pop) => pop,
            None => return None
        };
        match pop.into_i64().clone() {
            Some(v) => return Some(v.clone()),
            None => return None
        }
    }

    /// Return a number of matched columns in response.
    pub fn matched_columns(&mut self) -> Option<i64> {
        match self.status() {
            Some(&0) => self.matched_columns_num(),
            Some(_) => None,
            None    => None
        }
    }

    /// Get result in response.
    ///
    /// If request succeeded, it can get matched result array.
    /// Otherwise, one can get error messages.
    ///
    /// # Panics
    ///
    /// Panics if response json is corrupted.
    pub fn result(&mut self) -> Option<Vec<JFObject>> {
        match self.status() {
            Some(&0) => Some(vec![self.result[1][0].clone()]),
            Some(_) => Some(vec![self.result[0][3].clone()]),
            None    => None
        }
    }

    /// Convert to `Rows` type and return its type values.
    pub fn into_row(&mut self) -> Rows {
        Rows::new(self.result())
    }
}

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

    const RESPONSE: &'static str = "
    [[0,1452348610.39281,0.000101566314697266],
    [[[9],
     [[\"_id\",\"UInt32\"],[\"_key\",\"ShortText\"],[\"title\",\"ShortText\"]],
     [1,\"http://example.org/\",\"This is test record 1!\"],
     [2,\"http://example.net/\",\"test record 2.\"],
     [3,\"http://example.com/\",\"test test record three.\"],
     [4,\"http://example.net/afr\",\"test record four.\"],
     [5,\"http://example.org/aba\",\"test test test record five.\"],
     [6,\"http://example.com/rab\",\"test test test test record six.\"],
     [7,\"http://example.net/atv\",\"test test test record seven.\"],
     [8,\"http://example.org/gat\",\"test test record eight.\"],
     [9,\"http://example.com/vdw\",\"test test record nine.\"]]]]";

    #[test]
    fn parse_result() {
        let mut decode = ResultParser::new(RESPONSE.to_string());
        assert_eq!(&0, decode.status().unwrap());
        assert_eq!(&1452348610.39281, decode.start_time().unwrap());
        assert_eq!(&0.000101566314697266, decode.elapsed_time().unwrap());
        assert_eq!(9, decode.matched_columns().unwrap());
        let vec = decode.result().unwrap().pop().unwrap().unwrap_vec().clone();
        let expected = r#"Array([Integer(1), String("http://example.org/"), String("This is test record 1!")])"#.to_owned();
        assert_eq!(expected, format!("{:?}", vec[2]))
    }

    #[test]
    fn row_columns() {
        let mut decode = ResultParser::new(RESPONSE.to_string());
        let vec = decode.into_row().columns().unwrap();
        let expected = r#"Array([Integer(1), String("http://example.org/"), String("This is test record 1!")])"#.to_owned();
        assert_eq!(expected, format!("{:?}", vec[2]))
    }
}
<|endoftext|>


<commit_before>fn largest<T>(list: &[T]) -> T {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let numbers = vec![1, 3, 2, 5, 0];

    let result = largest(&numbers);

    println!("The largest number is {}", result);
}
<commit_msg>Example structure that uses generics<commit_after>fn largest<T>(list: &[T]) -> T {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }

    largest
}

struct Point<T> {
    x: T,
    y: T,
}

fn main() {
    let numbers = vec![1, 3, 2, 5, 0];

    let result = largest(&numbers);

    println!("The largest number is {}", result);
}
<|endoftext|>


<commit_before>// Currently the only cross compilers available via nightlies are on linux/osx,
// so we can only run these tests on those platforms
#![cfg(target_os = "linux")]
#![cfg(target_os = "macos")]

use std::os;
use std::path;

use support::{project, execs, basic_bin_manifest};
use support::{RUNNING, COMPILING, DOCTEST, cargo_dir};
use hamcrest::{assert_that, existing_file};
use cargo::util::process;

fn setup() {
}

fn disabled() -> bool {
    match os::getenv("CFG_DISABLE_CROSS_TESTS") {
        Some(ref s) if s.as_slice() == "1" => true,
        _ => false,
    }
}

fn alternate() -> &'static str {
    match os::consts::SYSNAME {
        "linux" => "i686-unknown-linux-gnu",
        "macos" => "i686-apple-darwin",
        _ => unreachable!(),
    }
}

test!(simple_cross {
    if disabled() { return }

    let mut build = project("builder");
    build = build
        .file("Cargo.toml", r#"
            [project]
            name = "foo"
            version = "0.5.0"
            authors = ["wycats@example.com"]
        "#)
        .file("src/main.rs", format!(r#"
            fn main() {{
                assert_eq!(std::os::getenv("TARGET").unwrap().as_slice(), "{}");
            }}
        "#, alternate()).as_slice());
    assert_that(build.cargo_process("build"),
                execs().with_status(0));

    let p = project("foo")
        .file("Cargo.toml", format!(r#"
            [package]
            name = "foo"
            version = "0.0.0"
            authors = []
            build = '{}'
        "#, build.bin("foo").display()))
        .file("src/main.rs", r#"
            use std::os;
            fn main() {
                assert_eq!(os::consts::ARCH, "x86");
            }
        "#);

    let target = alternate();
    assert_that(p.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
    assert_that(&p.target_bin(target, "foo"), existing_file());

    assert_that(
      process(p.target_bin(target, "foo")),
      execs().with_status(0));
})

test!(simple_deps {
    if disabled() { return }

    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "../bar"
        "#)
        .file("src/main.rs", r#"
            extern crate bar;
            fn main() { bar::bar(); }
        "#);
    let p2 = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []
        "#)
        .file("src/lib.rs", "pub fn bar() {}");
    p2.build();

    let target = alternate();
    assert_that(p.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
    assert_that(&p.target_bin(target, "foo"), existing_file());

    assert_that(
      process(p.target_bin(target, "foo")),
      execs().with_status(0));
})

test!(plugin_deps {
    if disabled() { return }

    let foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "../bar"

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/main.rs", r#"
            #![feature(phase)]
            #[phase(plugin)]
            extern crate bar;
            extern crate baz;
            fn main() {
                assert_eq!(bar!(), baz::baz());
            }
        "#);
    let bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true
        "#)
        .file("src/lib.rs", r#"
            #![feature(plugin_registrar, quote)]

            extern crate rustc;
            extern crate syntax;

            use rustc::plugin::Registry;
            use syntax::ast::TokenTree;
            use syntax::codemap::Span;
            use syntax::ext::base::{ExtCtxt, MacExpr, MacResult};

            #[plugin_registrar]
            pub fn foo(reg: &mut Registry) {
                reg.register_macro("bar", expand_bar);
            }

            fn expand_bar(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
                          -> Box<MacResult> {
                MacExpr::new(quote_expr!(cx, 1i))
            }
        "#);
    let baz = project("baz")
        .file("Cargo.toml", r#"
            [package]
            name = "baz"
            version = "0.0.1"
            authors = []
        "#)
        .file("src/lib.rs", "pub fn baz() -> int { 1 }");
    bar.build();
    baz.build();

    let target = alternate();
    assert_that(foo.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
    assert_that(&foo.target_bin(target, "foo"), existing_file());

    assert_that(
      process(foo.target_bin(target, "foo")),
      execs().with_status(0));
})

test!(plugin_to_the_max {
    if disabled() { return }

    let foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "../bar"

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/main.rs", r#"
            #![feature(phase)]
            #[phase(plugin)]
            extern crate bar;
            extern crate baz;
            fn main() {
                assert_eq!(bar!(), baz::baz());
            }
        "#);
    let bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/lib.rs", r#"
            #![feature(plugin_registrar, quote)]

            extern crate rustc;
            extern crate syntax;
            extern crate baz;

            use rustc::plugin::Registry;
            use syntax::ast::TokenTree;
            use syntax::codemap::Span;
            use syntax::ext::base::{ExtCtxt, MacExpr, MacResult};

            #[plugin_registrar]
            pub fn foo(reg: &mut Registry) {
                reg.register_macro("bar", expand_bar);
            }

            fn expand_bar(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
                          -> Box<MacResult> {
                MacExpr::new(quote_expr!(cx, baz::baz()))
            }
        "#);
    let baz = project("baz")
        .file("Cargo.toml", r#"
            [package]
            name = "baz"
            version = "0.0.1"
            authors = []
        "#)
        .file("src/lib.rs", "pub fn baz() -> int { 1 }");
    bar.build();
    baz.build();

    let target = alternate();
    assert_that(foo.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
    assert_that(foo.process(cargo_dir().join("cargo")).arg("build")
                   .arg("--target").arg(target),
                execs().with_status(0));
    assert_that(&foo.target_bin(target, "foo"), existing_file());

    assert_that(
      process(foo.target_bin(target, "foo")),
      execs().with_status(0));
})

test!(linker_and_ar {
    if disabled() { return }

    let target = alternate();
    let p = project("foo")
        .file(".cargo/config", format!(r#"
            [target.{}]
            ar = "my-ar-tool"
            linker = "my-linker-tool"
        "#, target).as_slice())
        .file("Cargo.toml", basic_bin_manifest("foo").as_slice())
        .file("src/foo.rs", r#"
            use std::os;
            fn main() {
                assert_eq!(os::consts::ARCH, "x86");
            }
        "#);

    assert_that(p.cargo_process("build").arg("--target").arg(target)
                                              .arg("-v"),
                execs().with_status(101)
                       .with_stdout(format!("\
{running} `rustc src/foo.rs --crate-name foo --crate-type bin -g \
    --out-dir {dir}{sep}target{sep}{target} \
    --dep-info [..] \
    --target {target} \
    -C ar=my-ar-tool -C linker=my-linker-tool \
    -L {dir}{sep}target{sep}{target} \
    -L {dir}{sep}target{sep}{target}{sep}deps`
{compiling} foo v0.5.0 ({url})
",
                            running = RUNNING,
                            compiling = COMPILING,
                            dir = p.root().display(),
                            url = p.url(),
                            target = target,
                            sep = path::SEP,
                            ).as_slice()));
})

test!(plugin_with_extra_dylib_dep {
    if disabled() { return }

    let foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "../bar"
        "#)
        .file("src/main.rs", r#"
            #![feature(phase)]
            #[phase(plugin)] extern crate bar;

            fn main() {}
        "#);
    let bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/lib.rs", r#"
            #![feature(plugin_registrar)]

            extern crate rustc;
            extern crate baz;

            use rustc::plugin::Registry;

            #[plugin_registrar]
            pub fn foo(reg: &mut Registry) {
                println!("{}", baz::baz());
            }
        "#);
    let baz = project("baz")
        .file("Cargo.toml", r#"
            [package]
            name = "baz"
            version = "0.0.1"
            authors = []

            [lib]
            name = "baz"
            crate_type = ["dylib"]
        "#)
        .file("src/lib.rs", "pub fn baz() -> int { 1 }");
    bar.build();
    baz.build();

    let target = alternate();
    assert_that(foo.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
})

test!(cross_tests {
    if disabled() { return }

    let p = project("foo")
        .file("Cargo.toml", r#"
            [project]
            name = "foo"
            authors = []
            version = "0.0.0"

            [[bin]]
            name = "bar"
        "#)
        .file("src/main.rs", r#"
            extern crate foo;
            use std::os;
            fn main() {
                assert_eq!(os::consts::ARCH, "x86");
            }
            #[test] fn test() { main() }
        "#)
        .file("src/lib.rs", r#"
            use std::os;
            pub fn foo() { assert_eq!(os::consts::ARCH, "x86"); }
            #[test] fn test_foo() { foo() }
        "#);

    let target = alternate();
    assert_that(p.cargo_process("test").arg("--target").arg(target),
                execs().with_status(0)
                       .with_stdout(format!("\
{compiling} foo v0.0.0 ({foo})
{running} target[..]{triple}[..]bar-[..]

running 1 test
test test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

{running} target[..]{triple}[..]foo-[..]

running 1 test
test test_foo ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

{doctest} foo

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

", compiling = COMPILING, running = RUNNING, foo = p.url(), triple = target,
   doctest = DOCTEST)));
})

test!(simple_cargo_run {
    if disabled() { return }

    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.0"
            authors = []
        "#)
        .file("src/main.rs", r#"
            use std::os;
            fn main() {
                assert_eq!(os::consts::ARCH, "x86");
            }
        "#);

    let target = alternate();
    assert_that(p.cargo_process("run").arg("--target").arg(target),
                execs().with_status(0));
})

test!(cross_but_no_dylibs {
    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.0"
            authors = []

            [lib]
            name = "foo"
            crate-type = ["dylib"]
        "#)
        .file("src/lib.rs", "");
    assert_that(p.cargo_process("build").arg("--target").arg("arm-apple-ios"),
                execs().with_status(101)
                       .with_stderr("dylib outputs are not supported for \
                                     arm-apple-ios"));
})
<commit_msg>Add back fix for cross compile tests<commit_after>// Currently the only cross compilers available via nightlies are on linux/osx,
// so we can only run these tests on those platforms
#![cfg(target_os = "linux")]
#![cfg(target_os = "macos")]

use std::os;
use std::path;

use support::{project, execs, basic_bin_manifest};
use support::{RUNNING, COMPILING, DOCTEST, cargo_dir};
use hamcrest::{assert_that, existing_file};
use cargo::util::process;

fn setup() {
}

fn disabled() -> bool {
    match os::getenv("CFG_DISABLE_CROSS_TESTS") {
        Some(ref s) if s.as_slice() == "1" => true,
        _ => false,
    }
}

fn alternate() -> &'static str {
    match os::consts::SYSNAME {
        "linux" => "i686-unknown-linux-gnu",
        "macos" => "i686-apple-darwin",
        _ => unreachable!(),
    }
}

test!(simple_cross {
    if disabled() { return }

    let mut build = project("builder");
    build = build
        .file("Cargo.toml", r#"
            [project]
            name = "foo"
            version = "0.5.0"
            authors = ["wycats@example.com"]
        "#)
        .file("src/main.rs", format!(r#"
            fn main() {{
                assert_eq!(std::os::getenv("TARGET").unwrap().as_slice(), "{}");
            }}
        "#, alternate()).as_slice());
    assert_that(build.cargo_process("build"),
                execs().with_status(0));

    let p = project("foo")
        .file("Cargo.toml", format!(r#"
            [package]
            name = "foo"
            version = "0.0.0"
            authors = []
            build = '{}'
        "#, build.bin("foo").display()))
        .file("src/main.rs", r#"
            use std::os;
            fn main() {
                assert_eq!(os::consts::ARCH, "x86");
            }
        "#);

    let target = alternate();
    assert_that(p.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
    assert_that(&p.target_bin(target, "foo"), existing_file());

    assert_that(
      process(p.target_bin(target, "foo")),
      execs().with_status(0));
})

test!(simple_deps {
    if disabled() { return }

    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "../bar"
        "#)
        .file("src/main.rs", r#"
            extern crate bar;
            fn main() { bar::bar(); }
        "#);
    let p2 = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []
        "#)
        .file("src/lib.rs", "pub fn bar() {}");
    p2.build();

    let target = alternate();
    assert_that(p.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
    assert_that(&p.target_bin(target, "foo"), existing_file());

    assert_that(
      process(p.target_bin(target, "foo")),
      execs().with_status(0));
})

test!(plugin_deps {
    if disabled() { return }

    let foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "../bar"

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/main.rs", r#"
            #![feature(phase)]
            #[phase(plugin)]
            extern crate bar;
            extern crate baz;
            fn main() {
                assert_eq!(bar!(), baz::baz());
            }
        "#);
    let bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true
        "#)
        .file("src/lib.rs", r#"
            #![feature(plugin_registrar, quote)]

            extern crate rustc;
            extern crate syntax;

            use rustc::plugin::Registry;
            use syntax::ast::TokenTree;
            use syntax::codemap::Span;
            use syntax::ext::base::{ExtCtxt, MacExpr, MacResult};

            #[plugin_registrar]
            pub fn foo(reg: &mut Registry) {
                reg.register_macro("bar", expand_bar);
            }

            fn expand_bar(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
                          -> Box<MacResult + 'static> {
                MacExpr::new(quote_expr!(cx, 1i))
            }
        "#);
    let baz = project("baz")
        .file("Cargo.toml", r#"
            [package]
            name = "baz"
            version = "0.0.1"
            authors = []
        "#)
        .file("src/lib.rs", "pub fn baz() -> int { 1 }");
    bar.build();
    baz.build();

    let target = alternate();
    assert_that(foo.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
    assert_that(&foo.target_bin(target, "foo"), existing_file());

    assert_that(
      process(foo.target_bin(target, "foo")),
      execs().with_status(0));
})

test!(plugin_to_the_max {
    if disabled() { return }

    let foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "../bar"

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/main.rs", r#"
            #![feature(phase)]
            #[phase(plugin)]
            extern crate bar;
            extern crate baz;
            fn main() {
                assert_eq!(bar!(), baz::baz());
            }
        "#);
    let bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/lib.rs", r#"
            #![feature(plugin_registrar, quote)]

            extern crate rustc;
            extern crate syntax;
            extern crate baz;

            use rustc::plugin::Registry;
            use syntax::ast::TokenTree;
            use syntax::codemap::Span;
            use syntax::ext::base::{ExtCtxt, MacExpr, MacResult};

            #[plugin_registrar]
            pub fn foo(reg: &mut Registry) {
                reg.register_macro("bar", expand_bar);
            }

            fn expand_bar(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
                          -> Box<MacResult + 'static> {
                MacExpr::new(quote_expr!(cx, baz::baz()))
            }
        "#);
    let baz = project("baz")
        .file("Cargo.toml", r#"
            [package]
            name = "baz"
            version = "0.0.1"
            authors = []
        "#)
        .file("src/lib.rs", "pub fn baz() -> int { 1 }");
    bar.build();
    baz.build();

    let target = alternate();
    assert_that(foo.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
    assert_that(foo.process(cargo_dir().join("cargo")).arg("build")
                   .arg("--target").arg(target),
                execs().with_status(0));
    assert_that(&foo.target_bin(target, "foo"), existing_file());

    assert_that(
      process(foo.target_bin(target, "foo")),
      execs().with_status(0));
})

test!(linker_and_ar {
    if disabled() { return }

    let target = alternate();
    let p = project("foo")
        .file(".cargo/config", format!(r#"
            [target.{}]
            ar = "my-ar-tool"
            linker = "my-linker-tool"
        "#, target).as_slice())
        .file("Cargo.toml", basic_bin_manifest("foo").as_slice())
        .file("src/foo.rs", r#"
            use std::os;
            fn main() {
                assert_eq!(os::consts::ARCH, "x86");
            }
        "#);

    assert_that(p.cargo_process("build").arg("--target").arg(target)
                                              .arg("-v"),
                execs().with_status(101)
                       .with_stdout(format!("\
{running} `rustc src/foo.rs --crate-name foo --crate-type bin -g \
    --out-dir {dir}{sep}target{sep}{target} \
    --dep-info [..] \
    --target {target} \
    -C ar=my-ar-tool -C linker=my-linker-tool \
    -L {dir}{sep}target{sep}{target} \
    -L {dir}{sep}target{sep}{target}{sep}deps`
{compiling} foo v0.5.0 ({url})
",
                            running = RUNNING,
                            compiling = COMPILING,
                            dir = p.root().display(),
                            url = p.url(),
                            target = target,
                            sep = path::SEP,
                            ).as_slice()));
})

test!(plugin_with_extra_dylib_dep {
    if disabled() { return }

    let foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "../bar"
        "#)
        .file("src/main.rs", r#"
            #![feature(phase)]
            #[phase(plugin)] extern crate bar;

            fn main() {}
        "#);
    let bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/lib.rs", r#"
            #![feature(plugin_registrar)]

            extern crate rustc;
            extern crate baz;

            use rustc::plugin::Registry;

            #[plugin_registrar]
            pub fn foo(reg: &mut Registry) {
                println!("{}", baz::baz());
            }
        "#);
    let baz = project("baz")
        .file("Cargo.toml", r#"
            [package]
            name = "baz"
            version = "0.0.1"
            authors = []

            [lib]
            name = "baz"
            crate_type = ["dylib"]
        "#)
        .file("src/lib.rs", "pub fn baz() -> int { 1 }");
    bar.build();
    baz.build();

    let target = alternate();
    assert_that(foo.cargo_process("build").arg("--target").arg(target),
                execs().with_status(0));
})

test!(cross_tests {
    if disabled() { return }

    let p = project("foo")
        .file("Cargo.toml", r#"
            [project]
            name = "foo"
            authors = []
            version = "0.0.0"

            [[bin]]
            name = "bar"
        "#)
        .file("src/main.rs", r#"
            extern crate foo;
            use std::os;
            fn main() {
                assert_eq!(os::consts::ARCH, "x86");
            }
            #[test] fn test() { main() }
        "#)
        .file("src/lib.rs", r#"
            use std::os;
            pub fn foo() { assert_eq!(os::consts::ARCH, "x86"); }
            #[test] fn test_foo() { foo() }
        "#);

    let target = alternate();
    assert_that(p.cargo_process("test").arg("--target").arg(target),
                execs().with_status(0)
                       .with_stdout(format!("\
{compiling} foo v0.0.0 ({foo})
{running} target[..]{triple}[..]bar-[..]

running 1 test
test test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

{running} target[..]{triple}[..]foo-[..]

running 1 test
test test_foo ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

{doctest} foo

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

", compiling = COMPILING, running = RUNNING, foo = p.url(), triple = target,
   doctest = DOCTEST)));
})

test!(simple_cargo_run {
    if disabled() { return }

    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.0"
            authors = []
        "#)
        .file("src/main.rs", r#"
            use std::os;
            fn main() {
                assert_eq!(os::consts::ARCH, "x86");
            }
        "#);

    let target = alternate();
    assert_that(p.cargo_process("run").arg("--target").arg(target),
                execs().with_status(0));
})

test!(cross_but_no_dylibs {
    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.0"
            authors = []

            [lib]
            name = "foo"
            crate-type = ["dylib"]
        "#)
        .file("src/lib.rs", "");
    assert_that(p.cargo_process("build").arg("--target").arg("arm-apple-ios"),
                execs().with_status(101)
                       .with_stderr("dylib outputs are not supported for \
                                     arm-apple-ios"));
})
<|endoftext|>


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

use crate::prelude::*;
use core::fmt;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

#[cfg(feature = "serde")]
impl Serialize for Uuid {
    fn serialize<S: Serializer>(
        &self,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        if serializer.is_human_readable() {
            serializer
                .serialize_str(&self.to_hyphenated().encode_lower(&mut [0; 36]))
        } else {
            serializer.serialize_bytes(self.as_bytes())
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Uuid {
    fn deserialize<D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        if deserializer.is_human_readable() {
            struct UuidStringVisitor;

            impl<'vi> de::Visitor<'vi> for UuidStringVisitor {
                type Value = Uuid;

                fn expecting(
                    &self,
                    formatter: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    write!(formatter, "a UUID string")
                }

                fn visit_str<E: de::Error>(
                    self,
                    value: &str,
                ) -> Result<Uuid, E> {
                    value.parse::<Uuid>().map_err(E::custom)
                }

                fn visit_bytes<E: de::Error>(
                    self,
                    value: &[u8],
                ) -> Result<Uuid, E> {
                    Uuid::from_slice(value).map_err(E::custom)
                }
            }

            deserializer.deserialize_str(UuidStringVisitor)
        } else {
            struct UuidBytesVisitor;

            impl<'vi> de::Visitor<'vi> for UuidBytesVisitor {
                type Value = Uuid;

                fn expecting(
                    &self,
                    formatter: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    write!(formatter, "bytes")
                }

                fn visit_bytes<E: de::Error>(
                    self,
                    value: &[u8],
                ) -> Result<Uuid, E> {
                    Uuid::from_slice(value).map_err(E::custom)
                }
            }

            deserializer.deserialize_bytes(UuidBytesVisitor)
        }
    }
}

#[cfg(all(test, feature = "serde"))]
mod serde_tests {
    use serde_test;

    use crate::prelude::*;

    #[test]
    fn test_serialize_readable() {
        use serde_test::Configure;

        let uuid_str = "f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4";
        let u = Uuid::parse_str(uuid_str).unwrap();
        serde_test::assert_tokens(
            &u.readable(),
            &[serde_test::Token::Str(uuid_str)],
        );
    }

    #[test]
    fn test_serialize_compact() {
        use serde_test::Configure;

        let uuid_bytes = b"F9168C5E-CEB2-4F";
        let u = Uuid::from_slice(uuid_bytes).unwrap();
        serde_test::assert_tokens(
            &u.compact(),
            &[serde_test::Token::Bytes(uuid_bytes)],
        );
    }
}
<commit_msg>Remove serde feature gates inside the serde_support module<commit_after>// Copyright 2013-2014 The Rust Project Developers.
// Copyright 2018 The Uuid Project Developers.
//
// See the COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::prelude::*;
use core::fmt;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

impl Serialize for Uuid {
    fn serialize<S: Serializer>(
        &self,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        if serializer.is_human_readable() {
            serializer
                .serialize_str(&self.to_hyphenated().encode_lower(&mut [0; 36]))
        } else {
            serializer.serialize_bytes(self.as_bytes())
        }
    }
}

impl<'de> Deserialize<'de> for Uuid {
    fn deserialize<D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        if deserializer.is_human_readable() {
            struct UuidStringVisitor;

            impl<'vi> de::Visitor<'vi> for UuidStringVisitor {
                type Value = Uuid;

                fn expecting(
                    &self,
                    formatter: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    write!(formatter, "a UUID string")
                }

                fn visit_str<E: de::Error>(
                    self,
                    value: &str,
                ) -> Result<Uuid, E> {
                    value.parse::<Uuid>().map_err(E::custom)
                }

                fn visit_bytes<E: de::Error>(
                    self,
                    value: &[u8],
                ) -> Result<Uuid, E> {
                    Uuid::from_slice(value).map_err(E::custom)
                }
            }

            deserializer.deserialize_str(UuidStringVisitor)
        } else {
            struct UuidBytesVisitor;

            impl<'vi> de::Visitor<'vi> for UuidBytesVisitor {
                type Value = Uuid;

                fn expecting(
                    &self,
                    formatter: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    write!(formatter, "bytes")
                }

                fn visit_bytes<E: de::Error>(
                    self,
                    value: &[u8],
                ) -> Result<Uuid, E> {
                    Uuid::from_slice(value).map_err(E::custom)
                }
            }

            deserializer.deserialize_bytes(UuidBytesVisitor)
        }
    }
}

#[cfg(test)]
mod serde_tests {
    use serde_test;

    use crate::prelude::*;

    #[test]
    fn test_serialize_readable() {
        use serde_test::Configure;

        let uuid_str = "f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4";
        let u = Uuid::parse_str(uuid_str).unwrap();
        serde_test::assert_tokens(
            &u.readable(),
            &[serde_test::Token::Str(uuid_str)],
        );
    }

    #[test]
    fn test_serialize_compact() {
        use serde_test::Configure;

        let uuid_bytes = b"F9168C5E-CEB2-4F";
        let u = Uuid::from_slice(uuid_bytes).unwrap();
        serde_test::assert_tokens(
            &u.compact(),
            &[serde_test::Token::Bytes(uuid_bytes)],
        );
    }
}
<|endoftext|>


<commit_before>use std::collections::BTreeMap;
use serde;
use serde_json;
use chill::DatabaseName;
use hex::ToHex;

#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct User {
    pub name: String,
    pub email: Option<String>,
    pub backends: Option<Vec<Backend>>,
}

impl User {
    pub fn db_name(&self) -> DatabaseName {
        let db_name = format!("userdb-{}", self.name.to_hex());
        DatabaseName::from(db_name)
    }
}

#[derive(Debug, PartialEq)]
pub enum Backend {
    File(FileBackend),
    Jamendo(JamendoBackend),
}

impl serde::Serialize for Backend {
    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
        where S: serde::Serializer
    {
        match *self {
            Backend::File(ref backend) => backend.serialize::<S>(serializer),
            Backend::Jamendo(ref backend) => backend.serialize::<S>(serializer),
        }
    }
}

impl serde::Deserialize for Backend {

    fn deserialize<D>(de: &mut D) -> Result<Self, D::Error>
        where D: serde::de::Deserializer,
    {
        let mut object: BTreeMap<String, serde_json::Value> = serde::de::Deserialize::deserialize(de)?;

        let object_type = match object.remove("type") {
            Some(v) => {
                match v.as_string() {
                    Some(object_type) => object_type.to_string(),
                    None => { return Err(serde::de::Error::invalid_value("type is not a string")); }
                }
            }
            None => { return Err(serde::de::Error::missing_field("type")); }
        };

        match object_type.as_ref() {
            "file" => {
                let machine_id = match object.remove("machine_id") {
                    Some(v) => {
                        match v.as_string() {
                            Some(machine_id) => machine_id.to_string(),
                            None => { return Err(serde::de::Error::invalid_value("machine_id is not a string")); }
                        }
                    }
                    None => { return Err(serde::de::Error::missing_field("machine_id")); }
                };

                let paths = match object.remove("paths") {
                    Some(paths) => serde_json::value::from_value(paths).map_err(|_| serde::de::Error::invalid_value("paths is not a string array"))?,
                    None => { return Err(serde::de::Error::missing_field("paths")); }
                };

                Ok(Backend::File(FileBackend {
                    _type: "file".to_string(),
                    machine_id: machine_id.into(),
                    paths: paths,
                }))
            },
            "jamendo" => {
                let user_name = match object.remove("user_name") {
                    Some(v) => {
                        match v.as_string() {
                            Some(user_name) => user_name.to_string(),
                            None => { return Err(serde::de::Error::invalid_value("user_name is not a string")); }
                        }
                    }
                    None => { return Err(serde::de::Error::missing_field("user_name")); }
                };

                Ok(Backend::Jamendo(JamendoBackend {
                    _type: "jamendo".to_string(),
                    user_name: user_name,
                }))
            },
            _ => Err(serde::de::Error::invalid_value("unkown type"))
        }
    }
}

// TODO implement custom serializer to get rid of _type
#[derive(Serialize, Debug, PartialEq)]
pub struct FileBackend {
    #[serde(rename="type")]
    pub _type: String,
    pub machine_id: String,
    pub paths: Vec<String>,
}

// TODO implement custom serializer to get rid of _type
#[derive(Serialize, Debug, PartialEq)]
pub struct JamendoBackend {
    #[serde(rename="type")]
    pub _type: String,
    pub user_name: String,
}

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

    #[test]
    fn file_backend() {
        let uri = Backend::File(FileBackend { machine_id: "foo-bar".into(), paths: Vec::new(), _type: "file".into() });
        let uri_str = serde_json::to_string(&uri).unwrap();
        assert_eq!(uri_str, "{\"type\":\"file\",\"machine_id\":\"foo-bar\",\"paths\":[]}");
        assert_eq!(serde_json::from_str::<Backend>(&uri_str).unwrap(), uri);
    }

    #[test]
    fn jamendo_backend() {
        let uri = Backend::Jamendo(JamendoBackend { user_name: "foo", _type: "jamendo".into() });
        let uri_str = serde_json::to_string(&uri).unwrap();
        assert_eq!(uri_str, "{\"type\":\"jamendo\",\"user_name\":\"foo\"}");
        assert_eq!(serde_json::from_str::<Backend>(&uri_str).unwrap(), uri);
    }

}
<commit_msg>fix(lib): fix tests (oops)<commit_after>use std::collections::BTreeMap;
use serde;
use serde_json;
use chill::DatabaseName;
use hex::ToHex;

#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct User {
    pub name: String,
    pub email: Option<String>,
    pub backends: Option<Vec<Backend>>,
}

impl User {
    pub fn db_name(&self) -> DatabaseName {
        let db_name = format!("userdb-{}", self.name.to_hex());
        DatabaseName::from(db_name)
    }
}

#[derive(Debug, PartialEq)]
pub enum Backend {
    File(FileBackend),
    Jamendo(JamendoBackend),
}

impl serde::Serialize for Backend {
    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
        where S: serde::Serializer
    {
        match *self {
            Backend::File(ref backend) => backend.serialize::<S>(serializer),
            Backend::Jamendo(ref backend) => backend.serialize::<S>(serializer),
        }
    }
}

impl serde::Deserialize for Backend {

    fn deserialize<D>(de: &mut D) -> Result<Self, D::Error>
        where D: serde::de::Deserializer,
    {
        let mut object: BTreeMap<String, serde_json::Value> = serde::de::Deserialize::deserialize(de)?;

        let object_type = match object.remove("type") {
            Some(v) => {
                match v.as_string() {
                    Some(object_type) => object_type.to_string(),
                    None => { return Err(serde::de::Error::invalid_value("type is not a string")); }
                }
            }
            None => { return Err(serde::de::Error::missing_field("type")); }
        };

        match object_type.as_ref() {
            "file" => {
                let machine_id = match object.remove("machine_id") {
                    Some(v) => {
                        match v.as_string() {
                            Some(machine_id) => machine_id.to_string(),
                            None => { return Err(serde::de::Error::invalid_value("machine_id is not a string")); }
                        }
                    }
                    None => { return Err(serde::de::Error::missing_field("machine_id")); }
                };

                let paths = match object.remove("paths") {
                    Some(paths) => serde_json::value::from_value(paths).map_err(|_| serde::de::Error::invalid_value("paths is not a string array"))?,
                    None => { return Err(serde::de::Error::missing_field("paths")); }
                };

                Ok(Backend::File(FileBackend {
                    _type: "file".to_string(),
                    machine_id: machine_id.into(),
                    paths: paths,
                }))
            },
            "jamendo" => {
                let user_name = match object.remove("user_name") {
                    Some(v) => {
                        match v.as_string() {
                            Some(user_name) => user_name.to_string(),
                            None => { return Err(serde::de::Error::invalid_value("user_name is not a string")); }
                        }
                    }
                    None => { return Err(serde::de::Error::missing_field("user_name")); }
                };

                Ok(Backend::Jamendo(JamendoBackend {
                    _type: "jamendo".to_string(),
                    user_name: user_name,
                }))
            },
            _ => Err(serde::de::Error::invalid_value("unkown type"))
        }
    }
}

// TODO implement custom serializer to get rid of _type
#[derive(Serialize, Debug, PartialEq)]
pub struct FileBackend {
    #[serde(rename="type")]
    pub _type: String,
    pub machine_id: String,
    pub paths: Vec<String>,
}

// TODO implement custom serializer to get rid of _type
#[derive(Serialize, Debug, PartialEq)]
pub struct JamendoBackend {
    #[serde(rename="type")]
    pub _type: String,
    pub user_name: String,
}

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

    #[test]
    fn file_backend() {
        let uri = Backend::File(FileBackend { machine_id: "foo-bar".into(), paths: Vec::new(), _type: "file".into() });
        let uri_str = serde_json::to_string(&uri).unwrap();
        assert_eq!(uri_str, "{\"type\":\"file\",\"machine_id\":\"foo-bar\",\"paths\":[]}");
        assert_eq!(serde_json::from_str::<Backend>(&uri_str).unwrap(), uri);
    }

    #[test]
    fn jamendo_backend() {
        let uri = Backend::Jamendo(JamendoBackend { user_name: "foo".into(), _type: "jamendo".into() });
        let uri_str = serde_json::to_string(&uri).unwrap();
        assert_eq!(uri_str, "{\"type\":\"jamendo\",\"user_name\":\"foo\"}");
        assert_eq!(serde_json::from_str::<Backend>(&uri_str).unwrap(), uri);
    }

}
<|endoftext|>