<commit_before>use std::ops::Not;
use std::ops::BitAnd;
use std::ops::BitOr;
use std::ops::BitXor;
use std::default::Default;

#[derive(PartialEq, Eq, Debug)]
pub enum Bit { Zero, One }

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

    #[test]
    fn eq_zero_zero_test() {
        assert!(Bit::Zero == Bit::Zero);
    }

    #[test]
    #[should_panic]
    fn eq_zero_one_test() {
        assert!(Bit::Zero == Bit::One);
    }

    #[test]
    #[should_panic]
    fn eq_one_zero_test() {
        assert!(Bit::One == Bit::Zero);
    }

    #[test]
    fn eq_one_one_test() {
        assert!(Bit::One == Bit::One);
    }

    #[test]
    #[should_panic]
    fn ne_zero_zero_test() {
        assert!(Bit::Zero != Bit::Zero);
    }

    #[test]
    fn ne_zero_one_test() {
        assert!(Bit::Zero != Bit::One);
    }

    #[test]
    fn ne_one_zero_test() {
        assert!(Bit::One != Bit::Zero);
    }

    #[test]
    #[should_panic]
    fn ne_one_one_test() {
        assert!(Bit::One != Bit::One);
    }
}

impl Bit {
    pub fn to_i32(&self) -> i32 {
        match *self {
            Bit::Zero => 0,
            Bit::One => 1
        }
    }
}

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

    #[test]
    fn zero_test() {
        assert_eq!(Bit::Zero.to_i32(), 0);
    }

    #[test]
    fn one_test() {
        assert_eq!(Bit::One.to_i32(), 1);
    }
}

impl Bit {
    pub fn to_u32(&self) -> u32 {
        match *self {
            Bit::Zero => 0u32,
            Bit::One => 1u32
        }
    }
}

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

    #[test]
    fn zero_test() {
        assert_eq!(Bit::Zero.to_u32(), 0);
    }

    #[test]
    fn one_test() {
        assert_eq!(Bit::One.to_u32(), 1);
    }
}

impl Not for Bit {
    type Output = Bit;

    fn not(self) -> Bit {
        not_impl(&self)
    }
}

fn not_impl(x: &Bit) -> Bit
{
    match *x {
        Bit::Zero => Bit::One,
        Bit::One => Bit::Zero
    }
}

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

    #[test]
    fn zero_test() {
        assert_eq!(!Bit::Zero, Bit::One);
    }

    #[test]
    fn one_test() {
        assert_eq!(!Bit::One, Bit::Zero);
    }
}

impl<'a> Not for &'a Bit {
    type Output = <Bit as Not>::Output;

    fn not(self) -> <Bit as Not>::Output {
        not_impl(self)
    }
}

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

    #[test]
    fn zero_test() {
        assert_eq!(!&Bit::Zero, Bit::One);
    }

    #[test]
    fn one_test() {
        assert_eq!(!&Bit::One, Bit::Zero);
    }
}

impl BitAnd for Bit {
    type Output = Bit;

    fn bitand(self, rhs: Bit) -> Bit {
        bitand_impl(&self, &rhs)
    }
}

fn bitand_impl(x: &Bit, y: &Bit) -> Bit {
    match (x, y) {
        (&Bit::Zero, &Bit::Zero) => Bit::Zero,
        (&Bit::Zero, &Bit::One) => Bit::Zero,
        (&Bit::One, &Bit::Zero) => Bit::Zero,
        (&Bit::One, &Bit::One) => Bit::One
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero & Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero & Bit::One, Bit::Zero);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One & Bit::Zero, Bit::Zero);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One & Bit::One, Bit::One);
    }
}

impl<'a> BitAnd<Bit> for &'a Bit {
    type Output = <Bit as BitAnd<Bit>>::Output;

    fn bitand(self, rhs: Bit) -> <Bit as BitAnd<Bit>>::Output {
        bitand_impl(self, &rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero & Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero & Bit::One, Bit::Zero);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One & Bit::Zero, Bit::Zero);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One & Bit::One, Bit::One);
    }
}

impl<'a> BitAnd<&'a Bit> for Bit {
    type Output = <Bit as BitAnd<Bit>>::Output;

    fn bitand(self, rhs: &'a Bit) -> <Bit as BitAnd<Bit>>::Output {
        bitand_impl(&self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero & &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero & &Bit::One, Bit::Zero);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One & &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One & &Bit::One, Bit::One);
    }
}

impl<'a, 'b> BitAnd<&'a Bit> for &'b Bit {
    type Output = <Bit as BitAnd<Bit>>::Output;

    fn bitand(self, rhs: &'a Bit) -> <Bit as BitAnd<Bit>>::Output {
        bitand_impl(self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero & &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero & &Bit::One, Bit::Zero);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One & &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One & &Bit::One, Bit::One);
    }
}

impl BitOr for Bit {
    type Output = Bit;

    fn bitor(self, rhs: Bit) -> Bit {
        bitor_impl(&self, &rhs)
    }
}

fn bitor_impl(x: &Bit, y: &Bit) -> Bit
{
    match (x, y) {
        (&Bit::Zero, &Bit::Zero) => Bit::Zero,
        (&Bit::Zero, &Bit::One) => Bit::One,
        (&Bit::One, &Bit::Zero) => Bit::One,
        (&Bit::One, &Bit::One) => Bit::One
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero | Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero | Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One | Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One | Bit::One, Bit::One);
    }
}

impl<'a> BitOr<Bit> for &'a Bit {
    type Output = <Bit as BitOr<Bit>>::Output;

    fn bitor(self, rhs: Bit) -> <Bit as BitOr<Bit>>::Output {
        bitor_impl(self, &rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero | Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero | Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One | Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One | Bit::One, Bit::One);
    }
}

impl<'a> BitOr<&'a Bit> for Bit {
    type Output = <Bit as BitOr<Bit>>::Output;

    fn bitor(self, rhs: &'a Bit) -> <Bit as BitOr<Bit>>::Output {
        bitor_impl(&self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero | &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero | &Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One | &Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One | &Bit::One, Bit::One);
    }
}

impl<'a, 'b> BitOr<&'a Bit> for &'b Bit {
    type Output = <Bit as BitOr<Bit>>::Output;

    fn bitor(self, rhs: &'a Bit) -> <Bit as BitOr<Bit>>::Output {
        bitor_impl(self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero | &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero | &Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One | &Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One | &Bit::One, Bit::One);
    }
}

impl BitXor for Bit {
    type Output = Bit;

    fn bitxor(self, rhs: Bit) -> Bit {
        bitxor_impl(&self, &rhs)
    }
}

fn bitxor_impl(x: &Bit, y: &Bit) -> Bit {
    match (x, y) {
        (&Bit::Zero, &Bit::Zero) => Bit::Zero,
        (&Bit::Zero, &Bit::One) => Bit::One,
        (&Bit::One, &Bit::Zero) => Bit::One,
        (&Bit::One, &Bit::One) => Bit::Zero
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero ^ Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero ^ Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One ^ Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One ^ Bit::One, Bit::Zero);
    }
}

impl<'a> BitXor<Bit> for &'a Bit {
    type Output = <Bit as BitXor<Bit>>::Output;

    fn bitxor(self, rhs: Bit) -> <Bit as BitXor<Bit>>::Output {
        bitxor_impl(self, &rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero ^ Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero ^ Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One ^ Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One ^ Bit::One, Bit::Zero);
    }
}

impl<'a> BitXor<&'a Bit> for Bit {
    type Output = <Bit as BitXor<Bit>>::Output;

    fn bitxor(self, rhs: &'a Bit) -> <Bit as BitXor<Bit>>::Output {
        bitxor_impl(&self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero ^ &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero ^ &Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One ^ &Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One ^ &Bit::One, Bit::Zero);
    }
}

impl<'a, 'b> BitXor<&'a Bit> for &'b Bit {
    type Output = <Bit as BitXor<Bit>>::Output;

    fn bitxor(self, rhs: &'a Bit) -> <Bit as BitXor<Bit>>::Output {
        bitxor_impl(self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero ^ &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero ^ &Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One ^ &Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One ^ &Bit::One, Bit::Zero);
    }
}

impl Default for Bit {
    fn default() -> Bit {
        Bit::Zero
    }
}

#[cfg(test)]
mod default_tests {
    use std::default::Default;
    use super::*;

    #[test]
    fn test()
    {
        assert_eq!(Default::default(), Bit::Zero);
    }
}
<commit_msg>added PartialOrd and Ord derivation to Bit<commit_after>use std::ops::Not;
use std::ops::BitAnd;
use std::ops::BitOr;
use std::ops::BitXor;
use std::default::Default;

#[derive(PartialEq, Eq, Debug, PartialOrd, Ord)]
pub enum Bit { Zero, One }

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

    #[test]
    fn eq_zero_zero_test() {
        assert!(Bit::Zero == Bit::Zero);
    }

    #[test]
    #[should_panic]
    fn eq_zero_one_test() {
        assert!(Bit::Zero == Bit::One);
    }

    #[test]
    #[should_panic]
    fn eq_one_zero_test() {
        assert!(Bit::One == Bit::Zero);
    }

    #[test]
    fn eq_one_one_test() {
        assert!(Bit::One == Bit::One);
    }

    #[test]
    #[should_panic]
    fn ne_zero_zero_test() {
        assert!(Bit::Zero != Bit::Zero);
    }

    #[test]
    fn ne_zero_one_test() {
        assert!(Bit::Zero != Bit::One);
    }

    #[test]
    fn ne_one_zero_test() {
        assert!(Bit::One != Bit::Zero);
    }

    #[test]
    #[should_panic]
    fn ne_one_one_test() {
        assert!(Bit::One != Bit::One);
    }
}

impl Bit {
    pub fn to_i32(&self) -> i32 {
        match *self {
            Bit::Zero => 0,
            Bit::One => 1
        }
    }
}

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

    #[test]
    fn zero_test() {
        assert_eq!(Bit::Zero.to_i32(), 0);
    }

    #[test]
    fn one_test() {
        assert_eq!(Bit::One.to_i32(), 1);
    }
}

impl Bit {
    pub fn to_u32(&self) -> u32 {
        match *self {
            Bit::Zero => 0u32,
            Bit::One => 1u32
        }
    }
}

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

    #[test]
    fn zero_test() {
        assert_eq!(Bit::Zero.to_u32(), 0);
    }

    #[test]
    fn one_test() {
        assert_eq!(Bit::One.to_u32(), 1);
    }
}

impl Not for Bit {
    type Output = Bit;

    fn not(self) -> Bit {
        not_impl(&self)
    }
}

fn not_impl(x: &Bit) -> Bit
{
    match *x {
        Bit::Zero => Bit::One,
        Bit::One => Bit::Zero
    }
}

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

    #[test]
    fn zero_test() {
        assert_eq!(!Bit::Zero, Bit::One);
    }

    #[test]
    fn one_test() {
        assert_eq!(!Bit::One, Bit::Zero);
    }
}

impl<'a> Not for &'a Bit {
    type Output = <Bit as Not>::Output;

