<commit_before>extern crate quick_xml;

use quick_xml::reader::Reader;
use quick_xml::events::Event::*;
use quick_xml::events::attributes::Attribute;
use std::io::Cursor;

#[test]
fn test_sample() {
    let src: &[u8] = include_bytes!("sample_rss.xml");
    let mut buf = Vec::new();
    let mut r = Reader::from_reader(src);
    let mut count = 0;
    loop {
        match r.read_event(&mut buf).unwrap() {
            Start(_) => count += 1,
            Decl(e) => println!("{:?}", e.version()),
            Eof => break,
            _ => (),
        }
        buf.clear();
    }
    println!("{}", count);
}

#[test]
fn test_attributes_empty() {
    let src = b"<a att1='a' att2='b'/>";
    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    match r.read_event(&mut buf) {
        Ok(Empty(e)) => {
            let mut atts = e.attributes();
            match atts.next() {
                Some(
                    Ok(Attribute {
                        key: b"att1",
                        value: b"a",
                    }),
                ) => (),
                e => panic!("Expecting att1='a' attribute, found {:?}", e),
            }
            match atts.next() {
                Some(
                    Ok(Attribute {
                        key: b"att2",
                        value: b"b",
                    }),
                ) => (),
                e => panic!("Expecting att2='b' attribute, found {:?}", e),
            }
            match atts.next() {
                None => (),
                e => panic!("Expecting None, found {:?}", e),
            }
        }
        e => panic!("Expecting Empty event, got {:?}", e),
    }
}

#[test]
fn test_attribute_equal() {
    let src = b"<a att1=\"a=b\"/>";
    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    match r.read_event(&mut buf) {
        Ok(Empty(e)) => {
            let mut atts = e.attributes();
            match atts.next() {
                Some(
                    Ok(Attribute {
                        key: b"att1",
                        value: b"a=b",
                    }),
                ) => (),
                e => panic!("Expecting att1=\"a=b\" attribute, found {:?}", e),
            }
            match atts.next() {
                None => (),
                e => panic!("Expecting None, found {:?}", e),
            }
        }
        e => panic!("Expecting Empty event, got {:?}", e),
    }
}

/// Single empty element with qualified attributes.
/// Empty element expansion: disabled
/// The code path for namespace handling is slightly different for `Empty` vs. `Start+End`.
#[test]
fn test_attributes_empty_ns() {
    let src = b"<a att1='a' r:att2='b' xmlns:r='urn:example:r' />";

    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    let mut ns_buf = Vec::new();

    let e = match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((None, Empty(e))) => e,
        e => panic!("Expecting Empty event, got {:?}", e),
    };

    let mut atts = e.attributes()
            .map(|ar| ar.expect("Expecting attribute parsing to succeed."))
            // we don't care about xmlns attributes for this test
            .filter(|kv| !kv.key.starts_with(b"xmlns"))
            .map(|Attribute { key: name, value }| {
                let (opt_ns, local_name) = r.resolve_namespace(name, &ns_buf);
                (opt_ns, local_name, value)
            });
    match atts.next() {
        Some((None, b"att1", b"a")) => (),
        e => panic!("Expecting att1='a' attribute, found {:?}", e),
    }
    match atts.next() {
        Some((Some(ns), b"att2", b"b")) => {
            assert_eq!(&ns[..], b"urn:example:r");
        }
        e => panic!(
            "Expecting {{urn:example:r}}att2='b' attribute, found {:?}",
            e
        ),
    }
    match atts.next() {
        None => (),
        e => panic!("Expecting None, found {:?}", e),
    }
}

/// Single empty element with qualified attributes.
/// Empty element expansion: enabled
/// The code path for namespace handling is slightly different for `Empty` vs. `Start+End`.
#[test]
fn test_attributes_empty_ns_expanded() {
    let src = b"<a att1='a' r:att2='b' xmlns:r='urn:example:r' />";

    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(true);
    let mut buf = Vec::new();
    let mut ns_buf = Vec::new();
    {
        let e = match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((None, Start(e))) => e,
            e => panic!("Expecting Empty event, got {:?}", e),
        };

        let mut atts = e.attributes()
            .map(|ar| ar.expect("Expecting attribute parsing to succeed."))
            // we don't care about xmlns attributes for this test
            .filter(|kv| !kv.key.starts_with(b"xmlns"))
            .map(|Attribute { key: name, value }| {
                let (opt_ns, local_name) = r.resolve_namespace(name, &ns_buf);
                (opt_ns, local_name, value)
            });
        match atts.next() {
            Some((None, b"att1", b"a")) => (),
            e => panic!("Expecting att1='a' attribute, found {:?}", e),
        }
        match atts.next() {
            Some((Some(ns), b"att2", b"b")) => {
                assert_eq!(&ns[..], b"urn:example:r");
            }
            e => panic!(
                "Expecting {{urn:example:r}}att2='b' attribute, found {:?}",
                e
            ),
        }
        match atts.next() {
            None => (),
            e => panic!("Expecting None, found {:?}", e),
        }
    }

    match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((None, End(e))) => assert_eq!(b"a", e.name()),
        e => panic!("Expecting End event, got {:?}", e),
    }
}

#[test]
fn test_default_ns_shadowing_empty() {
    let src = b"<e xmlns='urn:example:o'><e att1='a' xmlns='urn:example:i' /></e>";

    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    let mut ns_buf = Vec::new();

    // <outer xmlns='urn:example:o'>
    {
        match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((Some(ns), Start(e))) => {
                assert_eq!(&ns[..], b"urn:example:o");
                assert_eq!(e.name(), b"e");
            }
            e => panic!("Expected Start event (<outer>), got {:?}", e),
        }
    }

    // <inner att1='a' xmlns='urn:example:i' />
    {
        let e = match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((Some(ns), Empty(e))) => {
                assert_eq!(::std::str::from_utf8(ns).unwrap(), "urn:example:i");
                assert_eq!(e.name(), b"e");
                e
            }
            e => panic!("Expecting Empty event, got {:?}", e),
        };

        let mut atts = e.attributes()
            .map(|ar| ar.expect("Expecting attribute parsing to succeed."))
            // we don't care about xmlns attributes for this test
            .filter(|kv| !kv.key.starts_with(b"xmlns"))
            .map(|Attribute { key: name, value }| {
                let (opt_ns, local_name) = r.resolve_namespace(name, &ns_buf);
                (opt_ns, local_name, value)
            });
        // the attribute should _not_ have a namespace name. The default namespace does not
        // apply to attributes.
        match atts.next() {
            Some((None, b"att1", b"a")) => (),
            e => panic!("Expecting att1='a' attribute, found {:?}", e),
        }
        match atts.next() {
            None => (),
            e => panic!("Expecting None, found {:?}", e),
        }
    }

    // </outer>
    match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((Some(ns), End(e))) => {
            assert_eq!(&ns[..], b"urn:example:o");
            assert_eq!(e.name(), b"e");
        }
        e => panic!("Expected End event (<outer>), got {:?}", e),
    }
}

#[test]
fn test_default_ns_shadowing_expanded() {
    let src = b"<e xmlns='urn:example:o'><e att1='a' xmlns='urn:example:i' /></e>";

    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(true);
    let mut buf = Vec::new();
    let mut ns_buf = Vec::new();

    // <outer xmlns='urn:example:o'>
    {
        match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((Some(ns), Start(e))) => {
                assert_eq!(&ns[..], b"urn:example:o");
                assert_eq!(e.name(), b"e");
            }
            e => panic!("Expected Start event (<outer>), got {:?}", e),
        }
    }
    buf.clear();

    // <inner att1='a' xmlns='urn:example:i' />
    {
        let e = match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((Some(ns), Start(e))) => {
                assert_eq!(&ns[..], b"urn:example:i");
                assert_eq!(e.name(), b"e");
                e
            }
            e => panic!("Expecting Start event (<inner>), got {:?}", e),
        };
        let mut atts = e.attributes()
            .map(|ar| ar.expect("Expecting attribute parsing to succeed."))
            // we don't care about xmlns attributes for this test
            .filter(|kv| !kv.key.starts_with(b"xmlns"))
            .map(|Attribute { key: name, value }| {
                let (opt_ns, local_name) = r.resolve_namespace(name, &ns_buf);
                (opt_ns, local_name, value)
            });
        // the attribute should _not_ have a namespace name. The default namespace does not
        // apply to attributes.
        match atts.next() {
            Some((None, b"att1", b"a")) => (),
            e => panic!("Expecting att1='a' attribute, found {:?}", e),
        }
        match atts.next() {
            None => (),
            e => panic!("Expecting None, found {:?}", e),
        }
    }

    // virtual </inner>
    match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((Some(ns), End(e))) => {
            assert_eq!(&ns[..], b"urn:example:i");
            assert_eq!(e.name(), b"e");
        }
        e => panic!("Expected End event (</inner>), got {:?}", e),
    }
    // </outer>
    match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((Some(ns), End(e))) => {
            assert_eq!(&ns[..], b"urn:example:o");
            assert_eq!(e.name(), b"e");
        }
        e => panic!("Expected End event (</outer>), got {:?}", e),
    }
}

#[test]
fn test_koi8_r_encoding() {
    let src: &[u8] = include_bytes!("documents/opennews_all.rss");
    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    loop {
        match r.read_event(&mut buf) {
            Ok(Text(e)) => {
                e.unescape_and_decode(&r).unwrap();
            }
            Ok(Eof) => break,
            _ => (),
        }
    }
}

#[test]
fn fuzz_53() {
    let data: &[u8] = b"\xe9\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\n(\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\
\x00<>\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00<<\x00\x00\x00";
    let cursor = Cursor::new(data);
    let mut reader = Reader::from_reader(cursor);
    let mut buf = vec![];
    loop {
        match reader.read_event(&mut buf) {
            Ok(quick_xml::events::Event::Eof) | Err(..) => break,
            _ => buf.clear(),
        }
    }
}
<commit_msg>add broken test<commit_after>extern crate quick_xml;

use quick_xml::reader::Reader;
use quick_xml::events::Event::*;
use quick_xml::events::attributes::Attribute;
use std::io::Cursor;

#[test]
fn test_sample() {
    let src: &[u8] = include_bytes!("sample_rss.xml");
    let mut buf = Vec::new();
    let mut r = Reader::from_reader(src);
    let mut count = 0;
    loop {
        match r.read_event(&mut buf).unwrap() {
            Start(_) => count += 1,
            Decl(e) => println!("{:?}", e.version()),
            Eof => break,
            _ => (),
        }
        buf.clear();
    }
    println!("{}", count);
}

