<commit_before>use std::str;
use std::kinds::marker;

use {raw, Oid, Repository, Error};

/// A structure to represent a git [submodule][1]
///
/// [1]: http://git-scm.com/book/en/Git-Tools-Submodules
pub struct Submodule<'a> {
    raw: *mut raw::git_submodule,
    marker1: marker::ContravariantLifetime<'a>,
    marker2: marker::NoSend,
    marker3: marker::NoSync,
}

impl<'a> Submodule<'a> {
    /// Create a new object from its raw component.
    ///
    /// This method is unsafe as there is no guarantee that `raw` is a valid
    /// pointer.
    pub unsafe fn from_raw(_repo: &Repository,
                           raw: *mut raw::git_submodule) -> Submodule {
        Submodule {
            raw: raw,
            marker1: marker::ContravariantLifetime,
            marker2: marker::NoSend,
            marker3: marker::NoSync,
        }
    }

    /// Get the submodule's branch.
    ///
    /// Returns `None` if the branch is not valid utf-8 or if the branch is not
    /// yet available.
    pub fn branch(&self) -> Option<&str> {
        self.branch_bytes().and_then(str::from_utf8)
    }

    /// Get the branch for the submodule.
    ///
    /// Returns `None` if the branch is not yet available.
    pub fn branch_bytes(&self) -> Option<&[u8]> {
        unsafe {
            ::opt_bytes(self, raw::git_submodule_branch(self.raw))
        }
    }

    /// Get the submodule's url.
    ///
    /// Returns `None` if the url is not valid utf-8
    pub fn url(&self) -> Option<&str> { str::from_utf8(self.url_bytes()) }

    /// Get the url for the submodule.
    pub fn url_bytes(&self) -> &[u8] {
        unsafe {
            ::opt_bytes(self, raw::git_submodule_url(self.raw)).unwrap()
        }
    }

    /// Get the submodule's name.
    ///
    /// Returns `None` if the name is not valid utf-8
    pub fn name(&self) -> Option<&str> { str::from_utf8(self.name_bytes()) }

    /// Get the name for the submodule.
    pub fn name_bytes(&self) -> &[u8] {
        unsafe {
            ::opt_bytes(self, raw::git_submodule_name(self.raw)).unwrap()
        }
    }

    /// Get the path for the submodule.
    pub fn path(&self) -> Path {
        let bytes = unsafe {
            ::opt_bytes(self, raw::git_submodule_path(self.raw)).unwrap()
        };
        Path::new(bytes)
    }

    /// Get the OID for the submodule in the current HEAD tree.
    pub fn head_id(&self) -> Option<Oid> {
        unsafe {
            let ptr = raw::git_submodule_head_id(self.raw);
            if ptr.is_null() {
                None
            } else {
                Some(Oid::from_raw(ptr))
            }
        }
    }

    /// Get the OID for the submodule in the index.
    pub fn index_id(&self) -> Option<Oid> {
        unsafe {
            let ptr = raw::git_submodule_index_id(self.raw);
            if ptr.is_null() {
                None
            } else {
                Some(Oid::from_raw(ptr))
            }
        }
    }

    /// Get the OID for the submodule in the current working directory.
    ///
    /// This returns the OID that corresponds to looking up 'HEAD' in the
    /// checked out submodule. If there are pending changes in the index or
    /// anything else, this won't notice that.
    pub fn workdir_id(&self) -> Option<Oid> {
        unsafe {
            let ptr = raw::git_submodule_wd_id(self.raw);
            if ptr.is_null() {
                None
            } else {
                Some(Oid::from_raw(ptr))
            }
        }
    }

    /// Copy submodule info into ".git/config" file.
    ///
    /// Just like "git submodule init", this copies information about the
    /// submodule into ".git/config". You can use the accessor functions above
    /// to alter the in-memory git_submodule object and control what is written
    /// to the config, overriding what is in .gitmodules.
    ///
    /// By default, existing entries will not be overwritten, but passing `true`
    /// for `overwrite` forces them to be updated.
    pub fn init(&mut self, overwrite: bool) -> Result<(), Error> {
        unsafe {
            try_call!(raw::git_submodule_init(self.raw, overwrite));
        }
        Ok(())
    }

    /// Open the repository for a submodule.
    ///
    /// This will only work if the submodule is checked out into the working
    /// directory.
    pub fn open(&self) -> Result<Repository, Error> {
        let mut raw = 0 as *mut raw::git_repository;
        unsafe {
            try_call!(raw::git_submodule_open(&mut raw, self.raw));
        }
        Ok(unsafe { Repository::from_raw(raw) })
    }

    /// Access the underlying raw git submodule pointer.
    pub fn raw(&self) -> *mut raw::git_submodule { self.raw }

    /// Reread submodule info from config, index, and HEAD.
    ///
    /// Call this to reread cached submodule information for this submodule if
    /// you have reason to believe that it has changed.
    ///
    /// If `force` is `true`, then data will be reloaded even if it doesn't seem
    /// out of date
    pub fn reload(&mut self, force: bool) -> Result<(), Error> {
        unsafe {
            try_call!(raw::git_submodule_reload(self.raw, force));
        }
        Ok(())
    }

    /// Write submodule settings to .gitmodules file.
    ///
    /// This commits any in-memory changes to the submodule to the gitmodules
    /// file on disk. You may also be interested in `init()` which
    /// writes submodule info to ".git/config" (which is better for local
    /// changes to submodule settings) and/or `sync()` which writes
    /// settings about remotes to the actual submodule repository.
    pub fn save(&mut self) -> Result<(), Error> {
        unsafe { try_call!(raw::git_submodule_save(self.raw)); }
        Ok(())
    }

    /// Copy submodule remote info into submodule repo.
    ///
    /// This copies the information about the submodules URL into the checked
    /// out submodule config, acting like "git submodule sync". This is useful
    /// if you have altered the URL for the submodule (or it has been altered
    /// by a fetch of upstream changes) and you need to update your local repo.
    pub fn sync(&mut self) -> Result<(), Error> {
        unsafe { try_call!(raw::git_submodule_sync(self.raw)); }
        Ok(())
    }
}

#[unsafe_destructor]
impl<'a> Drop for Submodule<'a> {
    fn drop(&mut self) {
        unsafe { raw::git_submodule_free(self.raw) }
    }
}

#[cfg(test)]
mod tests {
    use std::io::TempDir;
    use Repository;

    #[test]
    fn smoke() {
        let td = TempDir::new("test").unwrap();
        let repo = Repository::init(td.path()).unwrap();
        let mut s1 = repo.submodule("/path/to/nowhere",
                                    &Path::new("foo"), true).unwrap();
        s1.init(false).unwrap();
        let s2 = repo.submodule("/path/to/nowhere",
                                &Path::new("bar"), true).unwrap();
        drop((s1, s2));

        let mut submodules = repo.submodules().unwrap();
        assert_eq!(submodules.len(), 2);
        let mut s = submodules.remove(0).unwrap();
        assert_eq!(s.name(), Some("bar"));
        assert_eq!(s.url(), Some("/path/to/nowhere"));
        assert_eq!(s.branch(), None);
        assert!(s.head_id().is_none());
        assert!(s.index_id().is_none());
        assert!(s.workdir_id().is_none());

        repo.find_submodule("bar").unwrap();
        s.open().unwrap();
        assert!(s.path() == Path::new("bar"));
        s.reload(true).unwrap();
    }
}
<commit_msg>Bind git_submodule_add_to_index<commit_after>use std::str;
use std::kinds::marker;

use {raw, Oid, Repository, Error};

/// A structure to represent a git [submodule][1]
///
/// [1]: http://git-scm.com/book/en/Git-Tools-Submodules
pub struct Submodule<'a> {
    raw: *mut raw::git_submodule,
    marker1: marker::ContravariantLifetime<'a>,
    marker2: marker::NoSend,
    marker3: marker::NoSync,
}

impl<'a> Submodule<'a> {
    /// Create a new object from its raw component.
    ///
    /// This method is unsafe as there is no guarantee that `raw` is a valid
    /// pointer.
    pub unsafe fn from_raw(_repo: &Repository,
                           raw: *mut raw::git_submodule) -> Submodule {
        Submodule {
            raw: raw,
            marker1: marker::ContravariantLifetime,
            marker2: marker::NoSend,
            marker3: marker::NoSync,
        }
    }

    /// Get the submodule's branch.
    ///
    /// Returns `None` if the branch is not valid utf-8 or if the branch is not
    /// yet available.
    pub fn branch(&self) -> Option<&str> {
        self.branch_bytes().and_then(str::from_utf8)
    }

    /// Get the branch for the submodule.
    ///
    /// Returns `None` if the branch is not yet available.
    pub fn branch_bytes(&self) -> Option<&[u8]> {
        unsafe {
            ::opt_bytes(self, raw::git_submodule_branch(self.raw))
        }
    }

    /// Get the submodule's url.
    ///
    /// Returns `None` if the url is not valid utf-8
    pub fn url(&self) -> Option<&str> { str::from_utf8(self.url_bytes()) }

    /// Get the url for the submodule.
    pub fn url_bytes(&self) -> &[u8] {
        unsafe {
            ::opt_bytes(self, raw::git_submodule_url(self.raw)).unwrap()
        }
    }

    /// Get the submodule's name.
    ///
    /// Returns `None` if the name is not valid utf-8
    pub fn name(&self) -> Option<&str> { str::from_utf8(self.name_bytes()) }

    /// Get the name for the submodule.
    pub fn name_bytes(&self) -> &[u8] {
        unsafe {
            ::opt_bytes(self, raw::git_submodule_name(self.raw)).unwrap()
        }
    }

    /// Get the path for the submodule.
    pub fn path(&self) -> Path {
        let bytes = unsafe {
            ::opt_bytes(self, raw::git_submodule_path(self.raw)).unwrap()
        };
        Path::new(bytes)
    }

    /// Get the OID for the submodule in the current HEAD tree.
    pub fn head_id(&self) -> Option<Oid> {
        unsafe {
            let ptr = raw::git_submodule_head_id(self.raw);
            if ptr.is_null() {
                None
            } else {
                Some(Oid::from_raw(ptr))
            }
        }
    }