    fn not(self) -> <Bit as Not>::Output {
        not_impl(self)
    }
}

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

    #[test]
    fn zero_test() {
        assert_eq!(!&Bit::Zero, Bit::One);
    }

    #[test]
    fn one_test() {
        assert_eq!(!&Bit::One, Bit::Zero);
    }
}

impl BitAnd for Bit {
    type Output = Bit;

    fn bitand(self, rhs: Bit) -> Bit {
        bitand_impl(&self, &rhs)
    }
}

fn bitand_impl(x: &Bit, y: &Bit) -> Bit {
    match (x, y) {
        (&Bit::Zero, &Bit::Zero) => Bit::Zero,
        (&Bit::Zero, &Bit::One) => Bit::Zero,
        (&Bit::One, &Bit::Zero) => Bit::Zero,
        (&Bit::One, &Bit::One) => Bit::One
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero & Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero & Bit::One, Bit::Zero);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One & Bit::Zero, Bit::Zero);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One & Bit::One, Bit::One);
    }
}

impl<'a> BitAnd<Bit> for &'a Bit {
    type Output = <Bit as BitAnd<Bit>>::Output;

    fn bitand(self, rhs: Bit) -> <Bit as BitAnd<Bit>>::Output {
        bitand_impl(self, &rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero & Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero & Bit::One, Bit::Zero);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One & Bit::Zero, Bit::Zero);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One & Bit::One, Bit::One);
    }
}

impl<'a> BitAnd<&'a Bit> for Bit {
    type Output = <Bit as BitAnd<Bit>>::Output;

    fn bitand(self, rhs: &'a Bit) -> <Bit as BitAnd<Bit>>::Output {
        bitand_impl(&self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero & &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero & &Bit::One, Bit::Zero);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One & &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One & &Bit::One, Bit::One);
    }
}

impl<'a, 'b> BitAnd<&'a Bit> for &'b Bit {
    type Output = <Bit as BitAnd<Bit>>::Output;

    fn bitand(self, rhs: &'a Bit) -> <Bit as BitAnd<Bit>>::Output {
        bitand_impl(self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero & &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero & &Bit::One, Bit::Zero);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One & &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One & &Bit::One, Bit::One);
    }
}

impl BitOr for Bit {
    type Output = Bit;

    fn bitor(self, rhs: Bit) -> Bit {
        bitor_impl(&self, &rhs)
    }
}

fn bitor_impl(x: &Bit, y: &Bit) -> Bit
{
    match (x, y) {
        (&Bit::Zero, &Bit::Zero) => Bit::Zero,
        (&Bit::Zero, &Bit::One) => Bit::One,
        (&Bit::One, &Bit::Zero) => Bit::One,
        (&Bit::One, &Bit::One) => Bit::One
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero | Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero | Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One | Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One | Bit::One, Bit::One);
    }
}

impl<'a> BitOr<Bit> for &'a Bit {
    type Output = <Bit as BitOr<Bit>>::Output;

    fn bitor(self, rhs: Bit) -> <Bit as BitOr<Bit>>::Output {
        bitor_impl(self, &rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero | Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero | Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One | Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One | Bit::One, Bit::One);
    }
}

impl<'a> BitOr<&'a Bit> for Bit {
    type Output = <Bit as BitOr<Bit>>::Output;

    fn bitor(self, rhs: &'a Bit) -> <Bit as BitOr<Bit>>::Output {
        bitor_impl(&self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero | &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero | &Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One | &Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One | &Bit::One, Bit::One);
    }
}

impl<'a, 'b> BitOr<&'a Bit> for &'b Bit {
    type Output = <Bit as BitOr<Bit>>::Output;

    fn bitor(self, rhs: &'a Bit) -> <Bit as BitOr<Bit>>::Output {
        bitor_impl(self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero | &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero | &Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One | &Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One | &Bit::One, Bit::One);
    }
}

impl BitXor for Bit {
    type Output = Bit;

    fn bitxor(self, rhs: Bit) -> Bit {
        bitxor_impl(&self, &rhs)
    }
}

fn bitxor_impl(x: &Bit, y: &Bit) -> Bit {
    match (x, y) {
        (&Bit::Zero, &Bit::Zero) => Bit::Zero,
        (&Bit::Zero, &Bit::One) => Bit::One,
        (&Bit::One, &Bit::Zero) => Bit::One,
        (&Bit::One, &Bit::One) => Bit::Zero
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero ^ Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero ^ Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One ^ Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One ^ Bit::One, Bit::Zero);
    }
}

impl<'a> BitXor<Bit> for &'a Bit {
    type Output = <Bit as BitXor<Bit>>::Output;

    fn bitxor(self, rhs: Bit) -> <Bit as BitXor<Bit>>::Output {
        bitxor_impl(self, &rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero ^ Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero ^ Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One ^ Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One ^ Bit::One, Bit::Zero);
    }
}

impl<'a> BitXor<&'a Bit> for Bit {
    type Output = <Bit as BitXor<Bit>>::Output;

    fn bitxor(self, rhs: &'a Bit) -> <Bit as BitXor<Bit>>::Output {
        bitxor_impl(&self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(Bit::Zero ^ &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(Bit::Zero ^ &Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(Bit::One ^ &Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(Bit::One ^ &Bit::One, Bit::Zero);
    }
}

impl<'a, 'b> BitXor<&'a Bit> for &'b Bit {
    type Output = <Bit as BitXor<Bit>>::Output;

    fn bitxor(self, rhs: &'a Bit) -> <Bit as BitXor<Bit>>::Output {
        bitxor_impl(self, rhs)
    }
}

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

    #[test]
    fn zero_zero_test() {
        assert_eq!(&Bit::Zero ^ &Bit::Zero, Bit::Zero);
    }

    #[test]
    fn zero_one_test() {
        assert_eq!(&Bit::Zero ^ &Bit::One, Bit::One);
    }

    #[test]
    fn one_zero_test() {
        assert_eq!(&Bit::One ^ &Bit::Zero, Bit::One);
    }

    #[test]
    fn one_one_test() {
        assert_eq!(&Bit::One ^ &Bit::One, Bit::Zero);
    }
}

impl Default for Bit {
    fn default() -> Bit {
        Bit::Zero
    }
}

#[cfg(test)]
mod default_tests {
    use std::default::Default;
    use super::*;

    #[test]
    fn test()
    {
        assert_eq!(Default::default(), Bit::Zero);
    }
}
<|endoftext|>


<commit_before>use std::io::prelude::*;
use std::fs::File;
use std::collections::HashMap;

use sxd_document::Package;
use sxd_document::dom::Document;
use sxd_document::writer::format_document;
use sxd_document::parser::Parser;
use sxd_xpath::{Value,Functions,Variables,Namespaces,Factory,EvaluationContext,Expression};
use sxd_xpath::function::register_core_functions;

pub struct XmiReader<'a> {
    package     : Package,
    functions   : Functions,
    variables   : Variables<'a>,
    namespaces  : Namespaces,
    factory     : Factory,
}
impl<'a> XmiReader<'a> {
    pub fn new() -> Self {
        let mut fns = HashMap::new();
        register_core_functions(&mut fns);
        XmiReader {
            package     : Package::new(),
            functions   : fns,
            variables   : HashMap::new(),
            namespaces  : HashMap::new(),
            factory     : Factory::new(),
        }
    }

    pub fn from_file(file: &str) -> Self {
        let mut f = File::open(file).expect("No such file");
        let mut s = String::new();
        f.read_to_string(&mut s).expect("Could not read to string");
        let parser = Parser::new();
        let parseres = parser.parse(&s);
        println!("{:#?}", parseres);
        let mut xmireader = XmiReader::new();
        xmireader.package = parseres.ok().expect("Could not parse");
        xmireader
    }

    fn evaluate(&self, xpath: &str) -> Value {
        let root = self.doc().root();
        let context = EvaluationContext::new(
            root,
            &self.functions,
            &self.variables,
            &self.namespaces,
        );
        let xpath = self.factory.build(xpath).unwrap().unwrap();
        xpath.evaluate(&context).ok().unwrap()
    }

    fn doc(&self) -> Document {
        self.package.as_document()
    }

    pub fn print(&mut self, file: &str) {
        let mut f = File::create(file).expect("Could not create file");
        let doc = self.doc();
        format_document(&doc, &mut f).ok().expect("unable to output XML");
    }

    pub fn test(&self) {
        let doc = self.doc();

        let hello = doc.create_element("hello");
        hello.set_attribute_value("planet", "Earth");
        let comment = doc.create_comment("What about other planets?");
        let text = doc.create_text("Greetings, Earthlings!");

        hello.append_child(comment);
        hello.append_child(text);
        doc.root().append_child(hello);
        info!("{:?}", doc);
    }
}
<commit_msg>working XmiReader<commit_after>use std::mem;
use std::io::prelude::*;
use std::fs::File;
use std::collections::HashMap;

use sxd_document::Package;
use sxd_document::dom::Document;
use sxd_document::writer::format_document;
use sxd_document::parser::Parser;
use sxd_xpath::{Value,Functions,Variables,Namespaces,Factory,EvaluationContext,Expression};
use sxd_xpath::function::register_core_functions;
use sxd_xpath::nodeset::Node;

struct InnerXmiReader <'d> {
    package : Package,
    doc     : Document<'d>,
}
impl<'d> InnerXmiReader<'d> {
    pub fn new(pkg: Package) -> Self {
        InnerXmiReader {
            package : pkg,
            doc     : unsafe {mem::uninitialized()},
        }
    }
    pub fn init(&self) {
        unsafe {
            let mut dest: *mut Document = mem::transmute(&self.doc);
            *dest = self.package.as_document();
        }
    }
    pub fn doc(&self) -> &Document<'d> {
        &self.doc
    }
}

pub struct XmiReader<'a, 'd> {
    inner       : Box<InnerXmiReader<'d>>,
    functions   : Functions,
    variables   : Variables<'a>,
    namespaces  : Namespaces,
    factory     : Factory,
}
impl<'a:'d, 'd> XmiReader<'a, 'd> {
    fn _new(pkg: Package) -> Self {
        let mut fns = HashMap::new();
        register_core_functions(&mut fns);
        let xr = XmiReader {
            inner       : Box::new(InnerXmiReader::new(pkg)),
            functions   : fns,
            variables   : HashMap::new(),
            namespaces  : HashMap::new(),
            factory     : Factory::new(),
        };
        xr.inner.init();
        xr
    }

    pub fn new() -> Self {
        XmiReader::_new(Package::new())
    }

    pub fn from_file(file: &str) -> Self {
        let mut f = File::open(file).expect("No such file");
        let mut s = String::new();
        f.read_to_string(&mut s).expect("Could not read to string");
        let parser = Parser::new();
        let parseres = parser.parse(&s);
        println!("{:#?}", parseres);
        XmiReader::_new(parseres.ok().expect("Could not parse"))
    }

    pub fn evaluate_root(&'a self, xpath: &str) -> Value<'d>{
        self.evaluate(self.inner.doc().root(), xpath)
    }

    pub fn evaluate<N>(&'a self, node: N, xpath: &str) -> Value<'d>
        where N: Into<Node<'d>> {
        let context = EvaluationContext::new(
            node,
            &self.functions,
            &self.variables,
            &self.namespaces,
        );
        let xpath = self.factory.build(xpath).unwrap().unwrap();
        xpath.evaluate(&context).ok().unwrap()
    }

    pub fn print(&'a self, file: &str) {
        let doc = self.inner.doc();
        let mut f = File::create(file).expect("Could not create file");
        println!("{:?}", doc);
        format_document(doc, &mut f).expect("Error formatting document");
    }

    pub fn test(&'a self) {
        let doc = self.inner.doc();
        let hello = doc.create_element("hello");
        hello.set_attribute_value("planet", "Earth");
        let comment = doc.create_comment("What about other planets?");
        let text = doc.create_text("Greetings, Earthlings!");

        hello.append_child(comment);
        hello.append_child(text);
        doc.root().append_child(hello);
        info!("{:?}", doc);
    }
}
<|endoftext|>