#[test]
fn test_attributes_empty() {
    let src = b"<a att1='a' att2='b'/>";
    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    match r.read_event(&mut buf) {
        Ok(Empty(e)) => {
            let mut atts = e.attributes();
            match atts.next() {
                Some(
                    Ok(Attribute {
                        key: b"att1",
                        value: b"a",
                    }),
                ) => (),
                e => panic!("Expecting att1='a' attribute, found {:?}", e),
            }
            match atts.next() {
                Some(
                    Ok(Attribute {
                        key: b"att2",
                        value: b"b",
                    }),
                ) => (),
                e => panic!("Expecting att2='b' attribute, found {:?}", e),
            }
            match atts.next() {
                None => (),
                e => panic!("Expecting None, found {:?}", e),
            }
        }
        e => panic!("Expecting Empty event, got {:?}", e),
    }
}

#[test]
fn test_attribute_equal() {
    let src = b"<a att1=\"a=b\"/>";
    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    match r.read_event(&mut buf) {
        Ok(Empty(e)) => {
            let mut atts = e.attributes();
            match atts.next() {
                Some(
                    Ok(Attribute {
                        key: b"att1",
                        value: b"a=b",
                    }),
                ) => (),
                e => panic!("Expecting att1=\"a=b\" attribute, found {:?}", e),
            }
            match atts.next() {
                None => (),
                e => panic!("Expecting None, found {:?}", e),
            }
        }
        e => panic!("Expecting Empty event, got {:?}", e),
    }
}

/// Single empty element with qualified attributes.
/// Empty element expansion: disabled
/// The code path for namespace handling is slightly different for `Empty` vs. `Start+End`.
#[test]
fn test_attributes_empty_ns() {
    let src = b"<a att1='a' r:att2='b' xmlns:r='urn:example:r' />";

    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    let mut ns_buf = Vec::new();

    let e = match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((None, Empty(e))) => e,
        e => panic!("Expecting Empty event, got {:?}", e),
    };

    let mut atts = e.attributes()
            .map(|ar| ar.expect("Expecting attribute parsing to succeed."))
            // we don't care about xmlns attributes for this test
            .filter(|kv| !kv.key.starts_with(b"xmlns"))
            .map(|Attribute { key: name, value }| {
                let (opt_ns, local_name) = r.resolve_namespace(name, &ns_buf);
                (opt_ns, local_name, value)
            });
    match atts.next() {
        Some((None, b"att1", b"a")) => (),
        e => panic!("Expecting att1='a' attribute, found {:?}", e),
    }
    match atts.next() {
        Some((Some(ns), b"att2", b"b")) => {
            assert_eq!(&ns[..], b"urn:example:r");
        }
        e => panic!(
            "Expecting {{urn:example:r}}att2='b' attribute, found {:?}",
            e
        ),
    }
    match atts.next() {
        None => (),
        e => panic!("Expecting None, found {:?}", e),
    }
}

/// Single empty element with qualified attributes.
/// Empty element expansion: enabled
/// The code path for namespace handling is slightly different for `Empty` vs. `Start+End`.
#[test]
fn test_attributes_empty_ns_expanded() {
    let src = b"<a att1='a' r:att2='b' xmlns:r='urn:example:r' />";

    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(true);
    let mut buf = Vec::new();
    let mut ns_buf = Vec::new();
    {
        let e = match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((None, Start(e))) => e,
            e => panic!("Expecting Empty event, got {:?}", e),
        };

        let mut atts = e.attributes()
            .map(|ar| ar.expect("Expecting attribute parsing to succeed."))
            // we don't care about xmlns attributes for this test
            .filter(|kv| !kv.key.starts_with(b"xmlns"))
            .map(|Attribute { key: name, value }| {
                let (opt_ns, local_name) = r.resolve_namespace(name, &ns_buf);
                (opt_ns, local_name, value)
            });
        match atts.next() {
            Some((None, b"att1", b"a")) => (),
            e => panic!("Expecting att1='a' attribute, found {:?}", e),
        }
        match atts.next() {
            Some((Some(ns), b"att2", b"b")) => {
                assert_eq!(&ns[..], b"urn:example:r");
            }
            e => panic!(
                "Expecting {{urn:example:r}}att2='b' attribute, found {:?}",
                e
            ),
        }
        match atts.next() {
            None => (),
            e => panic!("Expecting None, found {:?}", e),
        }
    }

    match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((None, End(e))) => assert_eq!(b"a", e.name()),
        e => panic!("Expecting End event, got {:?}", e),
    }
}

#[test]
fn test_default_ns_shadowing_empty() {
    let src = b"<e xmlns='urn:example:o'><e att1='a' xmlns='urn:example:i' /></e>";

    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    let mut ns_buf = Vec::new();

    // <outer xmlns='urn:example:o'>
    {
        match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((Some(ns), Start(e))) => {
                assert_eq!(&ns[..], b"urn:example:o");
                assert_eq!(e.name(), b"e");
            }
            e => panic!("Expected Start event (<outer>), got {:?}", e),
        }
    }

    // <inner att1='a' xmlns='urn:example:i' />
    {
        let e = match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((Some(ns), Empty(e))) => {
                assert_eq!(::std::str::from_utf8(ns).unwrap(), "urn:example:i");
                assert_eq!(e.name(), b"e");
                e
            }
            e => panic!("Expecting Empty event, got {:?}", e),
        };

        let mut atts = e.attributes()
            .map(|ar| ar.expect("Expecting attribute parsing to succeed."))
            // we don't care about xmlns attributes for this test
            .filter(|kv| !kv.key.starts_with(b"xmlns"))
            .map(|Attribute { key: name, value }| {
                let (opt_ns, local_name) = r.resolve_namespace(name, &ns_buf);
                (opt_ns, local_name, value)
            });
        // the attribute should _not_ have a namespace name. The default namespace does not
        // apply to attributes.
        match atts.next() {
            Some((None, b"att1", b"a")) => (),
            e => panic!("Expecting att1='a' attribute, found {:?}", e),
        }
        match atts.next() {
            None => (),
            e => panic!("Expecting None, found {:?}", e),
        }
    }

    // </outer>
    match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((Some(ns), End(e))) => {
            assert_eq!(&ns[..], b"urn:example:o");
            assert_eq!(e.name(), b"e");
        }
        e => panic!("Expected End event (<outer>), got {:?}", e),
    }
}

#[test]
fn test_default_ns_shadowing_expanded() {
    let src = b"<e xmlns='urn:example:o'><e att1='a' xmlns='urn:example:i' /></e>";

    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(true);
    let mut buf = Vec::new();
    let mut ns_buf = Vec::new();

    // <outer xmlns='urn:example:o'>
    {
        match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((Some(ns), Start(e))) => {
                assert_eq!(&ns[..], b"urn:example:o");
                assert_eq!(e.name(), b"e");
            }
            e => panic!("Expected Start event (<outer>), got {:?}", e),
        }
    }
    buf.clear();

    // <inner att1='a' xmlns='urn:example:i' />
    {
        let e = match r.read_namespaced_event(&mut buf, &mut ns_buf) {
            Ok((Some(ns), Start(e))) => {
                assert_eq!(&ns[..], b"urn:example:i");
                assert_eq!(e.name(), b"e");
                e
            }
            e => panic!("Expecting Start event (<inner>), got {:?}", e),
        };
        let mut atts = e.attributes()
            .map(|ar| ar.expect("Expecting attribute parsing to succeed."))
            // we don't care about xmlns attributes for this test
            .filter(|kv| !kv.key.starts_with(b"xmlns"))
            .map(|Attribute { key: name, value }| {
                let (opt_ns, local_name) = r.resolve_namespace(name, &ns_buf);
                (opt_ns, local_name, value)
            });
        // the attribute should _not_ have a namespace name. The default namespace does not
        // apply to attributes.
        match atts.next() {
            Some((None, b"att1", b"a")) => (),
            e => panic!("Expecting att1='a' attribute, found {:?}", e),
        }
        match atts.next() {
            None => (),
            e => panic!("Expecting None, found {:?}", e),
        }
    }

    // virtual </inner>
    match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((Some(ns), End(e))) => {
            assert_eq!(&ns[..], b"urn:example:i");
            assert_eq!(e.name(), b"e");
        }
        e => panic!("Expected End event (</inner>), got {:?}", e),
    }
    // </outer>
    match r.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((Some(ns), End(e))) => {
            assert_eq!(&ns[..], b"urn:example:o");
            assert_eq!(e.name(), b"e");
        }
        e => panic!("Expected End event (</outer>), got {:?}", e),
    }
}

#[test]
fn test_koi8_r_encoding() {
    let src: &[u8] = include_bytes!("documents/opennews_all.rss");
    let mut r = Reader::from_reader(src as &[u8]);
    r.trim_text(true).expand_empty_elements(false);
    let mut buf = Vec::new();
    loop {
        match r.read_event(&mut buf) {
            Ok(Text(e)) => {
                e.unescape_and_decode(&r).unwrap();
            }
            Ok(Eof) => break,
            _ => (),
        }
    }
}

#[test]
fn fuzz_53() {
    let data: &[u8] = b"\xe9\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\n(\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\
\x00<>\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00<<\x00\x00\x00";
    let cursor = Cursor::new(data);
    let mut reader = Reader::from_reader(cursor);
    let mut buf = vec![];
    loop {
        match reader.read_event(&mut buf) {
            Ok(quick_xml::events::Event::Eof) | Err(..) => break,
            _ => buf.clear(),
        }
    }
}

#[test]
fn test_issue94() {
    let data = br#"<Run>
<!B>
</Run>"#;
    let mut reader = Reader::from_reader(&data[..]);
    reader.trim_text(true);
    let mut buf = vec![];
    loop {
        match reader.read_event(&mut buf) {
            Ok(quick_xml::events::Event::Eof) | Err(..) => break,
            _ => buf.clear(),
        }
        buf.clear();
    }
}
<|endoftext|>


<commit_before>extern crate r2d2;

use std::comm;
use std::sync::{Mutex, Arc};
use std::sync::atomic::{AtomicBool, SeqCst};
use std::default::Default;

mod config;

#[deriving(Show, PartialEq)]
struct FakeConnection;

#[deriving(Default)]
struct OkManager;

impl r2d2::PoolManager<FakeConnection, ()> for OkManager {
    fn connect(&self) -> Result<FakeConnection, ()> {
        Ok(FakeConnection)
    }

    fn is_valid(&self, _: &FakeConnection) -> bool {
        true
    }
}

struct NthConnectFailManager {
    n: Mutex<uint>,
}

impl r2d2::PoolManager<FakeConnection, ()> for NthConnectFailManager {
    fn connect(&self) -> Result<FakeConnection, ()> {
        let mut n = self.n.lock();
        if *n > 0 {
            *n -= 1;
            Ok(FakeConnection)
        } else {
            Err(())
        }
    }

    fn is_valid(&self, _: &FakeConnection) -> bool {
        true
    }
}