    /// Get the OID for the submodule in the index.
    pub fn index_id(&self) -> Option<Oid> {
        unsafe {
            let ptr = raw::git_submodule_index_id(self.raw);
            if ptr.is_null() {
                None
            } else {
                Some(Oid::from_raw(ptr))
            }
        }
    }

    /// Get the OID for the submodule in the current working directory.
    ///
    /// This returns the OID that corresponds to looking up 'HEAD' in the
    /// checked out submodule. If there are pending changes in the index or
    /// anything else, this won't notice that.
    pub fn workdir_id(&self) -> Option<Oid> {
        unsafe {
            let ptr = raw::git_submodule_wd_id(self.raw);
            if ptr.is_null() {
                None
            } else {
                Some(Oid::from_raw(ptr))
            }
        }
    }

    /// Copy submodule info into ".git/config" file.
    ///
    /// Just like "git submodule init", this copies information about the
    /// submodule into ".git/config". You can use the accessor functions above
    /// to alter the in-memory git_submodule object and control what is written
    /// to the config, overriding what is in .gitmodules.
    ///
    /// By default, existing entries will not be overwritten, but passing `true`
    /// for `overwrite` forces them to be updated.
    pub fn init(&mut self, overwrite: bool) -> Result<(), Error> {
        unsafe {
            try_call!(raw::git_submodule_init(self.raw, overwrite));
        }
        Ok(())
    }

    /// Open the repository for a submodule.
    ///
    /// This will only work if the submodule is checked out into the working
    /// directory.
    pub fn open(&self) -> Result<Repository, Error> {
        let mut raw = 0 as *mut raw::git_repository;
        unsafe {
            try_call!(raw::git_submodule_open(&mut raw, self.raw));
        }
        Ok(unsafe { Repository::from_raw(raw) })
    }

    /// Access the underlying raw git submodule pointer.
    pub fn raw(&self) -> *mut raw::git_submodule { self.raw }

    /// Reread submodule info from config, index, and HEAD.
    ///
    /// Call this to reread cached submodule information for this submodule if
    /// you have reason to believe that it has changed.
    ///
    /// If `force` is `true`, then data will be reloaded even if it doesn't seem
    /// out of date
    pub fn reload(&mut self, force: bool) -> Result<(), Error> {
        unsafe {
            try_call!(raw::git_submodule_reload(self.raw, force));
        }
        Ok(())
    }

    /// Write submodule settings to .gitmodules file.
    ///
    /// This commits any in-memory changes to the submodule to the gitmodules
    /// file on disk. You may also be interested in `init()` which
    /// writes submodule info to ".git/config" (which is better for local
    /// changes to submodule settings) and/or `sync()` which writes
    /// settings about remotes to the actual submodule repository.
    pub fn save(&mut self) -> Result<(), Error> {
        unsafe { try_call!(raw::git_submodule_save(self.raw)); }
        Ok(())
    }

    /// Copy submodule remote info into submodule repo.
    ///
    /// This copies the information about the submodules URL into the checked
    /// out submodule config, acting like "git submodule sync". This is useful
    /// if you have altered the URL for the submodule (or it has been altered
    /// by a fetch of upstream changes) and you need to update your local repo.
    pub fn sync(&mut self) -> Result<(), Error> {
        unsafe { try_call!(raw::git_submodule_sync(self.raw)); }
        Ok(())
    }

    /// Add current submodule HEAD commit to index of superproject.
    ///
    /// If `write_index` is true, then the index file will be immediately
    /// written. Otherwise you must explicitly call `write()` on an `Index`
    /// later on.
    pub fn add_to_index(&mut self, write_index: bool) -> Result<(), Error> {
        unsafe {
            try_call!(raw::git_submodule_add_to_index(self.raw, write_index));
        }
        Ok(())
    }
}

#[unsafe_destructor]
impl<'a> Drop for Submodule<'a> {
    fn drop(&mut self) {
        unsafe { raw::git_submodule_free(self.raw) }
    }
}

#[cfg(test)]
mod tests {
    use std::io::TempDir;
    use Repository;

    #[test]
    fn smoke() {
        let td = TempDir::new("test").unwrap();
        let repo = Repository::init(td.path()).unwrap();
        let mut s1 = repo.submodule("/path/to/nowhere",
                                    &Path::new("foo"), true).unwrap();
        s1.init(false).unwrap();
        let s2 = repo.submodule("/path/to/nowhere",
                                &Path::new("bar"), true).unwrap();
        drop((s1, s2));

        let mut submodules = repo.submodules().unwrap();
        assert_eq!(submodules.len(), 2);
        let mut s = submodules.remove(0).unwrap();
        assert_eq!(s.name(), Some("bar"));
        assert_eq!(s.url(), Some("/path/to/nowhere"));
        assert_eq!(s.branch(), None);
        assert!(s.head_id().is_none());
        assert!(s.index_id().is_none());
        assert!(s.workdir_id().is_none());

        repo.find_submodule("bar").unwrap();
        s.open().unwrap();
        assert!(s.path() == Path::new("bar"));
        s.reload(true).unwrap();
    }
}
<|endoftext|>


<commit_before>// Struct
struct User {
    username: String,
    email: String,
    eye_color: EyeColor,
    sign_in_count: u64,
    active: bool,
}

// Tuple Struct
struct EyeColor(i32, i32, i32);

fn main() {
    let red = EyeColor(255, 0, 0);

    let mut user1 = build_user(
        String::from("someone@example.com"),
        String::from("someusername123")
    );

    println!("User1's email is: {}", user1.email);

    user1.email = String::from("fixedemail@example.com");

    let _user2 = User {
        email: String::from("another@example.com"),
        username: String::from("anotherusername567"),
        eye_color: red,
        ..user1
    };
}

fn build_user(email: String, username: String) -> User {
    let black = EyeColor(0, 0, 0);
    User {
        email: email,
        username: username,
        eye_color: black,
        active: true,
        sign_in_count: 1,
    }
}

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

    #[test]
    fn test_build_user_with_username() {
        let email = String::from("someone@example.com");
        let username = String::from("someusername123");
        let actual_user_instance: User = build_user(email, username);
        let expected_response: String = "someusername123".to_string();
        assert_eq!(actual_user_instance.username, expected_response);
    }
}<commit_msg>feat: Update User program with Matches using Some and None and Method on Enum<commit_after>// Struct
struct User {
    username: String,
    email: String,
    age: i32,
    eye_color: EyeColor,
    ip_address: IpAddr,
    voicemail_message: VoiceMail,
    sign_in_count: u64,
    active: bool
}

impl User {
    fn death(&self) -> Option<&i32> {
        match self.age >= 18 {
            true => {
                println!("Yup, you're gonna die");
                Some(&self.age)
            },
            false => None
        }
    }
}

struct Color(i32, i32, i32);

// Tuple Struct
struct EyeColor(Color);

struct Ipv4Address(u8, u8, u8, u8);

struct Ipv6Address(String);

// Enum - Custom Data Type that embeds address data structs inside enum variants
enum IpAddr {
    V4(Ipv4Address),
    V6(Ipv6Address)
}

// Enum - Embedding struct types in its variants instead of creating separate structs
enum VoiceMail {
    Quit,                           // No associated data
    Version { x: i32, y: i32 },     // Anonymous struct embedded
    Message(String),                // Single string of data
    Color(Color)                    // Anonymous tuple struct embedded
}

// Define Method on Enum
impl VoiceMail {
    fn call(&self) -> String {
        println!("Hello");
        "Hello".to_string()
    }
}

fn main() {
    let red = EyeColor(Color(255, 0, 0));

    let _user2_ip_address = IpAddr::V6(Ipv6Address(String::from("192.168.0.1")));
    let _user2_voicemail_message = VoiceMail::Message(String::from("Hi"));

    let mut user1 = build_user(
        String::from("someone@example.com"),
        String::from("someusername123"),
        50
    );

    println!("User1's email is: {}", user1.email);

    user1.email = String::from("fixedemail@example.com");

    let _user2 = User {
        email: String::from("another@example.com"),
        username: String::from("anotherusername567"),
        age: 30,
        eye_color: red,
        ip_address: _user2_ip_address,
        voicemail_message: _user2_voicemail_message,
        ..user1
    };

    match user1.death() {
        Some(death) => println!("User1's death is at {:#?}", death),
        None    => println!("Users only find out when they die after 18."),
    }
}

fn build_user(email: String, username: String, age: i32) -> User {
    let black = EyeColor(Color(0, 0, 0));
    let home = IpAddr::V4(Ipv4Address(127, 0, 0, 1));
    let voicemail_message_default = VoiceMail::Message(String::from("Hello"));
    User {
        email: email,
        username: username,
        age: age,
        eye_color: black,
        ip_address: home,
        voicemail_message: voicemail_message_default,
        active: true,
        sign_in_count: 1
    }
}

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

    #[test]
    fn test_build_user_with_username() {
        let email = String::from("someone@example.com");
        let username = String::from("someusername123");
        let age = 50;
        let actual_user_instance: User = build_user(email, username, age);
        let expected_response: String = "someusername123".to_string();
        assert_eq!(actual_user_instance.username, expected_response);
    }

    #[test]
    fn test_build_user_with_voicemail_message() {
        let email = String::from("someone@example.com");
        let username = String::from("someusername123");
        let age = 50;
        let voicemail_message_default = VoiceMail::Message(String::from("Hello"));
        let mut actual_user_instance: User = build_user(email, username, age);
        actual_user_instance.voicemail_message = voicemail_message_default;
        let expected_response: String = "Hello".to_string();
        assert_eq!(actual_user_instance.voicemail_message.call(), expected_response);
    }

    #[test]
    fn test_user_death() {
        let email = String::from("someone@example.com");
        let username = String::from("someusername123");
        let age = 50;
        let mut actual_user_instance: User = build_user(email, username, age);
        let expected_response: Option<&i32> = Some(&50);
        assert_eq!(actual_user_instance.death(), expected_response);
    }
}<|endoftext|>