<commit_before>//! Components needed to verify TUF metadata and targets.

use std::marker::PhantomData;

use Result;
use crypto::KeyId;
use error::Error;
use interchange::DataInterchange;
use metadata::{SignedMetadata, RootMetadata, VerificationStatus, TimestampMetadata};

/// Contains trusted TUF metadata and can be used to verify other metadata and targets.
#[derive(Debug)]
pub struct Tuf<D: DataInterchange> {
    root: RootMetadata,
    timestamp: Option<TimestampMetadata>,
    _interchange: PhantomData<D>,
}

impl<D: DataInterchange> Tuf<D> {
    /// Create a new `TUF` struct from a known set of pinned root keys that are used to verify the
    /// signed metadata.
    pub fn from_root_pinned<V>(
        mut signed_root: SignedMetadata<D, RootMetadata, V>,
        root_key_ids: &[KeyId],
    ) -> Result<Self>
    where
        V: VerificationStatus,
    {
        signed_root.signatures_mut().retain(|s| {
            root_key_ids.contains(s.key_id())
        });
        Self::from_root(signed_root)
    }

    /// Create a new `TUF` struct from a piece of metadata that is assumed to be trusted.
    ///
    /// *WARNING*: This is trust-on-first-use (TOFU) and offers weaker security guarantees than the
    /// related method `from_root_pinned`.
    pub fn from_root<V>(signed_root: SignedMetadata<D, RootMetadata, V>) -> Result<Self>
    where
        V: VerificationStatus,
    {
        let root = D::deserialize::<RootMetadata>(signed_root.unverified_signed())?;
        let _ = signed_root.verify(
            root.root().threshold(),
            root.root().key_ids(),
            root.keys(),
        )?;
        Ok(Tuf {
            root: root,
            timestamp: None,
            _interchange: PhantomData,
        })
    }

    /// An immutable reference to the root metadata.
    pub fn root(&self) -> &RootMetadata {
        &self.root
    }

    /// An immutable reference to the optinoal timestamp metadata.
    pub fn timestamp(&self) -> Option<&TimestampMetadata> {
        self.timestamp.as_ref()
    }

    /// Verify and update the root metadata.
    pub fn update_root<V>(
        &mut self,
        signed_root: SignedMetadata<D, RootMetadata, V>,
    ) -> Result<bool>
    where
        V: VerificationStatus,
    {
        let signed_root = signed_root.verify(
            self.root.root().threshold(),
            self.root.root().key_ids(),
            self.root.keys(),
        )?;

        let root = D::deserialize::<RootMetadata>(signed_root.unverified_signed())?;

        match root.version() {
            x if x == self.root.version() => {
                info!(
                    "Attempted to update root to new metadata with the same version. \
                      Refusing to update."
                );
                return Ok(false);
            }
            x if x < self.root.version() => {
                return Err(Error::VerificationFailure(format!(
                    "Attempted to roll back root metadata at version {} to {}.",
                    self.root.version(),
                    x
                )))
            }
            _ => (),
        }

        let _ = signed_root.verify(
            root.root().threshold(),
            root.root().key_ids(),
            root.keys(),
        )?;

        self.root = root;
        Ok(true)
    }

    /// Verify and update the timestamp metadata.
    pub fn update_timestamp<V>(
        &mut self,
        signed_timestamp: SignedMetadata<D, TimestampMetadata, V>,
    ) -> Result<bool>
    where
        V: VerificationStatus,
    {
        let signed_timestamp = signed_timestamp.verify(
            self.root.timestamp().threshold(),
            self.root.timestamp().key_ids(),
            self.root.keys(),
        )?;

        let current_version = self.timestamp.as_ref().map(|t| t.version()).unwrap_or(0);
        let timestamp: TimestampMetadata = D::deserialize(&signed_timestamp.signed())?;

        if timestamp.expires() <= &Utc::now() {
            return Err(Error::ExpiredMetadata(Role::Timestamp));
        }

        if timestamp.version() < current_version {
            Err(Error::VerificationFailure(format!(
                "Attempted to roll back timestamp metdata at version {} to {}.",
                current_version,
                timestamp.version()
            )))
        } else if timestamp.version() == current_version {
            Ok(false)
        } else {
            Ok(true)
        }
    }
}
<commit_msg>add imports, unbreak build<commit_after>//! Components needed to verify TUF metadata and targets.

use chrono::offset::Utc;
use std::marker::PhantomData;

use Result;
use crypto::KeyId;
use error::Error;
use interchange::DataInterchange;
use metadata::{SignedMetadata, RootMetadata, VerificationStatus, TimestampMetadata, Role};

/// Contains trusted TUF metadata and can be used to verify other metadata and targets.
#[derive(Debug)]
pub struct Tuf<D: DataInterchange> {
    root: RootMetadata,
    timestamp: Option<TimestampMetadata>,
    _interchange: PhantomData<D>,
}

impl<D: DataInterchange> Tuf<D> {
    /// Create a new `TUF` struct from a known set of pinned root keys that are used to verify the
    /// signed metadata.
    pub fn from_root_pinned<V>(
        mut signed_root: SignedMetadata<D, RootMetadata, V>,
        root_key_ids: &[KeyId],
    ) -> Result<Self>
    where
        V: VerificationStatus,
    {
        signed_root.signatures_mut().retain(|s| {
            root_key_ids.contains(s.key_id())
        });
        Self::from_root(signed_root)
    }

    /// Create a new `TUF` struct from a piece of metadata that is assumed to be trusted.
    ///
    /// *WARNING*: This is trust-on-first-use (TOFU) and offers weaker security guarantees than the
    /// related method `from_root_pinned`.
    pub fn from_root<V>(signed_root: SignedMetadata<D, RootMetadata, V>) -> Result<Self>
    where
        V: VerificationStatus,
    {
        let root = D::deserialize::<RootMetadata>(signed_root.unverified_signed())?;
        let _ = signed_root.verify(
            root.root().threshold(),
            root.root().key_ids(),
            root.keys(),
        )?;
        Ok(Tuf {
            root: root,
            timestamp: None,
            _interchange: PhantomData,
        })
    }

    /// An immutable reference to the root metadata.
    pub fn root(&self) -> &RootMetadata {
        &self.root
    }

    /// An immutable reference to the optinoal timestamp metadata.
    pub fn timestamp(&self) -> Option<&TimestampMetadata> {
        self.timestamp.as_ref()
    }

    /// Verify and update the root metadata.
    pub fn update_root<V>(
        &mut self,
        signed_root: SignedMetadata<D, RootMetadata, V>,
    ) -> Result<bool>
    where
        V: VerificationStatus,
    {
        let signed_root = signed_root.verify(
            self.root.root().threshold(),
            self.root.root().key_ids(),
            self.root.keys(),
        )?;

        let root = D::deserialize::<RootMetadata>(signed_root.unverified_signed())?;

        match root.version() {
            x if x == self.root.version() => {
                info!(
                    "Attempted to update root to new metadata with the same version. \
                      Refusing to update."
                );
                return Ok(false);
            }
            x if x < self.root.version() => {
                return Err(Error::VerificationFailure(format!(
                    "Attempted to roll back root metadata at version {} to {}.",
                    self.root.version(),
                    x
                )))
            }
            _ => (),
        }

        let _ = signed_root.verify(
            root.root().threshold(),
            root.root().key_ids(),
            root.keys(),
        )?;

        self.root = root;
        Ok(true)
    }

    /// Verify and update the timestamp metadata.
    pub fn update_timestamp<V>(
        &mut self,
        signed_timestamp: SignedMetadata<D, TimestampMetadata, V>,
    ) -> Result<bool>
    where
        V: VerificationStatus,
    {
        let signed_timestamp = signed_timestamp.verify(
            self.root.timestamp().threshold(),
            self.root.timestamp().key_ids(),
            self.root.keys(),
        )?;

        let current_version = self.timestamp.as_ref().map(|t| t.version()).unwrap_or(0);
        let timestamp: TimestampMetadata = D::deserialize(&signed_timestamp.signed())?;

        if timestamp.expires() <= &Utc::now() {
            return Err(Error::ExpiredMetadata(Role::Timestamp));
        }

        if timestamp.version() < current_version {
            Err(Error::VerificationFailure(format!(
                "Attempted to roll back timestamp metdata at version {} to {}.",
                current_version,
                timestamp.version()
            )))
        } else if timestamp.version() == current_version {
            Ok(false)
        } else {
            Ok(true)
        }
    }
}
<|endoftext|>


<commit_before>extern crate c_ares_sys;

use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::{
    c_int,
    c_uchar,
    c_void,
};
use std::ptr;
use std::slice;
use std::str;

use error::AresError;
use utils::ares_error;

/// The result of a successful TXT lookup.
#[derive(Debug)]
pub struct TXTResults {
    txt_reply: *mut c_ares_sys::Struct_ares_txt_ext,
    phantom: PhantomData<c_ares_sys::Struct_ares_txt_ext>,
}

/// The contents of a single TXT record.
#[derive(Clone, Copy, Debug)]
pub struct TXTResult<'a> {
    txt_reply: *const c_ares_sys::Struct_ares_txt_ext,
    phantom: PhantomData<&'a c_ares_sys::Struct_ares_txt_ext>,
}

impl TXTResults {
    /// Obtain a `TXTResults` from the response to a TXT lookup.
    pub fn parse_from(data: &[u8]) -> Result<TXTResults, AresError> {
        let mut txt_reply: *mut c_ares_sys::Struct_ares_txt_ext =
            ptr::null_mut();
        let parse_status = unsafe {
            c_ares_sys::ares_parse_txt_reply_ext(
                data.as_ptr(),
                data.len() as c_int,
                &mut txt_reply)
        };
        if parse_status != c_ares_sys::ARES_SUCCESS {
            Err(ares_error(parse_status))
        } else {
            let result = TXTResults::new(txt_reply);
            Ok(result)
        }
    }