#[test]
fn test_pool_size_ok() {
    let config = r2d2::Config {
        pool_size: 5,
        ..Default::default()
    };
    let manager = NthConnectFailManager { n: Mutex::new(5) };
    assert!(r2d2::Pool::new(config, manager, r2d2::NoopErrorHandler).is_ok());
}

#[test]
fn test_pool_size_err() {
    let config = r2d2::Config {
        pool_size: 5,
        ..Default::default()
    };
    let manager = NthConnectFailManager { n: Mutex::new(4) };
    assert_eq!(r2d2::Pool::new(config, manager, r2d2::NoopErrorHandler).err().unwrap(),
               r2d2::ConnectionError(()));
}

#[test]
fn test_acquire_release() {
    let config = r2d2::Config {
        pool_size: 2,
        ..Default::default()
    };
    let pool = r2d2::Pool::new(config, OkManager, r2d2::NoopErrorHandler).unwrap();

    let conn1 = pool.get().unwrap();
    let conn2 = pool.get().unwrap();
    drop(conn1);
    let conn3 = pool.get().unwrap();
    drop(conn2);
    drop(conn3);
}

#[test]
fn test_is_send_sync() {
    fn is_send_sync<T: Send+Sync>() {}
    is_send_sync::<r2d2::Pool<FakeConnection, (), OkManager, r2d2::NoopErrorHandler>>();
}

#[test]
fn test_issue_2_unlocked_during_is_valid() {
    struct BlockingChecker {
        first: AtomicBool,
        s: Mutex<SyncSender<()>>,
        r: Mutex<Receiver<()>>,
    }

    impl r2d2::PoolManager<FakeConnection, ()> for BlockingChecker {
        fn connect(&self) -> Result<FakeConnection, ()> {
            Ok(FakeConnection)
        }

        fn is_valid(&self, _: &FakeConnection) -> bool {
            if self.first.compare_and_swap(true, false, SeqCst) {
                self.s.lock().send(());
                self.r.lock().recv();
            }
            true
        }
    }

    let (s1, r1) = comm::sync_channel(0);
    let (s2, r2) = comm::sync_channel(0);

    let config = r2d2::Config {
        test_on_check_out: true,
        pool_size: 2,
        ..Default::default()
    };
    let manager = BlockingChecker {
        first: AtomicBool::new(true),
        s: Mutex::new(s1),
        r: Mutex::new(r2),
    };
    let pool = Arc::new(r2d2::Pool::new(config, manager, r2d2::NoopErrorHandler).unwrap());

    let p2 = pool.clone();
    spawn(proc() {
        p2.get().unwrap();
    });

    r1.recv();
    // get call by other task has triggered the health check
    pool.get().unwrap();
    s2.send(());
}
<commit_msg>Remove unnecessary deriving<commit_after>extern crate r2d2;

use std::comm;
use std::sync::{Mutex, Arc};
use std::sync::atomic::{AtomicBool, SeqCst};
use std::default::Default;

mod config;

#[deriving(Show, PartialEq)]
struct FakeConnection;

struct OkManager;

impl r2d2::PoolManager<FakeConnection, ()> for OkManager {
    fn connect(&self) -> Result<FakeConnection, ()> {
        Ok(FakeConnection)
    }

    fn is_valid(&self, _: &FakeConnection) -> bool {
        true
    }
}

struct NthConnectFailManager {
    n: Mutex<uint>,
}

impl r2d2::PoolManager<FakeConnection, ()> for NthConnectFailManager {
    fn connect(&self) -> Result<FakeConnection, ()> {
        let mut n = self.n.lock();
        if *n > 0 {
            *n -= 1;
            Ok(FakeConnection)
        } else {
            Err(())
        }
    }

    fn is_valid(&self, _: &FakeConnection) -> bool {
        true
    }
}

#[test]
fn test_pool_size_ok() {
    let config = r2d2::Config {
        pool_size: 5,
        ..Default::default()
    };
    let manager = NthConnectFailManager { n: Mutex::new(5) };
    assert!(r2d2::Pool::new(config, manager, r2d2::NoopErrorHandler).is_ok());
}

#[test]
fn test_pool_size_err() {
    let config = r2d2::Config {
        pool_size: 5,
        ..Default::default()
    };
    let manager = NthConnectFailManager { n: Mutex::new(4) };
    assert_eq!(r2d2::Pool::new(config, manager, r2d2::NoopErrorHandler).err().unwrap(),
               r2d2::ConnectionError(()));
}

#[test]
fn test_acquire_release() {
    let config = r2d2::Config {
        pool_size: 2,
        ..Default::default()
    };
    let pool = r2d2::Pool::new(config, OkManager, r2d2::NoopErrorHandler).unwrap();

    let conn1 = pool.get().unwrap();
    let conn2 = pool.get().unwrap();
    drop(conn1);
    let conn3 = pool.get().unwrap();
    drop(conn2);
    drop(conn3);
}

#[test]
fn test_is_send_sync() {
    fn is_send_sync<T: Send+Sync>() {}
    is_send_sync::<r2d2::Pool<FakeConnection, (), OkManager, r2d2::NoopErrorHandler>>();
}

#[test]
fn test_issue_2_unlocked_during_is_valid() {
    struct BlockingChecker {
        first: AtomicBool,
        s: Mutex<SyncSender<()>>,
        r: Mutex<Receiver<()>>,
    }

    impl r2d2::PoolManager<FakeConnection, ()> for BlockingChecker {
        fn connect(&self) -> Result<FakeConnection, ()> {
            Ok(FakeConnection)
        }

        fn is_valid(&self, _: &FakeConnection) -> bool {
            if self.first.compare_and_swap(true, false, SeqCst) {
                self.s.lock().send(());
                self.r.lock().recv();
            }
            true
        }
    }

    let (s1, r1) = comm::sync_channel(0);
    let (s2, r2) = comm::sync_channel(0);

    let config = r2d2::Config {
        test_on_check_out: true,
        pool_size: 2,
        ..Default::default()
    };
    let manager = BlockingChecker {
        first: AtomicBool::new(true),
        s: Mutex::new(s1),
        r: Mutex::new(r2),
    };
    let pool = Arc::new(r2d2::Pool::new(config, manager, r2d2::NoopErrorHandler).unwrap());

    let p2 = pool.clone();
    spawn(proc() {
        p2.get().unwrap();
    });

    r1.recv();
    // get call by other task has triggered the health check
    pool.get().unwrap();
    s2.send(());
}
<|endoftext|>


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

//! A wrapper around another RNG that reseeds it after it
//! generates a certain number of random bytes.

use core::prelude::*;

use {Rng, SeedableRng};
use core::default::Default;

/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
static DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024;

/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
pub struct ReseedingRng<R, Rsdr> {
    rng: R,
    generation_threshold: uint,
    bytes_generated: uint,
    /// Controls the behaviour when reseeding the RNG.
    pub reseeder: Rsdr,
}

impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
    /// Create a new `ReseedingRng` with the given parameters.
    ///
    /// # Arguments
    ///
    /// * `rng`: the random number generator to use.
    /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
    /// * `reseeder`: the reseeding object to use.
    pub fn new(rng: R, generation_threshold: uint, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> {
        ReseedingRng {
            rng: rng,
            generation_threshold: generation_threshold,
            bytes_generated: 0,
            reseeder: reseeder
        }
    }

    /// Reseed the internal RNG if the number of bytes that have been
    /// generated exceed the threshold.
    pub fn reseed_if_necessary(&mut self) {
        if self.bytes_generated >= self.generation_threshold {
            self.reseeder.reseed(&mut self.rng);
            self.bytes_generated = 0;
        }
    }
}

impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
    fn next_u32(&mut self) -> u32 {
        self.reseed_if_necessary();
        self.bytes_generated += 4;
        self.rng.next_u32()
    }

    fn next_u64(&mut self) -> u64 {
        self.reseed_if_necessary();
        self.bytes_generated += 8;
        self.rng.next_u64()
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        self.reseed_if_necessary();
        self.bytes_generated += dest.len();
        self.rng.fill_bytes(dest)
    }
}

impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default>
     SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
    fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
        self.rng.reseed(seed);
        self.reseeder = rsdr;
        self.bytes_generated = 0;
    }

    /// Create a new `ReseedingRng` from the given reseeder and
    /// seed. This uses a default value for `generation_threshold`.
    fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
        ReseedingRng {
            rng: SeedableRng::from_seed(seed),
            generation_threshold: DEFAULT_GENERATION_THRESHOLD,
            bytes_generated: 0,
            reseeder: rsdr
        }
    }
}

/// Something that can be used to reseed an RNG via `ReseedingRng`.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
/// use std::rand::reseeding::{Reseeder, ReseedingRng};
///
/// struct TickTockReseeder { tick: bool }
/// impl Reseeder<StdRng> for TickTockReseeder {
///     fn reseed(&mut self, rng: &mut StdRng) {
///         let val = if self.tick {0} else {1};
///         rng.reseed(&[val]);
///         self.tick = !self.tick;
///     }
/// }
/// fn main() {
///     let rsdr = TickTockReseeder { tick: true };
///
///     let inner = StdRng::new().unwrap();
///     let mut rng = ReseedingRng::new(inner, 10, rsdr);
///
///     // this will repeat, because it gets reseeded very regularly.
///     let s: String = rng.gen_ascii_chars().take(100).collect();
///     println!("{}", s);
/// }
///
/// ```
pub trait Reseeder<R> {
    /// Reseed the given RNG.
    fn reseed(&mut self, rng: &mut R);
}

/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
pub struct ReseedWithDefault;

impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
    fn reseed(&mut self, rng: &mut R) {
        *rng = Default::default();
    }
}
impl Default for ReseedWithDefault {
    fn default() -> ReseedWithDefault { ReseedWithDefault }
}

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

    use core::iter::order;
    use super::{ReseedingRng, ReseedWithDefault};
    use std::default::Default;
    use {SeedableRng, Rng};

    struct Counter {
        i: u32
    }

    impl Rng for Counter {
        fn next_u32(&mut self) -> u32 {
            self.i += 1;
            // very random
            self.i - 1
        }
    }
    impl Default for Counter {
        fn default() -> Counter {
            Counter { i: 0 }
        }
    }
    impl SeedableRng<u32> for Counter {
        fn reseed(&mut self, seed: u32) {
            self.i = seed;
        }
        fn from_seed(seed: u32) -> Counter {
            Counter { i: seed }
        }
    }
    type MyRng = ReseedingRng<Counter, ReseedWithDefault>;

    #[test]
    fn test_reseeding() {
        let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);

        let mut i = 0;
        for _ in range(0u, 1000) {
            assert_eq!(rs.next_u32(), i % 100);
            i += 1;
        }
    }

    #[test]
    fn test_rng_seeded() {
        let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
        let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
        assert!(order::equals(ra.gen_ascii_chars().take(100),
                              rb.gen_ascii_chars().take(100)));
    }

    #[test]
    fn test_rng_reseed() {
        let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
        let string1: String = r.gen_ascii_chars().take(100).collect();

        r.reseed((ReseedWithDefault, 3));

        let string2: String = r.gen_ascii_chars().take(100).collect();
        assert_eq!(string1, string2);
    }

    static fill_bytes_v_len: uint = 13579;
    #[test]
    fn test_rng_fill_bytes() {
        let mut v = Vec::from_elem(fill_bytes_v_len, 0u8);
        ::test::rng().fill_bytes(v.as_mut_slice());

        // Sanity test: if we've gotten here, `fill_bytes` has not infinitely
        // recursed.
        assert_eq!(v.len(), fill_bytes_v_len);

        // To test that `fill_bytes` actually did something, check that the
        // average of `v` is not 0.
        let mut sum = 0.0;
        for &x in v.iter() {
            sum += x as f64;
        }
        assert!(sum / v.len() as f64 != 0.0);
    }
}
<commit_msg>Set the `non_uppercase_statics` lint to warn by default<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A wrapper around another RNG that reseeds it after it
//! generates a certain number of random bytes.

