<commit_before>use std::cmp;

// 2 billion junctions is good enough for now
pub type JunctionIndex = usize;
pub type Time = i64;
pub type Level = bool;

#[derive (Clone, Copy)]
pub enum GateBehavior {
	And,
	Not,
	Or,
	Xor,
}

// In the future, at time "time", junction "junction" will be set to level "level".
#[derive (Clone, Copy)]
pub struct Signal {
	junction: JunctionIndex,
	level: Level,
	time: Time,
}

#[derive (Clone, Copy)]
pub struct Wire {
	input: JunctionIndex,
	output: JunctionIndex,
	delay: Time,
}

pub struct Gate {
	inputs: Vec <JunctionIndex>,
	output: JunctionIndex,
	behavior: GateBehavior,
}

pub struct Circuit {
	wires: Vec <Wire>,
	gates: Vec <Gate>,
}

pub struct World {
	// These don't change at runtime
	circuit: Circuit,

	junctions: Vec <Level>,
	time: Time,
	signals: Vec <Signal>,
}

pub enum WorldCreationErr {
	// Two elements point to the same junction, this is illegal
	FanIn,
}

impl Wire {
	fn new (input: JunctionIndex, output: JunctionIndex, delay: Time) -> Wire {
		Wire {
			input: input,
			output: output,
			delay: delay,
		}
	}

	fn offset_junctions (&self, offset: JunctionIndex) -> Wire {
		Wire {
			input: self.input + offset,
			output: self.output + offset,
			delay: self.delay,
		}
	}
}

impl Gate {
	fn offset_junctions (&self, offset: JunctionIndex) -> Gate {
		Gate {
			inputs: self.inputs.iter ().map (|junction| junction + offset).collect (),
			output: self.output + offset,
			behavior: self.behavior,
		}
	}
}

impl Circuit {
	fn wires_from_tuples (wire_tuples: Vec <(JunctionIndex, JunctionIndex, Time)>) -> Vec <Wire> {
		wire_tuples.iter ().map (|tuple| Wire::new (tuple.0, tuple.1, tuple.2)).collect ()
	}

	pub fn offset_junctions (&self, offset: JunctionIndex) -> Circuit {
		Circuit {
			wires: self.wires.iter ().map (|wire| wire.offset_junctions (offset)).collect (),
			gates: self.gates.iter ().map (|gate| gate.offset_junctions (offset)).collect (),
		}
	}

	fn max_junction (&self) -> JunctionIndex {
		let max_junction_wires = self.wires.iter ().fold (0, |max, wire| cmp::max (max, cmp::max (wire.input, wire.output)));
		let max_junction_gates = self.gates.iter ().fold (0, |max, gate| {
			let max_input = gate.inputs.iter ().max ();

			let max_junction_gate = match max_input {
				Option::Some (junction) => cmp::max (*junction, gate.output),
				Option::None => gate.output,
			};

			cmp::max (max, max_junction_gate)
		});

		cmp::max (max_junction_gates, max_junction_wires)
	}

	fn junction_count (&self) -> JunctionIndex {
		self.max_junction () + 1
	}

	fn has_fan_in (&self) -> bool {
		let mut junction_has_input = vec! [false; self.junction_count ()];

		for wire in self.wires.iter () {
			if junction_has_input [wire.output] {
				return true;
			}

			junction_has_input [wire.output] = true;
		}

		for gate in self.gates.iter () {
			if junction_has_input [gate.output] {
				return true;
			}

			junction_has_input [gate.output] = true;
		}

		false
	}
}

impl World {
	pub fn new (wires: Vec <Wire>, gates: Vec <Gate>) -> Result <World, WorldCreationErr> {
		let circuit = Circuit {
			wires: wires,
			gates: gates,
		};

		if circuit.has_fan_in () {
			return Err (WorldCreationErr::FanIn);
		}

		Ok (World {
			time: 0,
			signals: vec![],
			junctions: vec![false; circuit.junction_count ()],
			circuit: circuit,
		})
	}

	pub fn new_half_adder () -> World {
		World::new (
		Circuit::wires_from_tuples (vec![
			(0, 1, 4),
			(0, 5, 8),
			(2, 3, 4),
			(6, 7, 3),
			(8, 4, 8),
			(8, 9, 4),
		]),
		vec![
			Gate {
				inputs: vec![1, 4],
				output: 2,
				behavior: GateBehavior::And,
			},
			Gate {
				inputs: vec![5, 9],
				output: 6,
				behavior: GateBehavior::Xor,
			},
		]).ok ().expect ("Half adder circuit is invalid")
	}

	pub fn new_full_adder () -> World {
		World::new (
		Circuit::wires_from_tuples (vec![
			(0, 3, 1),
			(0, 5, 1),
			(1, 4, 1),
			(1, 6, 1),
			(2, 11, 1),
			(2, 9, 1),
			(7, 10, 1),
			(7, 8, 1),
			(12, 14, 1),
			(13, 15, 1),
		]),
		vec![
			Gate {
				inputs: vec![3, 4],
				output: 7,
				behavior: GateBehavior::Xor,
			},
			Gate {
				inputs: vec![10, 11],
				output: 16,
				behavior: GateBehavior::Xor,
			},
			Gate {
				inputs: vec![8, 9],
				output: 12,
				behavior: GateBehavior::And,
			},
			Gate {
				inputs: vec![5, 6],
				output: 13,
				behavior: GateBehavior::And,
			},
			Gate {
				inputs: vec![14, 15],
				output: 17,
				behavior: GateBehavior::Or,
			},
		]).ok ().expect ("Full adder circuit is invalid")
	}

	pub fn is_settled (& self) -> bool {
		self.signals.len () == 0
	}

	fn sort_signals (&mut self) {
		// This step is just a safety since we should be insertion sorting the delays already
		self.signals.sort_by (|a, b| a.time.cmp (&b.time));
	}

	fn step_gates (&mut self) {
		let mut new_signals = Vec::<Signal>::new ();

		// TODO: Optimize to only touch gates whose inputs have changed
		for gate in self.circuit.gates.iter () {
			let inputs: Vec <bool> = gate.inputs.iter ().map (|i| self.junctions [*i]).collect ();

			let output = match gate.behavior {
				GateBehavior::And => inputs.iter ().fold (true, |sum, a| sum && *a),
				GateBehavior::Not => ! inputs [0],
				GateBehavior::Or => inputs.iter ().fold (false, |sum, a| sum || *a),
				GateBehavior::Xor => inputs.iter ().fold (false, |sum, a| sum ^ *a),
			};

			let destiny_level = self.get_junction_destiny (gate.output);

			if destiny_level != output {
				new_signals.push (Signal {
					junction: gate.output,
					time: self.time,
					level: output,
				});
			}
		};

		// TODO: Proper insertion sorting
		// If the number of new signals is small compared to the number of
		// in-flight signals, I could do a few binary insertions sorts.
		// If the number is large, it might be better to do a mergesort.
		for signal in new_signals {
			self.signals.push (signal);
		}

		self.sort_signals ();
	}

	fn get_junction_destiny (& self, junction: JunctionIndex) -> Level {
		if self.signals.len () > 0 {
			// Find the last signal that was heading for that junction
			// Remember that junctions are not allowed to fan in
			for i in 0 .. self.signals.len () {
				let signals = self.signals [self.signals.len () - i - 1];

				if signals.junction == junction {
					return signals.level;
				}
			}
		}

		self.junctions [junction]
	}

	fn step_wires (&mut self) {
		for wire in self.circuit.wires.iter () {
			let input = self.junctions [wire.input];

			// Don't push redundant delays
			let destiny_level = self.get_junction_destiny (wire.output);

			if input != destiny_level {
				self.signals.push (Signal {
					junction: wire.output,
					time: self.time + wire.delay,
					level: input,
				});
			}
		};

		// TODO: Proper insertion sorting
		self.sort_signals ();
	}

	fn propagate_signals (&mut self) {
		let next_time = self.signals [0].time;

		for signal in self.signals.iter () {
			if signal.time == next_time {
				self.junctions [signal.junction] = signal.level;
			}
			else if signal.time > next_time {
				break;
			}
		}

		self.signals.retain (|signal| signal.time > next_time);

		self.time = next_time;
	}

	pub fn set_junction (&mut self, junction: JunctionIndex, level: Level) {
		self.signals.push (Signal {
			junction: junction,
			level: level,
			time: self.time,
		});
	}

	pub fn step (&mut self) {
		if self.is_settled () {
			return;
		}

		self.sort_signals ();

		self.propagate_signals ();

		self.step_gates ();
		self.step_wires ();
	}

	pub fn step_to_settled (&mut self) {
		while ! self.is_settled () {
			self.step ();
		}
	}
}

#[test]
pub fn test_fan_in () {
	let world_or_err = World::new (
		Circuit::wires_from_tuples (vec! [
		(0, 2, 1),
		(1, 2, 1),
		]),
		vec! []
	);

	if let Err (WorldCreationErr::FanIn) = world_or_err {
		// Good
	}
	else {
		panic! ("World creation should have thrown a FanIn error");
	}
}

#[test]
pub fn test_half_adder () {
	let mut world = World::new_half_adder ();
	world.step_to_settled ();

	let assert_outputs = |world: &World, msb: Level, lsb: Level| {
		assert_eq! (world.junctions [3], msb);
		assert_eq! (world.junctions [7], lsb);
	};

	assert_outputs (&world, false, false);

	// Junctions 0 and 8 are the input bits

	world.set_junction (0, true);
	world.step_to_settled ();
	assert_outputs (&world, false, true);

	world.set_junction (8, true);
	world.step_to_settled ();
	assert_outputs (&world, true, false);

	world.set_junction (0, false);
	world.step_to_settled ();
	assert_outputs (&world, false, true);
}

#[test]
pub fn test_full_adder () {
	let mut world = World::new_full_adder ();
	world.step_to_settled ();

	let assert_outputs = |world: &mut World, a: Level, b: Level, c: Level, carry: Level, sum: Level| {
		world.set_junction (0, a);
		world.set_junction (1, b);
		world.set_junction (2, c);

		world.step_to_settled ();

		assert_eq! (world.junctions [17], carry);
		assert_eq! (world.junctions [16], sum);
	};

	// Truth table for a full adder
	assert_outputs (&mut world, false, false, false, false, false);
	assert_outputs (&mut world, false, false, true, false, true);
	assert_outputs (&mut world, false, true, true, true, false);
	assert_outputs (&mut world, false, true, false, false, true);

	assert_outputs (&mut world, true, true, false, true, false);
	assert_outputs (&mut world, true, true, true, true, true);
	assert_outputs (&mut world, true, false, true, true, false);
	assert_outputs (&mut world, true, false, false, false, true);
}
<commit_msg>Moving the adder constructors into Circuit<commit_after>use std::cmp;

// 2 billion junctions is good enough for now
pub type JunctionIndex = usize;
pub type Time = i64;
pub type Level = bool;

#[derive (Clone, Copy)]
pub enum GateBehavior {
	And,
	Not,
	Or,
	Xor,
}

// In the future, at time "time", junction "junction" will be set to level "level".
#[derive (Clone, Copy)]
pub struct Signal {
	junction: JunctionIndex,
	level: Level,
	time: Time,
}

#[derive (Clone, Copy)]
pub struct Wire {
	input: JunctionIndex,
	output: JunctionIndex,
	delay: Time,
}