<commit_before>use {BatchFn, BatchFuture};
use cached;

use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
use std::collections::HashMap;
use std::hash::Hash;

use futures::Future;
use futures::future::{err, ok};

mod non_cached_loader;
mod cached_loader;

pub struct Batcher {
    invoke_cnt: AtomicUsize,
    max_batch_size: usize,
}

impl Batcher {
    pub fn new(max_batch_size: usize) -> Batcher {
        Batcher {
            invoke_cnt: AtomicUsize::new(0),
            max_batch_size: max_batch_size,
        }
    }
}

impl BatchFn<i32, i32> for Batcher {
    type Error = ();
    fn load(&self, keys: &[i32]) -> BatchFuture<i32, Self::Error> {
        self.invoke_cnt.fetch_add(1, Ordering::SeqCst);
        thread::sleep(Duration::from_millis(50)); // Some works
        ok(keys.into_iter().map(|v| v * 10).collect()).boxed()
    }

    fn max_batch_size(&self) -> usize {
        self.max_batch_size
    }
}

// Result with batch call seq
impl BatchFn<i32, (usize, i32)> for Batcher {
    type Error = ();
    fn load(&self, keys: &[i32]) -> BatchFuture<(usize, i32), Self::Error> {
        let seq = self.invoke_cnt.fetch_add(1, Ordering::SeqCst);
        thread::sleep(Duration::from_millis(50)); // Some works
        ok(keys.into_iter().map(|v| (seq + 1, v * 10)).collect()).boxed()
    }

    fn max_batch_size(&self) -> usize {
        self.max_batch_size
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum MyError {
    Unknown,
}

pub struct BadBatcher;
impl BatchFn<i32, i32> for BadBatcher {
    type Error = MyError;
    fn load(&self, _keys: &[i32]) -> BatchFuture<i32, Self::Error> {
        err(MyError::Unknown).boxed()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum ValueError {
    NotEven,
}

impl BatchFn<i32, Result<i32, ValueError>> for BadBatcher {
    type Error = MyError;
    fn load(&self, keys: &[i32]) -> BatchFuture<Result<i32, ValueError>, Self::Error> {
        ok(keys.into_iter()
                .map(|v| if v % 2 == 0 {
                    Ok(v * 10)
                } else {
                    Err(ValueError::NotEven)
                })
                .collect())
            .boxed()
    }
}

pub struct MyCache<K, V>(HashMap<K, V>);
impl<K, V> MyCache<K, V>
    where K: Ord + Hash,
          V: Clone
{
    pub fn new() -> MyCache<K, V> {
        MyCache(HashMap::new())
    }
}

impl<K, V> cached::Cache<K, V> for MyCache<K, V>
    where K: Ord + Hash,
          V: Clone
{
    fn contains_key(&self, key: &K) -> bool {
        HashMap::contains_key(&self.0, key)
    }

    fn get(&self, key: &K) -> Option<V> {
        HashMap::get(&self.0, key).map(|v| v.clone())
    }

    fn insert(&mut self, key: K, value: V) {
        HashMap::insert(&mut self.0, key, value);
    }

    fn remove(&mut self, key: &K) -> Option<V> {
        HashMap::remove(&mut self.0, key)
    }

    fn clear(&mut self) {
        HashMap::clear(&mut self.0);
    }
}<commit_msg>update test<commit_after>use {BatchFn, BatchFuture};
use cached;

use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
use std::collections::HashMap;
use std::hash::Hash;

use futures::Future;
use futures::future::{err, ok};

mod non_cached_loader;
mod cached_loader;

pub struct Batcher {
    invoke_cnt: AtomicUsize,
    max_batch_size: usize,
}

impl Batcher {
    pub fn new(max_batch_size: usize) -> Batcher {
        Batcher {
            invoke_cnt: AtomicUsize::new(0),
            max_batch_size: max_batch_size,
        }
    }
}

impl BatchFn<i32, i32> for Batcher {
    type Error = ();
    fn load(&self, keys: &[i32]) -> BatchFuture<i32, Self::Error> {
        self.invoke_cnt.fetch_add(1, Ordering::SeqCst);
        thread::sleep(Duration::from_millis(200)); // Some works
        ok(keys.into_iter().map(|v| v * 10).collect()).boxed()
    }

    fn max_batch_size(&self) -> usize {
        self.max_batch_size
    }
}

// Result with batch call seq
impl BatchFn<i32, (usize, i32)> for Batcher {
    type Error = ();
    fn load(&self, keys: &[i32]) -> BatchFuture<(usize, i32), Self::Error> {
        let seq = self.invoke_cnt.fetch_add(1, Ordering::SeqCst);
        thread::sleep(Duration::from_millis(200)); // Some works
        ok(keys.into_iter().map(|v| (seq + 1, v * 10)).collect()).boxed()
    }

    fn max_batch_size(&self) -> usize {
        self.max_batch_size
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum MyError {
    Unknown,
}

pub struct BadBatcher;
impl BatchFn<i32, i32> for BadBatcher {
    type Error = MyError;
    fn load(&self, _keys: &[i32]) -> BatchFuture<i32, Self::Error> {
        err(MyError::Unknown).boxed()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum ValueError {
    NotEven,
}

impl BatchFn<i32, Result<i32, ValueError>> for BadBatcher {
    type Error = MyError;
    fn load(&self, keys: &[i32]) -> BatchFuture<Result<i32, ValueError>, Self::Error> {
        ok(keys.into_iter()
                .map(|v| if v % 2 == 0 {
                    Ok(v * 10)
                } else {
                    Err(ValueError::NotEven)
                })
                .collect())
            .boxed()
    }
}

pub struct MyCache<K, V>(HashMap<K, V>);
impl<K, V> MyCache<K, V>
    where K: Ord + Hash,
          V: Clone
{
    pub fn new() -> MyCache<K, V> {
        MyCache(HashMap::new())
    }
}

impl<K, V> cached::Cache<K, V> for MyCache<K, V>
    where K: Ord + Hash,
          V: Clone
{
    fn contains_key(&self, key: &K) -> bool {
        HashMap::contains_key(&self.0, key)
    }

    fn get(&self, key: &K) -> Option<V> {
        HashMap::get(&self.0, key).map(|v| v.clone())
    }

    fn insert(&mut self, key: K, value: V) {
        HashMap::insert(&mut self.0, key, value);
    }

    fn remove(&mut self, key: &K) -> Option<V> {
        HashMap::remove(&mut self.0, key)
    }

    fn clear(&mut self) {
        HashMap::clear(&mut self.0);
    }
}<|endoftext|>


<commit_before>//! The actual Turing machine
//!

use super::transition::Transitions;
use super::tape::ConcreteTape;

pub struct Machine<S, Q> where S: Clone {
    state: Q,
    tape: ConcreteTape<S>,
    transitions: Transitions<S, Q>,
}
<commit_msg>Document Turing Machine<commit_after>//! The actual Turing machine
//!

use super::transition::Transitions;
use super::tape::ConcreteTape;

/// The actual Turing machine
pub struct Machine<S, Q> where S: Clone {
    state: Q,
    tape: ConcreteTape<S>,
    transitions: Transitions<S, Q>,
}
<|endoftext|>


<commit_before>use error::{SassError, ErrorKind, Result};
use event::Event;
use sass::output_style::SassOutputStyle;
use sass::variable::SassVariable;
use tokenizer_utils::*;
use inner_tokenizer::{InnerTokenizer, State};
use substituter::Substituter;

use std::io::Write;

#[derive(Debug)]
pub struct Tokenizer<'a> {
    toker: Toker<'a>,
}

impl<'a> Tokenizer<'a> {
    pub fn new(inner_str: &'a str) -> Tokenizer<'a> {
        Tokenizer {
            toker: Toker {
                inner_str: &inner_str,
                bytes: &inner_str.as_bytes(),
                offset: 0,
            },
        }
    }

    pub fn stream<W: Write>(&mut self, output: &mut W, style: SassOutputStyle) -> Result<()> {
        let mut subber = Substituter::new(self);

        while let Some(event) = subber.next() {
            match event {
                Ok(ev) => {
                    match ev.output(style) {
                        Ok(s) =>  try!(write!(output, "{}", s)),
                        Err(e) => return Err(e),
                    }
                },
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }

    fn limit(&self) -> usize {
        self.toker.limit()
    }

    fn parse(&mut self) -> Result<Option<Event<'a>>> {
        self.toker.skip_leading_whitespace();

        if self.toker.at_eof() {
            return Ok(None)
        }

        let c = self.toker.bytes[self.toker.offset];

        if c == b'$' {
            return self.next_variable()
        }

        if self.toker.eat("@mixin ").is_ok() {
            return self.next_mixin()
        }

        if self.toker.eat("@include ").is_ok() {
            return self.next_mixin_call()
        }

        if c == b'/' && (self.toker.offset + 1) < self.limit() {
            let d = self.toker.bytes[self.toker.offset + 1];
            if d == b'*' {
                return self.next_comment()
            }
        }

        let mut inner = InnerTokenizer {
            toker: Toker {
                inner_str: &self.toker.inner_str,
                bytes: &self.toker.bytes,
                offset: self.toker.offset,
            },
            state: State::InSelectors,
        };
        let ret = match inner.next_rule() {
            Ok(Some(Event::Rule(rule))) => Ok(Some(Event::Rule(rule))),
            other => return Err(SassError {
                kind: ErrorKind::TokenizerError,
                message: format!(
                    "Expected sass rule from inner tokenizer, got: {:?}.",
                    other
                ),
            }),
        };
        self.toker.offset = inner.toker.offset;
        return ret
    }

    fn next_comment(&mut self) -> Result<Option<Event<'a>>> {
        self.toker.next_comment()
    }

    fn next_variable(&mut self) -> Result<Option<Event<'a>>> {
        let var_name = try!(self.toker.next_name());

        try!(self.toker.eat(":"));
        self.toker.skip_leading_whitespace();

        let var_value = try!(self.toker.next_value());

        try!(self.toker.eat(";"));
        self.toker.skip_leading_whitespace();

        Ok(Some(Event::Variable(SassVariable {
            name:  var_name,
            value: var_value,
        })))
    }

    fn next_mixin(&mut self) -> Result<Option<Event<'a>>> {
        match self.toker.next_mixin() {
            Ok(Some(Event::Mixin(sass_mixin))) => {
                 Ok(Some(Event::Mixin(sass_mixin)))
            },
            Err(e) => Err(e),
            _ => unreachable!(),
        }
    }

    fn next_mixin_call(&mut self) -> Result<Option<Event<'a>>> {
        match self.toker.next_mixin_call() {
            Ok(Some(Event::MixinCall(sass_mixin_call))) => {
                 Ok(Some(Event::MixinCall(sass_mixin_call)))
            },
            Err(e) => Err(e),
            _ => unreachable!(),
        }
    }
}

impl<'a> Iterator for Tokenizer<'a> {
    type Item = Result<Event<'a>>;

    fn next(&mut self) -> Option<Result<Event<'a>>> {
        if !self.toker.at_eof() {
            return match self.parse() {
                Ok(Some(t)) => Some(Ok(t)),
                Ok(None) => None,
                Err(e) => Some(Err(e)),
            }
        }
        None
    }
}
<commit_msg>Clean up a bunch of matches<commit_after>use error::{SassError, ErrorKind, Result};
use event::Event;
use sass::output_style::SassOutputStyle;
use sass::variable::SassVariable;
use tokenizer_utils::*;
use inner_tokenizer::{InnerTokenizer, State};
use substituter::Substituter;

use std::io::Write;

#[derive(Debug)]
pub struct Tokenizer<'a> {
    toker: Toker<'a>,
}

impl<'a> Tokenizer<'a> {
    pub fn new(inner_str: &'a str) -> Tokenizer<'a> {
        Tokenizer {
            toker: Toker {
                inner_str: &inner_str,
                bytes: &inner_str.as_bytes(),
                offset: 0,
            },
        }
    }

    pub fn stream<W: Write>(&mut self, output: &mut W, style: SassOutputStyle) -> Result<()> {
        let subber = Substituter::new(self);

        for event in subber.into_iter() {
            try!(event.unwrap().output(style).and_then(|s| {
                write!(output, "{}", s).map_err(|e| {
                    SassError::from(e)
                })
            }));
        }
        Ok(())
    }

    fn limit(&self) -> usize {
        self.toker.limit()
    }

    fn parse(&mut self) -> Result<Option<Event<'a>>> {
        self.toker.skip_leading_whitespace();

        if self.toker.at_eof() {
            return Ok(None)
        }

        let c = self.toker.bytes[self.toker.offset];

        if c == b'$' {
            return self.next_variable()
        }

        if self.toker.eat("@mixin ").is_ok() {
            return self.next_mixin()
        }

        if self.toker.eat("@include ").is_ok() {
            return self.next_mixin_call()
        }

        if c == b'/' && (self.toker.offset + 1) < self.limit() {
            let d = self.toker.bytes[self.toker.offset + 1];
            if d == b'*' {
                return self.next_comment()
            }
        }

        let mut inner = InnerTokenizer {
            toker: Toker {
                inner_str: &self.toker.inner_str,
                bytes: &self.toker.bytes,
                offset: self.toker.offset,
            },
            state: State::InSelectors,
        };
        let ret = match inner.next_rule() {
            Ok(Some(Event::Rule(rule))) => Ok(Some(Event::Rule(rule))),
            other => return Err(SassError {
                kind: ErrorKind::TokenizerError,
                message: format!(
                    "Expected sass rule from inner tokenizer, got: {:?}.",
                    other
                ),
            }),
        };
        self.toker.offset = inner.toker.offset;
        return ret
    }

    fn next_comment(&mut self) -> Result<Option<Event<'a>>> {
        self.toker.next_comment()
    }

    fn next_variable(&mut self) -> Result<Option<Event<'a>>> {
        let var_name = try!(self.toker.next_name());

        try!(self.toker.eat(":"));
        self.toker.skip_leading_whitespace();

        let var_value = try!(self.toker.next_value());

        try!(self.toker.eat(";"));
        self.toker.skip_leading_whitespace();

        Ok(Some(Event::Variable(SassVariable {
            name:  var_name,
            value: var_value,
        })))
    }

    fn next_mixin(&mut self) -> Result<Option<Event<'a>>> {
        match self.toker.next_mixin() {
            Ok(Some(Event::Mixin(sass_mixin))) => {
                 Ok(Some(Event::Mixin(sass_mixin)))
            },
            Err(e) => Err(e),
            _ => unreachable!(),
        }
    }