use core::prelude::*;

use {Rng, SeedableRng};
use core::default::Default;

/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
static DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024;

/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
pub struct ReseedingRng<R, Rsdr> {
    rng: R,
    generation_threshold: uint,
    bytes_generated: uint,
    /// Controls the behaviour when reseeding the RNG.
    pub reseeder: Rsdr,
}

impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
    /// Create a new `ReseedingRng` with the given parameters.
    ///
    /// # Arguments
    ///
    /// * `rng`: the random number generator to use.
    /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
    /// * `reseeder`: the reseeding object to use.
    pub fn new(rng: R, generation_threshold: uint, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> {
        ReseedingRng {
            rng: rng,
            generation_threshold: generation_threshold,
            bytes_generated: 0,
            reseeder: reseeder
        }
    }

    /// Reseed the internal RNG if the number of bytes that have been
    /// generated exceed the threshold.
    pub fn reseed_if_necessary(&mut self) {
        if self.bytes_generated >= self.generation_threshold {
            self.reseeder.reseed(&mut self.rng);
            self.bytes_generated = 0;
        }
    }
}

impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
    fn next_u32(&mut self) -> u32 {
        self.reseed_if_necessary();
        self.bytes_generated += 4;
        self.rng.next_u32()
    }

    fn next_u64(&mut self) -> u64 {
        self.reseed_if_necessary();
        self.bytes_generated += 8;
        self.rng.next_u64()
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        self.reseed_if_necessary();
        self.bytes_generated += dest.len();
        self.rng.fill_bytes(dest)
    }
}

impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R> + Default>
     SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
    fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
        self.rng.reseed(seed);
        self.reseeder = rsdr;
        self.bytes_generated = 0;
    }

    /// Create a new `ReseedingRng` from the given reseeder and
    /// seed. This uses a default value for `generation_threshold`.
    fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
        ReseedingRng {
            rng: SeedableRng::from_seed(seed),
            generation_threshold: DEFAULT_GENERATION_THRESHOLD,
            bytes_generated: 0,
            reseeder: rsdr
        }
    }
}

/// Something that can be used to reseed an RNG via `ReseedingRng`.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
/// use std::rand::reseeding::{Reseeder, ReseedingRng};
///
/// struct TickTockReseeder { tick: bool }
/// impl Reseeder<StdRng> for TickTockReseeder {
///     fn reseed(&mut self, rng: &mut StdRng) {
///         let val = if self.tick {0} else {1};
///         rng.reseed(&[val]);
///         self.tick = !self.tick;
///     }
/// }
/// fn main() {
///     let rsdr = TickTockReseeder { tick: true };
///
///     let inner = StdRng::new().unwrap();
///     let mut rng = ReseedingRng::new(inner, 10, rsdr);
///
///     // this will repeat, because it gets reseeded very regularly.
///     let s: String = rng.gen_ascii_chars().take(100).collect();
///     println!("{}", s);
/// }
///
/// ```
pub trait Reseeder<R> {
    /// Reseed the given RNG.
    fn reseed(&mut self, rng: &mut R);
}

/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
pub struct ReseedWithDefault;

impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
    fn reseed(&mut self, rng: &mut R) {
        *rng = Default::default();
    }
}
impl Default for ReseedWithDefault {
    fn default() -> ReseedWithDefault { ReseedWithDefault }
}

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

    use core::iter::order;
    use super::{ReseedingRng, ReseedWithDefault};
    use std::default::Default;
    use {SeedableRng, Rng};

    struct Counter {
        i: u32
    }

    impl Rng for Counter {
        fn next_u32(&mut self) -> u32 {
            self.i += 1;
            // very random
            self.i - 1
        }
    }
    impl Default for Counter {
        fn default() -> Counter {
            Counter { i: 0 }
        }
    }
    impl SeedableRng<u32> for Counter {
        fn reseed(&mut self, seed: u32) {
            self.i = seed;
        }
        fn from_seed(seed: u32) -> Counter {
            Counter { i: seed }
        }
    }
    type MyRng = ReseedingRng<Counter, ReseedWithDefault>;

    #[test]
    fn test_reseeding() {
        let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);

        let mut i = 0;
        for _ in range(0u, 1000) {
            assert_eq!(rs.next_u32(), i % 100);
            i += 1;
        }
    }

    #[test]
    fn test_rng_seeded() {
        let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
        let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
        assert!(order::equals(ra.gen_ascii_chars().take(100),
                              rb.gen_ascii_chars().take(100)));
    }

    #[test]
    fn test_rng_reseed() {
        let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
        let string1: String = r.gen_ascii_chars().take(100).collect();

        r.reseed((ReseedWithDefault, 3));

        let string2: String = r.gen_ascii_chars().take(100).collect();
        assert_eq!(string1, string2);
    }

    static FILL_BYTES_V_LEN: uint = 13579;
    #[test]
    fn test_rng_fill_bytes() {
        let mut v = Vec::from_elem(FILL_BYTES_V_LEN, 0u8);
        ::test::rng().fill_bytes(v.as_mut_slice());

        // Sanity test: if we've gotten here, `fill_bytes` has not infinitely
        // recursed.
        assert_eq!(v.len(), FILL_BYTES_V_LEN);

        // To test that `fill_bytes` actually did something, check that the
        // average of `v` is not 0.
        let mut sum = 0.0;
        for &x in v.iter() {
            sum += x as f64;
        }
        assert!(sum / v.len() as f64 != 0.0);
    }
}
<|endoftext|>


<commit_before>use async_graphql::{Context, EmptyMutation, EmptySubscription, Schema};
use async_trait::async_trait;
use dataloader::cached::Loader;
use dataloader::BatchFn;
use fake::faker::company::en::CompanyName;
use fake::faker::name::en::Name;
use fake::{Dummy, Fake, Faker};
use futures::executor::block_on;
use std::collections::HashMap;

pub struct CultBatcher;

#[async_trait]
impl BatchFn<i32, Cult> for CultBatcher {
    type Error = ();

    async fn load(&self, keys: &[i32]) -> HashMap<i32, Result<Cult, Self::Error>> {
        println!("load cult by batch {:?}", keys);
        let ret = keys
            .iter()
            .map(|k| {
                let mut cult: Cult = Faker.fake();
                cult.id = k.clone();
                (k.clone(), Ok(cult))
            })
            .collect();
        ret
    }
}

#[derive(Clone)]
pub struct AppContext {
    cult_loader: Loader<i32, Cult, (), CultBatcher>,
}

impl AppContext {
    pub fn new() -> AppContext {
        AppContext {
            cult_loader: Loader::new(CultBatcher),
        }
    }
}

struct Query;

#[async_graphql::Object]
impl Query {
    #[field]
    async fn persons(&self, _ctx: &Context<'_>) -> Vec<Person> {
        let persons = fake::vec![Person; 10..20];
        persons
    }

    #[field]
    async fn cult(&self, ctx: &Context<'_>, id: i32) -> Cult {
        ctx.data::<AppContext>()
            .cult_loader
            .load(id)
            .await
            .expect("get cult")
    }
}

#[derive(Debug, Clone, Dummy)]
pub struct Person {
    #[dummy(faker = "1..999")]
    pub id: i32,
    #[dummy(faker = "Name()")]
    pub name: String,
    #[dummy(faker = "1..999")]
    pub cult: i32,
}

#[async_graphql::Object]
impl Person {
    #[field]
    async fn id(&self) -> i32 {
        self.id
    }

    #[field]
    async fn name(&self) -> &str {
        self.name.as_str()
    }

    #[field]
    async fn cult(&self, ctx: &Context<'_>) -> Cult {
        let fut = ctx.data::<AppContext>().cult_loader.load(self.cult);
        fut.await.expect("get cult")
    }

    #[field]
    async fn cult_by_id(&self, ctx: &Context<'_>, id: i32) -> Cult {
        ctx.data::<AppContext>()
            .cult_loader
            .load(id)
            .await
            .expect("get cult")
    }
}

#[derive(Debug, Clone, Dummy)]
pub struct Cult {
    #[dummy(faker = "1..999")]
    pub id: i32,
    #[dummy(faker = "CompanyName()")]
    pub name: String,
}

#[async_graphql::Object]
impl Cult {
    #[field]
    async fn id(&self) -> i32 {
        self.id
    }

    #[field]
    async fn name(&self) -> &str {
        self.name.as_str()
    }
}

fn main() {
    let schema = Schema::new(Query, EmptyMutation, EmptySubscription).data(AppContext::new());
    let q = r#"
        query {
            c1: cult(id: 1) {
              id
              name
            }
            c2: cult(id: 2) {
              id
              name
            }
            c3: cult(id: 3) {
              id
              name
            }
            persons {
              id
              name
              cult {
                id
                name
              }
              c1: cultById(id: 4) {
                id
                name
              }
              c2: cultById(id: 5) {
                id
                name
              }
              c3: cultById(id: 6) {
                id
                name
              }
            }
        }"#;
    let f = schema.query(&q).execute();
    let _r = block_on(f).unwrap();
}
<commit_msg>Update async-graphql example<commit_after>use async_graphql::{Context, EmptyMutation, EmptySubscription, Schema};
use async_trait::async_trait;
use dataloader::cached::Loader;
use dataloader::BatchFn;
use fake::faker::company::en::CompanyName;
use fake::faker::name::en::Name;
use fake::{Dummy, Fake, Faker};
use futures::executor::block_on;
use std::collections::HashMap;

pub struct CultBatcher;

#[async_trait]
impl BatchFn<i32, Cult> for CultBatcher {
    type Error = ();