pub struct Gate {
	inputs: Vec <JunctionIndex>,
	output: JunctionIndex,
	behavior: GateBehavior,
}

pub struct Circuit {
	wires: Vec <Wire>,
	gates: Vec <Gate>,
}

pub struct World {
	// These don't change at runtime
	circuit: Circuit,

	junctions: Vec <Level>,
	time: Time,
	signals: Vec <Signal>,
}

pub enum WorldCreationErr {
	// Two elements point to the same junction, this is illegal
	FanIn,
}

impl Wire {
	fn new (input: JunctionIndex, output: JunctionIndex, delay: Time) -> Wire {
		Wire {
			input: input,
			output: output,
			delay: delay,
		}
	}

	fn offset_junctions (&self, offset: JunctionIndex) -> Wire {
		Wire {
			input: self.input + offset,
			output: self.output + offset,
			delay: self.delay,
		}
	}
}

impl Gate {
	fn offset_junctions (&self, offset: JunctionIndex) -> Gate {
		Gate {
			inputs: self.inputs.iter ().map (|junction| junction + offset).collect (),
			output: self.output + offset,
			behavior: self.behavior,
		}
	}
}

impl Circuit {
	fn new_half_adder () -> Circuit {
		Circuit {
			wires: Circuit::wires_from_tuples (vec![
				(0, 1, 4),
				(0, 5, 8),
				(2, 3, 4),
				(6, 7, 3),
				(8, 4, 8),
				(8, 9, 4),
			]),
			gates: vec![
				Gate {
					inputs: vec![1, 4],
					output: 2,
					behavior: GateBehavior::And,
				},
				Gate {
					inputs: vec![5, 9],
					output: 6,
					behavior: GateBehavior::Xor,
				},
			]
		}
	}

	fn new_full_adder () -> Circuit {
		Circuit {
			wires: Circuit::wires_from_tuples (vec![
				(0, 3, 1),
				(0, 5, 1),
				(1, 4, 1),
				(1, 6, 1),
				(2, 11, 1),
				(2, 9, 1),
				(7, 10, 1),
				(7, 8, 1),
				(12, 14, 1),
				(13, 15, 1),
			]),
			gates: vec![
				Gate {
					inputs: vec![3, 4],
					output: 7,
					behavior: GateBehavior::Xor,
				},
				Gate {
					inputs: vec![10, 11],
					output: 16,
					behavior: GateBehavior::Xor,
				},
				Gate {
					inputs: vec![8, 9],
					output: 12,
					behavior: GateBehavior::And,
				},
				Gate {
					inputs: vec![5, 6],
					output: 13,
					behavior: GateBehavior::And,
				},
				Gate {
					inputs: vec![14, 15],
					output: 17,
					behavior: GateBehavior::Or,
				},
			]
		}
	}

	fn wires_from_tuples (wire_tuples: Vec <(JunctionIndex, JunctionIndex, Time)>) -> Vec <Wire> {
		wire_tuples.iter ().map (|tuple| Wire::new (tuple.0, tuple.1, tuple.2)).collect ()
	}

	fn offset_junctions (&self, offset: JunctionIndex) -> Circuit {
		Circuit {
			wires: self.wires.iter ().map (|wire| wire.offset_junctions (offset)).collect (),
			gates: self.gates.iter ().map (|gate| gate.offset_junctions (offset)).collect (),
		}
	}

	fn max_junction (&self) -> JunctionIndex {
		let max_junction_wires = self.wires.iter ().fold (0, |max, wire| cmp::max (max, cmp::max (wire.input, wire.output)));
		let max_junction_gates = self.gates.iter ().fold (0, |max, gate| {
			let max_input = gate.inputs.iter ().max ();

			let max_junction_gate = match max_input {
				Option::Some (junction) => cmp::max (*junction, gate.output),
				Option::None => gate.output,
			};

			cmp::max (max, max_junction_gate)
		});

		cmp::max (max_junction_gates, max_junction_wires)
	}

	fn junction_count (&self) -> JunctionIndex {
		self.max_junction () + 1
	}

	fn has_fan_in (&self) -> bool {
		let mut junction_has_input = vec! [false; self.junction_count ()];

		for wire in self.wires.iter () {
			if junction_has_input [wire.output] {
				return true;
			}

			junction_has_input [wire.output] = true;
		}

		for gate in self.gates.iter () {
			if junction_has_input [gate.output] {
				return true;
			}

			junction_has_input [gate.output] = true;
		}

		false
	}
}

impl World {
	pub fn new_from_circuit (circuit: Circuit) -> Result <World, WorldCreationErr> {
		if circuit.has_fan_in () {
			return Err (WorldCreationErr::FanIn);
		}

		Ok (World {
			time: 0,
			signals: vec![],
			junctions: vec![false; circuit.junction_count ()],
			circuit: circuit,
		})
	}

	pub fn new (wires: Vec <Wire>, gates: Vec <Gate>) -> Result <World, WorldCreationErr> {
		World::new_from_circuit (Circuit {
			wires: wires,
			gates: gates,
		})
	}

	pub fn new_half_adder () -> World {
		World::new_from_circuit (Circuit::new_half_adder ()).ok ().expect ("Half adder circuit is invalid")
	}

	pub fn new_full_adder () -> World {
		World::new_from_circuit (Circuit::new_full_adder ()).ok ().expect ("Full adder circuit is invalid")
	}

	pub fn is_settled (& self) -> bool {
		self.signals.len () == 0
	}

	fn sort_signals (&mut self) {
		// This step is just a safety since we should be insertion sorting the delays already
		self.signals.sort_by (|a, b| a.time.cmp (&b.time));
	}

	fn step_gates (&mut self) {
		let mut new_signals = Vec::<Signal>::new ();

		// TODO: Optimize to only touch gates whose inputs have changed
		for gate in self.circuit.gates.iter () {
			let inputs: Vec <bool> = gate.inputs.iter ().map (|i| self.junctions [*i]).collect ();

			let output = match gate.behavior {
				GateBehavior::And => inputs.iter ().fold (true, |sum, a| sum && *a),
				GateBehavior::Not => ! inputs [0],
				GateBehavior::Or => inputs.iter ().fold (false, |sum, a| sum || *a),
				GateBehavior::Xor => inputs.iter ().fold (false, |sum, a| sum ^ *a),
			};

			let destiny_level = self.get_junction_destiny (gate.output);

			if destiny_level != output {
				new_signals.push (Signal {
					junction: gate.output,
					time: self.time,
					level: output,
				});
			}
		};

		// TODO: Proper insertion sorting
		// If the number of new signals is small compared to the number of
		// in-flight signals, I could do a few binary insertions sorts.
		// If the number is large, it might be better to do a mergesort.
		for signal in new_signals {
			self.signals.push (signal);
		}

		self.sort_signals ();
	}

	fn get_junction_destiny (& self, junction: JunctionIndex) -> Level {
		if self.signals.len () > 0 {
			// Find the last signal that was heading for that junction
			// Remember that junctions are not allowed to fan in
			for i in 0 .. self.signals.len () {
				let signals = self.signals [self.signals.len () - i - 1];

				if signals.junction == junction {
					return signals.level;
				}
			}
		}

		self.junctions [junction]
	}

	fn step_wires (&mut self) {
		for wire in self.circuit.wires.iter () {
			let input = self.junctions [wire.input];

			// Don't push redundant delays
			let destiny_level = self.get_junction_destiny (wire.output);

			if input != destiny_level {
				self.signals.push (Signal {
					junction: wire.output,
					time: self.time + wire.delay,
					level: input,
				});
			}
		};

		// TODO: Proper insertion sorting
		self.sort_signals ();
	}

	fn propagate_signals (&mut self) {
		let next_time = self.signals [0].time;

		for signal in self.signals.iter () {
			if signal.time == next_time {
				self.junctions [signal.junction] = signal.level;
			}
			else if signal.time > next_time {
				break;
			}
		}

		self.signals.retain (|signal| signal.time > next_time);

		self.time = next_time;
	}

	pub fn set_junction (&mut self, junction: JunctionIndex, level: Level) {
		self.signals.push (Signal {
			junction: junction,
			level: level,
			time: self.time,
		});
	}

	pub fn step (&mut self) {
		if self.is_settled () {
			return;
		}

		self.sort_signals ();

		self.propagate_signals ();

		self.step_gates ();
		self.step_wires ();
	}

	pub fn step_to_settled (&mut self) {
		while ! self.is_settled () {
			self.step ();
		}
	}
}

#[test]
pub fn test_fan_in () {
	let world_or_err = World::new (
		Circuit::wires_from_tuples (vec! [
		(0, 2, 1),
		(1, 2, 1),
		]),
		vec! []
	);

	if let Err (WorldCreationErr::FanIn) = world_or_err {
		// Good
	}
	else {
		panic! ("World creation should have thrown a FanIn error");
	}
}

#[test]
pub fn test_half_adder () {
	let mut world = World::new_half_adder ();
	world.step_to_settled ();

	let assert_outputs = |world: &World, msb: Level, lsb: Level| {
		assert_eq! (world.junctions [3], msb);
		assert_eq! (world.junctions [7], lsb);
	};

	assert_outputs (&world, false, false);

	// Junctions 0 and 8 are the input bits

	world.set_junction (0, true);
	world.step_to_settled ();
	assert_outputs (&world, false, true);

	world.set_junction (8, true);
	world.step_to_settled ();
	assert_outputs (&world, true, false);

	world.set_junction (0, false);
	world.step_to_settled ();
	assert_outputs (&world, false, true);
}

#[test]
pub fn test_full_adder () {
	let mut world = World::new_full_adder ();
	world.step_to_settled ();

	let assert_outputs = |world: &mut World, a: Level, b: Level, c: Level, carry: Level, sum: Level| {
		world.set_junction (0, a);
		world.set_junction (1, b);
		world.set_junction (2, c);

		world.step_to_settled ();

		assert_eq! (world.junctions [17], carry);
		assert_eq! (world.junctions [16], sum);
	};

	// Truth table for a full adder
	assert_outputs (&mut world, false, false, false, false, false);
	assert_outputs (&mut world, false, false, true, false, true);
	assert_outputs (&mut world, false, true, true, true, false);
	assert_outputs (&mut world, false, true, false, false, true);

	assert_outputs (&mut world, true, true, false, true, false);
	assert_outputs (&mut world, true, true, true, true, true);
	assert_outputs (&mut world, true, false, true, true, false);
	assert_outputs (&mut world, true, false, false, false, true);
}

#[test]
pub fn test_ripple_adder () {
	//let
}<|endoftext|>


<commit_before>//! The library provides [special functions][1].
//!
//! [1]: https://en.wikipedia.org/wiki/Special_functions

#![feature(macro_rules)]

extern crate libc;

pub use beta::{ln_beta, inc_beta, inv_inc_beta};

mod beta;

#[link_name = "m"]
mod m {
    use libc::{c_double, c_int};

    extern {
        pub fn cos(x: c_double) -> c_double;
        pub fn erf(x: c_double) -> c_double;
        pub fn erfc(x: c_double) -> c_double;
        pub fn exp(x: c_double) -> c_double;
        pub fn lgamma_r(x: c_double, sign: &mut c_int) -> c_double;
        pub fn log(x: c_double) -> c_double;
        pub fn pow(x: c_double, y: c_double) -> c_double;
        pub fn sin(x: c_double) -> c_double;
        pub fn sqrt(x: c_double) -> c_double;
        pub fn tgamma(x: c_double) -> c_double;
    }
}