    fn next_mixin_call(&mut self) -> Result<Option<Event<'a>>> {
        match self.toker.next_mixin_call() {
            Ok(Some(Event::MixinCall(sass_mixin_call))) => {
                 Ok(Some(Event::MixinCall(sass_mixin_call)))
            },
            Err(e) => Err(e),
            _ => unreachable!(),
        }
    }
}

impl<'a> Iterator for Tokenizer<'a> {
    type Item = Result<Event<'a>>;

    fn next(&mut self) -> Option<Result<Event<'a>>> {
        if !self.toker.at_eof() {
            return match self.parse() {
                Ok(Some(t)) => Some(Ok(t)),
                Ok(None) => None,
                Err(e) => Some(Err(e)),
            }
        }
        None
    }
}
<|endoftext|>


<commit_before>//! Traits dealing with SQLite data types.
//!
//! SQLite uses a [dynamic type system](https://www.sqlite.org/datatype3.html). Implementations of
//! the `ToSql` and `FromSql` traits are provided for the basic types that
//! SQLite provides methods for:
//!
//! * Integers (`i32` and `i64`; SQLite uses `i64` internally, so getting an
//! `i32` will truncate   if the value is too large or too small).
//! * Reals (`f64`)
//! * Strings (`String` and `&str`)
//! * Blobs (`Vec<u8>` and `&[u8]`)
//!
//! Additionally, if the `time` feature is enabled, implementations are
//! provided for `time::OffsetDateTime` that use the RFC 3339 date/time format,
//! `"%Y-%m-%dT%H:%M:%S.%fZ"`, to store time values as strings.  These values
//! can be parsed by SQLite's builtin
//! [datetime](https://www.sqlite.org/lang_datefunc.html) functions.  If you
//! want different storage for datetimes, you can use a newtype.
//!
#![cfg_attr(feature = "time", doc = r##"
For example, to store datetimes as `i64`s counting the number of seconds since
the Unix epoch:

```
use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use rusqlite::Result;

pub struct DateTimeSql(pub time::OffsetDateTime);

impl FromSql for DateTimeSql {
    fn column_result(value: ValueRef) -> FromSqlResult<Self> {
        i64::column_result(value).map(|as_i64| {
            DateTimeSql(time::OffsetDateTime::from_unix_timestamp(as_i64))
        })
    }
}

impl ToSql for DateTimeSql {
    fn to_sql(&self) -> Result<ToSqlOutput> {
        Ok(self.0.timestamp().into())
    }
}
```

"##)]
//! `ToSql` and `FromSql` are also implemented for `Option<T>` where `T`
//! implements `ToSql` or `FromSql` for the cases where you want to know if a
//! value was NULL (which gets translated to `None`).

pub use self::from_sql::{FromSql, FromSqlError, FromSqlResult};
pub use self::to_sql::{ToSql, ToSqlOutput};
pub use self::value::Value;
pub use self::value_ref::ValueRef;

use std::fmt;

#[cfg(feature = "chrono")]
mod chrono;
mod from_sql;
#[cfg(feature = "serde_json")]
mod serde_json;
#[cfg(feature = "time")]
mod time;
mod to_sql;
#[cfg(feature = "url")]
mod url;
mod value;
mod value_ref;

/// Empty struct that can be used to fill in a query parameter as `NULL`.
///
/// ## Example
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// # use rusqlite::types::{Null};
///
/// fn insert_null(conn: &Connection) -> Result<usize> {
///     conn.execute("INSERT INTO people (name) VALUES (?)", &[Null])
/// }
/// ```
#[derive(Copy, Clone)]
pub struct Null;

/// SQLite data types.
/// See [Fundamental Datatypes](https://sqlite.org/c3ref/c_blob.html).
#[derive(Clone, Debug, PartialEq)]
pub enum Type {
    /// NULL
    Null,
    /// 64-bit signed integer
    Integer,
    /// 64-bit IEEE floating point number
    Real,
    /// String
    Text,
    /// BLOB
    Blob,
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Type::Null => write!(f, "Null"),
            Type::Integer => write!(f, "Integer"),
            Type::Real => write!(f, "Real"),
            Type::Text => write!(f, "Text"),
            Type::Blob => write!(f, "Blob"),
        }
    }
}

#[cfg(test)]
mod test {
    use super::Value;
    use crate::{Connection, Error, NO_PARAMS};
    use std::f64::EPSILON;
    use std::os::raw::{c_double, c_int};

    fn checked_memory_handle() -> Connection {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch("CREATE TABLE foo (b BLOB, t TEXT, i INTEGER, f FLOAT, n)")
            .unwrap();
        db
    }