    fn new(txt_reply: *mut c_ares_sys::Struct_ares_txt_ext) -> TXTResults {
        TXTResults {
            txt_reply: txt_reply,
            phantom: PhantomData,
        }
    }

    /// Returns an iterator over the `TXTResult` values in this `TXTResults`.
    pub fn iter(&self) -> TXTResultsIter {
        TXTResultsIter {
            next: self.txt_reply,
            phantom: PhantomData,
        }
    }
}

impl fmt::Display for TXTResults {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(fmt, "["));
        let mut first = true;
        for txt_result in self {
            let prefix = if first { "" } else { ", " };
            first = false;
            try!(write!(fmt, "{}{}", prefix, txt_result));
        }
        try!(write!(fmt, "]"));
        Ok(())
    }
}

/// Iterator of `TXTResult`s.
#[derive(Clone, Copy, Debug)]
pub struct TXTResultsIter<'a> {
    next: *const c_ares_sys::Struct_ares_txt_ext,
    phantom: PhantomData<&'a c_ares_sys::Struct_ares_txt_ext>,
}

impl<'a> Iterator for TXTResultsIter<'a> {
    type Item = TXTResult<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        let txt_reply = self.next;
        if txt_reply.is_null() {
            None
        } else {
            unsafe {
                self.next = (*txt_reply).next;
            }
            let txt_result = TXTResult {
                txt_reply: txt_reply,
                phantom: PhantomData,
            };
            Some(txt_result)
        }
    }
}
impl<'a> IntoIterator for &'a TXTResults {
    type Item = TXTResult<'a>;
    type IntoIter = TXTResultsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl Drop for TXTResults {
    fn drop(&mut self) {
        unsafe {
            c_ares_sys::ares_free_data(self.txt_reply as *mut c_void);
        }
    }
}

unsafe impl<'a> Send for TXTResult<'a> { }
unsafe impl<'a> Sync for TXTResult<'a> { }
unsafe impl Send for TXTResults { }
unsafe impl Sync for TXTResults { }
unsafe impl<'a> Send for TXTResultsIter<'a> { }
unsafe impl<'a> Sync for TXTResultsIter<'a> { }

impl<'a> TXTResult<'a> {
    /// Is this the start of a text record, or the continuation of a previous
    /// record?
    pub fn record_start(&self) -> bool {
        unsafe {
            (*self.txt_reply).record_start != 0
        }
    }

    /// Returns the text in this `TXTResult`.
    pub fn text(&self) -> &str {
        unsafe {
            let c_str = CStr::from_ptr((*self.txt_reply).txt as *const i8);
            str::from_utf8_unchecked(c_str.to_bytes())
        }
    }
}

impl<'a> fmt::Display for TXTResult<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        self.text().fmt(fmt)
    }
}

pub unsafe extern "C" fn query_txt_callback<F>(
    arg: *mut c_void,
    status: c_int,
    _timeouts: c_int,
    abuf: *mut c_uchar,
    alen: c_int)
    where F: FnOnce(Result<TXTResults, AresError>) + 'static {
    let result = if status != c_ares_sys::ARES_SUCCESS {
        Err(ares_error(status))
    } else {
        let data = slice::from_raw_parts(abuf, alen as usize);
        TXTResults::parse_from(data)
    };
    let handler = Box::from_raw(arg as *mut F);
    handler(result);
}
<commit_msg>Missing field in Display of TXTResult<commit_after>extern crate c_ares_sys;

use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::{
    c_int,
    c_uchar,
    c_void,
};
use std::ptr;
use std::slice;
use std::str;

use error::AresError;
use utils::ares_error;

/// The result of a successful TXT lookup.
#[derive(Debug)]
pub struct TXTResults {
    txt_reply: *mut c_ares_sys::Struct_ares_txt_ext,
    phantom: PhantomData<c_ares_sys::Struct_ares_txt_ext>,
}

/// The contents of a single TXT record.
#[derive(Clone, Copy, Debug)]
pub struct TXTResult<'a> {
    txt_reply: *const c_ares_sys::Struct_ares_txt_ext,
    phantom: PhantomData<&'a c_ares_sys::Struct_ares_txt_ext>,
}

impl TXTResults {
    /// Obtain a `TXTResults` from the response to a TXT lookup.
    pub fn parse_from(data: &[u8]) -> Result<TXTResults, AresError> {
        let mut txt_reply: *mut c_ares_sys::Struct_ares_txt_ext =
            ptr::null_mut();
        let parse_status = unsafe {
            c_ares_sys::ares_parse_txt_reply_ext(
                data.as_ptr(),
                data.len() as c_int,
                &mut txt_reply)
        };
        if parse_status != c_ares_sys::ARES_SUCCESS {
            Err(ares_error(parse_status))
        } else {
            let result = TXTResults::new(txt_reply);
            Ok(result)
        }
    }

    fn new(txt_reply: *mut c_ares_sys::Struct_ares_txt_ext) -> TXTResults {
        TXTResults {
            txt_reply: txt_reply,
            phantom: PhantomData,
        }
    }

    /// Returns an iterator over the `TXTResult` values in this `TXTResults`.
    pub fn iter(&self) -> TXTResultsIter {
        TXTResultsIter {
            next: self.txt_reply,
            phantom: PhantomData,
        }
    }
}

impl fmt::Display for TXTResults {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(fmt, "["));
        let mut first = true;
        for txt_result in self {
            let prefix = if first { "" } else { ", " };
            first = false;
            try!(write!(fmt, "{}{}", prefix, txt_result));
        }
        try!(write!(fmt, "]"));
        Ok(())
    }
}

/// Iterator of `TXTResult`s.
#[derive(Clone, Copy, Debug)]
pub struct TXTResultsIter<'a> {
    next: *const c_ares_sys::Struct_ares_txt_ext,
    phantom: PhantomData<&'a c_ares_sys::Struct_ares_txt_ext>,
}

impl<'a> Iterator for TXTResultsIter<'a> {
    type Item = TXTResult<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        let txt_reply = self.next;
        if txt_reply.is_null() {
            None
        } else {
            unsafe {
                self.next = (*txt_reply).next;
            }
            let txt_result = TXTResult {
                txt_reply: txt_reply,
                phantom: PhantomData,
            };
            Some(txt_result)
        }
    }
}
impl<'a> IntoIterator for &'a TXTResults {
    type Item = TXTResult<'a>;
    type IntoIter = TXTResultsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl Drop for TXTResults {
    fn drop(&mut self) {
        unsafe {
            c_ares_sys::ares_free_data(self.txt_reply as *mut c_void);
        }
    }
}

unsafe impl<'a> Send for TXTResult<'a> { }
unsafe impl<'a> Sync for TXTResult<'a> { }
unsafe impl Send for TXTResults { }
unsafe impl Sync for TXTResults { }
unsafe impl<'a> Send for TXTResultsIter<'a> { }
unsafe impl<'a> Sync for TXTResultsIter<'a> { }

impl<'a> TXTResult<'a> {
    /// Is this the start of a text record, or the continuation of a previous
    /// record?
    pub fn record_start(&self) -> bool {
        unsafe {
            (*self.txt_reply).record_start != 0
        }
    }

    /// Returns the text in this `TXTResult`.
    pub fn text(&self) -> &str {
        unsafe {
            let c_str = CStr::from_ptr((*self.txt_reply).txt as *const i8);
            str::from_utf8_unchecked(c_str.to_bytes())
        }
    }
}

impl<'a> fmt::Display for TXTResult<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(
            write!(
                fmt,
                "Record start: {}, Text: {}",
                self.record_start(),
                self.text()));
        Ok(())
    }
}

pub unsafe extern "C" fn query_txt_callback<F>(
    arg: *mut c_void,
    status: c_int,
    _timeouts: c_int,
    abuf: *mut c_uchar,
    alen: c_int)
    where F: FnOnce(Result<TXTResults, AresError>) + 'static {
    let result = if status != c_ares_sys::ARES_SUCCESS {
        Err(ares_error(status))
    } else {
        let data = slice::from_raw_parts(abuf, alen as usize);
        TXTResults::parse_from(data)
    };
    let handler = Box::from_raw(arg as *mut F);
    handler(result);
}
<|endoftext|>


<commit_before>use clap;
use std;
use std::env;
use std::path::PathBuf;
use errors::*;
use dir;

pub use clap::ArgMatches;

pub fn app<'a, 'b>() -> clap::App<'a, 'b> {
    clap::App::new("to")
        .version(crate_version!())
        .author(crate_authors!())
        .about("Bookmark directories")

        // User friendly info! output.
        .arg(clap::Arg::with_name("verbose")
            .long("verbose")
            .short("v")
            .help("Verbose log output")
            .takes_value(false))

        .arg(clap::Arg::with_name("config")
            .long("config")
            .short("c")
            .help("Config dir, defaults to ~/.to")
            .takes_value(true))

        // Positional arguments.
        .arg(clap::Arg::with_name("NAME")
            .help("Name of the bookamrk")
            .index(1))
        .arg(clap::Arg::with_name("DIRECTORY")
            .help("Path of the bookamrk")
            .index(2))

        // Flags.
        .arg(clap::Arg::with_name("info")
            .long("info")
            .short("i")
            .help("Show bookmark information")
            .takes_value(false))
        .arg(clap::Arg::with_name("save")
            .long("save")
            .short("s")
            .help("Save bookmark")
            .takes_value(false))
        .arg(clap::Arg::with_name("delete")
            .long("delete")
            .short("d")
            .help("Delete bookmark")
            .takes_value(false)
            .requires("NAME"))
        .arg(clap::Arg::with_name("list")
            .long("list")
            .short("l")
            .help("List all bookmarks")
            .takes_value(false))
        .arg(clap::Arg::with_name("initialize")
            .long("init")
            .help("Echo initialization script")
            .takes_value(false)
            .conflicts_with_all(&[
                "NAME",
                "DIRECTORY",
                "get",
                "put",
                "delete",
                "list"]))
}

#[derive(Debug, PartialEq)]
pub enum Action {
    Delete,
    Info,
    List,
    Save,
    Pathname,
}

pub struct Options {
    pub verbose: bool,
    pub initialize: bool,
    pub action: Action,
    pub name: String,
    pub path: PathBuf,
    pub config: PathBuf,
}

impl Options {
    /// Creates a new instance of Options from clap::ArgMatches.
    ///
    /// # Examples:
    ///
    /// ```
    /// use to::cli;
    ///
    /// let matches = cli::app().get_matches_from(vec![""]);
    /// let options = cli::Options::new(matches).unwrap();
    ///
    /// assert_eq!(options.verbose, false);
    /// assert_eq!(options.initialize, false);
    /// assert_eq!(options.action, cli::Action::Pathname);
    /// ```
    pub fn new(matches: clap::ArgMatches) -> Result<Options> {
        let (delete, info, list, save) = (
            matches.is_present("delete"),
            matches.is_present("info"),
            matches.is_present("list"),
            matches.is_present("save"),
        );

        let action = match (delete, info, list, save) {
            (true, _, _, _) => Action::Delete,
            (_, true, _, _) => Action::Info,
            (_, _, true, _) => Action::List,
            (_, _, _, true) => Action::Save,
            _ => Action::Pathname,
        };

        let directory = matches.value_of("DIRECTORY").map(PathBuf::from);
        let path = match directory {
            Some(value) => try!(dir::resolve(value)),
            None => try!(env::current_dir()),
        };

        let name = matches
            .value_of("NAME")
            .map(normalize)
            .unwrap_or(try!(dir::basename(&path)));

        Ok(Options {
            action: action,
            config: try!(config(matches.value_of("config"))),
            path: path,
            initialize: matches.is_present("initialize"),
            name: name,
            verbose: matches.is_present("verbose")})
    }
}