/// Computes the cosine.
#[inline]
pub fn cos(x: f64) -> f64 {
    unsafe { m::cos(x) }
}

/// Computes the error function.
#[inline]
pub fn erf(x: f64) -> f64 {
    unsafe { m::erf(x) }
}

/// Computes the complementary error function.
#[inline]
pub fn erfc(x: f64) -> f64 {
    unsafe { m::erfc(x) }
}

/// Computes the exponential function.
#[inline]
pub fn exp(x: f64) -> f64 {
    unsafe { m::exp(x) }
}

/// Computes the gamma function.
#[inline]
pub fn gamma(x: f64) -> f64 {
    unsafe { m::tgamma(x) }
}

/// Computes the natural logarithm of the gamma function.
#[inline]
pub fn ln_gamma(x: f64) -> (f64, i32) {
    let mut sign: i32 = 0;
    let value = unsafe { m::lgamma_r(x, &mut sign) };
    (value, sign)
}

/// Computes the natural logarithm.
///
/// The domain is positive real numbers.
#[inline]
pub fn ln(x: f64) -> f64 {
    unsafe { m::log(x) }
}

/// Computes a base raised to an exponent.
#[inline]
pub fn pow(base: f64, exp: f64) -> f64 {
    unsafe { m::pow(base, exp) }
}

/// Computes the sine.
#[inline]
pub fn sin(x: f64) -> f64 {
    unsafe { m::sin(x) }
}

/// Computes the square root function.
///
/// The domain is non-negative real numbers.
#[inline]
pub fn sqrt(x: f64) -> f64 {
    unsafe { m::sqrt(x) }
}

#[cfg(test)]
mod test {
    #[test]
    fn gamma() {
        use super::{exp, gamma, ln_gamma};

        let x = -2.5;

        let gamma1 = -0.9453087204829418;
        let gamma2 = gamma(x);
        let gamma3 = {
            let (value, sign) = ln_gamma(x);
            (sign as f64) * exp(value)
        };

        assert_eq!(gamma1, gamma2);
        assert_eq!(gamma1, gamma3);
    }

}

#[cfg(test)]
mod bech {
    extern crate test;

    #[bench]
    fn pow_float(bench: &mut test::Bencher) {
        use super::pow;

        bench.iter(|| {
            for exp in range(0i32, 100) {
                pow(2.7_1828_1828, exp as f64);
            }
        });
    }

    #[bench]
    fn pow_integer(bench: &mut test::Bencher) {
        #[inline]
        fn powi(x: f64, y: i32) -> f64 {
            x.powi(y)
        }

        bench.iter(|| {
            for exp in range(0i32, 100) {
                powi(2.7_1828_1828, exp);
            }
        });
    }
}
<commit_msg>Removed benchmarks for pow<commit_after>//! The library provides [special functions][1].
//!
//! [1]: https://en.wikipedia.org/wiki/Special_functions

#![feature(macro_rules)]

extern crate libc;

pub use beta::{ln_beta, inc_beta, inv_inc_beta};

mod beta;

#[link_name = "m"]
mod m {
    use libc::{c_double, c_int};

    extern {
        pub fn cos(x: c_double) -> c_double;
        pub fn erf(x: c_double) -> c_double;
        pub fn erfc(x: c_double) -> c_double;
        pub fn exp(x: c_double) -> c_double;
        pub fn lgamma_r(x: c_double, sign: &mut c_int) -> c_double;
        pub fn log(x: c_double) -> c_double;
        pub fn pow(x: c_double, y: c_double) -> c_double;
        pub fn sin(x: c_double) -> c_double;
        pub fn sqrt(x: c_double) -> c_double;
        pub fn tgamma(x: c_double) -> c_double;
    }
}

/// Computes the cosine.
#[inline]
pub fn cos(x: f64) -> f64 {
    unsafe { m::cos(x) }
}

/// Computes the error function.
#[inline]
pub fn erf(x: f64) -> f64 {
    unsafe { m::erf(x) }
}

/// Computes the complementary error function.
#[inline]
pub fn erfc(x: f64) -> f64 {
    unsafe { m::erfc(x) }
}

/// Computes the exponential function.
#[inline]
pub fn exp(x: f64) -> f64 {
    unsafe { m::exp(x) }
}

/// Computes the gamma function.
#[inline]
pub fn gamma(x: f64) -> f64 {
    unsafe { m::tgamma(x) }
}

/// Computes the natural logarithm of the gamma function.
#[inline]
pub fn ln_gamma(x: f64) -> (f64, i32) {
    let mut sign: i32 = 0;
    let value = unsafe { m::lgamma_r(x, &mut sign) };
    (value, sign)
}

/// Computes the natural logarithm.
///
/// The domain is positive real numbers.
#[inline]
pub fn ln(x: f64) -> f64 {
    unsafe { m::log(x) }
}

/// Computes a base raised to an exponent.
#[inline]
pub fn pow(base: f64, exp: f64) -> f64 {
    unsafe { m::pow(base, exp) }
}

/// Computes the sine.
#[inline]
pub fn sin(x: f64) -> f64 {
    unsafe { m::sin(x) }
}

/// Computes the square root function.
///
/// The domain is non-negative real numbers.
#[inline]
pub fn sqrt(x: f64) -> f64 {
    unsafe { m::sqrt(x) }
}

#[cfg(test)]
mod test {
    #[test]
    fn gamma() {
        use super::{exp, gamma, ln_gamma};

        let x = -2.5;

        let gamma1 = -0.9453087204829418;
        let gamma2 = gamma(x);
        let gamma3 = {
            let (value, sign) = ln_gamma(x);
            (sign as f64) * exp(value)
        };

        assert_eq!(gamma1, gamma2);
        assert_eq!(gamma1, gamma3);
    }
}
<|endoftext|>


<commit_before>// Copyright 2016 Serde YAML Developers
//
// 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.extern crate serde;

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]

extern crate serde;
extern crate yaml_rust;

pub use self::de::{
    Deserializer,
    from_str,
};
pub use self::ser::{
    Serializer,
    to_writer,
    to_string,
};
pub use self::error::{
    Error,
    Result,
};

pub mod de;
pub mod ser;
pub mod error;
<commit_msg>Turn clippy warnings into errors<commit_after>// Copyright 2016 Serde YAML Developers
//
// 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.extern crate serde;

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", deny(clippy))] // turn warnings into errors

extern crate serde;
extern crate yaml_rust;

pub use self::de::{
    Deserializer,
    from_str,
};
pub use self::ser::{
    Serializer,
    to_writer,
    to_string,
};
pub use self::error::{
    Error,
    Result,
};

pub mod de;
pub mod ser;
pub mod error;
<|endoftext|>


<commit_before>//! The Liquid templating language for Rust
//!
//! __http://liquidmarkup.org/__
//!
//! ```toml
//! [dependencies]
//! liquid = "0.20"
//! ```
//!
//! ## Example
//! ```rust
//! let template = liquid::ParserBuilder::with_stdlib()
//!     .build().unwrap()
//!     .parse("Liquid! {{num | minus: 2}}").unwrap();
//!
//! let mut globals = liquid::object!({
//!     "num": 4f64
//! });
//!
//! let output = template.render(&globals).unwrap();
//! assert_eq!(output, "Liquid! 2".to_string());
//! ```

mod parser;
mod template;

pub mod reflection;

pub use liquid_core::partials;
/// Liquid data model.
pub mod model {
    pub use liquid_core::array;
    pub use liquid_core::model::*;
    pub use liquid_core::object;
    pub use liquid_core::scalar;
    pub use liquid_core::value;
}

pub use crate::parser::*;
pub use crate::template::*;
pub use liquid_core::object;
pub use liquid_core::to_object;
pub use liquid_core::Error;
pub use liquid_core::Object;
pub use liquid_core::{ObjectView, ValueView};
pub use liquid_derive::{ObjectView, ValueView};

#[macro_use]
extern crate doc_comment;
doc_comment! {
    include_str!("../README.md")
}
<commit_msg>docs: Remove derives?<commit_after>//! The Liquid templating language for Rust
//!
//! __http://liquidmarkup.org/__
//!
//! ```toml
//! [dependencies]
//! liquid = "0.20"
//! ```
//!
//! ## Example
//! ```rust
//! let template = liquid::ParserBuilder::with_stdlib()
//!     .build().unwrap()
//!     .parse("Liquid! {{num | minus: 2}}").unwrap();
//!
//! let mut globals = liquid::object!({
//!     "num": 4f64
//! });
//!
//! let output = template.render(&globals).unwrap();
//! assert_eq!(output, "Liquid! 2".to_string());
//! ```

mod parser;
mod template;

pub mod reflection;

pub use liquid_core::partials;
/// Liquid data model.
pub mod model {
    pub use liquid_core::array;
    pub use liquid_core::model::*;
    pub use liquid_core::object;
    pub use liquid_core::scalar;
    pub use liquid_core::value;
}

pub use crate::parser::*;
pub use crate::template::*;
pub use liquid_core::object;
pub use liquid_core::to_object;
pub use liquid_core::Error;
pub use liquid_core::Object;
pub use liquid_core::{ObjectView, ValueView};
#[doc(hidden)]
pub use liquid_derive::{ObjectView, ValueView};

#[macro_use]
extern crate doc_comment;
doc_comment! {
    include_str!("../README.md")
}
<|endoftext|>


<commit_before>//! A Simple wrapper for libreadline or libedit
//!
//! Exports two functions:
//!
//!   - `add_history`
//!   - `readline`
//!

extern crate libc;

use libc::c_char;

use std::ffi::CString;
use std::ffi::CStr;
use std::ptr;
use std::string::String;

mod ext_readline {
    use libc::{c_char, c_void};

    #[repr(C)]
    pub struct HIST_ENTRY {
	pub line: *const c_char,
        pub data: *mut c_void,
    }

    extern "C" {
        /* History Support */
        pub fn add_history(line: *const c_char);
        pub fn next_history() -> *const HIST_ENTRY;
        pub fn previous_history() -> *const HIST_ENTRY;
        pub fn history_expand(input: *const c_char, expansion: *mut *mut c_char) -> i32;
        pub fn stifle_history(n: i32);
        pub fn unstifle_history() -> i32;
        pub fn history_is_stifled() -> i32;

        /* readline */
        pub fn readline(p: *const c_char) -> *const c_char;
    }
}

/// Update the internal history of input lines
///
/// Call this after a successful `readline()` call to add that line to the
/// history.
pub fn add_history(line: &str) {
    unsafe {
        ext_readline::add_history(CString::new(line).unwrap().as_ptr());
    }
}

pub fn stifle_history(n: i32) {
    unsafe {
        ext_readline::stifle_history(n);
    }
}

pub fn unstifle_history() -> i32 {
    unsafe {
        ext_readline::unstifle_history()
    }
}

pub fn history_is_stifled() -> bool {
    unsafe {
        ext_readline::history_is_stifled() != 0
    }
}