    #[test]
    fn test_blob() {
        let db = checked_memory_handle();

        let v1234 = vec![1u8, 2, 3, 4];
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&v1234])
            .unwrap();

        let v: Vec<u8> = db
            .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(v, v1234);
    }

    #[test]
    fn test_empty_blob() {
        let db = checked_memory_handle();

        let empty = vec![];
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&empty])
            .unwrap();

        let v: Vec<u8> = db
            .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(v, empty);
    }

    #[test]
    fn test_str() {
        let db = checked_memory_handle();

        let s = "hello, world!";
        db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap();

        let from: String = db
            .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(from, s);
    }

    #[test]
    fn test_string() {
        let db = checked_memory_handle();

        let s = "hello, world!";
        db.execute("INSERT INTO foo(t) VALUES (?)", &[s.to_owned()])
            .unwrap();

        let from: String = db
            .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(from, s);
    }

    #[test]
    fn test_value() {
        let db = checked_memory_handle();

        db.execute("INSERT INTO foo(i) VALUES (?)", &[Value::Integer(10)])
            .unwrap();

        assert_eq!(
            10i64,
            db.query_row::<i64, _, _>("SELECT i FROM foo", NO_PARAMS, |r| r.get(0))
                .unwrap()
        );
    }

    #[test]
    fn test_option() {
        let db = checked_memory_handle();

        let s = Some("hello, world!");
        let b = Some(vec![1u8, 2, 3, 4]);

        db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap();
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&b]).unwrap();

        let mut stmt = db
            .prepare("SELECT t, b FROM foo ORDER BY ROWID ASC")
            .unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        {
            let row1 = rows.next().unwrap().unwrap();
            let s1: Option<String> = row1.get_unwrap(0);
            let b1: Option<Vec<u8>> = row1.get_unwrap(1);
            assert_eq!(s.unwrap(), s1.unwrap());
            assert!(b1.is_none());
        }

        {
            let row2 = rows.next().unwrap().unwrap();
            let s2: Option<String> = row2.get_unwrap(0);
            let b2: Option<Vec<u8>> = row2.get_unwrap(1);
            assert!(s2.is_none());
            assert_eq!(b, b2);
        }
    }

    #[test]
    #[allow(clippy::cognitive_complexity)]
    fn test_mismatched_types() {
        fn is_invalid_column_type(err: Error) -> bool {
            match err {
                Error::InvalidColumnType(..) => true,
                _ => false,
            }
        }

        let db = checked_memory_handle();

        db.execute(
            "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
            NO_PARAMS,
        )
        .unwrap();

        let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        let row = rows.next().unwrap().unwrap();

        // check the correct types come back as expected
        assert_eq!(vec![1, 2], row.get::<_, Vec<u8>>(0).unwrap());
        assert_eq!("text", row.get::<_, String>(1).unwrap());
        assert_eq!(1, row.get::<_, c_int>(2).unwrap());
        assert!((1.5 - row.get::<_, c_double>(3).unwrap()).abs() < EPSILON);
        assert!(row.get::<_, Option<c_int>>(4).unwrap().is_none());
        assert!(row.get::<_, Option<c_double>>(4).unwrap().is_none());
        assert!(row.get::<_, Option<String>>(4).unwrap().is_none());

        // check some invalid types

        // 0 is actually a blob (Vec<u8>)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(0).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, String>(0).err().unwrap()
        ));
        #[cfg(feature = "time")]
        assert!(is_invalid_column_type(
            row.get::<_, time::OffsetDateTime>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(0).err().unwrap()
        ));

        // 1 is actually a text (String)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(1).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(1).err().unwrap()
        ));

        // 2 is actually an integer
        assert!(is_invalid_column_type(
            row.get::<_, String>(2).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(2).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<String>>(2).err().unwrap()
        ));

        // 3 is actually a float (c_double)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(3).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, String>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(3).err().unwrap()
        ));

        // 4 is actually NULL
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(4).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, String>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(4).err().unwrap()
        ));
        #[cfg(feature = "time")]
        assert!(is_invalid_column_type(
            row.get::<_, time::OffsetDateTime>(4).err().unwrap()
        ));
    }

    #[test]
    fn test_dynamic_type() {
        use super::Value;
        let db = checked_memory_handle();

        db.execute(
            "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
            NO_PARAMS,
        )
        .unwrap();

        let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        let row = rows.next().unwrap().unwrap();
        assert_eq!(Value::Blob(vec![1, 2]), row.get::<_, Value>(0).unwrap());
        assert_eq!(
            Value::Text(String::from("text")),
            row.get::<_, Value>(1).unwrap()
        );
        assert_eq!(Value::Integer(1), row.get::<_, Value>(2).unwrap());
        match row.get::<_, Value>(3).unwrap() {
            Value::Real(val) => assert!((1.5 - val).abs() < EPSILON),
            x => panic!("Invalid Value {:?}", x),
        }
        assert_eq!(Value::Null, row.get::<_, Value>(4).unwrap());
    }
}
<commit_msg>Fix clippy warning<commit_after>//! Traits dealing with SQLite data types.
//!
//! SQLite uses a [dynamic type system](https://www.sqlite.org/datatype3.html). Implementations of
//! the `ToSql` and `FromSql` traits are provided for the basic types that
//! SQLite provides methods for:
//!
//! * Integers (`i32` and `i64`; SQLite uses `i64` internally, so getting an
//! `i32` will truncate   if the value is too large or too small).
//! * Reals (`f64`)
//! * Strings (`String` and `&str`)
//! * Blobs (`Vec<u8>` and `&[u8]`)
//!
//! Additionally, if the `time` feature is enabled, implementations are
//! provided for `time::OffsetDateTime` that use the RFC 3339 date/time format,
//! `"%Y-%m-%dT%H:%M:%S.%fZ"`, to store time values as strings.  These values
//! can be parsed by SQLite's builtin
//! [datetime](https://www.sqlite.org/lang_datefunc.html) functions.  If you
//! want different storage for datetimes, you can use a newtype.
//!
#![cfg_attr(feature = "time", doc = r##"
For example, to store datetimes as `i64`s counting the number of seconds since
the Unix epoch:

```
use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use rusqlite::Result;

pub struct DateTimeSql(pub time::OffsetDateTime);

impl FromSql for DateTimeSql {
    fn column_result(value: ValueRef) -> FromSqlResult<Self> {
        i64::column_result(value).map(|as_i64| {
            DateTimeSql(time::OffsetDateTime::from_unix_timestamp(as_i64))
        })
    }
}

impl ToSql for DateTimeSql {
    fn to_sql(&self) -> Result<ToSqlOutput> {
        Ok(self.0.timestamp().into())
    }
}
```

"##)]
//! `ToSql` and `FromSql` are also implemented for `Option<T>` where `T`
//! implements `ToSql` or `FromSql` for the cases where you want to know if a
//! value was NULL (which gets translated to `None`).

pub use self::from_sql::{FromSql, FromSqlError, FromSqlResult};
pub use self::to_sql::{ToSql, ToSqlOutput};
pub use self::value::Value;
pub use self::value_ref::ValueRef;

use std::fmt;

#[cfg(feature = "chrono")]
mod chrono;
mod from_sql;
#[cfg(feature = "serde_json")]
mod serde_json;
#[cfg(feature = "time")]
mod time;
mod to_sql;
#[cfg(feature = "url")]
mod url;
mod value;
mod value_ref;

/// Empty struct that can be used to fill in a query parameter as `NULL`.
///
/// ## Example
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// # use rusqlite::types::{Null};
///
/// fn insert_null(conn: &Connection) -> Result<usize> {
///     conn.execute("INSERT INTO people (name) VALUES (?)", &[Null])
/// }
/// ```
#[derive(Copy, Clone)]
pub struct Null;

/// SQLite data types.
/// See [Fundamental Datatypes](https://sqlite.org/c3ref/c_blob.html).
#[derive(Clone, Debug, PartialEq)]
pub enum Type {
    /// NULL
    Null,
    /// 64-bit signed integer
    Integer,
    /// 64-bit IEEE floating point number
    Real,
    /// String
    Text,
    /// BLOB
    Blob,
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Type::Null => write!(f, "Null"),
            Type::Integer => write!(f, "Integer"),
            Type::Real => write!(f, "Real"),
            Type::Text => write!(f, "Text"),
            Type::Blob => write!(f, "Blob"),
        }
    }
}

#[cfg(test)]
mod test {
    use super::Value;
    use crate::{Connection, Error, NO_PARAMS};
    use std::f64::EPSILON;
    use std::os::raw::{c_double, c_int};

    fn checked_memory_handle() -> Connection {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch("CREATE TABLE foo (b BLOB, t TEXT, i INTEGER, f FLOAT, n)")
            .unwrap();
        db
    }