    async fn load(&self, keys: &[i32]) -> HashMap<i32, Result<Cult, Self::Error>> {
        println!("load cult by batch {:?}", keys);
        let ret = keys
            .iter()
            .map(|k| {
                let mut cult: Cult = Faker.fake();
                cult.id = k.clone();
                (k.clone(), Ok(cult))
            })
            .collect();
        ret
    }
}

#[derive(Clone)]
pub struct AppContext {
    cult_loader: Loader<i32, Cult, (), CultBatcher>,
}

impl AppContext {
    pub fn new() -> AppContext {
        AppContext {
            cult_loader: Loader::new(CultBatcher),
        }
    }
}

struct Query;

#[async_graphql::Object]
impl Query {
    #[field]
    async fn persons(&self, _ctx: &Context<'_>) -> Vec<Person> {
        let persons = fake::vec![Person; 10..20];
        persons
    }

    #[field]
    async fn cult(&self, ctx: &Context<'_>, id: i32) -> Cult {
        ctx.data::<AppContext>()
            .cult_loader
            .load(id)
            .await
            .expect("get cult")
    }
}

#[derive(Debug, Clone, Dummy)]
pub struct Person {
    #[dummy(faker = "1..999")]
    pub id: i32,
    #[dummy(faker = "Name()")]
    pub name: String,
    #[dummy(faker = "1..999")]
    pub cult: i32,
}

#[async_graphql::Object]
impl Person {
    #[field]
    async fn id(&self) -> i32 {
        self.id
    }

    #[field]
    async fn name(&self) -> &str {
        self.name.as_str()
    }

    #[field]
    async fn cult(&self, ctx: &Context<'_>) -> Cult {
        let fut = ctx.data::<AppContext>().cult_loader.load(self.cult);
        fut.await.expect("get cult")
    }

    #[field]
    async fn cult_by_id(&self, ctx: &Context<'_>, id: i32) -> Cult {
        ctx.data::<AppContext>()
            .cult_loader
            .load(id)
            .await
            .expect("get cult")
    }
}

#[derive(Debug, Clone, Dummy)]
pub struct Cult {
    #[dummy(faker = "1..999")]
    pub id: i32,
    #[dummy(faker = "CompanyName()")]
    pub name: String,
}

#[async_graphql::Object]
impl Cult {
    #[field]
    async fn id(&self) -> i32 {
        self.id
    }

    #[field]
    async fn name(&self) -> &str {
        self.name.as_str()
    }
}

fn main() {
    let schema = Schema::build(Query, EmptyMutation, EmptySubscription)
        .data(AppContext::new())
        .finish();
    let q = r#"
        query {
            c1: cult(id: 1) {
              id
              name
            }
            c2: cult(id: 2) {
              id
              name
            }
            c3: cult(id: 3) {
              id
              name
            }
            persons {
              id
              name
              cult {
                id
                name
              }
              c1: cultById(id: 4) {
                id
                name
              }
              c2: cultById(id: 5) {
                id
                name
              }
              c3: cultById(id: 6) {
                id
                name
              }
            }
        }"#;
    let f = schema.query(&q).execute();
    let _r = block_on(f).unwrap();
}
<|endoftext|>


<commit_before>use criterion::{criterion_group, criterion_main, Criterion};
use futures::channel::oneshot;
use futures::executor;
use std::sync::Arc;
use std::time::Instant;
use tokio::runtime::Runtime;
use tokio_postgres::{Client, NoTls};

fn setup() -> (Client, Runtime) {
    let runtime = Runtime::new().unwrap();
    let (client, conn) = runtime
        .block_on(tokio_postgres::connect(
            "host=localhost port=5433 user=postgres",
            NoTls,
        ))
        .unwrap();
    runtime.spawn(async { conn.await.unwrap() });
    (client, runtime)
}

fn query_prepared(c: &mut Criterion) {
    let (client, runtime) = setup();
    let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap();
    c.bench_function("runtime_block_on", move |b| {
        b.iter(|| {
            runtime
                .block_on(client.query(&statement, &[&1i64]))
                .unwrap()
        })
    });

    let (client, runtime) = setup();
    let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap();
    c.bench_function("executor_block_on", move |b| {
        b.iter(|| executor::block_on(client.query(&statement, &[&1i64])).unwrap())
    });

    let (client, runtime) = setup();
    let client = Arc::new(client);
    let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap();
    c.bench_function("spawned", move |b| {
        b.iter_custom(|iters| {
            let (tx, rx) = oneshot::channel();
            let client = client.clone();
            let statement = statement.clone();
            runtime.spawn(async move {
                let start = Instant::now();
                for _ in 0..iters {
                    client.query(&statement, &[&1i64]).await.unwrap();
                }
                tx.send(start.elapsed()).unwrap();
            });
            executor::block_on(rx).unwrap()
        })
    });
}

criterion_group!(benches, query_prepared);
criterion_main!(benches);
<commit_msg>Fix up benchmark<commit_after>use criterion::{criterion_group, criterion_main, Criterion};
use futures::channel::oneshot;
use futures::executor;
use std::sync::Arc;
use std::time::Instant;
use tokio::runtime::Runtime;
use tokio_postgres::{Client, NoTls};

fn setup() -> (Client, Runtime) {
    let mut runtime = Runtime::new().unwrap();
    let (client, conn) = runtime
        .block_on(tokio_postgres::connect(
            "host=localhost port=5433 user=postgres",
            NoTls,
        ))
        .unwrap();
    runtime.spawn(async { conn.await.unwrap() });
    (client, runtime)
}

fn query_prepared(c: &mut Criterion) {
    let (client, mut runtime) = setup();
    let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap();
    c.bench_function("runtime_block_on", move |b| {
        b.iter(|| {
            runtime
                .block_on(client.query(&statement, &[&1i64]))
                .unwrap()
        })
    });

    let (client, mut runtime) = setup();
    let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap();
    c.bench_function("executor_block_on", move |b| {
        b.iter(|| executor::block_on(client.query(&statement, &[&1i64])).unwrap())
    });

    let (client, mut runtime) = setup();
    let client = Arc::new(client);
    let statement = runtime.block_on(client.prepare("SELECT $1::INT8")).unwrap();
    c.bench_function("spawned", move |b| {
        b.iter_custom(|iters| {
            let (tx, rx) = oneshot::channel();
            let client = client.clone();
            let statement = statement.clone();
            runtime.spawn(async move {
                let start = Instant::now();
                for _ in 0..iters {
                    client.query(&statement, &[&1i64]).await.unwrap();
                }
                tx.send(start.elapsed()).unwrap();
            });
            executor::block_on(rx).unwrap()
        })
    });
}

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


<commit_before>// Copyright 2014-2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Rank/Select data structure based on Gonzalez, Grabowski, Mäkinen, Navarro (2005).
//! This implementation uses only a single level of blocks, and performs well for large n.
//!
//! Example
//!
//! ```
//! extern crate bv;
//! # extern crate bio;
//! # fn main() {
//! use bio::data_structures::rank_select::RankSelect;
//! use bv::BitVec;
//! use bv::BitsMut;
//!
//! let mut bits: BitVec<u8> = BitVec::new_fill(false, 64);
//! bits.set_bit(5, true);
//! bits.set_bit(32, true);
//! let rs = RankSelect::new(bits, 1);
//! assert!(rs.rank(6).unwrap() == 1);
//! # }
//! ```

use std::cmp;

use bv::BitVec;
use bv::Bits;

/// A rank/select data structure.
#[derive(Serialize, Deserialize)]
pub struct RankSelect {
    n: usize,
    bits: BitVec<u8>,
    superblocks_1: Vec<u64>,
    superblocks_0: Vec<u64>,
    s: usize,
    k: usize,
}

impl RankSelect {
    /// Create a new instance.
    ///
    /// # Arguments
    ///
    /// * `bits` - A bit vector.
    /// * `k` - Determines the size (k * 32 bits) of the superblocks.
    ///   A small k means faster rank query times at the expense of using more
    ///   space and slower select query times.
    ///   The data structure needs O(n + n log n / (k * 32)) bits with n being the bits of the given bitvector.
    ///   The data structure is succinct if k is chosen as a sublinear function of n
    ///   (e.g. k = (log n)² / 32).
    pub fn new(bits: BitVec<u8>, k: usize) -> RankSelect {
        let n = bits.len() as usize;
        let s = k * 32;

        RankSelect {
            n,
            s,
            k,
            superblocks_1: superblocks(true, n, s, &bits),
            superblocks_0: superblocks(false, n, s, &bits),
            bits,
        }
    }

    /// Return the used k (see `RankSelect::new()`).
    pub fn k(&self) -> usize {
        self.k
    }

    /// Get internal representation of bit vector.
    pub fn bits(&self) -> &BitVec<u8> {
        &self.bits
    }

    /// Return i-th bit.
    pub fn get(&self, i: u64) -> bool {
        self.bits.get_bit(i)
    }

    /// Get the 1-rank of a given bit, i.e. the number of 1-bits in the bitvector up to i (inclusive).
    /// Complexity: O(k).
    ///
    /// # Arguments
    ///
    /// * `i` - Position of the bit to determine the rank for.
    pub fn rank_1(&self, i: u64) -> Option<u64> {
        if i >= self.n as u64 {
            None
        } else {
            let s = i / self.s as u64; // the superblock
            let b = i / 8; // the block
            let j = i % 8; // the bit in the block
                           // take the superblock rank
            let mut rank = self.superblocks_1[s as usize];
            // add the rank within the block
            let mask = ((2u16 << j) - 1) as u8;
            rank += (self.bits.get_block(b as usize) & mask).count_ones() as u64;
            // add the popcounts of blocks in between
            for block in s * 32 / 8..b {
                let b = self.bits.get_block(block as usize);
                rank += b.count_ones() as u64;
            }

            Some(rank)
        }
    }

    /// Get the 0-rank of a given bit, i.e. the number of 0-bits in the bitvector up to i (inclusive).
    /// Complexity: O(k).
    ///
    /// # Arguments
    ///
    /// * `i` - Position of the bit to determine the rank for.
    pub fn rank_0(&self, i: u64) -> Option<u64> {
        self.rank_1(i).map(|r| (i + 1) - r)
    }

    /// Alias for `RankSelect::rank_1`.
    pub fn rank(&self, i: u64) -> Option<u64> {
        self.rank_1(i)
    }

    /// Get the smallest bit with a given 1-rank.
    /// Complexity: O(log (n / k) + k).
    ///
    /// # Arguments
    ///
    /// * `j` - The rank to find the smallest bit for.
    pub fn select_1(&self, j: u64) -> Option<u64> {
        self.select_x(
            j,
            &self.superblocks_1,
            |bit| bit != 0,
            |block| block.count_ones(),
        )
    }