pub fn history_expand(input: &str) -> Result<Option<String>, String> {
    unsafe {
        let mut expansion: *mut c_char = ptr::null_mut();
        let result = ext_readline::history_expand(CString::new(input).unwrap().as_ptr(),
                                                  (&mut expansion));
        if result == 0 {
            return Ok(None);
        }

        let slice = CStr::from_ptr(expansion);
        let bytes = slice.to_bytes();
        let output = String::from_utf8_lossy(bytes).into_owned().clone();

        libc::free(expansion as *mut libc::c_void);

        if result < 0 || result == 2 {
            Err(output)
        }
        else {
            Ok(Some(output))
        }
    }
}

/// Invoke the external `readline()`.
///
/// Returns an `Option<String>` representing whether a `String` was returned
/// or NULL. `None` indicates the user has signal end of input.
pub fn readline(prompt: &str) -> Option<String> {
    let cprmt = CString::new(prompt).unwrap().as_ptr();
    unsafe {
        let ret = ext_readline::readline(cprmt);
        if ret.is_null() {  // user pressed Ctrl-D
            None
        }
        else {
            let slice = CStr::from_ptr(ret);
            let bytes = slice.to_bytes();

            // the return from readline needs to be explicitly freed
            // so clone the input first
            let line = String::from_utf8_lossy(bytes).into_owned().clone();

            libc::free(ret as *mut libc::c_void);

            Some(line)
        }
    }
}

pub fn history() -> Vec<String> {
  unsafe {
    loop {
        let value = ext_readline::previous_history();
        if value.is_null() {
            break;
        }
    }

    let mut result: Vec<String> = Vec::new();

    loop {
        let value = ext_readline::next_history();
        if value.is_null() {
            break;
        }

        let slice = CStr::from_ptr((*value).line);
        let bytes = slice.to_bytes();
        let output = String::from_utf8_lossy(bytes).into_owned().clone();

        result.push(output);
    }

    result
  }
    // ReadlineIter { first: true }
}

pub struct ReadlineIter {
    first: bool,
}

impl Iterator for ReadlineIter {
    type Item = String;
    fn next(&mut self) -> Option<String> {
      unsafe {
        if self.first {
            loop {
                let value = ext_readline::previous_history();
                if value.is_null() {
                    break;
                }
            }

            self.first = false;
        }

        let value = ext_readline::next_history();
        if value.is_null() {
            return None;
        }

        let slice = CStr::from_ptr((*value).line);
        let bytes = slice.to_bytes();
        let output = String::from_utf8_lossy(bytes).into_owned().clone();

        Some(output)
      }
    }
}
<commit_msg>Remove dead iterator code<commit_after>//! A Simple wrapper for libreadline or libedit
//!
//! Exports two functions:
//!
//!   - `add_history`
//!   - `readline`
//!

extern crate libc;

use libc::c_char;

use std::ffi::CString;
use std::ffi::CStr;
use std::ptr;
use std::string::String;

mod ext_readline {
    use libc::{c_char, c_void};

    #[repr(C)]
    pub struct HIST_ENTRY {
	pub line: *const c_char,
        pub data: *mut c_void,
    }

    extern "C" {
        /* History Support */
        pub fn add_history(line: *const c_char);
        pub fn next_history() -> *const HIST_ENTRY;
        pub fn previous_history() -> *const HIST_ENTRY;
        pub fn history_expand(input: *const c_char, expansion: *mut *mut c_char) -> i32;
        pub fn stifle_history(n: i32);
        pub fn unstifle_history() -> i32;
        pub fn history_is_stifled() -> i32;

        /* readline */
        pub fn readline(p: *const c_char) -> *const c_char;
    }
}

/// Update the internal history of input lines
///
/// Call this after a successful `readline()` call to add that line to the
/// history.
pub fn add_history(line: &str) {
    unsafe {
        ext_readline::add_history(CString::new(line).unwrap().as_ptr());
    }
}

pub fn stifle_history(n: i32) {
    unsafe {
        ext_readline::stifle_history(n);
    }
}

pub fn unstifle_history() -> i32 {
    unsafe {
        ext_readline::unstifle_history()
    }
}

pub fn history_is_stifled() -> bool {
    unsafe {
        ext_readline::history_is_stifled() != 0
    }
}

pub fn history_expand(input: &str) -> Result<Option<String>, String> {
    unsafe {
        let mut expansion: *mut c_char = ptr::null_mut();
        let result = ext_readline::history_expand(CString::new(input).unwrap().as_ptr(),
                                                  (&mut expansion));
        if result == 0 {
            return Ok(None);
        }

        let slice = CStr::from_ptr(expansion);
        let bytes = slice.to_bytes();
        let output = String::from_utf8_lossy(bytes).into_owned().clone();

        libc::free(expansion as *mut libc::c_void);

        if result < 0 || result == 2 {
            Err(output)
        }
        else {
            Ok(Some(output))
        }
    }
}

/// Invoke the external `readline()`.
///
/// Returns an `Option<String>` representing whether a `String` was returned
/// or NULL. `None` indicates the user has signal end of input.
pub fn readline(prompt: &str) -> Option<String> {
    let cprmt = CString::new(prompt).unwrap().as_ptr();
    unsafe {
        let ret = ext_readline::readline(cprmt);
        if ret.is_null() {  // user pressed Ctrl-D
            None
        }
        else {
            let slice = CStr::from_ptr(ret);
            let bytes = slice.to_bytes();

            // the return from readline needs to be explicitly freed
            // so clone the input first
            let line = String::from_utf8_lossy(bytes).into_owned().clone();

            libc::free(ret as *mut libc::c_void);

            Some(line)
        }
    }
}

pub fn history() -> Vec<String> {
  unsafe {
    loop {
        let value = ext_readline::previous_history();
        if value.is_null() {
            break;
        }
    }

    let mut result: Vec<String> = Vec::new();

    loop {
        let value = ext_readline::next_history();
        if value.is_null() {
            break;
        }

        let slice = CStr::from_ptr((*value).line);
        let bytes = slice.to_bytes();
        let output = String::from_utf8_lossy(bytes).into_owned().clone();

        result.push(output);
    }

    result
  }
}
<|endoftext|>


<commit_before>#![crate_name = "xinerama"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]

#![feature(globs)]

extern crate libc;
extern crate xlib;

pub use xinerama::*;
mod xinerama;

<commit_msg>added libc feature<commit_after>#![crate_name = "xinerama"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]

#![feature(globs)]
#![feature(libc)]

extern crate libc;
extern crate xlib;

pub use xinerama::*;
mod xinerama;

<|endoftext|>


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

extern crate mio;

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use private::{promise_node, Event, BoolEvent, PromiseAndFulfillerHub,
              EVENT_LOOP, with_current_event_loop, PromiseNode};

pub mod io;

mod private;
mod handle_table;

pub type Error = Box<::std::error::Error>;
pub type Result<T> = ::std::result::Result<T, Error>;

/// The basic primitive of asynchronous computation in GJ.
pub struct Promise<T> where T: 'static {
    node : Box<PromiseNode<T>>,
}

impl <T> Promise <T> where T: 'static {
    pub fn then<F, R>(self, func: F) -> Promise<R>
        where F: 'static + FnOnce(T) -> Result<Promise<R>>,
              R: 'static {
                  self.then_else(func, |e| { return Err(e); })
        }

    pub fn then_else<F, G, R>(self, func: F, error_handler: G) -> Promise<R>
        where F: 'static + FnOnce(T) -> Result<Promise<R>>,
              G: 'static + FnOnce(Error) -> Result<Promise<R>>,
              R: 'static {
            let intermediate = Box::new(promise_node::Transform::new(self.node, func, error_handler));
            Promise { node: Box::new(promise_node::Chain::new(intermediate)) }
        }

    pub fn map<F, R>(self, func: F) -> Promise<R>
        where F: 'static + FnOnce(T) -> Result<R>,
              R: 'static {
            self.map_else(func, |e| { return Err(e); })
        }

    pub fn map_else<F, G, R>(self, func: F, error_handler: G) -> Promise<R>
        where F: 'static + FnOnce(T) -> Result<R>,
              G: 'static + FnOnce(Error) -> Result<R>,
              R: 'static {
            Promise { node: Box::new(promise_node::Transform::new(self.node, func, error_handler)) }
        }

    /// Runs the event loop until the promise is fulfilled.
    ///
    /// The `WaitScope` argument ensures that `wait()` can only be called the top level of a program.
    /// Waiting within event callbacks is disallowed.
    pub fn wait(mut self, _wait_scope: &WaitScope) -> Result<T> {
        with_current_event_loop(move |event_loop| {
            let fired = ::std::rc::Rc::new(::std::cell::Cell::new(false));
            let done_event = BoolEvent::new(fired.clone());
            let (handle, dropper) = private::EventHandle::new(Box::new(done_event));
            self.node.on_ready(handle);

            //event_loop.running = true;

            while !fired.get() {
                if !event_loop.turn() {
                    // No events in the queue.
                    event_loop.event_port.borrow_mut().wait();
                }
            }

            self.node.get()
        })
    }

    pub fn fulfilled(value: T) -> Promise<T> {
        return Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) };
    }

    pub fn rejected(error: Error) -> Promise<T> {
        return Promise { node: Box::new(promise_node::Immediate::new(Err(error))) };
    }
}

pub struct WaitScope(::std::marker::PhantomData<*mut u8>); // impl !Sync for WaitScope {}

/// Interface between an `EventLoop` and events originating from outside of the loop's thread.
pub trait EventPort {
    /// Waits for an external event to arrive, sleeping if necessary.
    /// Returns true if wake() has been called from another thread.
    fn wait(&mut self) -> bool;

    /// Checks whether any external events have arrived, but does not sleep.
    /// Returns true if wake() has been called from another thread.
    fn poll(&mut self) -> bool;

    /// Called to notify the `EventPort` when the `EventLoop` has work to do; specifically when it
    /// transitions from empty -> runnable or runnable -> empty. This is typically useful when
    /// intergrating with an external event loop; if the loop is currently runnable then you should
    /// arrange to call run() on it soon. The default implementation does nothing.
    fn set_runnable(&mut self, _runnable: bool) { }

    fn wake(&mut self) { unimplemented!(); }
}

/// A queue of events being executed in a loop.
pub struct EventLoop {
//    daemons: TaskSetImpl,
    event_port: RefCell<io::MioEventPort>,
    running: bool,
    _last_runnable_state: bool,
    events: RefCell<handle_table::HandleTable<private::EventNode>>,
    head: Cell<private::EventHandle>,
    tail: Cell<private::EventHandle>,
    depth_first_insertion_point: Cell<private::EventHandle>,
}

impl EventLoop {
    pub fn top_level<F>(f: F) where F: FnOnce(&WaitScope) {
        let mut events = handle_table::HandleTable::<private::EventNode>::new();
        let dummy = private::EventNode { event: None, next: None, prev: None };
        let head_handle = private::EventHandle(events.push(dummy));

        EVENT_LOOP.with(move |maybe_event_loop| {
            let event_loop = EventLoop {
                event_port: RefCell::new(io::MioEventPort::new().unwrap()),
                running: false,
                _last_runnable_state: false,
                events: RefCell::new(events),
                head: Cell::new(head_handle),
                tail: Cell::new(head_handle),
                depth_first_insertion_point: Cell::new(head_handle), // insert after this node
            };

            assert!(maybe_event_loop.borrow().is_none());
            *maybe_event_loop.borrow_mut() = Some(event_loop);
        });
        let wait_scope = WaitScope(::std::marker::PhantomData );
        f(&wait_scope);
    }