    #[test]
    fn test_blob() {
        let db = checked_memory_handle();

        let v1234 = vec![1u8, 2, 3, 4];
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&v1234])
            .unwrap();

        let v: Vec<u8> = db
            .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(v, v1234);
    }

    #[test]
    fn test_empty_blob() {
        let db = checked_memory_handle();

        let empty = vec![];
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&empty])
            .unwrap();

        let v: Vec<u8> = db
            .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(v, empty);
    }

    #[test]
    fn test_str() {
        let db = checked_memory_handle();

        let s = "hello, world!";
        db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap();

        let from: String = db
            .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(from, s);
    }

    #[test]
    fn test_string() {
        let db = checked_memory_handle();

        let s = "hello, world!";
        db.execute("INSERT INTO foo(t) VALUES (?)", &[s.to_owned()])
            .unwrap();

        let from: String = db
            .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(from, s);
    }

    #[test]
    fn test_value() {
        let db = checked_memory_handle();

        db.execute("INSERT INTO foo(i) VALUES (?)", &[Value::Integer(10)])
            .unwrap();

        assert_eq!(
            10i64,
            db.query_row::<i64, _, _>("SELECT i FROM foo", NO_PARAMS, |r| r.get(0))
                .unwrap()
        );
    }

    #[test]
    fn test_option() {
        let db = checked_memory_handle();

        let s = Some("hello, world!");
        let b = Some(vec![1u8, 2, 3, 4]);

        db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap();
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&b]).unwrap();

        let mut stmt = db
            .prepare("SELECT t, b FROM foo ORDER BY ROWID ASC")
            .unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        {
            let row1 = rows.next().unwrap().unwrap();
            let s1: Option<String> = row1.get_unwrap(0);
            let b1: Option<Vec<u8>> = row1.get_unwrap(1);
            assert_eq!(s.unwrap(), s1.unwrap());
            assert!(b1.is_none());
        }

        {
            let row2 = rows.next().unwrap().unwrap();
            let s2: Option<String> = row2.get_unwrap(0);
            let b2: Option<Vec<u8>> = row2.get_unwrap(1);
            assert!(s2.is_none());
            assert_eq!(b, b2);
        }
    }

    #[test]
    #[allow(clippy::cognitive_complexity)]
    fn test_mismatched_types() {
        fn is_invalid_column_type(err: Error) -> bool {
            matches!(err, Error::InvalidColumnType(..))
        }

        let db = checked_memory_handle();

        db.execute(
            "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
            NO_PARAMS,
        )
        .unwrap();

        let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        let row = rows.next().unwrap().unwrap();

        // check the correct types come back as expected
        assert_eq!(vec![1, 2], row.get::<_, Vec<u8>>(0).unwrap());
        assert_eq!("text", row.get::<_, String>(1).unwrap());
        assert_eq!(1, row.get::<_, c_int>(2).unwrap());
        assert!((1.5 - row.get::<_, c_double>(3).unwrap()).abs() < EPSILON);
        assert!(row.get::<_, Option<c_int>>(4).unwrap().is_none());
        assert!(row.get::<_, Option<c_double>>(4).unwrap().is_none());
        assert!(row.get::<_, Option<String>>(4).unwrap().is_none());

        // check some invalid types

        // 0 is actually a blob (Vec<u8>)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(0).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, String>(0).err().unwrap()
        ));
        #[cfg(feature = "time")]
        assert!(is_invalid_column_type(
            row.get::<_, time::OffsetDateTime>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(0).err().unwrap()
        ));

        // 1 is actually a text (String)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(1).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(1).err().unwrap()
        ));

        // 2 is actually an integer
        assert!(is_invalid_column_type(
            row.get::<_, String>(2).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(2).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<String>>(2).err().unwrap()
        ));

        // 3 is actually a float (c_double)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(3).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, String>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(3).err().unwrap()
        ));

        // 4 is actually NULL
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(4).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, String>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(4).err().unwrap()
        ));
        #[cfg(feature = "time")]
        assert!(is_invalid_column_type(
            row.get::<_, time::OffsetDateTime>(4).err().unwrap()
        ));
    }

    #[test]
    fn test_dynamic_type() {
        use super::Value;
        let db = checked_memory_handle();

        db.execute(
            "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
            NO_PARAMS,
        )
        .unwrap();

        let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        let row = rows.next().unwrap().unwrap();
        assert_eq!(Value::Blob(vec![1, 2]), row.get::<_, Value>(0).unwrap());
        assert_eq!(
            Value::Text(String::from("text")),
            row.get::<_, Value>(1).unwrap()
        );
        assert_eq!(Value::Integer(1), row.get::<_, Value>(2).unwrap());
        match row.get::<_, Value>(3).unwrap() {
            Value::Real(val) => assert!((1.5 - val).abs() < EPSILON),
            x => panic!("Invalid Value {:?}", x),
        }
        assert_eq!(Value::Null, row.get::<_, Value>(4).unwrap());
    }
}
<|endoftext|>


<commit_before>//! An efficient Fast Fourier transform.
//!
//! A `Transformer` must first be created to perform FFTs. The transformer
//! stores precomputed information to speed up the transform, and can only be
//! used to perform FFTs of the chosen size.

use std::f32::consts::PI;
use std::vec::Vec;

use num::complex::Complex32;
use num::traits::Zero;

/// A container for precomputed values to perform FFTs of a fixed size.
pub struct Transformer {
    size: usize,
    bit_reverses: Vec<usize>,
    twiddles: Vec<Complex32>,
}

impl Transformer {
    /// Initialize a transformer to perform FFTs of the provided size, rounded
    /// up to the nearest power of two.
    pub fn new(size: usize) -> Transformer {
        // Only operate in powers of two
        let bufsize = size.next_power_of_two();

        // Populate the bit reverses
        // We only use the lower log2(size) bits to express the index
        let mut bit_reverses = Vec::with_capacity(bufsize);
        for i in (0 .. size) {
            let br = bit_reverse(i as u32, int_log(bufsize as u32));
            bit_reverses.push(br as usize);
        }

        // Populate the twiddle factors w_n^i
        // w_n = exp(-j*2*pi*n/N)
        let mut twiddles = Vec::with_capacity(bufsize);
        let exponent = Complex32::new(0.0, -2.0*PI/(bufsize as f32));
        for i in (0 .. bufsize) {
            let c1 = exponent.scale(i as f32);
            let c = Complex32::new(c1.im.cos(), c1.im.sin()).scale(c1.re.exp());
            twiddles.push(c);
        }

        Transformer { size: bufsize, bit_reverses: bit_reverses,
            twiddles: twiddles }
    }

    /// Return the size FFT this Transformer performs.
    pub fn get_size(&self) -> usize {
        self.size
    }

    /// Perform an FFT on `input`, and place the result in `output`.
    ///
    /// The input is zero padded if less than `size` samples are provided, and
    /// truncated if more than `size` samples are provided.
    pub fn fft(&self, input: &[Complex32], output: &mut[Complex32]) {
        self.transform(input, output, false);
    }

    /// Perform an inverse FFT on `input`, and place the result in `output`.
    ///
    /// The input is zero padded if less than `size` samples are provided, and
    /// truncated if more than `size` samples are provided.
    pub fn ifft(&self, input: &[Complex32], output: &mut[Complex32]) {
        self.transform(input, output, true);
    }

    /// Perform the actual transform on `input`, placing the result in `output`.
    ///
    /// This function performs both forward and backwards transforms, since
    /// there are only minor algorithmic differences in the beginning and end
    /// of transformation.
    ///
    /// The input is zero padded if less than `size` samples are provided, and
    /// truncated if more than `size` samples are provided.
    fn transform(&self, input: &[Complex32], output: &mut[Complex32],
                 inverse: bool) {
        // Copy the input into bit reverse order, zero padding if necessary,
        // conjugating if we are inverse transforming
        for i in (0 .. input.len()) {
            output[self.bit_reverses[i]] =
                if inverse {
                    input[i].conj()
                } else {
                    input[i]
                }
        }
        for i in self.bit_reverses[input.len() .. self.size].iter() {
            output[*i] = Complex32::zero();
        }

        // Iteratively perform FFT, starting at 2 points
        let mut n = 2;
        while n <= self.size {
            // For each of the small FFTs
            for set in (0 .. self.size/n) {
                // For each pair of n
                for i in (0 .. n/2) {
                    let ilo = n*set + i;
                    let ihi = ilo + n/2;

                    // Grab out the lower and upper n
                    let lower = output[ilo];
                    let upper = output[ihi] * self.twiddles[self.size/n * i];

                    // Assign them back using a butterfly
                    output[ilo] = lower + upper;
                    output[ihi] = lower - upper;
                }
            }

            // Double the number of points per FFT
            n *= 2;
        }

        // If we are inverse transforming, conjugate and normalize the output
        if inverse {
            for i in (0 .. self.size) {
                output[i] = output[i].conj().scale(1.0/(self.size as f32));
            }
        }
    }
}

/// Return the bit reverse of `n`, for the lower `bits` bits.
///
/// For small examples, the bit reverse of 0b00011010 is 0b01011000, but the bit
/// reverse of just the lower 5 bits is 0b00001011.
fn bit_reverse(n: u32, bits: u32) -> u32 {
    let mut i = n;
    i = (i >> 16) | (i << 16);
    i = ((i & 0xFF00FF00) >> 8) | ((i & 0x00FF00FF) << 8);
    i = ((i & 0xF0F0F0F0) >> 4) | ((i & 0x0F0F0F0F) << 4);
    i = ((i & 0xCCCCCCCC) >> 2) | ((i & 0x33333333) << 2);
    i = ((i & 0xAAAAAAAA) >> 1) | ((i & 0x55555555) << 1);
    i >> ((32 - bits) as u32)
}

/// Return the log base 2 of n, rounded up.
fn int_log(n: u32) -> u32 {
    let mut i = n-1; // correct for exact powers of 2
    let mut res = 0;
    while i > 0 {
        i = i >> 1;
        res += 1;
    }
    res
}

// Unit tests...
#[cfg(test)]
mod test {
    use std::vec::Vec;

    use num::complex::Complex32;
    use num::traits::Zero;

    use super::{Transformer, int_log, bit_reverse};

    /// Tests int_log with many values
    #[test]
    fn test_int_log() {
        assert_eq!(int_log(1), 0);
        assert_eq!(int_log(2), 1);
        assert_eq!(int_log(3), 2);
        assert_eq!(int_log(4), 2);
        assert_eq!(int_log(7), 3);
        assert_eq!(int_log(8), 3);
        assert_eq!(int_log(31), 5);
        assert_eq!(int_log(32), 5);
    }

    /// Tests bit_reverse.
    #[test]
    fn test_bit_reverse() {
        assert_eq!(bit_reverse(0x00000000, 32), 0x00000000);
        assert_eq!(bit_reverse(0xFFFFFFFF, 32), 0xFFFFFFFF);
        assert_eq!(bit_reverse(0x00000001, 32), 0x80000000);
        assert_eq!(bit_reverse(0x11111111, 32), 0x88888888);
        assert_eq!(bit_reverse(0x234f9e01, 32), 0x8079f2c4); //random
        assert_eq!(bit_reverse(0x00000001, 4), 0x00000008);
        assert_eq!(bit_reverse(0x0000000F, 4), 0x0000000F);
    }

    /// Tests the FFT of an impulse function.
    ///
    /// Analytically, an impulse function has a constant fourier transform.
    #[test]
    fn test_fft_impulse() {
        let zero = Complex32::zero();
        let one = Complex32::new(1.0, 0.0);

        let mut impulse = Vec::with_capacity(8);
        let mut out = Vec::with_capacity(8);
        for i in (0 .. 8) {
            impulse.push(if i == 0 { one } else { zero });
            out.push(Complex32::zero());
        }

        let t = Transformer::new(8);
        t.fft(&impulse, &mut out);

        for c in out.iter() {
            assert!(c.eq(&one))
        }
    }

    /// Tests the IFFT of an impulse function.
    ///
    /// Analytically, a constant frequency domain results in an impulse
    /// function.
    #[test]
    fn test_ifft_impulse() {
        let zero = Complex32::zero();
        let one = Complex32::new(1.0, 0.0);

        let mut impulse = Vec::with_capacity(8);
        let mut out = Vec::with_capacity(8);
        for _i in (0 .. 8) {
            impulse.push(one);
            out.push(zero);
        }

        let t = Transformer::new(8);
        t.ifft(&impulse, &mut out);

        assert!(out[0].eq(&one));
        for c in out[1 .. 8].iter() {
            assert!(c.eq(&zero));
        }
    }