// Normalize CLI text input.
//
// Will convert to lowercase, remove whitespace, and trim trailing slashes sometimes added by tab
// completion.
fn normalize(string: &str) -> String {
    string
        .trim()
        .trim_right_matches(std::path::MAIN_SEPARATOR)
        .to_lowercase()
}

fn config(value: Option<&str>) -> Result<PathBuf> {
    value
        .map(PathBuf::from)
        .or_else(|| {
            env::home_dir().map(|mut home| {
                home.push(".to");
                home
            })
        })
        .ok_or_else(|| ErrorKind::ConfigError.into())
}

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

    #[test]
    fn normalize_name_input() {
        assert_eq!(normalize("trim-trailing/"), "trim-trailing");
        assert_eq!(normalize("LOWERCASE"), "lowercase");
        assert_eq!(normalize("  spaces "), "spaces");
    }
}
<commit_msg>Format<commit_after>use clap;
use std;
use std::env;
use std::path::PathBuf;
use errors::*;
use dir;

pub use clap::ArgMatches;

pub fn app<'a, 'b>() -> clap::App<'a, 'b> {
    clap::App::new("to")
        .version(crate_version!())
        .author(crate_authors!())
        .about("Bookmark directories")

        // User friendly info! output.
        .arg(clap::Arg::with_name("verbose")
            .long("verbose")
            .short("v")
            .help("Verbose log output")
            .takes_value(false))

        .arg(clap::Arg::with_name("config")
            .long("config")
            .short("c")
            .help("Config dir, defaults to ~/.to")
            .takes_value(true))

        // Positional arguments.
        .arg(clap::Arg::with_name("NAME")
            .help("Name of the bookamrk")
            .index(1))
        .arg(clap::Arg::with_name("DIRECTORY")
            .help("Path of the bookamrk")
            .index(2))

        // Flags.
        .arg(clap::Arg::with_name("info")
            .long("info")
            .short("i")
            .help("Show bookmark information")
            .takes_value(false))
        .arg(clap::Arg::with_name("save")
            .long("save")
            .short("s")
            .help("Save bookmark")
            .takes_value(false))
        .arg(clap::Arg::with_name("delete")
            .long("delete")
            .short("d")
            .help("Delete bookmark")
            .takes_value(false)
            .requires("NAME"))
        .arg(clap::Arg::with_name("list")
            .long("list")
            .short("l")
            .help("List all bookmarks")
            .takes_value(false))
        .arg(clap::Arg::with_name("initialize")
            .long("init")
            .help("Echo initialization script")
            .takes_value(false)
            .conflicts_with_all(&[
                "NAME",
                "DIRECTORY",
                "get",
                "put",
                "delete",
                "list"]))
}

#[derive(Debug, PartialEq)]
pub enum Action {
    Delete,
    Info,
    List,
    Save,
    Pathname,
}

pub struct Options {
    pub verbose: bool,
    pub initialize: bool,
    pub action: Action,
    pub name: String,
    pub path: PathBuf,
    pub config: PathBuf,
}

impl Options {
    /// Creates a new instance of Options from clap::ArgMatches.
    ///
    /// # Examples:
    ///
    /// ```
    /// use to::cli;
    ///
    /// let matches = cli::app().get_matches_from(vec![""]);
    /// let options = cli::Options::new(matches).unwrap();
    ///
    /// assert_eq!(options.verbose, false);
    /// assert_eq!(options.initialize, false);
    /// assert_eq!(options.action, cli::Action::Pathname);
    /// ```
    pub fn new(matches: clap::ArgMatches) -> Result<Options> {
        let (delete, info, list, save) = (
            matches.is_present("delete"),
            matches.is_present("info"),
            matches.is_present("list"),
            matches.is_present("save"),
        );

        let action = match (delete, info, list, save) {
            (true, _, _, _) => Action::Delete,
            (_, true, _, _) => Action::Info,
            (_, _, true, _) => Action::List,
            (_, _, _, true) => Action::Save,
            _ => Action::Pathname,
        };

        let directory = matches.value_of("DIRECTORY").map(PathBuf::from);
        let path = match directory {
            Some(value) => try!(dir::resolve(value)),
            None => try!(env::current_dir()),
        };

        let name = matches
            .value_of("NAME")
            .map(normalize)
            .unwrap_or(try!(dir::basename(&path)));

        Ok(Options {
            action: action,
            config: try!(config(matches.value_of("config"))),
            path: path,
            initialize: matches.is_present("initialize"),
            name: name,
            verbose: matches.is_present("verbose"),
        })
    }
}

// Normalize CLI text input.
//
// Will convert to lowercase, remove whitespace, and trim trailing slashes sometimes added by tab
// completion.
fn normalize(string: &str) -> String {
    string
        .trim()
        .trim_right_matches(std::path::MAIN_SEPARATOR)
        .to_lowercase()
}

fn config(value: Option<&str>) -> Result<PathBuf> {
    value
        .map(PathBuf::from)
        .or_else(|| {
            env::home_dir().map(|mut home| {
                home.push(".to");
                home
            })
        })
        .ok_or_else(|| ErrorKind::ConfigError.into())
}

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

    #[test]
    fn normalize_name_input() {
        assert_eq!(normalize("trim-trailing/"), "trim-trailing");
        assert_eq!(normalize("LOWERCASE"), "lowercase");
        assert_eq!(normalize("  spaces "), "spaces");
    }
}
<|endoftext|>


<commit_before>use crate::rpcclient::RpcClient;
use crate::{
    sign::Sign,
    types::{Bufnr, QuickfixEntry, VimExp, VirtualText},
    utils::Canonicalize,
    viewport::Viewport,
};
use anyhow::Result;
use jsonrpc_core::Value;
use log::*;
use lsp_types::Position;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::json;
use std::{path::Path, sync::Arc};

/// Try get value of an variable from RPC params.
pub fn try_get<R: DeserializeOwned>(key: &str, params: &Value) -> Result<Option<R>> {
    let value = &params[key];
    if value == &Value::Null {
        Ok(None)
    } else {
        Ok(serde_json::from_value(value.clone())?)
    }
}

#[derive(PartialEq)]
pub enum Mode {
    Normal,
    Insert,
    Replace,
    Visual,
    VisualLine,
    VisualBlock,
    Command,
    Select,
    SelectLine,
    SelectBlock,
    Terminal,
}

impl From<&str> for Mode {
    fn from(mode: &str) -> Self {
        match mode {
            "n" => Mode::Normal,
            "i" => Mode::Insert,
            "R" => Mode::Replace,
            "v" => Mode::Visual,
            "V" => Mode::VisualLine,
            "<C-v>" => Mode::VisualBlock,
            "c" => Mode::Command,
            "s" => Mode::Select,
            "S" => Mode::SelectLine,
            "<C-s>" => Mode::SelectBlock,
            "t" => Mode::Terminal,
            m => {
                error!("unknown mode {}, falling back to Mode::Normal", m);
                Mode::Normal
            }
        }
    }
}

#[derive(Clone)]
pub struct Vim {
    pub rpcclient: Arc<RpcClient>,
}

impl Vim {
    pub fn new(rpcclient: Arc<RpcClient>) -> Self {
        Self { rpcclient }
    }

    /// Fundamental functions.

    pub fn get_mode(&self) -> Result<Mode> {
        let mode: String = self.rpcclient.call("mode", json!([]))?;
        Ok(Mode::from(mode.as_str()))
    }

    pub fn command(&self, cmds: impl Serialize) -> Result<()> {
        self.rpcclient.notify("s:command", &cmds)
    }

    pub fn eval<E, T>(&self, exp: E) -> Result<T>
    where
        E: VimExp,
        T: DeserializeOwned,
    {
        self.rpcclient.call("eval", &exp.to_exp())
    }

    /// Function wrappers.

    pub fn getbufvar<R: DeserializeOwned>(&self, bufname: &str, var: &str) -> Result<R> {
        self.rpcclient.call("getbufvar", json!([bufname, var]))
    }

    pub fn get_filename(&self, params: &Value) -> Result<String> {
        let key = "filename";
        let expr = "LSP#filename()";

        let filename: String = try_get(key, params)?.map_or_else(|| self.eval(expr), Ok)?;
        Ok(filename.canonicalize())
    }

    pub fn get_language_id(&self, filename: &str, params: &Value) -> Result<String> {
        let key = "languageId";
        let expr = "&filetype";

        try_get(key, params)?.map_or_else(|| self.getbufvar(filename, expr), Ok)
    }

    pub fn get_bufnr(&self, filename: &str, params: &Value) -> Result<Bufnr> {
        let key = "bufnr";

        try_get(key, params)?.map_or_else(|| self.eval(format!("bufnr('{}')", filename)), Ok)
    }

    pub fn get_viewport(&self, params: &Value) -> Result<Viewport> {
        let key = "viewport";
        let expr = "LSP#viewport()";

        try_get(key, params)?.map_or_else(|| self.eval(expr), Ok)
    }

    pub fn get_position(&self, params: &Value) -> Result<Position> {
        let key = "position";
        let expr = "LSP#position()";

        try_get(key, params)?.map_or_else(|| self.eval(expr), Ok)
    }

    pub fn get_current_word(&self, params: &Value) -> Result<String> {
        let key = "cword";
        let expr = "expand('<cword>')";

        try_get(key, params)?.map_or_else(|| self.eval(expr), Ok)
    }

    pub fn get_goto_cmd(&self, params: &Value) -> Result<Option<String>> {
        let key = "gotoCmd";

        try_get(key, params)
    }

    pub fn get_tab_size(&self) -> Result<u64> {
        let expr = "shiftwidth()";

        self.eval(expr)
    }

    pub fn get_insert_spaces(&self, filename: &str) -> Result<bool> {
        let insert_spaces: i8 = self.getbufvar(filename, "&expandtab")?;
        Ok(insert_spaces == 1)
    }

    pub fn get_text(&self, bufname: &str) -> Result<Vec<String>> {
        self.rpcclient.call("LSP#text", json!([bufname]))
    }

    pub fn get_handle(&self, params: &Value) -> Result<bool> {
        let key = "handle";

        try_get(key, params)?.map_or_else(|| Ok(true), Ok)
    }

    pub fn echo(&self, message: impl AsRef<str>) -> Result<()> {
        self.rpcclient.notify("s:Echo", message.as_ref())
    }