    fn arm_depth_first(&self, event_handle: private::EventHandle) {

        let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0].next;

        match insertion_node_next {
            Some(next_handle) => {
                self.events.borrow_mut()[next_handle.0].prev = Some(event_handle);
                self.events.borrow_mut()[event_handle.0].next = Some(next_handle);
            }
            None => {
                self.tail.set(event_handle);
            }
        }

        self.events.borrow_mut()[event_handle.0].prev = Some(self.depth_first_insertion_point.get());
        self.events.borrow_mut()[self.depth_first_insertion_point.get().0].next = Some(event_handle);
        self.depth_first_insertion_point.set(event_handle);
    }

    fn arm_breadth_first(&self, event_handle: private::EventHandle) {
        let events = &mut *self.events.borrow_mut();
        events[self.tail.get().0].next = Some(event_handle);
        events[event_handle.0].prev = Some(self.tail.get());
        self.tail.set(event_handle);
    }

    /// Runs the event loop for `max_turn_count` turns or until there is nothing left to be done,
    /// whichever comes first. This never calls the `EventPort`'s `sleep()` or `poll()`. It will
    /// call the `EventPort`'s `set_runnable(false)` if the queue becomes empty.
    pub fn run(&mut self, max_turn_count : u32) {
        self.running = true;

        for _ in 0..max_turn_count {
            if !self.turn() {
                break;
            }
        }
    }

    fn turn(&self) -> bool {

        let mut event_handle = match self.events.borrow()[self.head.get().0].next {
            None => return false,
            Some(event_handle) => { event_handle }
        };
        self.depth_first_insertion_point.set(event_handle);

        // When we're firing, head is the dummy event, as always. head.next is the firing event.
        // depth-first-insertion-point starts out as the firing event.
        // tail is the last event in the queue. If there are no further events,
        // tail is the firing event.

        let mut event = ::std::mem::replace(&mut self.events.borrow_mut()[event_handle.0].event, None)
            .expect("No event to fire?");
        event.fire();

        let event_node = self.events.borrow_mut().remove(event_handle.0).unwrap();

        // event_node.next.prev = event_node.prev
        match event_node.next {
            Some(e) => {
                self.events.borrow_mut()[e.0].prev = event_node.prev;
            }
            None => {}
        }

        // event_node.prev.next = event_node.next
        match event_node.prev {
            Some(e) => {
                self.events.borrow_mut()[e.0].next = event_node.next;
            }
            None => {}
        }

        if self.tail.get() == event_handle {
            self.tail.set(self.head.get());
        }
        return true;
    }
}

/// A callback which can be used to fulfill a promise.
pub trait PromiseFulfiller<T> where T: 'static {
    fn fulfill(self: Box<Self>, value: T);
    fn reject(self: Box<Self>, error: Error);
}

pub fn new_promise_and_fulfiller<T>() -> (Promise<T>, Box<PromiseFulfiller<T>>) where T: 'static {
    let result = ::std::rc::Rc::new(::std::cell::RefCell::new(PromiseAndFulfillerHub::new()));
    let result_promise : Promise<T> = Promise { node: Box::new(result.clone())};
    (result_promise, Box::new(result))
}

/// Holds a collection of Promise<()>s and ensures that each executes to comleteion.
/// Destroying a TaskSet automatically cancels all of its unfinished promises.
pub struct TaskSet {
    task_set_impl: Rc<RefCell<private::TaskSetImpl>>,
}

impl TaskSet {
    pub fn new(error_handler: Box<ErrorHandler>) -> TaskSet {
        TaskSet { task_set_impl : Rc::new(RefCell::new(private::TaskSetImpl::new(error_handler))) }
    }

    pub fn add(&mut self, promise: Promise<()>) {
        private::TaskSetImpl::add(self.task_set_impl.clone(), promise.node);
    }
}

pub trait ErrorHandler {
    fn task_failed(&mut self, error: Error);
}

<commit_msg>Fix another bug. All tests pass, but example proxy is still broken.<commit_after>// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

extern crate mio;

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use private::{promise_node, Event, BoolEvent, PromiseAndFulfillerHub,
              EVENT_LOOP, with_current_event_loop, PromiseNode};

pub mod io;

mod private;
mod handle_table;

pub type Error = Box<::std::error::Error>;
pub type Result<T> = ::std::result::Result<T, Error>;

/// The basic primitive of asynchronous computation in GJ.
pub struct Promise<T> where T: 'static {
    node : Box<PromiseNode<T>>,
}

impl <T> Promise <T> where T: 'static {
    pub fn then<F, R>(self, func: F) -> Promise<R>
        where F: 'static + FnOnce(T) -> Result<Promise<R>>,
              R: 'static {
                  self.then_else(func, |e| { return Err(e); })
        }

    pub fn then_else<F, G, R>(self, func: F, error_handler: G) -> Promise<R>
        where F: 'static + FnOnce(T) -> Result<Promise<R>>,
              G: 'static + FnOnce(Error) -> Result<Promise<R>>,
              R: 'static {
            let intermediate = Box::new(promise_node::Transform::new(self.node, func, error_handler));
            Promise { node: Box::new(promise_node::Chain::new(intermediate)) }
        }

    pub fn map<F, R>(self, func: F) -> Promise<R>
        where F: 'static + FnOnce(T) -> Result<R>,
              R: 'static {
            self.map_else(func, |e| { return Err(e); })
        }

    pub fn map_else<F, G, R>(self, func: F, error_handler: G) -> Promise<R>
        where F: 'static + FnOnce(T) -> Result<R>,
              G: 'static + FnOnce(Error) -> Result<R>,
              R: 'static {
            Promise { node: Box::new(promise_node::Transform::new(self.node, func, error_handler)) }
        }

    /// Runs the event loop until the promise is fulfilled.
    ///
    /// The `WaitScope` argument ensures that `wait()` can only be called the top level of a program.
    /// Waiting within event callbacks is disallowed.
    pub fn wait(mut self, _wait_scope: &WaitScope) -> Result<T> {
        with_current_event_loop(move |event_loop| {
            let fired = ::std::rc::Rc::new(::std::cell::Cell::new(false));
            let done_event = BoolEvent::new(fired.clone());
            let (handle, dropper) = private::EventHandle::new(Box::new(done_event));
            self.node.on_ready(handle);

            //event_loop.running = true;

            while !fired.get() {
                if !event_loop.turn() {
                    // No events in the queue.
                    event_loop.event_port.borrow_mut().wait();
                }
            }

            self.node.get()
        })
    }

    pub fn fulfilled(value: T) -> Promise<T> {
        return Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) };
    }

    pub fn rejected(error: Error) -> Promise<T> {
        return Promise { node: Box::new(promise_node::Immediate::new(Err(error))) };
    }
}

pub struct WaitScope(::std::marker::PhantomData<*mut u8>); // impl !Sync for WaitScope {}

/// Interface between an `EventLoop` and events originating from outside of the loop's thread.
pub trait EventPort {
    /// Waits for an external event to arrive, sleeping if necessary.
    /// Returns true if wake() has been called from another thread.
    fn wait(&mut self) -> bool;

    /// Checks whether any external events have arrived, but does not sleep.
    /// Returns true if wake() has been called from another thread.
    fn poll(&mut self) -> bool;

    /// Called to notify the `EventPort` when the `EventLoop` has work to do; specifically when it
    /// transitions from empty -> runnable or runnable -> empty. This is typically useful when
    /// intergrating with an external event loop; if the loop is currently runnable then you should
    /// arrange to call run() on it soon. The default implementation does nothing.
    fn set_runnable(&mut self, _runnable: bool) { }

    fn wake(&mut self) { unimplemented!(); }
}

/// A queue of events being executed in a loop.
pub struct EventLoop {
//    daemons: TaskSetImpl,
    event_port: RefCell<io::MioEventPort>,
    running: bool,
    _last_runnable_state: bool,
    events: RefCell<handle_table::HandleTable<private::EventNode>>,
    head: Cell<private::EventHandle>,
    tail: Cell<private::EventHandle>,
    depth_first_insertion_point: Cell<private::EventHandle>,
}

impl EventLoop {
    pub fn top_level<F>(f: F) where F: FnOnce(&WaitScope) {
        let mut events = handle_table::HandleTable::<private::EventNode>::new();
        let dummy = private::EventNode { event: None, next: None, prev: None };
        let head_handle = private::EventHandle(events.push(dummy));

        EVENT_LOOP.with(move |maybe_event_loop| {
            let event_loop = EventLoop {
                event_port: RefCell::new(io::MioEventPort::new().unwrap()),
                running: false,
                _last_runnable_state: false,
                events: RefCell::new(events),
                head: Cell::new(head_handle),
                tail: Cell::new(head_handle),
                depth_first_insertion_point: Cell::new(head_handle), // insert after this node
            };

            assert!(maybe_event_loop.borrow().is_none());
            *maybe_event_loop.borrow_mut() = Some(event_loop);
        });
        let wait_scope = WaitScope(::std::marker::PhantomData );
        f(&wait_scope);
    }

    fn arm_depth_first(&self, event_handle: private::EventHandle) {

        let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0].next;

        match insertion_node_next {
            Some(next_handle) => {
                self.events.borrow_mut()[next_handle.0].prev = Some(event_handle);
                self.events.borrow_mut()[event_handle.0].next = Some(next_handle);
            }
            None => {
                self.tail.set(event_handle);
            }
        }

        self.events.borrow_mut()[event_handle.0].prev = Some(self.depth_first_insertion_point.get());
        self.events.borrow_mut()[self.depth_first_insertion_point.get().0].next = Some(event_handle);
        self.depth_first_insertion_point.set(event_handle);
    }

    fn arm_breadth_first(&self, event_handle: private::EventHandle) {
        let events = &mut *self.events.borrow_mut();
        events[self.tail.get().0].next = Some(event_handle);
        events[event_handle.0].prev = Some(self.tail.get());
        self.tail.set(event_handle);
    }

    /// Runs the event loop for `max_turn_count` turns or until there is nothing left to be done,
    /// whichever comes first. This never calls the `EventPort`'s `sleep()` or `poll()`. It will
    /// call the `EventPort`'s `set_runnable(false)` if the queue becomes empty.
    pub fn run(&mut self, max_turn_count : u32) {
        self.running = true;

        for _ in 0..max_turn_count {
            if !self.turn() {
                break;
            }
        }
    }

    fn turn(&self) -> bool {

        let mut event_handle = match self.events.borrow()[self.head.get().0].next {
            None => return false,
            Some(event_handle) => { event_handle }
        };
        self.depth_first_insertion_point.set(event_handle);

        // When we're firing, head is the dummy event, as always. head.next is the firing event.
        // depth-first-insertion-point starts out as the firing event.
        // tail is the last event in the queue. If there are no further events,
        // tail is the firing event.

        let mut event = ::std::mem::replace(&mut self.events.borrow_mut()[event_handle.0].event, None)
            .expect("No event to fire?");
        event.fire();

        let event_node = self.events.borrow_mut().remove(event_handle.0).unwrap();

        // event_node.next.prev = event_node.prev
        match event_node.next {
            Some(e) => {
                self.events.borrow_mut()[e.0].prev = event_node.prev;
            }
            None => {}
        }

        // event_node.prev.next = event_node.next
        match event_node.prev {
            Some(e) => {
                self.events.borrow_mut()[e.0].next = event_node.next;
            }
            None => {}
        }

        if self.tail.get() == event_handle {
            self.tail.set(self.head.get());
        }

        self.depth_first_insertion_point.set(self.head.get());
        return true;
    }
}