    /// Tests that the identify property, i.e. IFFT(FTT(f)) == f
    #[test]
    fn test_fft_identity() {
        let zero = Complex32::zero();
        let epsilon = 1e-6;

        let mut input = Vec::with_capacity(8);
        let mut fft = Vec::with_capacity(8);
        let mut out = Vec::with_capacity(8);
        for i in (0 .. 8) {
            input.push(Complex32::new((i+1) as f32, 0.0));
            fft.push(zero);
            out.push(zero);
        }

        let t = Transformer::new(8);
        t.fft(&input, &mut fft);
        t.ifft(&fft, &mut out);

        for i in (0 .. 7) {
            println!("{}",out[i].re - ((i+1) as f32));
            assert!(out[i].re - ((i+1) as f32) < epsilon);
            assert!(out[i].im < epsilon);
        }
    }

    /// Tests that the Transformer properly handles input buffers that are too
    /// short by zero padding them.
    #[test]
    fn test_fft_zero_pad() {
        let zero = Complex32::zero();
        let epsilon = 1e-6;

        let mut input = Vec::with_capacity(7);
        let mut fft = Vec::with_capacity(8);
        let mut out = Vec::with_capacity(8);
        for i in (0 .. 8) {
            if i < 7 {
                input.push(Complex32::new((i+1) as f32, 0.0));
            }
            fft.push(zero);
            out.push(zero);
        }

        let t = Transformer::new(8);
        t.fft(&input, &mut fft);
        t.ifft(&fft, &mut out);

        for i in (0 .. 7) {
            println!("{}",out[i].re - ((i+1) as f32));
            assert!(out[i].re - ((i+1) as f32) < epsilon);
            assert!(out[i].im < epsilon);
        }
    }
}
<commit_msg>Better use traits and constants in FFT testing<commit_after>//! An efficient Fast Fourier transform.
//!
//! A `Transformer` must first be created to perform FFTs. The transformer
//! stores precomputed information to speed up the transform, and can only be
//! used to perform FFTs of the chosen size.

use std::f32::consts::PI;
use std::vec::Vec;

use num::complex::Complex32;
use num::traits::Zero;

/// A container for precomputed values to perform FFTs of a fixed size.
pub struct Transformer {
    size: usize,
    bit_reverses: Vec<usize>,
    twiddles: Vec<Complex32>,
}

impl Transformer {
    /// Initialize a transformer to perform FFTs of the provided size, rounded
    /// up to the nearest power of two.
    pub fn new(size: usize) -> Transformer {
        // Only operate in powers of two
        let bufsize = size.next_power_of_two();

        // Populate the bit reverses
        // We only use the lower log2(size) bits to express the index
        let mut bit_reverses = Vec::with_capacity(bufsize);
        for i in (0 .. size) {
            let br = bit_reverse(i as u32, int_log(bufsize as u32));
            bit_reverses.push(br as usize);
        }

        // Populate the twiddle factors w_n^i
        // w_n = exp(-j*2*pi*n/N)
        let mut twiddles = Vec::with_capacity(bufsize);
        let exponent = Complex32::new(0.0, -2.0*PI/(bufsize as f32));
        for i in (0 .. bufsize) {
            let c1 = exponent.scale(i as f32);
            let c = Complex32::new(c1.im.cos(), c1.im.sin()).scale(c1.re.exp());
            twiddles.push(c);
        }

        Transformer { size: bufsize, bit_reverses: bit_reverses,
            twiddles: twiddles }
    }

    /// Return the size FFT this Transformer performs.
    pub fn get_size(&self) -> usize {
        self.size
    }

    /// Perform an FFT on `input`, and place the result in `output`.
    ///
    /// The input is zero padded if less than `size` samples are provided, and
    /// truncated if more than `size` samples are provided.
    pub fn fft(&self, input: &[Complex32], output: &mut[Complex32]) {
        self.transform(input, output, false);
    }

    /// Perform an inverse FFT on `input`, and place the result in `output`.
    ///
    /// The input is zero padded if less than `size` samples are provided, and
    /// truncated if more than `size` samples are provided.
    pub fn ifft(&self, input: &[Complex32], output: &mut[Complex32]) {
        self.transform(input, output, true);
    }

    /// Perform the actual transform on `input`, placing the result in `output`.
    ///
    /// This function performs both forward and backwards transforms, since
    /// there are only minor algorithmic differences in the beginning and end
    /// of transformation.
    ///
    /// The input is zero padded if less than `size` samples are provided, and
    /// truncated if more than `size` samples are provided.
    fn transform(&self, input: &[Complex32], output: &mut[Complex32],
                 inverse: bool) {
        // Copy the input into bit reverse order, zero padding if necessary,
        // conjugating if we are inverse transforming
        for i in (0 .. input.len()) {
            output[self.bit_reverses[i]] =
                if inverse {
                    input[i].conj()
                } else {
                    input[i]
                }
        }
        for i in self.bit_reverses[input.len() .. self.size].iter() {
            output[*i] = Complex32::zero();
        }

        // Iteratively perform FFT, starting at 2 points
        let mut n = 2;
        while n <= self.size {
            // For each of the small FFTs
            for set in (0 .. self.size/n) {
                // For each pair of n
                for i in (0 .. n/2) {
                    let ilo = n*set + i;
                    let ihi = ilo + n/2;

                    // Grab out the lower and upper n
                    let lower = output[ilo];
                    let upper = output[ihi] * self.twiddles[self.size/n * i];

                    // Assign them back using a butterfly
                    output[ilo] = lower + upper;
                    output[ihi] = lower - upper;
                }
            }

            // Double the number of points per FFT
            n *= 2;
        }

        // If we are inverse transforming, conjugate and normalize the output
        if inverse {
            for i in (0 .. self.size) {
                output[i] = output[i].conj().scale(1.0/(self.size as f32));
            }
        }
    }
}

/// Return the bit reverse of `n`, for the lower `bits` bits.
///
/// For small examples, the bit reverse of 0b00011010 is 0b01011000, but the bit
/// reverse of just the lower 5 bits is 0b00001011.
fn bit_reverse(n: u32, bits: u32) -> u32 {
    let mut i = n;
    i = (i >> 16) | (i << 16);
    i = ((i & 0xFF00FF00) >> 8) | ((i & 0x00FF00FF) << 8);
    i = ((i & 0xF0F0F0F0) >> 4) | ((i & 0x0F0F0F0F) << 4);
    i = ((i & 0xCCCCCCCC) >> 2) | ((i & 0x33333333) << 2);
    i = ((i & 0xAAAAAAAA) >> 1) | ((i & 0x55555555) << 1);
    i >> ((32 - bits) as u32)
}

/// Return the log base 2 of n, rounded up.
fn int_log(n: u32) -> u32 {
    let mut i = n-1; // correct for exact powers of 2
    let mut res = 0;
    while i > 0 {
        i = i >> 1;
        res += 1;
    }
    res
}

// Unit tests...
#[cfg(test)]
mod test {
    use std::vec::Vec;

    use num::complex::Complex32;
    use num::traits::{One, Zero};

    use super::{Transformer, int_log, bit_reverse};

    // For floating point comparison
    static EPSILON: f32 = 1e-6;

    /// Tests int_log with many values
    #[test]
    fn test_int_log() {
        assert_eq!(int_log(1), 0);
        assert_eq!(int_log(2), 1);
        assert_eq!(int_log(3), 2);
        assert_eq!(int_log(4), 2);
        assert_eq!(int_log(7), 3);
        assert_eq!(int_log(8), 3);
        assert_eq!(int_log(31), 5);
        assert_eq!(int_log(32), 5);
    }

    /// Tests bit_reverse.
    #[test]
    fn test_bit_reverse() {
        assert_eq!(bit_reverse(0x00000000, 32), 0x00000000);
        assert_eq!(bit_reverse(0xFFFFFFFF, 32), 0xFFFFFFFF);
        assert_eq!(bit_reverse(0x00000001, 32), 0x80000000);
        assert_eq!(bit_reverse(0x11111111, 32), 0x88888888);
        assert_eq!(bit_reverse(0x234f9e01, 32), 0x8079f2c4); //random
        assert_eq!(bit_reverse(0x00000001, 4), 0x00000008);
        assert_eq!(bit_reverse(0x0000000F, 4), 0x0000000F);
    }

    /// Tests the FFT of an impulse function.
    ///
    /// Analytically, an impulse function has a constant fourier transform.
    #[test]
    fn test_fft_impulse() {
        let mut impulse = Vec::with_capacity(8);
        let mut out = Vec::with_capacity(8);
        for i in (0 .. 8) {
            impulse.push(if i == 0 { Complex32::one() } else { Complex32::zero() });
            out.push(Complex32::zero());
        }

        let t = Transformer::new(8);
        t.fft(&impulse, &mut out);

        for c in out.iter() {
            assert!(c.eq(&Complex32::one()))
        }
    }

    /// Tests the IFFT of an impulse function.
    ///
    /// Analytically, a constant frequency domain results in an impulse
    /// function.
    #[test]
    fn test_ifft_impulse() {
        let mut impulse = Vec::with_capacity(8);
        let mut out = Vec::with_capacity(8);
        for _i in (0 .. 8) {
            impulse.push(Complex32::one());
            out.push(Complex32::zero());
        }

        let t = Transformer::new(8);
        t.ifft(&impulse, &mut out);

        assert!(out[0].eq(&Complex32::one()));
        for c in out[1 .. 8].iter() {
            assert!(c.eq(&Complex32::zero()));
        }
    }