    /// Get the smallest bit with a given 0-rank.
    /// Complexity: O(log (n / k) + k).
    ///
    /// # Arguments
    ///
    /// * `j` - The rank to find the smallest bit for.
    pub fn select_0(&self, j: u64) -> Option<u64> {
        self.select_x(
            j,
            &self.superblocks_0,
            |bit| bit == 0,
            |block| block.count_zeros(),
        )
    }

    fn select_x<F: Fn(u8) -> bool, C: Fn(u8) -> u32>(
        &self,
        j: u64,
        superblocks: &[u64],
        is_match: F,
        count_all: C,
    ) -> Option<u64> {
        let mut superblock = match superblocks.binary_search(&j) {
            Ok(i) | Err(i) => i, // superblock with same rank exists
        };
        if superblock > 0 {
            superblock -= 1;
        }
        let mut rank = superblocks[superblock];

        let first_block = superblock * self.s / 8;
        for block in first_block..cmp::min(first_block + self.s / 8, self.bits.block_len()) {
            let b = self.bits.get_block(block);
            let p = count_all(b) as u64;
            if rank + p >= j {
                let mut bit = 0b1;
                // do not look at unused bits of the last block
                let max_bit = cmp::min(8, self.bits.len() - block as u64 * 8);
                for i in 0..max_bit {
                    rank += is_match(b & bit) as u64;
                    if rank == j {
                        return Some((first_block + block) as u64 * 8 + i);
                    }
                    bit <<= 1;
                }
            }
            rank += p;
        }

        None
    }

    /// Alias for `RankSelect::select_1`.
    pub fn select(&self, j: u64) -> Option<u64> {
        self.select_1(j)
    }
}

/// Create `n` superblocks of size `s` from a given bitvector.
fn superblocks(t: bool, n: usize, s: usize, bits: &BitVec<u8>) -> Vec<u64> {
    let mut superblocks = Vec::with_capacity(n / s + 1);
    let mut rank: u64 = 0;
    let mut i = 0;
    let nblocks = (bits.len() as f64 / 8.0).ceil() as usize;
    for block in 0..nblocks {
        let b = bits.get_block(block);
        if i % s == 0 {
            superblocks.push(rank);
        }
        rank += if t {
            b.count_ones() as u64
        } else {
            b.count_zeros() as u64
        };
        i += 8;
    }

    superblocks
}

#[cfg(test)]
mod tests {
    use super::*;
    use bv::bit_vec;
    use bv::BitVec;
    use bv::BitsMut;

    #[test]
    fn test_rank_select() {
        let mut bits: BitVec<u8> = BitVec::new_fill(false, 64);
        bits.set_bit(5, true);
        bits.set_bit(32, true);
        let rs = RankSelect::new(bits, 1);
        assert_eq!(rs.rank_1(1).unwrap(), 0);
        assert_eq!(rs.rank_1(5).unwrap(), 1);
        assert_eq!(rs.rank_1(6).unwrap(), 1);
        assert_eq!(rs.rank_1(7).unwrap(), 1);
        assert_eq!(rs.rank_1(32).unwrap(), 2);
        assert_eq!(rs.rank_1(33).unwrap(), 2);
        assert_eq!(rs.rank_1(64), None);
        assert_eq!(rs.select_1(0).unwrap(), 0);
        assert_eq!(rs.select_1(1).unwrap(), 5);
        assert_eq!(rs.rank_0(1).unwrap(), 2);
        assert_eq!(rs.rank_0(4).unwrap(), 5);
        assert_eq!(rs.rank_0(5).unwrap(), 5);
        assert_eq!(rs.select_0(0), None);
        assert_eq!(rs.select_0(1).unwrap(), 0);
        assert_eq!(rs.get(5), true);
        assert_eq!(rs.get(1), false);
        assert_eq!(rs.get(32), true);
    }

    #[test]
    fn test_select() {
        let bits: BitVec<u8> = bit_vec![true, false];
        let rs = RankSelect::new(bits, 1);

        assert_eq!(rs.select_0(0), Some(0));
        assert_eq!(rs.select_1(0), None);

        assert_eq!(rs.select_0(1), Some(1));
        assert_eq!(rs.select_1(1), Some(0));

        assert_eq!(rs.select_0(2), None);
        assert_eq!(rs.select_1(2), None);
    }

    #[test]
    fn test_single_select() {
        let bits: BitVec<u8> = bit_vec![true];
        let rs = RankSelect::new(bits, 1);
        assert_eq!(rs.select_1(0), None);
        assert_eq!(rs.select_1(1), Some(0));
        assert_eq!(rs.select_0(0), Some(0));
        assert_eq!(rs.select_0(1), None);

        let bits: BitVec<u8> = bit_vec![false];
        let rs = RankSelect::new(bits, 1);
        assert_eq!(rs.select_1(1), None);
        assert_eq!(rs.select_1(0), Some(0));
        assert_eq!(rs.select_0(0), None);
        assert_eq!(rs.select_0(1), Some(0));
        assert_eq!(rs.rank_0(0), Some(1));
        assert_eq!(rs.rank_1(0), Some(0));
    }
}
<commit_msg>fix rank (#219)<commit_after>// Copyright 2014-2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Rank/Select data structure based on Gonzalez, Grabowski, Mäkinen, Navarro (2005).
//! This implementation uses only a single level of blocks, and performs well for large n.
//!
//! Example
//!
//! ```
//! extern crate bv;
//! # extern crate bio;
//! # fn main() {
//! use bio::data_structures::rank_select::RankSelect;
//! use bv::BitVec;
//! use bv::BitsMut;
//!
//! let mut bits: BitVec<u8> = BitVec::new_fill(false, 64);
//! bits.set_bit(5, true);
//! bits.set_bit(32, true);
//! let rs = RankSelect::new(bits, 1);
//! assert!(rs.rank(6).unwrap() == 1);
//! # }
//! ```

use std::cmp;

use bv::BitVec;
use bv::Bits;

/// A rank/select data structure.
#[derive(Serialize, Deserialize)]
pub struct RankSelect {
    n: usize,
    bits: BitVec<u8>,
    superblocks_1: Vec<u64>,
    superblocks_0: Vec<u64>,
    s: usize,
    k: usize,
}

impl RankSelect {
    /// Create a new instance.
    ///
    /// # Arguments
    ///
    /// * `bits` - A bit vector.
    /// * `k` - Determines the size (k * 32 bits) of the superblocks.
    ///   A small k means faster rank query times at the expense of using more
    ///   space and slower select query times.
    ///   The data structure needs O(n + n log n / (k * 32)) bits with n being the bits of the given bitvector.
    ///   The data structure is succinct if k is chosen as a sublinear function of n
    ///   (e.g. k = (log n)² / 32).
    pub fn new(bits: BitVec<u8>, k: usize) -> RankSelect {
        let n = bits.len() as usize;
        let s = k * 32;

        RankSelect {
            n,
            s,
            k,
            superblocks_1: superblocks(true, n, s, &bits),
            superblocks_0: superblocks(false, n, s, &bits),
            bits,
        }
    }

    /// Return the used k (see `RankSelect::new()`).
    pub fn k(&self) -> usize {
        self.k
    }

    /// Get internal representation of bit vector.
    pub fn bits(&self) -> &BitVec<u8> {
        &self.bits
    }

    /// Return i-th bit.
    pub fn get(&self, i: u64) -> bool {
        self.bits.get_bit(i)
    }

    /// Get the 1-rank of a given bit, i.e. the number of 1-bits in the bitvector up to i (inclusive).
    /// Complexity: O(k).
    ///
    /// # Arguments
    ///
    /// * `i` - Position of the bit to determine the rank for.
    pub fn rank_1(&self, i: u64) -> Option<u64> {
        if i >= self.n as u64 {
            None
        } else {
            let s = i / self.s as u64; // the superblock
            let b = i / 8; // the block
            let j = i % 8; // the bit in the block
                           // take the superblock rank
            let mut rank = self.superblocks_1[s as usize];
            // add the rank within the block
            let mask = ((2u16 << j) - 1) as u8;
            rank += (self.bits.get_block(b as usize) & mask).count_ones() as u64;
            // add the popcounts of blocks from the beginning of the current superblock
            // up to the current block
            for block in (s * self.s as u64 / 8)..b {
                let b = self.bits.get_block(block as usize);
                rank += b.count_ones() as u64;
            }

            Some(rank)
        }
    }

    /// Get the 0-rank of a given bit, i.e. the number of 0-bits in the bitvector up to i (inclusive).
    /// Complexity: O(k).
    ///
    /// # Arguments
    ///
    /// * `i` - Position of the bit to determine the rank for.
    pub fn rank_0(&self, i: u64) -> Option<u64> {
        self.rank_1(i).map(|r| (i + 1) - r)
    }

    /// Alias for `RankSelect::rank_1`.
    pub fn rank(&self, i: u64) -> Option<u64> {
        self.rank_1(i)
    }

    /// Get the smallest bit with a given 1-rank.
    /// Complexity: O(log (n / k) + k).
    ///
    /// # Arguments
    ///
    /// * `j` - The rank to find the smallest bit for.
    pub fn select_1(&self, j: u64) -> Option<u64> {
        self.select_x(
            j,
            &self.superblocks_1,
            |bit| bit != 0,
            |block| block.count_ones(),
        )
    }

    /// Get the smallest bit with a given 0-rank.
    /// Complexity: O(log (n / k) + k).
    ///
    /// # Arguments
    ///
    /// * `j` - The rank to find the smallest bit for.
    pub fn select_0(&self, j: u64) -> Option<u64> {
        self.select_x(
            j,
            &self.superblocks_0,
            |bit| bit == 0,
            |block| block.count_zeros(),
        )
    }

    fn select_x<F: Fn(u8) -> bool, C: Fn(u8) -> u32>(
        &self,
        j: u64,
        superblocks: &[u64],
        is_match: F,
        count_all: C,
    ) -> Option<u64> {
        let mut superblock = match superblocks.binary_search(&j) {
            Ok(i) | Err(i) => i, // superblock with same rank exists
        };
        if superblock > 0 {
            superblock -= 1;
        }
        let mut rank = superblocks[superblock];

        let first_block = superblock * self.s / 8;
        for block in first_block..cmp::min(first_block + self.s / 8, self.bits.block_len()) {
            let b = self.bits.get_block(block);
            let p = count_all(b) as u64;
            if rank + p >= j {
                let mut bit = 0b1;
                // do not look at unused bits of the last block
                let max_bit = cmp::min(8, self.bits.len() - block as u64 * 8);
                for i in 0..max_bit {
                    rank += is_match(b & bit) as u64;
                    if rank == j {
                        return Some((first_block + block) as u64 * 8 + i);
                    }
                    bit <<= 1;
                }
            }
            rank += p;
        }

        None
    }

    /// Alias for `RankSelect::select_1`.
    pub fn select(&self, j: u64) -> Option<u64> {
        self.select_1(j)
    }
}

/// Create `n` superblocks of size `s` from a given bitvector.
fn superblocks(t: bool, n: usize, s: usize, bits: &BitVec<u8>) -> Vec<u64> {
    let mut superblocks = Vec::with_capacity(n / s + 1);
    let mut rank: u64 = 0;
    let mut i = 0;
    let nblocks = (bits.len() as f64 / 8.0).ceil() as usize;
    for block in 0..nblocks {
        let b = bits.get_block(block);
        if i % s == 0 {
            superblocks.push(rank);
        }
        rank += if t {
            b.count_ones() as u64
        } else {
            b.count_zeros() as u64
        };
        i += 8;
    }

    superblocks
}

#[cfg(test)]
mod tests {
    use super::*;
    use bv::bit_vec;
    use bv::BitVec;
    use bv::BitsMut;

    #[test]
    fn test_rank_select() {
        let mut bits: BitVec<u8> = BitVec::new_fill(false, 64);
        bits.set_bit(5, true);
        bits.set_bit(32, true);
        let rs = RankSelect::new(bits, 1);
        assert_eq!(rs.rank_1(1).unwrap(), 0);
        assert_eq!(rs.rank_1(5).unwrap(), 1);
        assert_eq!(rs.rank_1(6).unwrap(), 1);
        assert_eq!(rs.rank_1(7).unwrap(), 1);
        assert_eq!(rs.rank_1(32).unwrap(), 2);
        assert_eq!(rs.rank_1(33).unwrap(), 2);
        assert_eq!(rs.rank_1(64), None);
        assert_eq!(rs.select_1(0).unwrap(), 0);
        assert_eq!(rs.select_1(1).unwrap(), 5);
        assert_eq!(rs.rank_0(1).unwrap(), 2);
        assert_eq!(rs.rank_0(4).unwrap(), 5);
        assert_eq!(rs.rank_0(5).unwrap(), 5);
        assert_eq!(rs.select_0(0), None);
        assert_eq!(rs.select_0(1).unwrap(), 0);
        assert_eq!(rs.get(5), true);
        assert_eq!(rs.get(1), false);
        assert_eq!(rs.get(32), true);
    }

    #[test]
    fn test_select() {
        let bits: BitVec<u8> = bit_vec![true, false];
        let rs = RankSelect::new(bits, 1);

        assert_eq!(rs.select_0(0), Some(0));
        assert_eq!(rs.select_1(0), None);

        assert_eq!(rs.select_0(1), Some(1));
        assert_eq!(rs.select_1(1), Some(0));

        assert_eq!(rs.select_0(2), None);
        assert_eq!(rs.select_1(2), None);
    }

    #[test]
    fn test_single_select() {
        let bits: BitVec<u8> = bit_vec![true];
        let rs = RankSelect::new(bits, 1);
        assert_eq!(rs.select_1(0), None);
        assert_eq!(rs.select_1(1), Some(0));
        assert_eq!(rs.select_0(0), Some(0));
        assert_eq!(rs.select_0(1), None);

        let bits: BitVec<u8> = bit_vec![false];
        let rs = RankSelect::new(bits, 1);
        assert_eq!(rs.select_1(1), None);
        assert_eq!(rs.select_1(0), Some(0));
        assert_eq!(rs.select_0(0), None);
        assert_eq!(rs.select_0(1), Some(0));
        assert_eq!(rs.rank_0(0), Some(1));
        assert_eq!(rs.rank_1(0), Some(0));
    }

    #[test]
    fn test_rank_k() {
        let mut bits: BitVec<u8> = BitVec::new_fill(false, 72);
        bits.set_bit(63, true);
        let rs = RankSelect::new(bits, 2);
        assert_eq!(rs.rank_1(63), Some(1));
        assert_eq!(rs.rank_1(64), Some(1));
        assert_eq!(rs.rank_1(71), Some(1));
    }
}
<|endoftext|>


<commit_before>use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;
use std::clone::Clone;

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum RuntimeErrorKind {
    Instantiate,

    // more?
}

#[derive(Debug)]
pub struct RuntimeError {
    kind: RuntimeErrorKind,
    cause: Option<Box<Error>>,
}

impl RuntimeError {

    pub fn new(kind: RuntimeErrorKind, cause: Option<Box<Error>>) -> RuntimeError {
        RuntimeError {
            kind: kind,
            cause: cause,
        }
    }

}

fn runtime_error_kind_as_str(e: &RuntimeErrorKind) -> &'static str {
    match e {
        &RuntimeErrorKind::Instantiate => "Could not instantiate",
    }
}