/// A callback which can be used to fulfill a promise.
pub trait PromiseFulfiller<T> where T: 'static {
    fn fulfill(self: Box<Self>, value: T);
    fn reject(self: Box<Self>, error: Error);
}

pub fn new_promise_and_fulfiller<T>() -> (Promise<T>, Box<PromiseFulfiller<T>>) where T: 'static {
    let result = ::std::rc::Rc::new(::std::cell::RefCell::new(PromiseAndFulfillerHub::new()));
    let result_promise : Promise<T> = Promise { node: Box::new(result.clone())};
    (result_promise, Box::new(result))
}

/// Holds a collection of Promise<()>s and ensures that each executes to comleteion.
/// Destroying a TaskSet automatically cancels all of its unfinished promises.
pub struct TaskSet {
    task_set_impl: Rc<RefCell<private::TaskSetImpl>>,
}

impl TaskSet {
    pub fn new(error_handler: Box<ErrorHandler>) -> TaskSet {
        TaskSet { task_set_impl : Rc::new(RefCell::new(private::TaskSetImpl::new(error_handler))) }
    }

    pub fn add(&mut self, promise: Promise<()>) {
        private::TaskSetImpl::add(self.task_set_impl.clone(), promise.node);
    }
}

pub trait ErrorHandler {
    fn task_failed(&mut self, error: Error);
}

<|endoftext|>


<commit_before>fn check_easter_happened(year: i32) {
    if year < 33 {
        panic!(format!("Jesus isn't dead yet in the year {}", year));
    }
}

pub mod gregorian {
    /// Easter in the Gregorian calendar
    pub fn month_day(year: i32) -> (u32, u32) {
        super::check_easter_happened(year);
        let a = year % 19;
        let b = year / 100;
        let c = year % 100;
        let d = b / 4;
        let e = b % 4;
        let f = (b + 8) / 25;
        let g = (b - f + 1) / 3;
        let h = (19 * a + b - d - g + 15) % 30;
        let i = c / 4;
        let k = c % 4;
        let l = (32 + 2 * e + 2 * i - h - k) % 7;
        let m = (a + 11 * h + 22 * l) / 451;
        let month = (h + l - 7 * m + 114) / 31;
        let day = (h + l - 7 * m + 114) % 31 + 1;
        (month as u32, day as u32)
    }
}

pub mod julian {
    /// Easter in the Julian calendar
    pub fn month_day(year: i32) -> (u32, u32) {
        super::check_easter_happened(year);
        let a = year % 4;
        let b = year % 7;
        let c = year % 19;
        let d = (19 * c + 15) % 30;
        let e = (2 * a + 4 * b - d + 34) % 7;
        let f = d + e + 114;
        let month = f / 31;
        let day = f % 31 + 1;
        (month as u32, day as u32)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn gregorian_month_day() {
        use super::gregorian::month_day;
        assert_eq!(month_day(1961), (4, 2));
        assert_eq!(month_day(1996), (4, 7));
        assert_eq!(month_day(1997), (3, 30));
        assert_eq!(month_day(1998), (4, 12));
        assert_eq!(month_day(2000), (4, 23));
        assert_eq!(month_day(2001), (4, 15));
        assert_eq!(month_day(2002), (3, 31));
        assert_eq!(month_day(2003), (4, 20));
        assert_eq!(month_day(2004), (4, 11));
        assert_eq!(month_day(2005), (3, 27));
        assert_eq!(month_day(2006), (4, 16));
        assert_eq!(month_day(2007), (4, 8));
        assert_eq!(month_day(2008), (3, 23));
        assert_eq!(month_day(2009), (4, 12));
        assert_eq!(month_day(2010), (4, 4));
        assert_eq!(month_day(2011), (4, 24));
        assert_eq!(month_day(2012), (4, 8));
        assert_eq!(month_day(2013), (3, 31));
        assert_eq!(month_day(2014), (4, 20));
        assert_eq!(month_day(2015), (4, 5));
        assert_eq!(month_day(2016), (3, 27));
        assert_eq!(month_day(2017), (4, 16));
        assert_eq!(month_day(2018), (4, 1));
        assert_eq!(month_day(2019), (4, 21));
        assert_eq!(month_day(2020), (4, 12));
    }

    #[test]
    fn julian_month_day() {
        use super::julian::month_day;
        assert_eq!(month_day(1961), (3, 27));
        assert_eq!(month_day(1996), (4, 1));
        assert_eq!(month_day(1997), (4, 14));
        assert_eq!(month_day(1998), (4, 6));
        assert_eq!(month_day(1999), (3, 29));
        assert_eq!(month_day(2000), (4, 17));
        assert_eq!(month_day(2001), (4, 2));
        assert_eq!(month_day(2002), (4, 22));
        assert_eq!(month_day(2003), (4, 14));
        assert_eq!(month_day(2004), (3, 29));
        assert_eq!(month_day(2005), (4, 18));
        assert_eq!(month_day(2006), (4, 10));
        assert_eq!(month_day(2007), (3, 26));
        assert_eq!(month_day(2008), (4, 14));
        assert_eq!(month_day(2009), (4, 6));
        assert_eq!(month_day(2010), (3, 22));
        assert_eq!(month_day(2011), (4, 11));
        assert_eq!(month_day(2012), (4, 2));
        assert_eq!(month_day(2013), (4, 22));
        assert_eq!(month_day(2014), (4, 7));
        assert_eq!(month_day(2015), (3, 30));
        assert_eq!(month_day(2016), (4, 18));
        assert_eq!(month_day(2017), (4, 3));
        assert_eq!(month_day(2018), (3, 26));
        assert_eq!(month_day(2019), (4, 15));
        assert_eq!(month_day(2020), (4, 6));
    }
}
<commit_msg>convince clippy to quieten down<commit_after>fn check_easter_happened(year: i32) {
    if year < 33 {
        panic!(format!("Jesus isn't dead yet in the year {}", year));
    }
}

pub mod gregorian {
    /// Easter in the Gregorian calendar
    pub fn month_day(year: i32) -> (u32, u32) {
        super::check_easter_happened(year);
        let aa = year % 19;
        let bb = year / 100;
        let cc = year % 100;
        let dd = bb / 4;
        let ee = bb % 4;
        let ff = (bb + 8) / 25;
        let gg = (bb - ff + 1) / 3;
        let hh = (19 * aa + bb - dd - gg + 15) % 30;
        let ii = cc / 4;
        let kk = cc % 4;
        let ll = (32 + 2 * ee + 2 * ii - hh - kk) % 7;
        let mm = (aa + 11 * hh + 22 * ll) / 451;
        let month = (hh + ll - 7 * mm + 114) / 31;
        let day = (hh + ll - 7 * mm + 114) % 31 + 1;
        (month as u32, day as u32)
    }
}

pub mod julian {
    /// Easter in the Julian calendar
    pub fn month_day(year: i32) -> (u32, u32) {
        super::check_easter_happened(year);
        let aa = year % 4;
        let bb = year % 7;
        let cc = year % 19;
        let dd = (19 * cc + 15) % 30;
        let ee = (2 * aa + 4 * bb - dd + 34) % 7;
        let ff = dd + ee + 114;
        let month = ff / 31;
        let day = ff % 31 + 1;
        (month as u32, day as u32)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn gregorian_month_day() {
        use super::gregorian::month_day;
        assert_eq!(month_day(1961), (4, 2));
        assert_eq!(month_day(1996), (4, 7));
        assert_eq!(month_day(1997), (3, 30));
        assert_eq!(month_day(1998), (4, 12));
        assert_eq!(month_day(2000), (4, 23));
        assert_eq!(month_day(2001), (4, 15));
        assert_eq!(month_day(2002), (3, 31));
        assert_eq!(month_day(2003), (4, 20));
        assert_eq!(month_day(2004), (4, 11));
        assert_eq!(month_day(2005), (3, 27));
        assert_eq!(month_day(2006), (4, 16));
        assert_eq!(month_day(2007), (4, 8));
        assert_eq!(month_day(2008), (3, 23));
        assert_eq!(month_day(2009), (4, 12));
        assert_eq!(month_day(2010), (4, 4));
        assert_eq!(month_day(2011), (4, 24));
        assert_eq!(month_day(2012), (4, 8));
        assert_eq!(month_day(2013), (3, 31));
        assert_eq!(month_day(2014), (4, 20));
        assert_eq!(month_day(2015), (4, 5));
        assert_eq!(month_day(2016), (3, 27));
        assert_eq!(month_day(2017), (4, 16));
        assert_eq!(month_day(2018), (4, 1));
        assert_eq!(month_day(2019), (4, 21));
        assert_eq!(month_day(2020), (4, 12));
    }

    #[test]
    fn julian_month_day() {
        use super::julian::month_day;
        assert_eq!(month_day(1961), (3, 27));
        assert_eq!(month_day(1996), (4, 1));
        assert_eq!(month_day(1997), (4, 14));
        assert_eq!(month_day(1998), (4, 6));
        assert_eq!(month_day(1999), (3, 29));
        assert_eq!(month_day(2000), (4, 17));
        assert_eq!(month_day(2001), (4, 2));
        assert_eq!(month_day(2002), (4, 22));
        assert_eq!(month_day(2003), (4, 14));
        assert_eq!(month_day(2004), (3, 29));
        assert_eq!(month_day(2005), (4, 18));
        assert_eq!(month_day(2006), (4, 10));
        assert_eq!(month_day(2007), (3, 26));
        assert_eq!(month_day(2008), (4, 14));
        assert_eq!(month_day(2009), (4, 6));
        assert_eq!(month_day(2010), (3, 22));
        assert_eq!(month_day(2011), (4, 11));
        assert_eq!(month_day(2012), (4, 2));
        assert_eq!(month_day(2013), (4, 22));
        assert_eq!(month_day(2014), (4, 7));
        assert_eq!(month_day(2015), (3, 30));
        assert_eq!(month_day(2016), (4, 18));
        assert_eq!(month_day(2017), (4, 3));
        assert_eq!(month_day(2018), (3, 26));
        assert_eq!(month_day(2019), (4, 15));
        assert_eq!(month_day(2020), (4, 6));
    }
}
<|endoftext|>


<commit_before>//! A database access library for leveldb
//!
//! Usage:
//!
//! ```rust
//! #![allow(unstable)]
//!
//! use std::fs::TempDir;
//! use leveldb::database::Database;
//! use leveldb::kv::KV;
//! use leveldb::options::{Options,WriteOptions,ReadOptions};
//!
//! let tempdir = TempDir::new("demo").unwrap();
//! let path = tempdir.path();
//!
//! let mut options = Options::new();
//! options.create_if_missing = true;
//! let mut database = match Database::open(path, options) {
//!     Ok(db) => { db },
//!     Err(e) => { panic!("failed to open database: {:?}", e) }
//! };
//!
//! let write_opts = WriteOptions::new();
//! match database.put(write_opts, 1, &[1]) {
//!     Ok(_) => { () },
//!     Err(e) => { panic!("failed to write to database: {:?}", e) }
//! };
//!
//! let read_opts = ReadOptions::new();
//! let res = database.get(read_opts,
//!                        1);
//! match res {
//!   Ok(data) => {
//!     assert!(data.is_some());
//!     assert_eq!(data, Some(vec![1]));
//!   }
//!   Err(e) => { panic!("failed reading data: {:?}", e) }
//! }
//! ```

#![crate_type = "lib"]
#![crate_name = "leveldb"]
#![deny(warnings)]
#![deny(missing_docs)]
#![feature(std_misc)]
#![feature(core)]
#![feature(collections)]
#![feature(path)]

extern crate libc;
extern crate core;

use cbits::leveldb::{leveldb_major_version,leveldb_minor_version};
pub use database::options as options;
pub use database::error as error;
pub use database::iterator as iterator;
pub use database::snapshots as snapshots;
pub use database::comparator as comparator;
pub use database::kv as kv;

use core::marker::PhantomFn;

#[allow(missing_docs)]
pub mod cbits;
pub mod database;

/// Library version information
///
/// Need a recent version of leveldb to be used.

pub trait Version : PhantomFn<Self, ()> {
    /// The major version.
    fn major() -> isize {
        unsafe { leveldb_major_version() as isize }
    }