    /// Tests that the identify property, i.e. IFFT(FTT(f)) == f
    #[test]
    fn test_fft_identity() {
        let mut input = Vec::with_capacity(8);
        let mut fft = Vec::with_capacity(8);
        let mut out = Vec::with_capacity(8);
        for i in (0 .. 8) {
            input.push(Complex32::new((i+1) as f32, 0.0));
            fft.push(Complex32::zero());
            out.push(Complex32::zero());
        }

        let t = Transformer::new(8);
        t.fft(&input, &mut fft);
        t.ifft(&fft, &mut out);

        for i in (0 .. 7) {
            println!("{}",out[i].re - ((i+1) as f32));
            assert!(out[i].re - ((i+1) as f32) < EPSILON);
            assert!(out[i].im < EPSILON);
        }
    }

    /// Tests that the Transformer properly handles input buffers that are too
    /// short by zero padding them.
    #[test]
    fn test_fft_zero_pad() {
        let mut input = Vec::with_capacity(7);
        let mut fft = Vec::with_capacity(8);
        let mut out = Vec::with_capacity(8);
        for i in (0 .. 8) {
            if i < 7 {
                input.push(Complex32::new((i+1) as f32, 0.0));
            }
            fft.push(Complex32::zero());
            out.push(Complex32::zero());
        }

        let t = Transformer::new(8);
        t.fft(&input, &mut fft);
        t.ifft(&fft, &mut out);

        for i in (0 .. 7) {
            println!("{}",out[i].re - ((i+1) as f32));
            assert!(out[i].re - ((i+1) as f32) < EPSILON);
            assert!(out[i].im < EPSILON);
        }
    }
}
<|endoftext|>


<commit_before>#![doc(html_root_url = "https://docs.rs/tokio-macros/0.2.5")]
#![allow(clippy::needless_doctest_main)]
#![warn(
    missing_debug_implementations,
    missing_docs,
    rust_2018_idioms,
    unreachable_pub
)]
#![deny(intra_doc_link_resolution_failure)]
#![doc(test(
    no_crate_inject,
    attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
))]

//! Macros for use with Tokio

// This `extern` is required for older `rustc` versions but newer `rustc`
// versions warn about the unused `extern crate`.
#[allow(unused_extern_crates)]
extern crate proc_macro;

mod entry;
mod select;

use proc_macro::TokenStream;

/// Marks async function to be executed by selected runtime. This macro helps set up a `Runtime`
/// without requiring the user to use [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.builder.html) directly.
///
/// ## Options:
///
///
/// - `core_threads=n` - Sets core threads to `n` (requires `rt-threaded` feature).
/// - `max_threads=n` - Sets max threads to `n` (requires `rt-core` or `rt-threaded` feature).
///
/// ## Function arguments:
///
/// Arguments are allowed for any functions aside from `main` which is special
///
/// ## Usage
///
/// ### Using default
///
/// ```rust
/// #[tokio::main]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .threaded_scheduler()
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### Set number of core threads
///
/// ```rust
/// #[tokio::main(core_threads = 2)]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .threaded_scheduler()
///         .core_threads(2)
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::main(args, item, true)
}

/// Marks async function to be executed by selected runtime. This macro helps set up a `Runtime`
/// without requiring the user to use [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.builder.html) directly.
///
/// ## Options:
///
/// - `basic_scheduler` - All tasks are executed on the current thread.
/// - `threaded_scheduler` - Uses the multi-threaded scheduler. Used by default (requires `rt-threaded` feature).
///
/// ## Function arguments:
///
/// Arguments are allowed for any functions aside from `main` which is special
///
/// ## Usage
///
/// ### Using default
///
/// ```rust
/// #[tokio::main]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Runtime::new()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### Select runtime
///
/// ```rust
/// #[tokio::main(basic_scheduler)]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .basic_scheduler()
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::old::main(args, item)
}

/// Marks async function to be executed by selected runtime. This macro helps set up a `Runtime`
/// without requiring the user to use [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.builder.html) directly.
///
/// ## Options:
///
/// - `max_threads=n` - Sets max threads to `n`.
///
/// ## Function arguments:
///
/// Arguments are allowed for any functions aside from `main` which is special
///
/// ## Usage
///
/// ### Using default
///
/// ```rust
/// #[tokio::main]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .basic_scheduler()
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main_basic(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::main(args, item, false)
}

/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `core_threads=n` - Sets core threads to `n` (requires `rt-threaded` feature).
/// - `max_threads=n` - Sets max threads to `n` (requires `rt-core` or `rt-threaded` feature).
///
/// ## Usage
///
/// ### Select runtime
///
/// ```no_run
/// #[tokio::test(core_threads = 1)]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### Using default
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
pub fn test_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::test(args, item, true)
}

/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `basic_scheduler` - All tasks are executed on the current thread. Used by default.
/// - `threaded_scheduler` - Use multi-threaded scheduler (requires `rt-threaded` feature).
///
/// ## Usage
///
/// ### Select runtime
///
/// ```no_run
/// #[tokio::test(threaded_scheduler)]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### Using default
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::old::test(args, item)
}

/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `max_threads=n` - Sets max threads to `n`.
///
/// ## Usage
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
pub fn test_basic(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::test(args, item, false)
}

/// Implementation detail of the `select!` macro. This macro is **not** intended
/// to be used as part of the public API and is permitted to change.
#[proc_macro]
#[doc(hidden)]
pub fn select_priv_declare_output_enum(input: TokenStream) -> TokenStream {
    select::declare_output_enum(input)
}
<commit_msg>macros: document basic_scheduler option (#2697)<commit_after>#![doc(html_root_url = "https://docs.rs/tokio-macros/0.2.5")]
#![allow(clippy::needless_doctest_main)]
#![warn(
    missing_debug_implementations,
    missing_docs,
    rust_2018_idioms,
    unreachable_pub
)]
#![deny(intra_doc_link_resolution_failure)]
#![doc(test(
    no_crate_inject,
    attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
))]

//! Macros for use with Tokio

// This `extern` is required for older `rustc` versions but newer `rustc`
// versions warn about the unused `extern crate`.
#[allow(unused_extern_crates)]
extern crate proc_macro;

mod entry;
mod select;

use proc_macro::TokenStream;

/// Marks async function to be executed by selected runtime. This macro helps set up a `Runtime`
/// without requiring the user to use [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.builder.html) directly.
///
/// ## Options:
///
/// If you want to set the number of worker threads used for asynchronous code, use the
/// `core_threads` option.
///
/// - `core_threads=n` - Sets core threads to `n` (requires `rt-threaded` feature).
/// - `max_threads=n` - Sets max threads to `n` (requires `rt-core` or `rt-threaded` feature).
/// - `basic_scheduler` - Use the basic schduler (requires `rt-core`).
///
/// ## Function arguments:
///
/// Arguments are allowed for any functions aside from `main` which is special
///
/// ## Usage
///
/// ### Using default
///
/// ```rust
/// #[tokio::main]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .threaded_scheduler()
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### Using basic scheduler
///
/// The basic scheduler is single-threaded.
///
/// ```rust
/// #[tokio::main(basic_scheduler)]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .basic_scheduler()
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### Set number of core threads
///
/// ```rust
/// #[tokio::main(core_threads = 2)]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .threaded_scheduler()
///         .core_threads(2)
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::main(args, item, true)
}

/// Marks async function to be executed by selected runtime. This macro helps set up a `Runtime`
/// without requiring the user to use [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.builder.html) directly.
///
/// ## Options:
///
/// - `basic_scheduler` - All tasks are executed on the current thread.
/// - `threaded_scheduler` - Uses the multi-threaded scheduler. Used by default (requires `rt-threaded` feature).
///
/// ## Function arguments:
///
/// Arguments are allowed for any functions aside from `main` which is special
///
/// ## Usage
///
/// ### Using default
///
/// ```rust
/// #[tokio::main]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Runtime::new()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### Select runtime
///
/// ```rust
/// #[tokio::main(basic_scheduler)]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .basic_scheduler()
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::old::main(args, item)
}

/// Marks async function to be executed by selected runtime. This macro helps set up a `Runtime`
/// without requiring the user to use [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.builder.html) directly.
///
/// ## Options:
///
/// - `max_threads=n` - Sets max threads to `n`.
///
/// ## Function arguments:
///
/// Arguments are allowed for any functions aside from `main` which is special
///
/// ## Usage
///
/// ### Using default
///
/// ```rust
/// #[tokio::main]
/// async fn main() {
///     println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
///     tokio::runtime::Builder::new()
///         .basic_scheduler()
///         .enable_all()
///         .build()
///         .unwrap()
///         .block_on(async {
///             println!("Hello world");
///         })
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main_basic(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::main(args, item, false)
}

/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `core_threads=n` - Sets core threads to `n` (requires `rt-threaded` feature).
/// - `max_threads=n` - Sets max threads to `n` (requires `rt-core` or `rt-threaded` feature).
///
/// ## Usage
///
/// ### Select runtime
///
/// ```no_run
/// #[tokio::test(core_threads = 1)]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### Using default
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
pub fn test_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::test(args, item, true)
}

/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `basic_scheduler` - All tasks are executed on the current thread. Used by default.
/// - `threaded_scheduler` - Use multi-threaded scheduler (requires `rt-threaded` feature).
///
/// ## Usage
///
/// ### Select runtime
///
/// ```no_run
/// #[tokio::test(threaded_scheduler)]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### Using default
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::old::test(args, item)
}

/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `max_threads=n` - Sets max threads to `n`.
///
/// ## Usage
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
///     assert!(true);
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the tokio crate in your dependencies this macro
/// will not work. If you must rename the 0.2 version of tokio because
/// you're also using the 0.1 version of tokio, you _must_ make the
/// tokio 0.2 crate available as `tokio` in the module where this
/// macro is expanded.
#[proc_macro_attribute]
pub fn test_basic(args: TokenStream, item: TokenStream) -> TokenStream {
    entry::test(args, item, false)
}

/// Implementation detail of the `select!` macro. This macro is **not** intended
/// to be used as part of the public API and is permitted to change.
#[proc_macro]
#[doc(hidden)]
pub fn select_priv_declare_output_enum(input: TokenStream) -> TokenStream {
    select::declare_output_enum(input)
}
<|endoftext|>


<commit_before><commit_msg>Add padding to website footer bottom<commit_after><|endoftext|>