    pub fn echo_ellipsis(&self, message: impl AsRef<str>) -> Result<()> {
        let message = message.as_ref().lines().collect::<Vec<_>>().join(" ");
        self.rpcclient.notify("s:EchoEllipsis", message)
    }

    pub fn echomsg_ellipsis(&self, message: impl AsRef<str>) -> Result<()> {
        let message = message.as_ref().lines().collect::<Vec<_>>().join(" ");
        self.rpcclient.notify("s:EchomsgEllipsis", message)
    }

    pub fn echomsg(&self, message: impl AsRef<str>) -> Result<()> {
        self.rpcclient.notify("s:Echomsg", message.as_ref())
    }

    pub fn echoerr(&self, message: impl AsRef<str>) -> Result<()> {
        self.rpcclient.notify("s:Echoerr", message.as_ref())
    }

    pub fn echowarn(&self, message: impl AsRef<str>) -> Result<()> {
        self.rpcclient.notify("s:Echowarn", message.as_ref())
    }

    pub fn cursor(&self, lnum: u64, col: u64) -> Result<()> {
        self.rpcclient.notify("cursor", json!([lnum, col]))
    }

    #[allow(dead_code)]
    pub fn setline(&self, lnum: u64, text: &[String]) -> Result<()> {
        self.rpcclient.notify("setline", json!([lnum, text]))
    }

    pub fn edit(&self, goto_cmd: &Option<String>, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref().to_string_lossy();
        let goto = goto_cmd.as_deref().unwrap_or("edit");
        self.rpcclient.notify("s:Edit", json!([goto, path]))?;
        Ok(())
    }

    pub fn setqflist(&self, list: &[QuickfixEntry], action: &str, title: &str) -> Result<()> {
        info!("Begin setqflist");
        let parms = json!([list, action]);
        self.rpcclient.notify("setqflist", parms)?;
        let parms = json!([[], "a", { "title": title }]);
        self.rpcclient.notify("setqflist", parms)?;
        Ok(())
    }

    pub fn setloclist(&self, list: &[QuickfixEntry], action: &str, title: &str) -> Result<()> {
        let parms = json!([0, list, action]);
        self.rpcclient.notify("setloclist", parms)?;
        let parms = json!([0, [], "a", { "title": title }]);
        self.rpcclient.notify("setloclist", parms)?;
        Ok(())
    }

    pub fn create_namespace(&self, name: &str) -> Result<i64> {
        self.rpcclient.call("nvim_create_namespace", [name])
    }

    pub fn set_virtual_texts(
        &self,
        buf_id: i64,
        ns_id: i64,
        line_start: u64,
        line_end: u64,
        virtual_texts: &[VirtualText],
    ) -> Result<i8> {
        self.rpcclient.call(
            "s:set_virtual_texts",
            json!([buf_id, ns_id, line_start, line_end, virtual_texts]),
        )
    }

    pub fn set_signs(&self, filename: &str, signs: &[Sign]) -> Result<i8> {
        self.rpcclient.call("s:set_signs", json!([filename, signs]))
    }
}
<commit_msg>Prefer T::deserialize over T::from_value to avoid clone (#1130)<commit_after>use crate::rpcclient::RpcClient;
use crate::{
    sign::Sign,
    types::{Bufnr, QuickfixEntry, VimExp, VirtualText},
    utils::Canonicalize,
    viewport::Viewport,
};
use anyhow::Result;
use jsonrpc_core::Value;
use log::*;
use lsp_types::Position;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::json;
use std::{path::Path, sync::Arc};

/// Try get value of an variable from RPC params.
pub fn try_get<'a, R: Deserialize<'a>>(key: &str, params: &'a Value) -> Result<Option<R>> {
    let value = &params[key];
    if value == &Value::Null {
        Ok(None)
    } else {
        Ok(<Option<R>>::deserialize(value)?)
    }
}

#[derive(PartialEq)]
pub enum Mode {
    Normal,
    Insert,
    Replace,
    Visual,
    VisualLine,
    VisualBlock,
    Command,
    Select,
    SelectLine,
    SelectBlock,
    Terminal,
}

impl From<&str> for Mode {
    fn from(mode: &str) -> Self {
        match mode {
            "n" => Mode::Normal,
            "i" => Mode::Insert,
            "R" => Mode::Replace,
            "v" => Mode::Visual,
            "V" => Mode::VisualLine,
            "<C-v>" => Mode::VisualBlock,
            "c" => Mode::Command,
            "s" => Mode::Select,
            "S" => Mode::SelectLine,
            "<C-s>" => Mode::SelectBlock,
            "t" => Mode::Terminal,
            m => {
                error!("unknown mode {}, falling back to Mode::Normal", m);
                Mode::Normal
            }
        }
    }
}

#[derive(Clone)]
pub struct Vim {
    pub rpcclient: Arc<RpcClient>,
}

impl Vim {
    pub fn new(rpcclient: Arc<RpcClient>) -> Self {
        Self { rpcclient }
    }

    /// Fundamental functions.

    pub fn get_mode(&self) -> Result<Mode> {
        let mode: String = self.rpcclient.call("mode", json!([]))?;
        Ok(Mode::from(mode.as_str()))
    }

    pub fn command(&self, cmds: impl Serialize) -> Result<()> {
        self.rpcclient.notify("s:command", &cmds)
    }

    pub fn eval<E, T>(&self, exp: E) -> Result<T>
    where
        E: VimExp,
        T: DeserializeOwned,
    {
        self.rpcclient.call("eval", &exp.to_exp())
    }

    /// Function wrappers.

    pub fn getbufvar<R: DeserializeOwned>(&self, bufname: &str, var: &str) -> Result<R> {
        self.rpcclient.call("getbufvar", json!([bufname, var]))
    }

    pub fn get_filename(&self, params: &Value) -> Result<String> {
        let key = "filename";
        let expr = "LSP#filename()";

        let filename: String = try_get(key, params)?.map_or_else(|| self.eval(expr), Ok)?;
        Ok(filename.canonicalize())
    }

    pub fn get_language_id(&self, filename: &str, params: &Value) -> Result<String> {
        let key = "languageId";
        let expr = "&filetype";

        try_get(key, params)?.map_or_else(|| self.getbufvar(filename, expr), Ok)
    }

    pub fn get_bufnr(&self, filename: &str, params: &Value) -> Result<Bufnr> {
        let key = "bufnr";

        try_get(key, params)?.map_or_else(|| self.eval(format!("bufnr('{}')", filename)), Ok)
    }

    pub fn get_viewport(&self, params: &Value) -> Result<Viewport> {
        let key = "viewport";
        let expr = "LSP#viewport()";

        try_get(key, params)?.map_or_else(|| self.eval(expr), Ok)
    }

    pub fn get_position(&self, params: &Value) -> Result<Position> {
        let key = "position";
        let expr = "LSP#position()";

        try_get(key, params)?.map_or_else(|| self.eval(expr), Ok)
    }

    pub fn get_current_word(&self, params: &Value) -> Result<String> {
        let key = "cword";
        let expr = "expand('<cword>')";

        try_get(key, params)?.map_or_else(|| self.eval(expr), Ok)
    }

    pub fn get_goto_cmd(&self, params: &Value) -> Result<Option<String>> {
        let key = "gotoCmd";

        try_get(key, params)
    }

    pub fn get_tab_size(&self) -> Result<u64> {
        let expr = "shiftwidth()";

        self.eval(expr)
    }

    pub fn get_insert_spaces(&self, filename: &str) -> Result<bool> {
        let insert_spaces: i8 = self.getbufvar(filename, "&expandtab")?;
        Ok(insert_spaces == 1)
    }

    pub fn get_text(&self, bufname: &str) -> Result<Vec<String>> {
        self.rpcclient.call("LSP#text", json!([bufname]))
    }

    pub fn get_handle(&self, params: &Value) -> Result<bool> {
        let key = "handle";

        try_get(key, params)?.map_or_else(|| Ok(true), Ok)
    }

    pub fn echo(&self, message: impl AsRef<str>) -> Result<()> {
        self.rpcclient.notify("s:Echo", message.as_ref())
    }

    pub fn echo_ellipsis(&self, message: impl AsRef<str>) -> Result<()> {
        let message = message.as_ref().lines().collect::<Vec<_>>().join(" ");
        self.rpcclient.notify("s:EchoEllipsis", message)
    }

    pub fn echomsg_ellipsis(&self, message: impl AsRef<str>) -> Result<()> {
        let message = message.as_ref().lines().collect::<Vec<_>>().join(" ");
        self.rpcclient.notify("s:EchomsgEllipsis", message)
    }

    pub fn echomsg(&self, message: impl AsRef<str>) -> Result<()> {
        self.rpcclient.notify("s:Echomsg", message.as_ref())
    }

    pub fn echoerr(&self, message: impl AsRef<str>) -> Result<()> {
        self.rpcclient.notify("s:Echoerr", message.as_ref())
    }

    pub fn echowarn(&self, message: impl AsRef<str>) -> Result<()> {
        self.rpcclient.notify("s:Echowarn", message.as_ref())
    }

    pub fn cursor(&self, lnum: u64, col: u64) -> Result<()> {
        self.rpcclient.notify("cursor", json!([lnum, col]))
    }

    #[allow(dead_code)]
    pub fn setline(&self, lnum: u64, text: &[String]) -> Result<()> {
        self.rpcclient.notify("setline", json!([lnum, text]))
    }

    pub fn edit(&self, goto_cmd: &Option<String>, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref().to_string_lossy();
        let goto = goto_cmd.as_deref().unwrap_or("edit");
        self.rpcclient.notify("s:Edit", json!([goto, path]))?;
        Ok(())
    }

    pub fn setqflist(&self, list: &[QuickfixEntry], action: &str, title: &str) -> Result<()> {
        info!("Begin setqflist");
        let parms = json!([list, action]);
        self.rpcclient.notify("setqflist", parms)?;
        let parms = json!([[], "a", { "title": title }]);
        self.rpcclient.notify("setqflist", parms)?;
        Ok(())
    }

    pub fn setloclist(&self, list: &[QuickfixEntry], action: &str, title: &str) -> Result<()> {
        let parms = json!([0, list, action]);
        self.rpcclient.notify("setloclist", parms)?;
        let parms = json!([0, [], "a", { "title": title }]);
        self.rpcclient.notify("setloclist", parms)?;
        Ok(())
    }

    pub fn create_namespace(&self, name: &str) -> Result<i64> {
        self.rpcclient.call("nvim_create_namespace", [name])
    }

    pub fn set_virtual_texts(
        &self,
        buf_id: i64,
        ns_id: i64,
        line_start: u64,
        line_end: u64,
        virtual_texts: &[VirtualText],
    ) -> Result<i8> {
        self.rpcclient.call(
            "s:set_virtual_texts",
            json!([buf_id, ns_id, line_start, line_end, virtual_texts]),
        )
    }

    pub fn set_signs(&self, filename: &str, signs: &[Sign]) -> Result<i8> {
        self.rpcclient.call("s:set_signs", json!([filename, signs]))
    }
}
<|endoftext|>


<commit_before>// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

use glib::translate::*;
use ffi;

use surface::Surface;

pub struct XCBDrawable(pub u32);

impl XCBDrawable {
    fn to_glib_none(&self) -> u32 {
        self.0
    }
}

pub struct XCBPixmap(pub u32);

impl XCBPixmap {
    fn to_glib_none(&self) -> u32 {
        self.0
    }
}

pub struct XCBConnection(pub *mut ffi::xcb_connection_t);

impl<'a> ToGlibPtr<'a, *mut ffi::xcb_connection_t> for &'a XCBConnection {
    type Storage = &'a XCBConnection;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::xcb_connection_t, &'a XCBConnection> {
        Stash(self.0, *self)
    }
}