    /// The minor version
    fn minor() -> isize {
        unsafe { leveldb_minor_version() as isize }
    }
}
<commit_msg>Remove std_misc feature flag<commit_after>//! A database access library for leveldb
//!
//! Usage:
//!
//! ```rust
//! #![allow(unstable)]
//!
//! use std::fs::TempDir;
//! use leveldb::database::Database;
//! use leveldb::kv::KV;
//! use leveldb::options::{Options,WriteOptions,ReadOptions};
//!
//! let tempdir = TempDir::new("demo").unwrap();
//! let path = tempdir.path();
//!
//! let mut options = Options::new();
//! options.create_if_missing = true;
//! let mut database = match Database::open(path, options) {
//!     Ok(db) => { db },
//!     Err(e) => { panic!("failed to open database: {:?}", e) }
//! };
//!
//! let write_opts = WriteOptions::new();
//! match database.put(write_opts, 1, &[1]) {
//!     Ok(_) => { () },
//!     Err(e) => { panic!("failed to write to database: {:?}", e) }
//! };
//!
//! let read_opts = ReadOptions::new();
//! let res = database.get(read_opts,
//!                        1);
//! match res {
//!   Ok(data) => {
//!     assert!(data.is_some());
//!     assert_eq!(data, Some(vec![1]));
//!   }
//!   Err(e) => { panic!("failed reading data: {:?}", e) }
//! }
//! ```

#![crate_type = "lib"]
#![crate_name = "leveldb"]
#![deny(warnings)]
#![deny(missing_docs)]
#![feature(core)]
#![feature(collections)]
#![feature(path)]

extern crate libc;
extern crate core;

use cbits::leveldb::{leveldb_major_version,leveldb_minor_version};
pub use database::options as options;
pub use database::error as error;
pub use database::iterator as iterator;
pub use database::snapshots as snapshots;
pub use database::comparator as comparator;
pub use database::kv as kv;

use core::marker::PhantomFn;

#[allow(missing_docs)]
pub mod cbits;
pub mod database;

/// Library version information
///
/// Need a recent version of leveldb to be used.

pub trait Version : PhantomFn<Self, ()> {
    /// The major version.
    fn major() -> isize {
        unsafe { leveldb_major_version() as isize }
    }

    /// The minor version
    fn minor() -> isize {
        unsafe { leveldb_minor_version() as isize }
    }
}
<|endoftext|>


<commit_before>#![deny(warnings)]

//! [![Build Status](https://travis-ci.org/whatisinternet/inflector.svg?branch=master)](https://travis-ci.org/whatisinternet/inflector) [![Crates.io](https://img.shields.io/crates/v/inflector.svg)](https://crates.io/crates/inflector)

//! Adds String based inflections for Rust. Snake, kebab, camel,
//! sentence, class, title, upper, and lower cases as well as ordinalize,
//! deordinalize, demodulize, deconstantize, and foreign key are supported as
//! both traits and pure functions acting on String types.
//!
//! ```rust
//! use inflector::Inflector;
//! let camel_case_string: String = "some_string".to_camel_case();
//! let is_camel_cased: bool= camel_case_string.is_camel_case();
//! assert!(is_camel_cased == true);
//! ```
extern crate regex;
#[macro_use]
extern crate lazy_static;
/// Provides case inflections
/// - Camel case
/// - Class case
/// - Kebab case
/// - Lower case
/// - Screaming snake case
/// - Table case
/// - Sentence case
/// - Snake case
/// - Upper case
pub mod cases;
/// Provides number inflections
/// - Ordinalize
/// - Deordinalize
pub mod numbers;
/// Provides suffix inflections
/// - Foreign key
pub mod suffix;
/// Provides string inflections
/// - Deconstantize
/// - Demodulize
/// - Pluralize
/// - Singularize
pub mod string;

use cases::classcase::to_class_case;
use cases::classcase::is_class_case;

use cases::camelcase::to_camel_case;
use cases::camelcase::is_camel_case;

use cases::snakecase::to_snake_case;
use cases::snakecase::is_snake_case;

use cases::screamingsnakecase::to_screaming_snake_case;
use cases::screamingsnakecase::is_screaming_snake_case;

use cases::kebabcase::to_kebab_case;
use cases::kebabcase::is_kebab_case;

use cases::sentencecase::to_sentence_case;
use cases::sentencecase::is_sentence_case;

use cases::titlecase::to_title_case;
use cases::titlecase::is_title_case;

use cases::tablecase::to_table_case;
use cases::tablecase::is_table_case;

use cases::uppercase::to_upper_case;
use cases::uppercase::is_upper_case;

use cases::lowercase::to_lower_case;
use cases::lowercase::is_lower_case;

use numbers::ordinalize::ordinalize;
use numbers::deordinalize::deordinalize;

use suffix::foreignkey::to_foreign_key;
use suffix::foreignkey::is_foreign_key;

use string::demodulize::demodulize;
use string::deconstantize::deconstantize;

use string::pluralize::to_plural;
use string::singularize::to_singular;

pub trait Inflector {
    fn to_class_case(&self) -> String;
    fn is_class_case(&self) -> bool;

    fn to_camel_case(&self) -> String;
    fn is_camel_case(&self) -> bool;

    fn to_table_case(&self) -> String;
    fn is_table_case(&self) -> bool;

    fn to_snake_case(&self) -> String;
    fn is_snake_case(&self) -> bool;

    fn to_screaming_snake_case(&self) -> String;
    fn is_screaming_snake_case(&self) -> bool;

    fn to_kebab_case(&self) -> String;
    fn is_kebab_case(&self) -> bool;

    fn to_sentence_case(&self) -> String;
    fn is_sentence_case(&self) -> bool;

    fn to_title_case(&self) -> String;
    fn is_title_case(&self) -> bool;

    fn to_upper_case(&self) -> String;
    fn is_upper_case(&self) -> bool;

    fn to_lower_case(&self) -> String;
    fn is_lower_case(&self) -> bool;

    fn ordinalize(&self) -> String;
    fn deordinalize(&self) -> String;

    fn to_foreign_key(&self) -> String;
    fn is_foreign_key(&self) -> bool;

    fn demodulize(&self) -> String;
    fn deconstantize(&self) -> String;

    fn to_plural(&self) -> String;
    fn to_singular(&self) -> String;
}

impl<'c> Inflector for String {
    fn to_class_case(&self) -> String {
        to_class_case(self.to_string())
    }
    fn is_class_case(&self) -> bool {
        is_class_case(self.to_string())
    }
    fn to_camel_case(&self) -> String {
        to_camel_case(self.to_string())
    }
    fn is_camel_case(&self) -> bool {
        is_camel_case(self.to_string())
    }
    fn to_table_case(&self) -> String {
        to_table_case(self.to_string())
    }
    fn is_table_case(&self) -> bool {
        is_table_case(self.to_string())
    }
    fn to_screaming_snake_case(&self) -> String {
        to_screaming_snake_case(self.to_string())
    }
    fn is_screaming_snake_case(&self) -> bool {
        is_screaming_snake_case(self.to_string())
    }
    fn to_snake_case(&self) -> String {
        to_snake_case(self.to_string())
    }
    fn is_snake_case(&self) -> bool {
        is_snake_case(self.to_string())
    }
    fn to_kebab_case(&self) -> String {
        to_kebab_case(self.to_string())
    }
    fn is_kebab_case(&self) -> bool {
        is_kebab_case(self.to_string())
    }
    fn to_sentence_case(&self) -> String {
        to_sentence_case(self.to_string())
    }
    fn is_sentence_case(&self) -> bool {
        is_sentence_case(self.to_string())
    }
    fn to_title_case(&self) -> String {
        to_title_case(self.to_string())
    }
    fn is_title_case(&self) -> bool {
        is_title_case(self.to_string())
    }
    fn to_upper_case(&self) -> String {
        to_upper_case(self.to_string())
    }
    fn is_upper_case(&self) -> bool {
        is_upper_case(self.to_string())
    }
    fn to_lower_case(&self) -> String {
        to_lower_case(self.to_string())
    }
    fn is_lower_case(&self) -> bool {
        is_lower_case(self.to_string())
    }
    fn ordinalize(&self) -> String {
        ordinalize(self.to_string())
    }
    fn deordinalize(&self) -> String {
        deordinalize(self.to_string())
    }
    fn to_foreign_key(&self) -> String {
        to_foreign_key(self.to_string())
    }
    fn is_foreign_key(&self) -> bool {
        is_foreign_key(self.to_string())
    }
    fn demodulize(&self) -> String {
        demodulize(self.to_string())
    }
    fn deconstantize(&self) -> String {
        deconstantize(self.to_string())
    }
    fn to_plural(&self) -> String {
        to_plural(self.to_string())
    }
    fn to_singular(&self) -> String {
        to_singular(self.to_string())
    }
}

impl<'c> Inflector for str {
    fn to_class_case(&self) -> String {
        to_class_case(self.to_string())
    }
    fn is_class_case(&self) -> bool {
        is_class_case(self.to_string())
    }
    fn to_camel_case(&self) -> String {
        to_camel_case(self.to_string())
    }
    fn is_camel_case(&self) -> bool {
        is_camel_case(self.to_string())
    }
    fn to_table_case(&self) -> String {
        to_table_case(self.to_string())
    }
    fn is_table_case(&self) -> bool {
        is_table_case(self.to_string())
    }
    fn to_screaming_snake_case(&self) -> String {
        to_screaming_snake_case(self.to_string())
    }
    fn is_screaming_snake_case(&self) -> bool {
        is_screaming_snake_case(self.to_string())
    }
    fn to_snake_case(&self) -> String {
        to_snake_case(self.to_string())
    }
    fn is_snake_case(&self) -> bool {
        is_snake_case(self.to_string())
    }
    fn to_kebab_case(&self) -> String {
        to_kebab_case(self.to_string())
    }
    fn is_kebab_case(&self) -> bool {
        is_kebab_case(self.to_string())
    }
    fn to_sentence_case(&self) -> String {
        to_sentence_case(self.to_string())
    }
    fn is_sentence_case(&self) -> bool {
        is_sentence_case(self.to_string())
    }
    fn to_title_case(&self) -> String {
        to_title_case(self.to_string())
    }
    fn is_title_case(&self) -> bool {
        is_title_case(self.to_string())
    }
    fn to_upper_case(&self) -> String {
        to_upper_case(self.to_string())
    }
    fn is_upper_case(&self) -> bool {
        is_upper_case(self.to_string())
    }
    fn to_lower_case(&self) -> String {
        to_lower_case(self.to_string())
    }
    fn is_lower_case(&self) -> bool {
        is_lower_case(self.to_string())
    }
    fn ordinalize(&self) -> String {
        ordinalize(self.to_string())
    }
    fn deordinalize(&self) -> String {
        deordinalize(self.to_string())
    }
    fn to_foreign_key(&self) -> String {
        to_foreign_key(self.to_string())
    }
    fn is_foreign_key(&self) -> bool {
        is_foreign_key(self.to_string())
    }
    fn demodulize(&self) -> String {
        demodulize(self.to_string())
    }
    fn deconstantize(&self) -> String {
        deconstantize(self.to_string())
    }