impl Display for RuntimeError {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        try!(write!(fmt, "{}", runtime_error_kind_as_str(&self.kind)));
        Ok(())
    }

}

impl Error for RuntimeError {

    fn description(&self) -> &str {
        runtime_error_kind_as_str(&self.kind)
    }

    fn cause(&self) -> Option<&Error> {
        self.cause.as_ref().map(|e| &**e)
    }

}

<commit_msg>rt/error: Remove unused imports<commit_after>use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum RuntimeErrorKind {
    Instantiate,

    // more?
}

#[derive(Debug)]
pub struct RuntimeError {
    kind: RuntimeErrorKind,
    cause: Option<Box<Error>>,
}

impl RuntimeError {

    pub fn new(kind: RuntimeErrorKind, cause: Option<Box<Error>>) -> RuntimeError {
        RuntimeError {
            kind: kind,
            cause: cause,
        }
    }

}

fn runtime_error_kind_as_str(e: &RuntimeErrorKind) -> &'static str {
    match e {
        &RuntimeErrorKind::Instantiate => "Could not instantiate",
    }
}

impl Display for RuntimeError {

    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
        try!(write!(fmt, "{}", runtime_error_kind_as_str(&self.kind)));
        Ok(())
    }

}

impl Error for RuntimeError {

    fn description(&self) -> &str {
        runtime_error_kind_as_str(&self.kind)
    }

    fn cause(&self) -> Option<&Error> {
        self.cause.as_ref().map(|e| &**e)
    }

}

<|endoftext|>


<commit_before>extern crate libc;

pub mod anoncreds;
pub mod crypto;
pub mod ledger;
pub mod pairwise;
pub mod pool;
pub mod did;
pub mod wallet;
pub mod blob_storage;
pub mod payments;

#[derive(Debug, PartialEq, Copy, Clone)]
#[repr(i32)]
pub enum ErrorCode
{
    Success = 0,

    // Common errors

    // Caller passed invalid value as param 1 (null, invalid json and etc..)
    CommonInvalidParam1 = 100,

    // Caller passed invalid value as param 2 (null, invalid json and etc..)
    CommonInvalidParam2 = 101,

    // Caller passed invalid value as param 3 (null, invalid json and etc..)
    CommonInvalidParam3 = 102,

    // Caller passed invalid value as param 4 (null, invalid json and etc..)
    CommonInvalidParam4 = 103,

    // Caller passed invalid value as param 5 (null, invalid json and etc..)
    CommonInvalidParam5 = 104,

    // Caller passed invalid value as param 6 (null, invalid json and etc..)
    CommonInvalidParam6 = 105,

    // Caller passed invalid value as param 7 (null, invalid json and etc..)
    CommonInvalidParam7 = 106,

    // Caller passed invalid value as param 8 (null, invalid json and etc..)
    CommonInvalidParam8 = 107,

    // Caller passed invalid value as param 9 (null, invalid json and etc..)
    CommonInvalidParam9 = 108,

    // Caller passed invalid value as param 10 (null, invalid json and etc..)
    CommonInvalidParam10 = 109,

    // Caller passed invalid value as param 11 (null, invalid json and etc..)
    CommonInvalidParam11 = 110,

    // Caller passed invalid value as param 12 (null, invalid json and etc..)
    CommonInvalidParam12 = 111,

    // Invalid library state was detected in runtime. It signals library bug
    CommonInvalidState = 112,

    // Object (json, config, key, credential and etc...) passed by library caller has invalid structure
    CommonInvalidStructure = 113,

    // IO Error
    CommonIOError = 114,

    // Caller passed invalid value as param 13 (null, invalid json and etc..)
    CommonInvalidParam13 = 115,

    // Caller passed invalid value as param 14 (null, invalid json and etc..)
    CommonInvalidParam14 = 116,

    // Wallet errors
    // Caller passed invalid wallet handle
    WalletInvalidHandle = 200,

    // Unknown type of wallet was passed on create_wallet
    WalletUnknownTypeError = 201,

    // Attempt to register already existing wallet type
    WalletTypeAlreadyRegisteredError = 202,

    // Attempt to create wallet with name used for another exists wallet
    WalletAlreadyExistsError = 203,

    // Requested entity id isn't present in wallet
    WalletNotFoundError = 204,

    // Trying to use wallet with pool that has different name
    WalletIncompatiblePoolError = 205,

    // Trying to open wallet that was opened already
    WalletAlreadyOpenedError = 206,

    // Attempt to open encrypted wallet with invalid credentials
    WalletAccessFailed = 207,

    // Ledger errors
    // Trying to open pool ledger that wasn't created before
    PoolLedgerNotCreatedError = 300,

    // Caller passed invalid pool ledger handle
    PoolLedgerInvalidPoolHandle = 301,

    // Pool ledger terminated
    PoolLedgerTerminated = 302,

    // No concensus during ledger operation
    LedgerNoConsensusError = 303,

    // Attempt to parse invalid transaction response
    LedgerInvalidTransaction = 304,

    // Attempt to send transaction without the necessary privileges
    LedgerSecurityError = 305,

    // Attempt to create pool ledger config with name used for another existing pool
    PoolLedgerConfigAlreadyExistsError = 306,

    // Timeout for action
    PoolLedgerTimeout = 307,

    // Revocation registry is full and creation of new registry is necessary
    AnoncredsRevocationRegistryFullError = 400,

    AnoncredsInvalidUserRevocId = 401,

    // Attempt to generate master secret with duplicated name
    AnoncredsMasterSecretDuplicateNameError = 404,

    AnoncredsProofRejected = 405,

    AnoncredsCredentialRevoked = 406,

    // Attempt to create credential definition with duplicated id
    AnoncredsCredDefAlreadyExistsError = 407,

    // Crypto errors
    // Unknown format of DID entity keys
    UnknownCryptoTypeError = 500,

    // Attempt to create duplicate did
    DidAlreadyExistsError = 600,

    // Unknown payment method was given
    PaymentUnknownMethodError = 700,

    //No method were scraped from inputs/outputs or more than one were scraped
    PaymentIncompatibleMethodsError = 701,

    //Insufficient funds on inputs
    PaymentInsufficientFundsError = 703,
}
<commit_msg>Add whitespace before comment<commit_after>extern crate libc;