impl FromGlibPtrNone<*mut ffi::xcb_connection_t> for XCBConnection {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::xcb_connection_t) -> XCBConnection {
        assert!(!ptr.is_null());
        XCBConnection(ptr)
    }
}

impl FromGlibPtrFull<*mut ffi::xcb_connection_t> for XCBConnection {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::xcb_connection_t) -> XCBConnection {
        assert!(!ptr.is_null());
        XCBConnection(ptr)
    }
}

impl AsRef<XCBConnection> for XCBConnection {
    fn as_ref(&self) -> &XCBConnection {
        self
    }
}

impl Clone for XCBConnection {
    fn clone(&self) -> XCBConnection {
        unsafe { from_glib_none(self.to_glib_none().0) }
    }
}

pub struct XCBRenderPictFormInfo(pub *mut ffi::xcb_render_pictforminfo_t);

impl<'a> ToGlibPtr<'a, *mut ffi::xcb_render_pictforminfo_t> for &'a XCBRenderPictFormInfo {
    type Storage = &'a XCBRenderPictFormInfo;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::xcb_render_pictforminfo_t, &'a XCBRenderPictFormInfo> {
        Stash(self.0, *self)
    }
}

impl FromGlibPtrNone<*mut ffi::xcb_render_pictforminfo_t> for XCBRenderPictFormInfo {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::xcb_render_pictforminfo_t) -> XCBRenderPictFormInfo {
        assert!(!ptr.is_null());
        XCBRenderPictFormInfo(ptr)
    }
}

impl FromGlibPtrFull<*mut ffi::xcb_render_pictforminfo_t> for XCBRenderPictFormInfo {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::xcb_render_pictforminfo_t) -> XCBRenderPictFormInfo {
        assert!(!ptr.is_null());
        XCBRenderPictFormInfo(ptr)
    }
}

impl AsRef<XCBRenderPictFormInfo> for XCBRenderPictFormInfo {
    fn as_ref(&self) -> &XCBRenderPictFormInfo {
        self
    }
}

impl Clone for XCBRenderPictFormInfo {
    fn clone(&self) -> XCBRenderPictFormInfo {
        unsafe { from_glib_none(self.to_glib_none().0) }
    }
}

pub struct XCBScreen(pub *mut ffi::xcb_screen_t);

impl<'a> ToGlibPtr<'a, *mut ffi::xcb_screen_t> for &'a XCBScreen {
    type Storage = &'a XCBScreen;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::xcb_screen_t, &'a XCBScreen> {
        Stash(self.0, *self)
    }
}

impl FromGlibPtrNone<*mut ffi::xcb_screen_t> for XCBScreen {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::xcb_screen_t) -> XCBScreen {
        assert!(!ptr.is_null());
        XCBScreen(ptr)
    }
}

impl FromGlibPtrFull<*mut ffi::xcb_screen_t> for XCBScreen {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::xcb_screen_t) -> XCBScreen {
        assert!(!ptr.is_null());
        XCBScreen(ptr)
    }
}

impl AsRef<XCBScreen> for XCBScreen {
    fn as_ref(&self) -> &XCBScreen {
        self
    }
}

impl Clone for XCBScreen {
    fn clone(&self) -> XCBScreen {
        unsafe { from_glib_none(self.to_glib_none().0) }
    }
}

pub trait XCBSurface {
    fn create(connection: &XCBConnection, drawable: &XCBDrawable, visual: &XCBVisualType,
              width: i32, height: i32) -> Surface;
    fn create_for_bitmap(connection: &XCBConnection, screen: &XCBScreen, bitmap: &XCBPixmap,
                         width: i32, height: i32) -> Surface;
    fn create_with_xrender_format(connection: &XCBConnection, screen: &XCBScreen,
                                  bitmap: &XCBPixmap, format: &XCBRenderPictFormInfo,
                                  width: i32, height: i32) -> Surface;
    fn set_size(&self, width: i32, height: i32);
    fn set_drawable(&self, drawable: &XCBDrawable, width: i32, height: i32);
}

impl XCBSurface for Surface {
    fn create(connection: &XCBConnection, drawable: &XCBDrawable, visual: &XCBVisualType,
              width: i32, height: i32) -> Surface {
        unsafe {
            from_glib_full(ffi::cairo_xcb_surface_create(connection.to_glib_none().0,
                                                         drawable.to_glib_none(),
                                                         visual.to_glib_none().0,
                                                         width,
                                                         height))
        }
    }

    fn create_for_bitmap(connection: &XCBConnection, screen: &XCBScreen, bitmap: &XCBPixmap,
                         width: i32, height: i32) -> Surface {
        unsafe {
            from_glib_full(ffi::cairo_xcb_surface_create_for_bitmap(connection.to_glib_none().0,
                                                                    screen.to_glib_none().0,
                                                                    bitmap.to_glib_none(),
                                                                    width,
                                                                    height))
        }
    }

    fn create_with_xrender_format(connection: &XCBConnection, screen: &XCBScreen,
                                  bitmap: &XCBPixmap, format: &XCBRenderPictFormInfo,
                                  width: i32, height: i32) -> Surface {
        unsafe {
            from_glib_full(ffi::cairo_xcb_surface_create_with_xrender_format(connection.to_glib_none().0,
                                                                             screen.to_glib_none().0,
                                                                             bitmap.to_glib_none(),
                                                                             format.to_glib_none().0,
                                                                             width,
                                                                             height))
        }
    }

    fn set_size(self: &Surface, width: i32, height: i32) {
        unsafe {
            ffi::cairo_xcb_surface_set_size(self.to_glib_none().0, width, height)
        }
    }

    fn set_drawable(self: &Surface, drawable: &XCBDrawable, width: i32, height: i32) {
        unsafe {
            ffi::cairo_xcb_surface_set_drawable(self.to_glib_none().0, drawable.to_glib_none(),
                                                width, height)
        }
    }
}

pub struct XCBVisualType(pub *mut ffi::xcb_visualtype_t);

impl<'a> ToGlibPtr<'a, *mut ffi::xcb_visualtype_t> for &'a XCBVisualType {
    type Storage = &'a XCBVisualType;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::xcb_visualtype_t, &'a XCBVisualType> {
        Stash(self.0, *self)
    }
}

impl FromGlibPtrNone<*mut ffi::xcb_visualtype_t> for XCBVisualType {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::xcb_visualtype_t) -> XCBVisualType {
        assert!(!ptr.is_null());
        XCBVisualType(ptr)
    }
}

impl FromGlibPtrFull<*mut ffi::xcb_visualtype_t> for XCBVisualType {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::xcb_visualtype_t) -> XCBVisualType {
        assert!(!ptr.is_null());
        XCBVisualType(ptr)
    }
}

impl AsRef<XCBVisualType> for XCBVisualType {
    fn as_ref(&self) -> &XCBVisualType {
        self
    }
}

impl Clone for XCBVisualType {
    fn clone(&self) -> XCBVisualType {
        unsafe { from_glib_none(self.to_glib_none().0) }
    }
}

pub struct Device(pub *mut ffi::cairo_device_t);

impl<'a> ToGlibPtr<'a, *mut ffi::cairo_device_t> for &'a Device {
    type Storage = &'a Device;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::cairo_device_t, &'a Device> {
        Stash(self.0, *self)
    }
}

impl FromGlibPtrNone<*mut ffi::cairo_device_t> for Device {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::cairo_device_t) -> Device {
        assert!(!ptr.is_null());
        Device(ptr)
    }
}

impl FromGlibPtrFull<*mut ffi::cairo_device_t> for Device {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::cairo_device_t) -> Device {
        assert!(!ptr.is_null());
        Device(ptr)
    }
}

impl AsRef<Device> for Device {
    fn as_ref(&self) -> &Device {
        self
    }
}

impl Clone for Device {
    fn clone(&self) -> Device {
        unsafe { from_glib_none(self.to_glib_none().0) }
    }
}

impl Device {
    pub fn get_connection(&self) -> XCBConnection {
        unsafe {
            from_glib_full(ffi::cairo_xcb_device_get_connection(self.to_glib_none().0))
        }
    }

    pub fn debug_cap_xrender_version(&self, major_version: i32, minor_version: i32) {
        unsafe {
            ffi::cairo_xcb_device_debug_cap_xrender_version(self.to_glib_none().0,
                                                            major_version,
                                                            minor_version)
        }
    }

    pub fn debug_cap_xshm_version(&self, major_version: i32, minor_version: i32) {
        unsafe {
            ffi::cairo_xcb_device_debug_cap_xshm_version(self.to_glib_none().0,
                                                         major_version,
                                                         minor_version)
        }
    }

    pub fn debug_get_precision(&self) -> i32 {
        unsafe {
            ffi::cairo_xcb_device_debug_get_precision(self.to_glib_none().0)
        }
    }

    pub fn debug_set_precision(&self, precision: i32) {
        unsafe {
            ffi::cairo_xcb_device_debug_set_precision(self.to_glib_none().0, precision)
        }
    }
}
<commit_msg>make glib optional for xcb features<commit_after>// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

#[cfg(feature = "glib")]
use glib::translate::*;
use ffi;

use surface::Surface;

pub struct XCBDrawable(pub u32);

impl XCBDrawable {
    fn to_raw_none(&self) -> u32 {
        self.0
    }
}

pub struct XCBPixmap(pub u32);

impl XCBPixmap {
    fn to_raw_none(&self) -> u32 {
        self.0
    }
}

pub struct XCBConnection(pub *mut ffi::xcb_connection_t);

impl XCBConnection {
    pub fn to_raw_none(&self) -> *mut ffi::xcb_connection_t {
        self.0
    }

    pub unsafe fn from_raw_none(ptr: *mut ffi::xcb_connection_t) -> XCBConnection {
        assert!(!ptr.is_null());
        XCBConnection(ptr)
    }

    pub unsafe fn from_raw_full(ptr: *mut ffi::xcb_connection_t) -> XCBConnection {
        assert!(!ptr.is_null());
        XCBConnection(ptr)
    }
}