    fn to_plural(&self) -> String {
        to_plural(self.to_string())
    }

    fn to_singular(&self) -> String {
        to_singular(self.to_string())
    }
}
<commit_msg>Removed build status from docs<commit_after>#![deny(warnings)]

//! Adds String based inflections for Rust. Snake, kebab, camel,
//! sentence, class, title, upper, and lower cases as well as ordinalize,
//! deordinalize, demodulize, deconstantize, and foreign key are supported as
//! both traits and pure functions acting on String types.
//!
//! ```rust
//! use inflector::Inflector;
//! let camel_case_string: String = "some_string".to_camel_case();
//! let is_camel_cased: bool= camel_case_string.is_camel_case();
//! assert!(is_camel_cased == true);
//! ```
extern crate regex;
#[macro_use]
extern crate lazy_static;
/// Provides case inflections
/// - Camel case
/// - Class case
/// - Kebab case
/// - Lower case
/// - Screaming snake case
/// - Table case
/// - Sentence case
/// - Snake case
/// - Upper case
pub mod cases;
/// Provides number inflections
/// - Ordinalize
/// - Deordinalize
pub mod numbers;
/// Provides suffix inflections
/// - Foreign key
pub mod suffix;
/// Provides string inflections
/// - Deconstantize
/// - Demodulize
/// - Pluralize
/// - Singularize
pub mod string;

use cases::classcase::to_class_case;
use cases::classcase::is_class_case;

use cases::camelcase::to_camel_case;
use cases::camelcase::is_camel_case;

use cases::snakecase::to_snake_case;
use cases::snakecase::is_snake_case;

use cases::screamingsnakecase::to_screaming_snake_case;
use cases::screamingsnakecase::is_screaming_snake_case;

use cases::kebabcase::to_kebab_case;
use cases::kebabcase::is_kebab_case;

use cases::sentencecase::to_sentence_case;
use cases::sentencecase::is_sentence_case;

use cases::titlecase::to_title_case;
use cases::titlecase::is_title_case;

use cases::tablecase::to_table_case;
use cases::tablecase::is_table_case;

use cases::uppercase::to_upper_case;
use cases::uppercase::is_upper_case;

use cases::lowercase::to_lower_case;
use cases::lowercase::is_lower_case;

use numbers::ordinalize::ordinalize;
use numbers::deordinalize::deordinalize;

use suffix::foreignkey::to_foreign_key;
use suffix::foreignkey::is_foreign_key;

use string::demodulize::demodulize;
use string::deconstantize::deconstantize;

use string::pluralize::to_plural;
use string::singularize::to_singular;

pub trait Inflector {
    fn to_class_case(&self) -> String;
    fn is_class_case(&self) -> bool;

    fn to_camel_case(&self) -> String;
    fn is_camel_case(&self) -> bool;

    fn to_table_case(&self) -> String;
    fn is_table_case(&self) -> bool;

    fn to_snake_case(&self) -> String;
    fn is_snake_case(&self) -> bool;

    fn to_screaming_snake_case(&self) -> String;
    fn is_screaming_snake_case(&self) -> bool;

    fn to_kebab_case(&self) -> String;
    fn is_kebab_case(&self) -> bool;

    fn to_sentence_case(&self) -> String;
    fn is_sentence_case(&self) -> bool;

    fn to_title_case(&self) -> String;
    fn is_title_case(&self) -> bool;

    fn to_upper_case(&self) -> String;
    fn is_upper_case(&self) -> bool;

    fn to_lower_case(&self) -> String;
    fn is_lower_case(&self) -> bool;

    fn ordinalize(&self) -> String;
    fn deordinalize(&self) -> String;

    fn to_foreign_key(&self) -> String;
    fn is_foreign_key(&self) -> bool;

    fn demodulize(&self) -> String;
    fn deconstantize(&self) -> String;

    fn to_plural(&self) -> String;
    fn to_singular(&self) -> String;
}

impl<'c> Inflector for String {
    fn to_class_case(&self) -> String {
        to_class_case(self.to_string())
    }
    fn is_class_case(&self) -> bool {
        is_class_case(self.to_string())
    }
    fn to_camel_case(&self) -> String {
        to_camel_case(self.to_string())
    }
    fn is_camel_case(&self) -> bool {
        is_camel_case(self.to_string())
    }
    fn to_table_case(&self) -> String {
        to_table_case(self.to_string())
    }
    fn is_table_case(&self) -> bool {
        is_table_case(self.to_string())
    }
    fn to_screaming_snake_case(&self) -> String {
        to_screaming_snake_case(self.to_string())
    }
    fn is_screaming_snake_case(&self) -> bool {
        is_screaming_snake_case(self.to_string())
    }
    fn to_snake_case(&self) -> String {
        to_snake_case(self.to_string())
    }
    fn is_snake_case(&self) -> bool {
        is_snake_case(self.to_string())
    }
    fn to_kebab_case(&self) -> String {
        to_kebab_case(self.to_string())
    }
    fn is_kebab_case(&self) -> bool {
        is_kebab_case(self.to_string())
    }
    fn to_sentence_case(&self) -> String {
        to_sentence_case(self.to_string())
    }
    fn is_sentence_case(&self) -> bool {
        is_sentence_case(self.to_string())
    }
    fn to_title_case(&self) -> String {
        to_title_case(self.to_string())
    }
    fn is_title_case(&self) -> bool {
        is_title_case(self.to_string())
    }
    fn to_upper_case(&self) -> String {
        to_upper_case(self.to_string())
    }
    fn is_upper_case(&self) -> bool {
        is_upper_case(self.to_string())
    }
    fn to_lower_case(&self) -> String {
        to_lower_case(self.to_string())
    }
    fn is_lower_case(&self) -> bool {
        is_lower_case(self.to_string())
    }
    fn ordinalize(&self) -> String {
        ordinalize(self.to_string())
    }
    fn deordinalize(&self) -> String {
        deordinalize(self.to_string())
    }
    fn to_foreign_key(&self) -> String {
        to_foreign_key(self.to_string())
    }
    fn is_foreign_key(&self) -> bool {
        is_foreign_key(self.to_string())
    }
    fn demodulize(&self) -> String {
        demodulize(self.to_string())
    }
    fn deconstantize(&self) -> String {
        deconstantize(self.to_string())
    }
    fn to_plural(&self) -> String {
        to_plural(self.to_string())
    }
    fn to_singular(&self) -> String {
        to_singular(self.to_string())
    }
}

impl<'c> Inflector for str {
    fn to_class_case(&self) -> String {
        to_class_case(self.to_string())
    }
    fn is_class_case(&self) -> bool {
        is_class_case(self.to_string())
    }
    fn to_camel_case(&self) -> String {
        to_camel_case(self.to_string())
    }
    fn is_camel_case(&self) -> bool {
        is_camel_case(self.to_string())
    }
    fn to_table_case(&self) -> String {
        to_table_case(self.to_string())
    }
    fn is_table_case(&self) -> bool {
        is_table_case(self.to_string())
    }
    fn to_screaming_snake_case(&self) -> String {
        to_screaming_snake_case(self.to_string())
    }
    fn is_screaming_snake_case(&self) -> bool {
        is_screaming_snake_case(self.to_string())
    }
    fn to_snake_case(&self) -> String {
        to_snake_case(self.to_string())
    }
    fn is_snake_case(&self) -> bool {
        is_snake_case(self.to_string())
    }
    fn to_kebab_case(&self) -> String {
        to_kebab_case(self.to_string())
    }
    fn is_kebab_case(&self) -> bool {
        is_kebab_case(self.to_string())
    }
    fn to_sentence_case(&self) -> String {
        to_sentence_case(self.to_string())
    }
    fn is_sentence_case(&self) -> bool {
        is_sentence_case(self.to_string())
    }
    fn to_title_case(&self) -> String {
        to_title_case(self.to_string())
    }
    fn is_title_case(&self) -> bool {
        is_title_case(self.to_string())
    }
    fn to_upper_case(&self) -> String {
        to_upper_case(self.to_string())
    }
    fn is_upper_case(&self) -> bool {
        is_upper_case(self.to_string())
    }
    fn to_lower_case(&self) -> String {
        to_lower_case(self.to_string())
    }
    fn is_lower_case(&self) -> bool {
        is_lower_case(self.to_string())
    }
    fn ordinalize(&self) -> String {
        ordinalize(self.to_string())
    }
    fn deordinalize(&self) -> String {
        deordinalize(self.to_string())
    }
    fn to_foreign_key(&self) -> String {
        to_foreign_key(self.to_string())
    }
    fn is_foreign_key(&self) -> bool {
        is_foreign_key(self.to_string())
    }
    fn demodulize(&self) -> String {
        demodulize(self.to_string())
    }
    fn deconstantize(&self) -> String {
        deconstantize(self.to_string())
    }

    fn to_plural(&self) -> String {
        to_plural(self.to_string())
    }

    fn to_singular(&self) -> String {
        to_singular(self.to_string())
    }
}
<|endoftext|>


<commit_before>//! A collection of data structures that are based probability theory and therefore only provide
//! the correct answer if a certain probability. In exchange they have a better runtime and memory
//! complexity compared to traditional data structures.

#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![deny(unused_extern_crates)]

extern crate bytecount;
extern crate fixedbitset;
pub extern crate num_traits;
pub extern crate rand;

pub mod bloomfilter;
pub mod countminsketch;
pub mod cuckoofilter;
pub mod hash_utils;
pub mod hyperloglog;
pub mod reservoirsampling;
pub mod topk;
<commit_msg>global: deny unsafe code<commit_after>//! A collection of data structures that are based probability theory and therefore only provide
//! the correct answer if a certain probability. In exchange they have a better runtime and memory
//! complexity compared to traditional data structures.

#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![deny(unsafe_code)]
#![deny(unused_extern_crates)]

extern crate bytecount;
extern crate fixedbitset;
pub extern crate num_traits;
pub extern crate rand;

pub mod bloomfilter;
pub mod countminsketch;
pub mod cuckoofilter;
pub mod hash_utils;
pub mod hyperloglog;
pub mod reservoirsampling;
pub mod topk;
<|endoftext|>