pub mod anoncreds;
pub mod crypto;
pub mod ledger;
pub mod pairwise;
pub mod pool;
pub mod did;
pub mod wallet;
pub mod blob_storage;
pub mod payments;

#[derive(Debug, PartialEq, Copy, Clone)]
#[repr(i32)]
pub enum ErrorCode
{
    Success = 0,

    // Common errors

    // Caller passed invalid value as param 1 (null, invalid json and etc..)
    CommonInvalidParam1 = 100,

    // Caller passed invalid value as param 2 (null, invalid json and etc..)
    CommonInvalidParam2 = 101,

    // Caller passed invalid value as param 3 (null, invalid json and etc..)
    CommonInvalidParam3 = 102,

    // Caller passed invalid value as param 4 (null, invalid json and etc..)
    CommonInvalidParam4 = 103,

    // Caller passed invalid value as param 5 (null, invalid json and etc..)
    CommonInvalidParam5 = 104,

    // Caller passed invalid value as param 6 (null, invalid json and etc..)
    CommonInvalidParam6 = 105,

    // Caller passed invalid value as param 7 (null, invalid json and etc..)
    CommonInvalidParam7 = 106,

    // Caller passed invalid value as param 8 (null, invalid json and etc..)
    CommonInvalidParam8 = 107,

    // Caller passed invalid value as param 9 (null, invalid json and etc..)
    CommonInvalidParam9 = 108,

    // Caller passed invalid value as param 10 (null, invalid json and etc..)
    CommonInvalidParam10 = 109,

    // Caller passed invalid value as param 11 (null, invalid json and etc..)
    CommonInvalidParam11 = 110,

    // Caller passed invalid value as param 12 (null, invalid json and etc..)
    CommonInvalidParam12 = 111,

    // Invalid library state was detected in runtime. It signals library bug
    CommonInvalidState = 112,

    // Object (json, config, key, credential and etc...) passed by library caller has invalid structure
    CommonInvalidStructure = 113,

    // IO Error
    CommonIOError = 114,

    // Caller passed invalid value as param 13 (null, invalid json and etc..)
    CommonInvalidParam13 = 115,

    // Caller passed invalid value as param 14 (null, invalid json and etc..)
    CommonInvalidParam14 = 116,

    // Wallet errors
    // Caller passed invalid wallet handle
    WalletInvalidHandle = 200,

    // Unknown type of wallet was passed on create_wallet
    WalletUnknownTypeError = 201,

    // Attempt to register already existing wallet type
    WalletTypeAlreadyRegisteredError = 202,

    // Attempt to create wallet with name used for another exists wallet
    WalletAlreadyExistsError = 203,

    // Requested entity id isn't present in wallet
    WalletNotFoundError = 204,

    // Trying to use wallet with pool that has different name
    WalletIncompatiblePoolError = 205,

    // Trying to open wallet that was opened already
    WalletAlreadyOpenedError = 206,

    // Attempt to open encrypted wallet with invalid credentials
    WalletAccessFailed = 207,

    // Ledger errors
    // Trying to open pool ledger that wasn't created before
    PoolLedgerNotCreatedError = 300,

    // Caller passed invalid pool ledger handle
    PoolLedgerInvalidPoolHandle = 301,

    // Pool ledger terminated
    PoolLedgerTerminated = 302,

    // No concensus during ledger operation
    LedgerNoConsensusError = 303,

    // Attempt to parse invalid transaction response
    LedgerInvalidTransaction = 304,

    // Attempt to send transaction without the necessary privileges
    LedgerSecurityError = 305,

    // Attempt to create pool ledger config with name used for another existing pool
    PoolLedgerConfigAlreadyExistsError = 306,

    // Timeout for action
    PoolLedgerTimeout = 307,

    // Revocation registry is full and creation of new registry is necessary
    AnoncredsRevocationRegistryFullError = 400,

    AnoncredsInvalidUserRevocId = 401,

    // Attempt to generate master secret with duplicated name
    AnoncredsMasterSecretDuplicateNameError = 404,

    AnoncredsProofRejected = 405,

    AnoncredsCredentialRevoked = 406,

    // Attempt to create credential definition with duplicated id
    AnoncredsCredDefAlreadyExistsError = 407,

    // Crypto errors
    // Unknown format of DID entity keys
    UnknownCryptoTypeError = 500,

    // Attempt to create duplicate did
    DidAlreadyExistsError = 600,

    // Unknown payment method was given
    PaymentUnknownMethodError = 700,

    //No method were scraped from inputs/outputs or more than one were scraped
    PaymentIncompatibleMethodsError = 701,

    // Insufficient funds on inputs
    PaymentInsufficientFundsError = 702,
}
<|endoftext|>


<commit_before>// "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/lib/mem/aref.rs
//! Atomic reference type (Arc but with weak pointers only)
use prelude::*;
use core::atomic::{AtomicUsize,Ordering};
use core::nonzero::NonZero;
use core::ops;

/// Atomic referencable type. Panics if the type is dropped while any references are active.
/// Internally uses a `Box` to contain an ArefInner
pub struct Aref<T: Sync>
{
	__inner: Box<ArefInner<T>>,
}
/// A borrow of an Aref
pub struct ArefBorrow<T: Sync>
{
	__ptr: NonZero<*const ArefInner<T>>,
}
unsafe impl<T: Sync+Send> Send for ArefBorrow<T> {}

/// Interior of an Aref. Requires that is is not relocated while any borrows are active
pub struct ArefInner<T: Sync>
{
	count: AtomicUsize,
	data: T,
}

impl<T: Sync> Aref<T>
{
	/// Construct a new Aref
	pub fn new(val: T) -> Aref<T> {
		Aref {
			__inner: Box::new(unsafe{ ArefInner::new(val) }),
		}
	}

	/// Borrow the `Aref`
	pub fn borrow(&self) -> ArefBorrow<T> {
		self.__inner.borrow()
	}
}
impl<T: Sync> ops::Deref for Aref<T>
{
	type Target = T;
	fn deref(&self) -> &T {
		&self.__inner.data
	}
}

impl<T: Sync> ArefInner<T>
{
	/// Unsafely create a new interior
	///
	/// You MUST ensure that the inner is not moved out of its memory location while any borrows are active
	pub unsafe fn new(val: T) -> ArefInner<T> {
		ArefInner {
			count: AtomicUsize::new(0),
			data: val,
			}
	}
	/// Borrow the inner
	pub fn borrow(&self) -> ArefBorrow<T> {
		self.count.fetch_add(1, Ordering::Relaxed);
		ArefBorrow {
			// SAFE: Pointers are never 0
			__ptr: unsafe { NonZero::new(self) },
			}
	}
}
impl<T: Sync> ops::Deref for ArefInner<T>
{
	type Target = T;
	fn deref(&self) -> &T {
		&self.data
	}
}
impl<T: Sync> ops::Drop for ArefInner<T>
{
	fn drop(&mut self) {
		assert_eq!(self.count.load(Ordering::Relaxed), 0);
	}
}

impl<T: Sync> ArefBorrow<T>
{
	fn __inner(&self) -> &ArefInner<T> {
		unsafe { &**self.__ptr }
	}
}
impl<T: Sync> ops::Deref for ArefBorrow<T>
{
	type Target = T;
	fn deref(&self) -> &T {
		&self.__inner().data
	}
}
impl<T: Sync> ops::Drop for ArefBorrow<T>
{
	fn drop(&mut self) {
		self.__inner().count.fetch_sub(1, Ordering::Relaxed);
	}
}
<commit_msg>Kernel/lib - More docs on Aref<commit_after>// "Tifflin" Kernel
// - By John Hodge (thePowersGang)
//
// Core/lib/mem/aref.rs
//! Atomic reference type (Arc but with weak pointers only)
//!
//! Provides runtime lifetime checking (similar to how RefCell provides runtime borrow checking)
//!
//! This type is designed to be used where there is a definitive owner of a peice of memory (e.g. a box)
//! but you also want to lend pointers to that memory out (where the pointers should never outlive the
//! original memory).
use prelude::*;
use core::atomic::{AtomicUsize,Ordering};
use core::nonzero::NonZero;
use core::ops;

/// Atomic referencable type. Panics if the type is dropped while any references are active.
/// Internally uses a `Box` to contain an ArefInner
pub struct Aref<T: Sync>
{
	__inner: Box<ArefInner<T>>,
}
/// A borrow of an Aref
pub struct ArefBorrow<T: Sync>
{
	__ptr: NonZero<*const ArefInner<T>>,
}
unsafe impl<T: Sync+Send> Send for ArefBorrow<T> {}

/// Interior of an Aref. Requires that is is not relocated while any borrows are active
pub struct ArefInner<T: Sync>
{
	count: AtomicUsize,
	data: T,
}

impl<T: Sync> Aref<T>
{
	/// Construct a new Aref
	pub fn new(val: T) -> Aref<T> {
		Aref {
			__inner: Box::new(unsafe{ ArefInner::new(val) }),
		}
	}

	/// Borrow the `Aref`
	pub fn borrow(&self) -> ArefBorrow<T> {
		self.__inner.borrow()
	}
}
impl<T: Sync> ops::Deref for Aref<T>
{
	type Target = T;
	fn deref(&self) -> &T {
		&self.__inner.data
	}
}

impl<T: Sync> ArefInner<T>
{
	/// Unsafely create a new interior
	///
	/// You MUST ensure that the inner is not moved out of its memory location while any borrows are active
	pub unsafe fn new(val: T) -> ArefInner<T> {
		&ArefInner {
			count: AtomicUsize::new(0),
			data: val,
			}
	}
	/// Borrow the inner
	pub fn borrow(&self) -> ArefBorrow<T> {
		self.count.fetch_add(1, Ordering::Relaxed);
		ArefBorrow {
			// SAFE: Pointers are never 0
			__ptr: unsafe { NonZero::new(self) },
			}
	}
}
impl<T: Sync> ops::Deref for ArefInner<T>
{
	type Target = T;
	fn deref(&self) -> &T {
		&self.data
	}
}
impl<T: Sync> ops::Drop for ArefInner<T>
{
	fn drop(&mut self) {
		assert_eq!(self.count.load(Ordering::Relaxed), 0);
	}
}

impl<T: Sync> ArefBorrow<T>
{
	fn __inner(&self) -> &ArefInner<T> {
		unsafe { &**self.__ptr }
	}
}
impl<T: Sync> ops::Deref for ArefBorrow<T>
{
	type Target = T;
	fn deref(&self) -> &T {
		&self.__inner().data
	}
}
impl<T: Sync> ops::Drop for ArefBorrow<T>
{
	fn drop(&mut self) {
		self.__inner().count.fetch_sub(1, Ordering::Relaxed);
	}
}
<|endoftext|>