#[cfg(feature = "glib")]
impl<'a> ToGlibPtr<'a, *mut ffi::xcb_connection_t> for &'a XCBConnection {
    type Storage = &'a XCBConnection;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::xcb_connection_t, &'a XCBConnection> {
        Stash(self.to_raw_none(), *self)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrNone<*mut ffi::xcb_connection_t> for XCBConnection {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::xcb_connection_t) -> XCBConnection {
        Self::from_raw_none(ptr)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrFull<*mut ffi::xcb_connection_t> for XCBConnection {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::xcb_connection_t) -> XCBConnection {
        Self::from_raw_full(ptr)
    }
}

impl AsRef<XCBConnection> for XCBConnection {
    fn as_ref(&self) -> &XCBConnection {
        self
    }
}

impl Clone for XCBConnection {
    fn clone(&self) -> XCBConnection {
        unsafe { Self::from_raw_none(self.to_raw_none()) }
    }
}

pub struct XCBRenderPictFormInfo(pub *mut ffi::xcb_render_pictforminfo_t);

impl XCBRenderPictFormInfo {
    pub fn to_raw_none(&self) ->  *mut ffi::xcb_render_pictforminfo_t {
        self.0
    }

    pub unsafe fn from_raw_none(ptr: *mut ffi::xcb_render_pictforminfo_t) -> XCBRenderPictFormInfo {
        assert!(!ptr.is_null());
        XCBRenderPictFormInfo(ptr)
    }

    pub unsafe fn from_raw_full(ptr: *mut ffi::xcb_render_pictforminfo_t) -> XCBRenderPictFormInfo {
        assert!(!ptr.is_null());
        XCBRenderPictFormInfo(ptr)
    }
}

#[cfg(feature = "glib")]
impl<'a> ToGlibPtr<'a, *mut ffi::xcb_render_pictforminfo_t> for &'a XCBRenderPictFormInfo {
    type Storage = &'a XCBRenderPictFormInfo;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::xcb_render_pictforminfo_t, &'a XCBRenderPictFormInfo> {
        Stash(self.to_raw_none(), *self)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrNone<*mut ffi::xcb_render_pictforminfo_t> for XCBRenderPictFormInfo {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::xcb_render_pictforminfo_t) -> XCBRenderPictFormInfo {
        Self::from_raw_none(ptr)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrFull<*mut ffi::xcb_render_pictforminfo_t> for XCBRenderPictFormInfo {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::xcb_render_pictforminfo_t) -> XCBRenderPictFormInfo {
        Self::from_raw_full(ptr)
    }
}

impl AsRef<XCBRenderPictFormInfo> for XCBRenderPictFormInfo {
    fn as_ref(&self) -> &XCBRenderPictFormInfo {
        self
    }
}

impl Clone for XCBRenderPictFormInfo {
    fn clone(&self) -> XCBRenderPictFormInfo {
        unsafe { Self::from_raw_none(self.to_raw_none()) }
    }
}

pub struct XCBScreen(pub *mut ffi::xcb_screen_t);

impl XCBScreen {
    pub fn to_raw_none(&self) -> *mut ffi::xcb_screen_t {
        self.0
    }

    pub unsafe fn from_raw_none(ptr: *mut ffi::xcb_screen_t) -> XCBScreen {
        assert!(!ptr.is_null());
        XCBScreen(ptr)
    }

    pub unsafe fn from_raw_full(ptr: *mut ffi::xcb_screen_t) -> XCBScreen {
        assert!(!ptr.is_null());
        XCBScreen(ptr)
    }
}

#[cfg(feature = "glib")]
impl<'a> ToGlibPtr<'a, *mut ffi::xcb_screen_t> for &'a XCBScreen {
    type Storage = &'a XCBScreen;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::xcb_screen_t, &'a XCBScreen> {
        Stash(self.to_raw_none(), *self)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrNone<*mut ffi::xcb_screen_t> for XCBScreen {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::xcb_screen_t) -> XCBScreen {
        Self::from_raw_none(ptr)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrFull<*mut ffi::xcb_screen_t> for XCBScreen {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::xcb_screen_t) -> XCBScreen {
        Self::from_raw_full(ptr)
    }
}

impl AsRef<XCBScreen> for XCBScreen {
    fn as_ref(&self) -> &XCBScreen {
        self
    }
}

impl Clone for XCBScreen {
    fn clone(&self) -> XCBScreen {
        unsafe { Self::from_raw_none(self.to_raw_none()) }
    }
}

pub trait XCBSurface {
    fn create(connection: &XCBConnection, drawable: &XCBDrawable, visual: &XCBVisualType,
              width: i32, height: i32) -> Surface;
    fn create_for_bitmap(connection: &XCBConnection, screen: &XCBScreen, bitmap: &XCBPixmap,
                         width: i32, height: i32) -> Surface;
    fn create_with_xrender_format(connection: &XCBConnection, screen: &XCBScreen,
                                  bitmap: &XCBPixmap, format: &XCBRenderPictFormInfo,
                                  width: i32, height: i32) -> Surface;
    fn set_size(&self, width: i32, height: i32);
    fn set_drawable(&self, drawable: &XCBDrawable, width: i32, height: i32);
}

impl XCBSurface for Surface {
    fn create(connection: &XCBConnection, drawable: &XCBDrawable, visual: &XCBVisualType,
              width: i32, height: i32) -> Surface {
        unsafe {
            Surface::from_raw_full(ffi::cairo_xcb_surface_create(connection.to_raw_none(),
                                                                 drawable.to_raw_none(),
                                                                 visual.to_raw_none(),
                                                                 width,
                                                                 height))
        }
    }

    fn create_for_bitmap(connection: &XCBConnection, screen: &XCBScreen, bitmap: &XCBPixmap,
                         width: i32, height: i32) -> Surface {
        unsafe {
            Surface::from_raw_full(ffi::cairo_xcb_surface_create_for_bitmap(connection.to_raw_none(),
                                                                            screen.to_raw_none(),
                                                                            bitmap.to_raw_none(),
                                                                            width,
                                                                            height))
        }
    }

    fn create_with_xrender_format(connection: &XCBConnection, screen: &XCBScreen,
                                  bitmap: &XCBPixmap, format: &XCBRenderPictFormInfo,
                                  width: i32, height: i32) -> Surface {
        unsafe {
            Surface::from_raw_full(ffi::cairo_xcb_surface_create_with_xrender_format(connection.to_raw_none(),
                                                                                screen.to_raw_none(),
                                                                                bitmap.to_raw_none(),
                                                                                format.to_raw_none(),
                                                                                width,
                                                                                height))
        }
    }

    fn set_size(self: &Surface, width: i32, height: i32) {
        unsafe {
            ffi::cairo_xcb_surface_set_size(self.to_raw_none(), width, height)
        }
    }

    fn set_drawable(self: &Surface, drawable: &XCBDrawable, width: i32, height: i32) {
        unsafe {
            ffi::cairo_xcb_surface_set_drawable(self.to_raw_none(), drawable.to_raw_none(),
                                                width, height)
        }
    }
}

pub struct XCBVisualType(pub *mut ffi::xcb_visualtype_t);

impl XCBVisualType {
    pub fn to_raw_none(&self) -> *mut ffi::xcb_visualtype_t {
        self.0
    }

    pub unsafe fn from_raw_none(ptr: *mut ffi::xcb_visualtype_t) -> XCBVisualType {
        assert!(!ptr.is_null());
        XCBVisualType(ptr)
    }

    pub unsafe fn from_raw_full(ptr: *mut ffi::xcb_visualtype_t) -> XCBVisualType {
        assert!(!ptr.is_null());
        XCBVisualType(ptr)
    }
}

#[cfg(feature = "glib")]
impl<'a> ToGlibPtr<'a, *mut ffi::xcb_visualtype_t> for &'a XCBVisualType {
    type Storage = &'a XCBVisualType;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::xcb_visualtype_t, &'a XCBVisualType> {
        Stash(self.to_raw_none(), *self)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrNone<*mut ffi::xcb_visualtype_t> for XCBVisualType {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::xcb_visualtype_t) -> XCBVisualType {
        Self::from_raw_none(ptr)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrFull<*mut ffi::xcb_visualtype_t> for XCBVisualType {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::xcb_visualtype_t) -> XCBVisualType {
        Self::from_raw_full(ptr)
    }
}

impl AsRef<XCBVisualType> for XCBVisualType {
    fn as_ref(&self) -> &XCBVisualType {
        self
    }
}

impl Clone for XCBVisualType {
    fn clone(&self) -> XCBVisualType {
        unsafe { Self::from_raw_none(self.to_raw_none()) }
    }
}

pub struct Device(pub *mut ffi::cairo_device_t);

impl Device {
    pub fn to_raw_none(&self) -> *mut ffi::cairo_device_t {
        self.0
    }

    pub unsafe fn from_raw_none(ptr: *mut ffi::cairo_device_t) -> Device {
        assert!(!ptr.is_null());
        Device(ptr)
    }

    pub unsafe fn from_raw_full(ptr: *mut ffi::cairo_device_t) -> Device {
        assert!(!ptr.is_null());
        Device(ptr)
    }
}

#[cfg(feature = "glib")]
impl<'a> ToGlibPtr<'a, *mut ffi::cairo_device_t> for &'a Device {
    type Storage = &'a Device;

    #[inline]
    fn to_glib_none(&self) -> Stash<'a, *mut ffi::cairo_device_t, &'a Device> {
        Stash(self.to_raw_none(), *self)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrNone<*mut ffi::cairo_device_t> for Device {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::cairo_device_t) -> Device {
        Self::from_raw_none(ptr)
    }
}

#[cfg(feature = "glib")]
impl FromGlibPtrFull<*mut ffi::cairo_device_t> for Device {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::cairo_device_t) -> Device {
        Self::from_raw_full(ptr)
    }
}

impl AsRef<Device> for Device {
    fn as_ref(&self) -> &Device {
        self
    }
}

impl Clone for Device {
    fn clone(&self) -> Device {
        unsafe { Self::from_raw_none(self.to_raw_none()) }
    }
}

impl Device {
    pub fn get_connection(&self) -> XCBConnection {
        unsafe {
            XCBConnection::from_raw_full(ffi::cairo_xcb_device_get_connection(self.to_raw_none()))
        }
    }

    pub fn debug_cap_xrender_version(&self, major_version: i32, minor_version: i32) {
        unsafe {
            ffi::cairo_xcb_device_debug_cap_xrender_version(self.to_raw_none(),
                                                            major_version,
                                                            minor_version)
        }
    }

    pub fn debug_cap_xshm_version(&self, major_version: i32, minor_version: i32) {
        unsafe {
            ffi::cairo_xcb_device_debug_cap_xshm_version(self.to_raw_none(),
                                                         major_version,
                                                         minor_version)
        }
    }

    pub fn debug_get_precision(&self) -> i32 {
        unsafe {
            ffi::cairo_xcb_device_debug_get_precision(self.to_raw_none())
        }
    }

    pub fn debug_set_precision(&self, precision: i32) {
        unsafe {
            ffi::cairo_xcb_device_debug_set_precision(self.to_raw_none(), precision)
        }
    }
}
<|endoftext|>