<commit_before>#[macro_use]
extern crate pink_spider;
use pink_spider::youtube;
use pink_spider::soundcloud;
use pink_spider::spotify;
use pink_spider::model::{Model, Enclosure, Playlist, Provider};
use pink_spider::model::{conn};
use std::time::Duration;
use std::thread;

pub fn main() {
    let conn = conn().unwrap();
    let stmt = conn.prepare(
        &format!("SELECT {} FROM playlists WHERE playlists.provider = 'Spotify' AND playlists.description IS NULL ORDER BY playlists.published_at DESC", Playlist::props_str(""))).unwrap();
    let rows = stmt.query(&[]).unwrap();
    let playlists = Playlist::rows_to_items(rows);
    println!("len {}\n", playlists.len());
    for mut playlist in playlists {
        thread::sleep(Duration::from_millis(500));
        playlist.fetch_props();
        println!("description {:?}", playlist.description);
        match playlist.save() {
            Ok(_) => {
                print!("playlist id: {} {}:{} state: {:?} is updated\n", playlist.id, playlist.provider, playlist.identifier, playlist.state);
            },
            Err(e) => {
                print!("Failed to update playlist id: {} {}:{}\n", playlist.id, playlist.provider, playlist.identifier);
                print!("{}\n", e);
            },
        }
    }
}
<commit_msg>Prevent warnings of update_playlists<commit_after>extern crate pink_spider;
use pink_spider::model::{Model, Enclosure, Playlist};
use pink_spider::model::{conn};
use std::time::Duration;
use std::thread;

pub fn main() {
    let conn = conn().unwrap();
    let stmt = conn.prepare(
        &format!("SELECT {} FROM playlists WHERE playlists.provider = 'Spotify' AND playlists.description IS NULL ORDER BY playlists.published_at DESC", Playlist::props_str(""))).unwrap();
    let rows = stmt.query(&[]).unwrap();
    let playlists = Playlist::rows_to_items(rows);
    println!("len {}\n", playlists.len());
    for mut playlist in playlists {
        thread::sleep(Duration::from_millis(500));
        playlist.fetch_props();
        println!("description {:?}", playlist.description);
        match playlist.save() {
            Ok(_) => {
                print!("playlist id: {} {}:{} state: {:?} is updated\n", playlist.id, playlist.provider, playlist.identifier, playlist.state);
            },
            Err(e) => {
                print!("Failed to update playlist id: {} {}:{}\n", playlist.id, playlist.provider, playlist.identifier);
                print!("{}\n", e);
            },
        }
    }
}
<|endoftext|>


<commit_before>use euler;

import iter::*;
import euler::prime;

fn gen_triangles(&trigs: [uint]) {
    alt vec::len(trigs) {
      0u { trigs = [1u]; }
      x  { trigs += [trigs[x - 1u] + x + 1u]; }
    }
}

fn num_factors(num: u64, primes: prime::prime) -> u64 {
    let mut prod = 1u;
    prime::factors(num, primes) { |f|
        let (_base, exp): (u64, i64) = f;
        prod *= ((exp + 1) as u64)
    }
    ret prod;
}

fn main() {
    let primes = prime::prime();
    let mut trigs  = [];
    while true {
        gen_triangles(trigs);
        let t = vec::last(trigs);
        let num = num_factors(t, primes);
        if num > 500u {
            io::println(#fmt("%u -> %u", t, num_factors(t, primes)));
            break;
        }
    }
}
<commit_msg>Modify methods for generating triangle numbers.<commit_after>use euler;

import euler::prime;

fn each_triangles(f: fn(&&uint) -> bool) {
    let mut idx = 0u;
    let mut t   = 1u;
    loop {
        if !f(t) {
            break;
        }
        idx += 1u;
        t   += idx + 1u;
    }
}

fn num_factors(num: u64, primes: prime::prime) -> u64 {
    let mut prod = 1u;
    prime::factors(num, primes) { |f|
        let (_base, exp): (u64, i64) = f;
        prod *= ((exp + 1) as u64)
    }
    ret prod;
}

fn main() {
    let primes = prime::prime();
    for each_triangles {|t|
        let num = num_factors(t, primes);
        if num > 500u {
            io::println(#fmt("%u -> %u", t, num_factors(t, primes)));
            break;
        }
    }
}
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::prelude::*;
use std::env;
use std::process;

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() < 2 {
        println!("No file was passed in to be parsed");
        process::exit(1);
    }

    let mut f = File::open(&args[1]).unwrap();
    let mut instructions = String::new();
    f.read_to_string(&mut instructions).unwrap();
    let final_floor = process_instructions(instructions);

    println!("Santa ends up on floor {}", final_floor);
}

fn process_instructions(ins: String) -> i32{
    let mut floor = 0;

    for c in ins.chars() {
        match c {
            '(' => { floor += 1; },
            ')' => { floor -= 1; },
            _ => {}
        }
    }
    floor
}

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

    #[test]
    fn test_process() {
        assert_eq!(process_instructions(String::from("((()))")), 0);
        assert_eq!(process_instructions(String::from(")))(((")), 0);
        assert_eq!(process_instructions(String::from("()()()")), 0);
        assert_eq!(process_instructions(String::from("((())")), 1);
        assert_eq!(process_instructions(String::from("(()))")), -1);
        assert_eq!(process_instructions(String::from("(((((")), 5);
        assert_eq!(process_instructions(String::from(")))))")), -5);
    }
}
<commit_msg>Finish part 2 of day 1<commit_after>use std::fs::File;
use std::io::prelude::*;
use std::env;
use std::process;

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() < 2 {
        println!("No file was passed in to be parsed");
        process::exit(1);
    }

    let mut f = File::open(&args[1]).unwrap();
    let mut instructions = String::new();
    f.read_to_string(&mut instructions).unwrap();
    let final_floor = process_instructions(&instructions);

    let first_basement = find_first_basement(&instructions);

    println!("Santa ends up on floor {}", final_floor);
    println!("Entered basement for the first time at position {}",
             first_basement)
}

fn process_instructions(ins: &String) -> i32{
    let mut floor = 0;

    for c in ins.chars() {
        match c {
            '(' => { floor += 1; },
            ')' => { floor -= 1; },
            _ => {}
        }
    }
    floor
}

fn find_first_basement(ins: &String) -> i32 {
    let mut floor = 0;
    let mut pos = 1;

    for c in ins.chars() {
        match c {
            '(' => { floor += 1; },
            ')' => { floor -= 1; },
            _ => {}
        }

        if floor == -1 {
            return pos;
        }

        pos += 1;
    }

    pos
}

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

    #[test]
    fn test_process() {
        assert_eq!(process_instructions(&String::from("((()))")), 0);
        assert_eq!(process_instructions(&String::from(")))(((")), 0);
        assert_eq!(process_instructions(&String::from("()()()")), 0);
        assert_eq!(process_instructions(&String::from("((())")), 1);
        assert_eq!(process_instructions(&String::from("(()))")), -1);
        assert_eq!(process_instructions(&String::from("(((((")), 5);
        assert_eq!(process_instructions(&String::from(")))))")), -5);
    }

    #[test]
    fn test_first_basement() {
        let cases: Vec<(String, i32)> = vec![
            (String::from(")"), 1),
            (String::from("(()))"), 5),
            (String::from("()())"), 5),
            (String::from("(()(())))"), 9),
            (String::from("())"), 3),
        ];

        for case in cases {
            assert_eq!(find_first_basement(&case.0), case.1);
        }
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

use crate::WatchmanFile;
use log::debug;
use serde_bser::value::Value;
use std::process::Command;
use watchman_client::prelude::*;
use watchman_client::{Subscription as WatchmanSubscription, SubscriptionData};

#[derive(Debug)]
pub enum WatchmanFileSourceSubscriptionNextChange {
    Result(WatchmanFileSourceResult),
    /// This value indicated the beginning of the source control update.
    /// We may stop the compilation process and wait for the next event.
    SourceControlUpdateEnter,
    /// If source control update has not changed the base revision of the commit
    /// We may continue the `watch(...)` loop of the compiler, expecting to receive
    /// a `Result` event after `SourceControlUpdateLeave`.
    SourceControlUpdateLeave,
    /// When source control update completed and we detected changed base revision,
    /// we may need to create a new compiler state.
    SourceControlUpdate,
    None,
}

#[derive(Debug)]
pub struct WatchmanFileSourceResult {
    pub files: Vec<WatchmanFile>,
    pub resolved_root: ResolvedRoot,
    pub clock: Clock,
    pub saved_state_info: Option<Value>,
}

pub struct WatchmanFileSourceSubscription {
    resolved_root: ResolvedRoot,
    subscription: WatchmanSubscription<WatchmanFile>,
    base_revision: String,
}

impl WatchmanFileSourceSubscription {
    pub fn new(
        resolved_root: ResolvedRoot,
        subscription: WatchmanSubscription<WatchmanFile>,
    ) -> Self {
        Self {
            resolved_root,
            subscription,
            base_revision: get_base_revision(None),
        }
    }

    /// Awaits changes from Watchman and provides the next set of changes
    /// if there were any changes to files
    pub async fn next_change(
        &mut self,
    ) -> Result<WatchmanFileSourceSubscriptionNextChange, watchman_client::Error> {
        match self.subscription.next().await? {
            SubscriptionData::FilesChanged(changes) => {
                if let Some(files) = changes.files {
                    debug!("number of files in this update: {}", files.len());
                    return Ok(WatchmanFileSourceSubscriptionNextChange::Result(
                        WatchmanFileSourceResult {
                            files,
                            resolved_root: self.resolved_root.clone(),
                            clock: changes.clock,
                            saved_state_info: None,
                        },
                    ));
                }
            }
            SubscriptionData::StateEnter { state_name, .. } => {
                if state_name == "hg.update" {
                    return Ok(WatchmanFileSourceSubscriptionNextChange::SourceControlUpdateEnter);
                }
            }
            SubscriptionData::StateLeave {
                state_name,
                metadata,
            } => {
                if state_name == "hg.update" {
                    let current_commit = if let Some(Value::ByteString(value)) = metadata {
                        Some(value.to_string())
                    } else {
                        None
                    };
                    let current_base_revision = get_base_revision(current_commit);
                    if current_base_revision != self.base_revision {
                        self.base_revision = current_base_revision;
                        return Ok(WatchmanFileSourceSubscriptionNextChange::SourceControlUpdate);
                    } else {
                        return Ok(
                            WatchmanFileSourceSubscriptionNextChange::SourceControlUpdateLeave,
                        );
                    }
                }
            }
            SubscriptionData::Canceled => {
                return Err(watchman_client::Error::WatchmanResponseError {
                    message: String::from("Watchman subscription canceled"),
                });
            }
        }
        Ok(WatchmanFileSourceSubscriptionNextChange::None)
    }
}

/// Base revision in this case is a common ancestor of two revisions:
/// `master` and current commit hash or `.`
///
/// TODO: Make this dynamic on the default branch name.
fn get_base_revision(commit_hash: Option<String>) -> String {
    let output = Command::new("hg")
        .arg("log".to_string())
        .arg("-r".to_string())
        .arg(format!(
            "ancestor(master, {})",
            commit_hash.unwrap_or_else(|| ".".to_string())
        ))
        .arg("-T={node}")
        .output()
        .expect("Expect `hg` command getting base revision.");

    if output.stdout.is_empty() {
        panic!(
            "Failed to get base revision hash:\n {:?}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    String::from_utf8_lossy(&output.stdout).to_string()
}
<commit_msg>Do not panic if `hg` command is not available<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

use crate::WatchmanFile;
use log::debug;
use serde_bser::value::Value;
use std::process::Command;
use watchman_client::prelude::*;
use watchman_client::{Subscription as WatchmanSubscription, SubscriptionData};

#[derive(Debug)]
pub enum WatchmanFileSourceSubscriptionNextChange {
    Result(WatchmanFileSourceResult),
    /// This value indicated the beginning of the source control update.
    /// We may stop the compilation process and wait for the next event.
    SourceControlUpdateEnter,
    /// If source control update has not changed the base revision of the commit
    /// We may continue the `watch(...)` loop of the compiler, expecting to receive
    /// a `Result` event after `SourceControlUpdateLeave`.
    SourceControlUpdateLeave,
    /// When source control update completed and we detected changed base revision,
    /// we may need to create a new compiler state.
    SourceControlUpdate,
    None,
}

#[derive(Debug)]
pub struct WatchmanFileSourceResult {
    pub files: Vec<WatchmanFile>,
    pub resolved_root: ResolvedRoot,
    pub clock: Clock,
    pub saved_state_info: Option<Value>,
}

pub struct WatchmanFileSourceSubscription {
    resolved_root: ResolvedRoot,
    subscription: WatchmanSubscription<WatchmanFile>,
    base_revision: Option<String>,
}

impl WatchmanFileSourceSubscription {
    pub fn new(
        resolved_root: ResolvedRoot,
        subscription: WatchmanSubscription<WatchmanFile>,
    ) -> Self {
        Self {
            resolved_root,
            subscription,
            base_revision: get_base_hg_revision(None),
        }
    }

    /// Awaits changes from Watchman and provides the next set of changes
    /// if there were any changes to files
    pub async fn next_change(
        &mut self,
    ) -> Result<WatchmanFileSourceSubscriptionNextChange, watchman_client::Error> {
        match self.subscription.next().await? {
            SubscriptionData::FilesChanged(changes) => {
                if let Some(files) = changes.files {
                    debug!("number of files in this update: {}", files.len());
                    return Ok(WatchmanFileSourceSubscriptionNextChange::Result(
                        WatchmanFileSourceResult {
                            files,
                            resolved_root: self.resolved_root.clone(),
                            clock: changes.clock,
                            saved_state_info: None,
                        },
                    ));
                }
            }
            SubscriptionData::StateEnter { state_name, .. } => {
                if state_name == "hg.update" {
                    return Ok(WatchmanFileSourceSubscriptionNextChange::SourceControlUpdateEnter);
                }
            }
            SubscriptionData::StateLeave {
                state_name,
                metadata,
            } => {
                if state_name == "hg.update" {
                    let current_commit = if let Some(Value::ByteString(value)) = metadata {
                        Some(value.to_string())
                    } else {
                        None
                    };
                    let current_base_revision = get_base_hg_revision(current_commit);
                    if current_base_revision != self.base_revision {
                        self.base_revision = current_base_revision;
                        return Ok(WatchmanFileSourceSubscriptionNextChange::SourceControlUpdate);
                    } else {
                        return Ok(
                            WatchmanFileSourceSubscriptionNextChange::SourceControlUpdateLeave,
                        );
                    }
                }
            }
            SubscriptionData::Canceled => {
                return Err(watchman_client::Error::WatchmanResponseError {
                    message: String::from("Watchman subscription canceled"),
                });
            }
        }
        Ok(WatchmanFileSourceSubscriptionNextChange::None)
    }
}

/// Base revision in this case is a common ancestor of two revisions:
/// `master` and current commit hash or `.`
///
/// TODO: Make this dynamic on the default branch name.
fn get_base_hg_revision(commit_hash: Option<String>) -> Option<String> {
    let output = Command::new("hg")
        .arg("log".to_string())
        .arg("-r".to_string())
        .arg(format!(
            "ancestor(master, {})",
            commit_hash.unwrap_or_else(|| ".".to_string())
        ))
        .arg("-T={node}")
        .output()
        .ok()?;

    if output.stdout.is_empty() {
        return None;
    }

    Some(String::from_utf8_lossy(&output.stdout).to_string())
}
<|endoftext|>


<commit_before>//! Name resolution algorithm
use rustc_hash::FxHashMap;

use ra_syntax::{
    SmolStr, SyntaxKind,
    ast::{self, NameOwner}
};

use crate::{
    loc2id::DefId,
    descriptors::module::ModuleId,
    syntax_ptr::LocalSyntaxPtr,
};

/// A set of items and imports declared inside a module, without relation to
/// other modules.
///
/// This stands in-between raw syntax and name resolution and alow us to avoid
/// recomputing name res: if `InputModuleItems` are the same, we can avoid
/// running name resolution.
#[derive(Debug, Default)]
struct InputModuleItems {
    items: Vec<ModuleItem>,
    glob_imports: Vec<Path>,
    imports: Vec<Path>,
}

#[derive(Debug, Clone)]
struct Path {
    kind: PathKind,
    segments: Vec<SmolStr>,
}

#[derive(Debug, Clone, Copy)]
enum PathKind {
    Abs,
    Self_,
    Super,
    Crate,
}

#[derive(Debug)]
struct ItemMap {
    per_module: FxHashMap<ModuleId, ModuleItems>,
}

#[derive(Debug)]
struct ModuleItems {
    items: FxHashMap<SmolStr, PerNs<DefId>>,
    import_resolutions: FxHashMap<LocalSyntaxPtr, DefId>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Namespace {
    Types,
    Values,
}

#[derive(Debug)]
struct PerNs<T> {
    types: Option<T>,
    values: Option<T>,
}

#[derive(Debug)]
struct ModuleItem {
    ptr: LocalSyntaxPtr,
    name: SmolStr,
    kind: SyntaxKind,
    vis: Vis,
}

#[derive(Debug)]
enum Vis {
    Priv,
    Other,
}

impl InputModuleItems {
    fn new<'a>(items: impl Iterator<Item = ast::ModuleItem<'a>>) -> InputModuleItems {
        let mut res = InputModuleItems::default();
        for item in items {
            res.add_item(item);
        }
        res
    }

    fn add_item(&mut self, item: ast::ModuleItem) -> Option<()> {
        match item {
            ast::ModuleItem::StructDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::EnumDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::FnDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::TraitDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::TypeDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::ImplItem(it) => {
                // impls don't define items
            }
            ast::ModuleItem::UseItem(it) => self.add_use_item(it),
            ast::ModuleItem::ExternCrateItem(it) => (),
            ast::ModuleItem::ConstDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::StaticDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::Module(it) => self.items.push(ModuleItem::new(it)?),
        }
        Some(())
    }

    fn add_use_item(&mut self, item: ast::UseItem) {
        if let Some(tree) = item.use_tree() {
            self.add_use_tree(None, tree);
        }
    }

    fn add_use_tree(&mut self, prefix: Option<Path>, tree: ast::UseTree) {
        if let Some(use_tree_list) = tree.use_tree_list() {
            let prefix = match tree.path() {
                None => prefix,
                Some(path) => match convert_path(prefix, path) {
                    Some(it) => Some(it),
                    None => return, // TODO: report errors somewhere
                },
            };
            for tree in use_tree_list.use_trees() {
                self.add_use_tree(prefix.clone(), tree);
            }
        } else {
            if let Some(path) = tree.path() {
                if let Some(path) = convert_path(prefix, path) {
                    if tree.has_star() {
                        &mut self.glob_imports
                    } else {
                        &mut self.imports
                    }
                    .push(path);
                }
            }
        }
    }
}

fn convert_path(prefix: Option<Path>, path: ast::Path) -> Option<Path> {
    let prefix = if let Some(qual) = path.qualifier() {
        Some(convert_path(prefix, qual)?)
    } else {
        None
    };
    let segment = path.segment()?;
    let res = match segment.kind()? {
        ast::PathSegmentKind::Name(name) => {
            let mut res = prefix.unwrap_or_else(|| Path {
                kind: PathKind::Abs,
                segments: Vec::with_capacity(1),
            });
            res.segments.push(name.text());
            res
        }
        ast::PathSegmentKind::CrateKw => {
            if prefix.is_some() {
                return None;
            }
            Path {
                kind: PathKind::Crate,
                segments: Vec::new(),
            }
        }
        ast::PathSegmentKind::SelfKw => {
            if prefix.is_some() {
                return None;
            }
            Path {
                kind: PathKind::Self_,
                segments: Vec::new(),
            }
        }
        ast::PathSegmentKind::SuperKw => {
            if prefix.is_some() {
                return None;
            }
            Path {
                kind: PathKind::Super,
                segments: Vec::new(),
            }
        }
    };
    Some(res)
}

impl ModuleItem {
    fn new<'a>(item: impl ast::NameOwner<'a>) -> Option<ModuleItem> {
        let name = item.name()?.text();
        let ptr = LocalSyntaxPtr::new(item.syntax());
        let kind = item.syntax().kind();
        let vis = Vis::Other;
        let res = ModuleItem {
            ptr,
            name,
            kind,
            vis,
        };
        Some(res)
    }
}

struct Resolver {
    input: FxHashMap<ModuleId, InputModuleItems>,
    result: ModuleItems,
}

impl Resolver {
    fn resolve(&mut self){

    }
}
<commit_msg>remember spans with paths<commit_after>//! Name resolution algorithm
use rustc_hash::FxHashMap;

use ra_syntax::{
    SmolStr, SyntaxKind,
    ast::{self, NameOwner, AstNode}
};

use crate::{
    loc2id::DefId,
    descriptors::module::ModuleId,
    syntax_ptr::LocalSyntaxPtr,
};

/// A set of items and imports declared inside a module, without relation to
/// other modules.
///
/// This stands in-between raw syntax and name resolution and alow us to avoid
/// recomputing name res: if `InputModuleItems` are the same, we can avoid
/// running name resolution.
#[derive(Debug, Default)]
struct InputModuleItems {
    items: Vec<ModuleItem>,
    glob_imports: Vec<Path>,
    imports: Vec<Path>,
}

#[derive(Debug, Clone)]
struct Path {
    kind: PathKind,
    segments: Vec<(LocalSyntaxPtr, SmolStr)>,
}

#[derive(Debug, Clone, Copy)]
enum PathKind {
    Abs,
    Self_,
    Super,
    Crate,
}

#[derive(Debug)]
struct ItemMap {
    per_module: FxHashMap<ModuleId, ModuleItems>,
}

#[derive(Debug)]
struct ModuleItems {
    items: FxHashMap<SmolStr, PerNs<DefId>>,
    import_resolutions: FxHashMap<LocalSyntaxPtr, DefId>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Namespace {
    Types,
    Values,
}

#[derive(Debug)]
struct PerNs<T> {
    types: Option<T>,
    values: Option<T>,
}

#[derive(Debug)]
struct ModuleItem {
    ptr: LocalSyntaxPtr,
    name: SmolStr,
    kind: SyntaxKind,
    vis: Vis,
}

#[derive(Debug)]
enum Vis {
    Priv,
    Other,
}

impl InputModuleItems {
    fn new<'a>(items: impl Iterator<Item = ast::ModuleItem<'a>>) -> InputModuleItems {
        let mut res = InputModuleItems::default();
        for item in items {
            res.add_item(item);
        }
        res
    }

    fn add_item(&mut self, item: ast::ModuleItem) -> Option<()> {
        match item {
            ast::ModuleItem::StructDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::EnumDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::FnDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::TraitDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::TypeDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::ImplItem(it) => {
                // impls don't define items
            }
            ast::ModuleItem::UseItem(it) => self.add_use_item(it),
            ast::ModuleItem::ExternCrateItem(it) => (),
            ast::ModuleItem::ConstDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::StaticDef(it) => self.items.push(ModuleItem::new(it)?),
            ast::ModuleItem::Module(it) => self.items.push(ModuleItem::new(it)?),
        }
        Some(())
    }

    fn add_use_item(&mut self, item: ast::UseItem) {
        if let Some(tree) = item.use_tree() {
            self.add_use_tree(None, tree);
        }
    }

    fn add_use_tree(&mut self, prefix: Option<Path>, tree: ast::UseTree) {
        if let Some(use_tree_list) = tree.use_tree_list() {
            let prefix = match tree.path() {
                None => prefix,
                Some(path) => match convert_path(prefix, path) {
                    Some(it) => Some(it),
                    None => return, // TODO: report errors somewhere
                },
            };
            for tree in use_tree_list.use_trees() {
                self.add_use_tree(prefix.clone(), tree);
            }
        } else {
            if let Some(path) = tree.path() {
                if let Some(path) = convert_path(prefix, path) {
                    if tree.has_star() {
                        &mut self.glob_imports
                    } else {
                        &mut self.imports
                    }
                    .push(path);
                }
            }
        }
    }
}

fn convert_path(prefix: Option<Path>, path: ast::Path) -> Option<Path> {
    let prefix = if let Some(qual) = path.qualifier() {
        Some(convert_path(prefix, qual)?)
    } else {
        None
    };
    let segment = path.segment()?;
    let res = match segment.kind()? {
        ast::PathSegmentKind::Name(name) => {
            let mut res = prefix.unwrap_or_else(|| Path {
                kind: PathKind::Abs,
                segments: Vec::with_capacity(1),
            });
            let ptr = LocalSyntaxPtr::new(name.syntax());
            res.segments.push((ptr, name.text()));
            res
        }
        ast::PathSegmentKind::CrateKw => {
            if prefix.is_some() {
                return None;
            }
            Path {
                kind: PathKind::Crate,
                segments: Vec::new(),
            }
        }
        ast::PathSegmentKind::SelfKw => {
            if prefix.is_some() {
                return None;
            }
            Path {
                kind: PathKind::Self_,
                segments: Vec::new(),
            }
        }
        ast::PathSegmentKind::SuperKw => {
            if prefix.is_some() {
                return None;
            }
            Path {
                kind: PathKind::Super,
                segments: Vec::new(),
            }
        }
    };
    Some(res)
}

impl ModuleItem {
    fn new<'a>(item: impl ast::NameOwner<'a>) -> Option<ModuleItem> {
        let name = item.name()?.text();
        let ptr = LocalSyntaxPtr::new(item.syntax());
        let kind = item.syntax().kind();
        let vis = Vis::Other;
        let res = ModuleItem {
            ptr,
            name,
            kind,
            vis,
        };
        Some(res)
    }
}

struct Resolver {
    input: FxHashMap<ModuleId, InputModuleItems>,
    result: ModuleItems,
}

impl Resolver {
    fn resolve(&mut self){

    }
}
<|endoftext|>


<commit_before>
use prelude::*;
use super::common::*;

use std::iter;

use idents;
use utils;
use tyhandlers::{Direction, ModelTypeSystem};
use model;
use methodinfo::ComMethodInfo;

extern crate proc_macro;
use syn::*;

/// Interface level output.
#[derive(Default)]
struct InterfaceOutput {
    iid_arms : Vec<TokenStream>,
}

/// Expands the `com_interface` attribute.
///
/// The attribute expansion results in the following items:
///
/// - Global IID for the interface.
/// - Virtual table struct definition for the interface.
/// - Implementation for the delegating methods when calling the COM interface
///   from Rust.
pub fn expand_com_interface(
    attr_tokens: TokenStreamNightly,
    item_tokens: TokenStreamNightly,
) -> Result<TokenStreamNightly, model::ParseError>
{
    // Parse the attribute.
    let mut output = vec![];
    let itf = model::ComInterface::parse(
            &lib_name(),
            attr_tokens.into(),
            &item_tokens.to_string() )?;
    let itf_ident = itf.name();

    let mut itf_output = InterfaceOutput::default();
    for ( &ts, itf_variant ) in itf.variants() {
        process_itf_variant(
                &itf, ts, itf_variant,
                &mut output, &mut itf_output );
    }

    // Implement the ComInterface for the trait.
    let iid_arms = itf_output.iid_arms;
    let ( deref_impl, deref_ret ) = if itf.item_type() == utils::InterfaceType::Trait {
        ( quote!( com_itf ), quote!( &( #itf_ident + 'static ) ) )
    } else {
        ( quote!( panic!( "Cannot deref into struct-interface" ) ),
            quote!( & #itf_ident ) )
    };
    output.push( quote!(
        impl ::intercom::ComInterface for #itf_ident {

            #[doc = "Returns the IID of the requested interface."]
            fn iid( ts : TypeSystem ) -> Option< &'static ::intercom::IID > {
                match ts {
                    #( #iid_arms ),*
                }
            }

            fn deref(
                com_itf : &ComItf< #itf_ident >
            ) -> #deref_ret {
                #deref_impl
            }
        }
    ) );

    Ok( tokens_to_tokenstream( item_tokens, output ) )
}

/// Processes the interface type system variant.
///
/// # Arguments
///
/// * `itf` - Interface details.
/// * `ts` - Type system the variant represents.
/// * `itf_variant` - Interface variant details.
/// * `output` - Direct output emitted for each interface variant.
/// * `itf_output` - Interface variant data for the interface level output.
fn process_itf_variant(
    itf : &model::ComInterface,
    ts : ModelTypeSystem,
    itf_variant : &model::ComInterfaceVariant,
    output : &mut Vec<TokenStream>,
    itf_output : &mut InterfaceOutput,
) {

    let itf_ident = itf.name();
    let visibility = itf.visibility();
    let iid_ident = idents::iid( itf_variant.unique_name() );
    let vtable_ident = idents::vtable_struct( itf_variant.unique_name() );

    // IID_IInterface GUID.
    let iid_tokens = utils::get_guid_tokens( itf_variant.iid() );
    let iid_doc = format!( "`{}` interface ID.", itf_ident );
    output.push( quote!(
        #[doc = #iid_doc]
        #[allow(non_upper_case_globals)]
        #visibility const #iid_ident : ::intercom::IID = #iid_tokens;
    ) );

    // Construct the iid(ts) match arm for this type system.
    let ts_match = ts.as_typesystem_tokens();
    itf_output.iid_arms.push( quote!( #ts_match => Some( & #iid_ident ) ) );

    // Create a vector for the virtual table fields and insert the base
    // interface virtual table in it if required.
    let mut vtbl_fields = vec![];
    if let Some( ref base ) = *itf.base_interface() {
        let vtbl = match base.to_string().as_ref() {
            "IUnknown" => quote!( ::intercom::IUnknownVtbl ),
            _ => { let vtbl = idents::vtable_struct( &base ); quote!( #vtbl ) }
        };
        vtbl_fields.push( quote!( pub __base : #vtbl ) );
    }

    // Gather all the trait methods for the remaining vtable fields.
    let calling_convention = get_calling_convetion();
    for method_info in itf_variant.methods() {

        let method_ident = &method_info.unique_name;
        let in_out_args = method_info.raw_com_args()
                .into_iter()
                .map( |com_arg| {
                    let name = &com_arg.name;
                    let com_ty = &com_arg.handler.com_ty();
                    let dir = match com_arg.dir {
                        Direction::In => quote!(),
                        Direction::Out | Direction::Retval => quote!( *mut )
                    };
                    quote!( #name : #dir #com_ty )
                } );
        let self_arg = quote!( self_vtable : ::intercom::RawComPtr );
        let args = iter::once( self_arg ).chain( in_out_args );

        // Create the vtable field and add it to the vector of fields.
        let ret_ty = method_info.returnhandler.com_ty();
        vtbl_fields.push( quote!(
            pub #method_ident :
                unsafe extern #calling_convention fn( #( #args ),* ) -> #ret_ty
        ) );
    }

    // Create the vtable. We've already gathered all the vtable method
    // pointer fields so defining the struct is simple enough.
    output.push( quote!(
        #[allow(non_camel_case_types)]
        #[repr(C)]
        #[doc(hidden)]
        #visibility struct #vtable_ident { #( #vtbl_fields, )* }
    ) );

    // COM delegation implementation for COM traits.
    //
    // This is done only for the primary interface, whic is currently always the Automation
    // interface.
    if ts == ModelTypeSystem::Automation &&
        itf.item_type() == utils::InterfaceType::Trait {

        // Gather method implementations.
        let impls = itf_variant.methods().iter()
                .map( |m| rust_to_com_delegate( m, &vtable_ident ) );

        let unsafety = if itf.is_unsafe() { quote!( unsafe ) } else { quote!() };
        output.push( quote!(
            #unsafety impl #itf_ident for ::intercom::ComItf< #itf_ident > {
                #( #impls )*
            }
        ) );
    }
}

/// Creates the functions responsible for delegating calls from Rust to COM
/// interfaces.
///
/// # Arguments
///
/// * `method_info` - Method to delegate.
/// * `vtable_ident` - Vtable to use for the delegation.
fn rust_to_com_delegate(
    method_info : &ComMethodInfo,
    vtable_ident : &Ident,
) -> TokenStream {

    // Format the method arguments into tokens.
    let impl_args = method_info.args.iter().map( |ca| {
        let name = &ca.name;
        let ty = &ca.ty;
        quote!( #name : #ty )
    } );

    // The COM out-arguments that mirror the Rust return value will
    // require temporary variables during the COM call. Format their
    // declarations.
    let out_arg_declarations = method_info.returnhandler.com_out_args()
            .iter()
            .map( |ca| {
                let ident = &ca.name;
                let ty = &ca.handler.com_ty();
                let default = ca.handler.default_value();
                quote!( let mut #ident : #ty = #default; )
            } ).collect::<Vec<_>>();

    // Format the in and out parameters for the COM call.
    let ( temporaries, params ) : ( Vec<_>, Vec<_> ) = method_info.raw_com_args()
            .into_iter()
            .map( |com_arg| {
                let name = com_arg.name;
                match com_arg.dir {
                    Direction::In => {
                        let param = com_arg.handler.rust_to_com( &name );
                        ( param.temporary, param.value )
                    },
                    Direction::Out | Direction::Retval
                        => ( None, quote!( &mut #name ) ),
                }
            } )
            .unzip();

    // Combine the parameters into the final parameter list.
    // This includes the 'this' pointer and both the IN and OUT
    // parameters.
    let params = iter::once( quote!( comptr.ptr ) ).chain( params );

    // Create the return statement.
    let return_ident = Ident::new( "__result", Span::call_site() );
    let return_statement = method_info
            .returnhandler
            .com_to_rust_return( &return_ident );

    // Resolve some of the fields needed for quote.
    let method_ident = &method_info.unique_name;
    let method_rust_ident = &method_info.display_name;
    let self_arg = &method_info.rust_self_arg;
    let return_ty = &method_info.rust_return_ty;
    let unsafety = if method_info.is_unsafe { quote!( unsafe ) } else { quote!() };

    // Construct the final method.
    quote!(
        #unsafety fn #method_rust_ident(
            #self_arg, #( #impl_args ),*
        ) -> #return_ty
        {
            #[allow(unused_imports)]
            use ::intercom::ComInto;

            let comptr = ::intercom::ComItf::ptr( self, ::intercom::TypeSystem::Automation );
            let vtbl = comptr.ptr as *const *const #vtable_ident;

            #( #temporaries )*

            // Use an IIFE to act as a try/catch block. The various template
            // substitutions might end up using ?'s for error handling. The IIFE allows
            // us to handle the results here immediately.
            #[allow(unused_unsafe)]  // The fn itself _might_ be unsafe.
            let result : Result< #return_ty, ::intercom::ComError > = ( || unsafe {
                #( #out_arg_declarations )*;
                let #return_ident = ((**vtbl).#method_ident)( #( #params ),* );

                Ok( { #return_statement } )
            } )();

            #[allow(unused_imports)]
            use ::intercom::ErrorValue;
            match result {
                Ok( v ) => v,
                Err( err ) => < #return_ty as ErrorValue >::from_error(
                        ::intercom::return_hresult( err ) ),
            }
        }
    )
}
<commit_msg>Make com_interface emitted type refs into absolute<commit_after>
use prelude::*;
use super::common::*;

use std::iter;

use idents;
use utils;
use tyhandlers::{Direction, ModelTypeSystem};
use model;
use methodinfo::ComMethodInfo;

extern crate proc_macro;
use syn::*;

/// Interface level output.
#[derive(Default)]
struct InterfaceOutput {
    iid_arms : Vec<TokenStream>,
}

/// Expands the `com_interface` attribute.
///
/// The attribute expansion results in the following items:
///
/// - Global IID for the interface.
/// - Virtual table struct definition for the interface.
/// - Implementation for the delegating methods when calling the COM interface
///   from Rust.
pub fn expand_com_interface(
    attr_tokens: TokenStreamNightly,
    item_tokens: TokenStreamNightly,
) -> Result<TokenStreamNightly, model::ParseError>
{
    // Parse the attribute.
    let mut output = vec![];
    let itf = model::ComInterface::parse(
            &lib_name(),
            attr_tokens.into(),
            &item_tokens.to_string() )?;
    let itf_ident = itf.name();

    let mut itf_output = InterfaceOutput::default();
    for ( &ts, itf_variant ) in itf.variants() {
        process_itf_variant(
                &itf, ts, itf_variant,
                &mut output, &mut itf_output );
    }

    // Implement the ComInterface for the trait.
    let iid_arms = itf_output.iid_arms;
    let ( deref_impl, deref_ret ) = if itf.item_type() == utils::InterfaceType::Trait {
        ( quote!( com_itf ), quote!( &( #itf_ident + 'static ) ) )
    } else {
        ( quote!( panic!( "Cannot deref into struct-interface" ) ),
            quote!( & #itf_ident ) )
    };
    output.push( quote!(
        impl ::intercom::ComInterface for #itf_ident {

            #[doc = "Returns the IID of the requested interface."]
            fn iid( ts : ::intercom::TypeSystem ) -> Option< &'static ::intercom::IID > {
                match ts {
                    #( #iid_arms ),*
                }
            }

            fn deref(
                com_itf : &::intercom::ComItf< #itf_ident >
            ) -> #deref_ret {
                #deref_impl
            }
        }
    ) );

    Ok( tokens_to_tokenstream( item_tokens, output ) )
}

/// Processes the interface type system variant.
///
/// # Arguments
///
/// * `itf` - Interface details.
/// * `ts` - Type system the variant represents.
/// * `itf_variant` - Interface variant details.
/// * `output` - Direct output emitted for each interface variant.
/// * `itf_output` - Interface variant data for the interface level output.
fn process_itf_variant(
    itf : &model::ComInterface,
    ts : ModelTypeSystem,
    itf_variant : &model::ComInterfaceVariant,
    output : &mut Vec<TokenStream>,
    itf_output : &mut InterfaceOutput,
) {

    let itf_ident = itf.name();
    let visibility = itf.visibility();
    let iid_ident = idents::iid( itf_variant.unique_name() );
    let vtable_ident = idents::vtable_struct( itf_variant.unique_name() );

    // IID_IInterface GUID.
    let iid_tokens = utils::get_guid_tokens( itf_variant.iid() );
    let iid_doc = format!( "`{}` interface ID.", itf_ident );
    output.push( quote!(
        #[doc = #iid_doc]
        #[allow(non_upper_case_globals)]
        #visibility const #iid_ident : ::intercom::IID = #iid_tokens;
    ) );

    // Construct the iid(ts) match arm for this type system.
    let ts_match = ts.as_typesystem_tokens();
    itf_output.iid_arms.push( quote!( #ts_match => Some( & #iid_ident ) ) );

    // Create a vector for the virtual table fields and insert the base
    // interface virtual table in it if required.
    let mut vtbl_fields = vec![];
    if let Some( ref base ) = *itf.base_interface() {
        let vtbl = match base.to_string().as_ref() {
            "IUnknown" => quote!( ::intercom::IUnknownVtbl ),
            _ => { let vtbl = idents::vtable_struct( &base ); quote!( #vtbl ) }
        };
        vtbl_fields.push( quote!( pub __base : #vtbl ) );
    }

    // Gather all the trait methods for the remaining vtable fields.
    let calling_convention = get_calling_convetion();
    for method_info in itf_variant.methods() {

        let method_ident = &method_info.unique_name;
        let in_out_args = method_info.raw_com_args()
                .into_iter()
                .map( |com_arg| {
                    let name = &com_arg.name;
                    let com_ty = &com_arg.handler.com_ty();
                    let dir = match com_arg.dir {
                        Direction::In => quote!(),
                        Direction::Out | Direction::Retval => quote!( *mut )
                    };
                    quote!( #name : #dir #com_ty )
                } );
        let self_arg = quote!( self_vtable : ::intercom::RawComPtr );
        let args = iter::once( self_arg ).chain( in_out_args );

        // Create the vtable field and add it to the vector of fields.
        let ret_ty = method_info.returnhandler.com_ty();
        vtbl_fields.push( quote!(
            pub #method_ident :
                unsafe extern #calling_convention fn( #( #args ),* ) -> #ret_ty
        ) );
    }

    // Create the vtable. We've already gathered all the vtable method
    // pointer fields so defining the struct is simple enough.
    output.push( quote!(
        #[allow(non_camel_case_types)]
        #[repr(C)]
        #[doc(hidden)]
        #visibility struct #vtable_ident { #( #vtbl_fields, )* }
    ) );

    // COM delegation implementation for COM traits.
    //
    // This is done only for the primary interface, whic is currently always the Automation
    // interface.
    if ts == ModelTypeSystem::Automation &&
        itf.item_type() == utils::InterfaceType::Trait {

        // Gather method implementations.
        let impls = itf_variant.methods().iter()
                .map( |m| rust_to_com_delegate( m, &vtable_ident ) );

        let unsafety = if itf.is_unsafe() { quote!( unsafe ) } else { quote!() };
        output.push( quote!(
            #unsafety impl #itf_ident for ::intercom::ComItf< #itf_ident > {
                #( #impls )*
            }
        ) );
    }
}

/// Creates the functions responsible for delegating calls from Rust to COM
/// interfaces.
///
/// # Arguments
///
/// * `method_info` - Method to delegate.
/// * `vtable_ident` - Vtable to use for the delegation.
fn rust_to_com_delegate(
    method_info : &ComMethodInfo,
    vtable_ident : &Ident,
) -> TokenStream {

    // Format the method arguments into tokens.
    let impl_args = method_info.args.iter().map( |ca| {
        let name = &ca.name;
        let ty = &ca.ty;
        quote!( #name : #ty )
    } );

    // The COM out-arguments that mirror the Rust return value will
    // require temporary variables during the COM call. Format their
    // declarations.
    let out_arg_declarations = method_info.returnhandler.com_out_args()
            .iter()
            .map( |ca| {
                let ident = &ca.name;
                let ty = &ca.handler.com_ty();
                let default = ca.handler.default_value();
                quote!( let mut #ident : #ty = #default; )
            } ).collect::<Vec<_>>();

    // Format the in and out parameters for the COM call.
    let ( temporaries, params ) : ( Vec<_>, Vec<_> ) = method_info.raw_com_args()
            .into_iter()
            .map( |com_arg| {
                let name = com_arg.name;
                match com_arg.dir {
                    Direction::In => {
                        let param = com_arg.handler.rust_to_com( &name );
                        ( param.temporary, param.value )
                    },
                    Direction::Out | Direction::Retval
                        => ( None, quote!( &mut #name ) ),
                }
            } )
            .unzip();

    // Combine the parameters into the final parameter list.
    // This includes the 'this' pointer and both the IN and OUT
    // parameters.
    let params = iter::once( quote!( comptr.ptr ) ).chain( params );

    // Create the return statement.
    let return_ident = Ident::new( "__result", Span::call_site() );
    let return_statement = method_info
            .returnhandler
            .com_to_rust_return( &return_ident );

    // Resolve some of the fields needed for quote.
    let method_ident = &method_info.unique_name;
    let method_rust_ident = &method_info.display_name;
    let self_arg = &method_info.rust_self_arg;
    let return_ty = &method_info.rust_return_ty;
    let unsafety = if method_info.is_unsafe { quote!( unsafe ) } else { quote!() };

    // Construct the final method.
    quote!(
        #unsafety fn #method_rust_ident(
            #self_arg, #( #impl_args ),*
        ) -> #return_ty
        {
            #[allow(unused_imports)]
            use ::intercom::ComInto;

            let comptr = ::intercom::ComItf::ptr( self, ::intercom::TypeSystem::Automation );
            let vtbl = comptr.ptr as *const *const #vtable_ident;

            #( #temporaries )*

            // Use an IIFE to act as a try/catch block. The various template
            // substitutions might end up using ?'s for error handling. The IIFE allows
            // us to handle the results here immediately.
            #[allow(unused_unsafe)]  // The fn itself _might_ be unsafe.
            let result : Result< #return_ty, ::intercom::ComError > = ( || unsafe {
                #( #out_arg_declarations )*;
                let #return_ident = ((**vtbl).#method_ident)( #( #params ),* );

                Ok( { #return_statement } )
            } )();

            #[allow(unused_imports)]
            use ::intercom::ErrorValue;
            match result {
                Ok( v ) => v,
                Err( err ) => < #return_ty as ErrorValue >::from_error(
                        ::intercom::return_hresult( err ) ),
            }
        }
    )
}
<|endoftext|>


<commit_before>extern crate cc;
extern crate vcpkg;

fn main() {
    //vcpkg::find_package("harfbuzz").unwrap();
    let libs = vcpkg::Config::new().find_package("harfbuzz").unwrap();

    // println!("{:?}",libs);
    // panic!();

    let mut build = cc::Build::new();
    build.file("src/test.c");
    for inc in libs.include_paths {
        build.include(&inc);
        println!("inc={}", inc.to_string_lossy());
    }
    build.compile("harfbuzz_header");
}
<commit_msg>work-around for link order issue on linux<commit_after>extern crate cc;
extern crate vcpkg;

fn main() {
    let libs = vcpkg::Config::new().find_package("harfbuzz").unwrap();

    // vcpkg-rs is not capable of working out the correct order to link
    // libraries in. This only matters on Linux at present. (vcpkg itself
    // does fine, but vcpkg-rs needs to work out how to get the link order
    // from the it.)
    println!("cargo:rustc-link-lib=brotlicommon-static");

    let mut build = cc::Build::new();
    build.file("src/test.c");
    for inc in libs.include_paths {
        build.include(&inc);
        println!("inc={}", inc.to_string_lossy());
    }
    build.compile("harfbuzz_header");
}
<|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use anyhow::{ensure, format_err, Context, Result};
use executor::db_bootstrapper::calculate_genesis;
use libra_types::{transaction::Transaction, waypoint::Waypoint};
use libra_vm::LibraVM;
use libradb::LibraDB;
use std::{fs::File, io::Read, path::PathBuf};
use storage_interface::DbReaderWriter;
use structopt::StructOpt;

#[derive(StructOpt)]
#[structopt(
    name = "db-bootstrapper",
    about = "Calculate, verify and commit the genesis to local DB without a consensus among validators."
)]
struct Opt {
    #[structopt(parse(from_os_str))]
    db_dir: PathBuf,

    #[structopt(short, long, parse(from_os_str))]
    genesis_txn_file: PathBuf,

    #[structopt(short, long)]
    waypoint_to_verify: Option<Waypoint>,

    #[structopt(long, requires("waypoint-to-verify"))]
    commit: bool,
}

fn main() -> Result<()> {
    let opt = Opt::from_args();

    let genesis_txn = load_genesis_txn(&opt.genesis_txn_file)
        .with_context(|| format_err!("Failed loading genesis txn."))?;
    assert!(
        matches!(genesis_txn, Transaction::GenesisTransaction(_)),
        "Not a GenesisTransaction"
    );
    let db = DbReaderWriter::new(
        LibraDB::open(
            &opt.db_dir,
            false, /* readonly */
            None,  /* pruner */
        )
        .with_context(|| format_err!("Failed to open DB."))?,
    );

    let tree_state = db
        .reader
        .get_latest_tree_state()
        .with_context(|| format_err!("Failed to get latest tree state."))?;
    println!("Got DB state successfully: {}", tree_state.describe());
    if let Some(waypoint) = opt.waypoint_to_verify {
        ensure!(
            waypoint.version() == tree_state.num_transactions,
            "Trying to generate waypoint at version {}, but DB has {} transactions.",
            waypoint.version(),
            tree_state.num_transactions,
        )
    }

    let committer = calculate_genesis::<LibraVM>(&db, tree_state, &genesis_txn)
        .with_context(|| format_err!("Failed to calculate genesis."))?;
    println!(
        "Successfully calculated genesis. Got waypoint: {}",
        committer.waypoint()
    );

    if let Some(waypoint) = opt.waypoint_to_verify {
        ensure!(
            waypoint == committer.waypoint(),
            "Waypoint verification failed. Expected {:?}, got {:?}.",
            waypoint,
            committer.waypoint(),
        );
        println!("Waypoint verified.");

        if opt.commit {
            committer
                .commit()
                .with_context(|| format_err!("Committing genesis to DB."))?;
            println!("Successfully committed genesis.")
        }
    }

    Ok(())
}

fn load_genesis_txn(path: &PathBuf) -> Result<Transaction> {
    let mut file = File::open(&path)?;
    let mut buffer = vec![];
    file.read_to_end(&mut buffer)?;

    Ok(lcs::from_bytes(&buffer)?)
}
<commit_msg>[db-bootstrapper] use read-only for waypoint generation<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use anyhow::{ensure, format_err, Context, Result};
use executor::db_bootstrapper::calculate_genesis;
use libra_types::{transaction::Transaction, waypoint::Waypoint};
use libra_vm::LibraVM;
use libradb::LibraDB;
use std::{fs::File, io::Read, path::PathBuf};
use storage_interface::DbReaderWriter;
use structopt::StructOpt;

#[derive(StructOpt)]
#[structopt(
    name = "db-bootstrapper",
    about = "Calculate, verify and commit the genesis to local DB without a consensus among validators."
)]
struct Opt {
    #[structopt(parse(from_os_str))]
    db_dir: PathBuf,

    #[structopt(short, long, parse(from_os_str))]
    genesis_txn_file: PathBuf,

    #[structopt(short, long)]
    waypoint_to_verify: Option<Waypoint>,

    #[structopt(long, requires("waypoint-to-verify"))]
    commit: bool,
}

fn main() -> Result<()> {
    let opt = Opt::from_args();

    let genesis_txn = load_genesis_txn(&opt.genesis_txn_file)
        .with_context(|| format_err!("Failed loading genesis txn."))?;
    assert!(
        matches!(genesis_txn, Transaction::GenesisTransaction(_)),
        "Not a GenesisTransaction"
    );
    let db = DbReaderWriter::new(
        LibraDB::open(
            &opt.db_dir,
            !opt.commit, /* readonly */
            None,        /* pruner */
        )
        .with_context(|| format_err!("Failed to open DB."))?,
    );

    let tree_state = db
        .reader
        .get_latest_tree_state()
        .with_context(|| format_err!("Failed to get latest tree state."))?;
    println!("Got DB state successfully: {}", tree_state.describe());
    if let Some(waypoint) = opt.waypoint_to_verify {
        ensure!(
            waypoint.version() == tree_state.num_transactions,
            "Trying to generate waypoint at version {}, but DB has {} transactions.",
            waypoint.version(),
            tree_state.num_transactions,
        )
    }

    let committer = calculate_genesis::<LibraVM>(&db, tree_state, &genesis_txn)
        .with_context(|| format_err!("Failed to calculate genesis."))?;
    println!(
        "Successfully calculated genesis. Got waypoint: {}",
        committer.waypoint()
    );

    if let Some(waypoint) = opt.waypoint_to_verify {
        ensure!(
            waypoint == committer.waypoint(),
            "Waypoint verification failed. Expected {:?}, got {:?}.",
            waypoint,
            committer.waypoint(),
        );
        println!("Waypoint verified.");

        if opt.commit {
            committer
                .commit()
                .with_context(|| format_err!("Committing genesis to DB."))?;
            println!("Successfully committed genesis.")
        }
    }

    Ok(())
}

fn load_genesis_txn(path: &PathBuf) -> Result<Transaction> {
    let mut file = File::open(&path)?;
    let mut buffer = vec![];
    file.read_to_end(&mut buffer)?;

    Ok(lcs::from_bytes(&buffer)?)
}
<|endoftext|>


<commit_before>extern mod extra;
extern mod std;

use std::hashmap::HashMap;

use extra::json::List;
use extra::json::Number;
use extra::json::Object;
use extra::json::String;
use extra::json::from_str;
use extra::json::Json;
use JsonError = extra::json::Error;

fn emptyObjectExample() {
    let o:~HashMap<~str, Json> = match from_str("{}") {
        Ok(Object(o)) => {
            o
        },
        Ok(_) => {
            fail!("Expected an object after parsing");
        },
        Err(e) => {
            println(fmt!("ERROR: %?", e));
            fail!("What, no parsing?");
        }
    };
    let mut counter = 0;
    for o.iter().advance() |k| {
        counter += 1;
    }
    println(fmt!("0 = %?", counter));
}

fn simpleObjectWithANumber() {
    match from_str("{\"foo\": 33}") {
        Ok(Object(o)) => {
            let map: ~HashMap<~str, Json> = o;
            println(fmt!("true = %?\n", map.contains_key(&~"foo")));
            if (map.contains_key(&~"foo")) {
                let foo = match map.find(&~"foo") {
                    Some( & Number(value)) =>  {
                            value
                    },
                    Some(_) => fail!("foo was wrong type"),
                    None => fail!("No element")
                };
                println(fmt!("33 = %?\n", foo))
            } else {
                println("No key foo")
            }
        },
        Ok(_) => {
            println(fmt!("Unexpected JSON value"));
        },
        Err(e) => {
            println(fmt!("ERROR: %?\n", e));
        }
    }
}

fn listObjects() {
  let j:Result<Json,JsonError> = from_str("[{\"bar\":\"baz\", \"biz\":123}]");
  let l:List = match j {
    Ok(List(l)) => l,
    Ok(_) => fail!("Expected a list at the top level"),
    Err(e) => fail!(fmt!("Error: %?", e))
  };
  println(fmt!("item = %?", l.iter().advance(|i|{
    let item:Json = copy *i;
    match item {
        Object(o) => {
            println(fmt!("true = %?", o.contains_key(&~"bar")));
            //let barItem = ;
            let baz = match copy *o.get(&~"bar") {
                String(abaz) => abaz,
                _ => fail!("Expected bar property")
            };
            println(fmt!("bar = %?", baz));
        },
        _ => {
            fail!("Should be a list of objects, no?");
        }
    }
    true
  })));

}

fn main() {
    emptyObjectExample();
    simpleObjectWithANumber();
    listObjects();
}<commit_msg>Learning a little something about dereferencing<commit_after>extern mod extra;
extern mod std;

use std::hashmap::HashMap;

use extra::json::List;
use extra::json::Number;
use extra::json::Object;
use extra::json::String;
use extra::json::from_str;
use extra::json::Json;
use JsonError = extra::json::Error;

fn emptyObjectExample() {
    let o:~HashMap<~str, Json> = match from_str("{}") {
        Ok(Object(o)) => {
            o
        },
        Ok(_) => {
            fail!("Expected an object after parsing");
        },
        Err(e) => {
            println(fmt!("ERROR: %?", e));
            fail!("What, no parsing?");
        }
    };
    let mut counter = 0;
    for o.iter().advance() |k| {
        counter += 1;
    }
    println(fmt!("0 = %?", counter));
}

fn simpleObjectWithANumber() {
    match from_str("{\"foo\": 33}") {
        Ok(Object(o)) => {
            let map: ~HashMap<~str, Json> = o;
            println(fmt!("true = %?\n", map.contains_key(&~"foo")));
            if (map.contains_key(&~"foo")) {
                let foo = match map.find(&~"foo") {
                    Some( & Number(value)) =>  {
                            value
                    },
                    Some(_) => fail!("foo was wrong type"),
                    None => fail!("No element")
                };
                println(fmt!("33 = %?\n", foo))
            } else {
                println("No key foo")
            }
        },
        Ok(_) => {
            println(fmt!("Unexpected JSON value"));
        },
        Err(e) => {
            println(fmt!("ERROR: %?\n", e));
        }
    }
}

fn listObjects() {
  let j:Result<Json,JsonError> = from_str("[{\"bar\":\"baz\", \"biz\":123}]");
  let l:List = match j {
    Ok(List(l)) => l,
    Ok(_) => fail!("Expected a list at the top level"),
    Err(e) => fail!(fmt!("Error: %?", e))
  };
  println(fmt!("item = %?", l.iter().advance(|i|{
    let item:Json = copy *i;
    match item {
        Object(o) => {
            println(fmt!("true = %?", o.contains_key(&~"bar")));
            //let barItem = ;
            let baz = match copy *o.get(&~"bar") {
                String(abaz) => abaz,
                _ => fail!("Expected bar property")
            };
            println(fmt!("bar = %?", baz));

            println(fmt!("true = %?", o.contains_key(&~"biz")));
            //let barItem = ;
            let biz = match *o.get_copy(&~"biz") {
                Number(abiz) => abiz,
                _ => fail!("Expected biz property")
            };
            println(fmt!("biz = %?", biz));

        },
        _ => {
            fail!("Should be a list of objects, no?");
        }
    }
    true
  })));

}

fn main() {
    emptyObjectExample();
    simpleObjectWithANumber();
    listObjects();
}<|endoftext|>


<commit_before>use std::io;
use std::mem;

use bytes::{BufMut, Bytes, BytesMut};
use nom::{self, Needed};
use tokio_util::codec::{Decoder, Encoder};

use imap_proto::types::{Request, RequestId, Response};

#[derive(Default)]
pub struct ImapCodec {
    decode_need_message_bytes: usize,
}

impl<'a> Decoder for ImapCodec {
    type Item = ResponseData;
    type Error = io::Error;
    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, io::Error> {
        if self.decode_need_message_bytes > buf.len() {
            return Ok(None);
        }
        let (response, rsp_len) = match imap_proto::Response::from_bytes(buf) {
            Ok((remaining, response)) => {
                // This SHOULD be acceptable/safe: BytesMut storage memory is
                // allocated on the heap and should not move. It will not be
                // freed as long as we keep a reference alive, which we do
                // by retaining a reference to the split buffer, below.
                let response = unsafe { mem::transmute(response) };
                (response, buf.len() - remaining.len())
            }
            Err(nom::Err::Incomplete(Needed::Size(min))) => {
                self.decode_need_message_bytes = min;
                return Ok(None);
            }
            Err(nom::Err::Incomplete(_)) => {
                return Ok(None);
            }
            Err(nom::Err::Error((_input, err_kind)))
            | Err(nom::Err::Failure((_input, err_kind))) => {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    format!("{:?} during parsing of {:?}", err_kind, buf),
                ));
            }
        };
        let raw = buf.split_to(rsp_len).freeze();
        self.decode_need_message_bytes = 0;
        Ok(Some(ResponseData { raw, response }))
    }
}

impl<'a> Encoder<&'a Request<'a>> for ImapCodec {
    type Error = io::Error;
    fn encode(&mut self, msg: &Request, dst: &mut BytesMut) -> Result<(), io::Error> {
        dst.put(msg.0);
        dst.put_u8(b' ');
        dst.put_slice(msg.1);
        dst.put_slice(b"\r\n");
        Ok(())
    }
}

#[derive(Debug)]
pub struct ResponseData {
    raw: Bytes,
    // This reference is really scoped to the lifetime of the `raw`
    // member, but unfortunately Rust does not allow that yet. It
    // is transmuted to `'static` by the `Decoder`, instead, and
    // references returned to callers of `ResponseData` are limited
    // to the lifetime of the `ResponseData` struct.
    //
    // `raw` is never mutated during the lifetime of `ResponseData`,
    // and `Response` does not not implement any specific drop glue.
    response: Response<'static>,
}

impl ResponseData {
    pub fn request_id(&self) -> Option<&RequestId> {
        match self.response {
            Response::Done { ref tag, .. } => Some(tag),
            _ => None,
        }
    }
    pub fn parsed<'a>(&'a self) -> &'a Response<'a> {
        &self.response
    }
}
<commit_msg>Silence clippy warnings<commit_after>use std::io;
use std::mem;

use bytes::{BufMut, Bytes, BytesMut};
use nom::{self, Needed};
use tokio_util::codec::{Decoder, Encoder};

use imap_proto::types::{Request, RequestId, Response};

#[derive(Default)]
pub struct ImapCodec {
    decode_need_message_bytes: usize,
}

impl<'a> Decoder for ImapCodec {
    type Item = ResponseData;
    type Error = io::Error;
    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, io::Error> {
        if self.decode_need_message_bytes > buf.len() {
            return Ok(None);
        }
        let (response, rsp_len) = match imap_proto::Response::from_bytes(buf) {
            Ok((remaining, response)) => {
                // This SHOULD be acceptable/safe: BytesMut storage memory is
                // allocated on the heap and should not move. It will not be
                // freed as long as we keep a reference alive, which we do
                // by retaining a reference to the split buffer, below.
                let response = unsafe { mem::transmute(response) };
                (response, buf.len() - remaining.len())
            }
            Err(nom::Err::Incomplete(Needed::Size(min))) => {
                self.decode_need_message_bytes = min;
                return Ok(None);
            }
            Err(nom::Err::Incomplete(_)) => {
                return Ok(None);
            }
            Err(nom::Err::Error((_input, err_kind)))
            | Err(nom::Err::Failure((_input, err_kind))) => {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    format!("{:?} during parsing of {:?}", err_kind, buf),
                ));
            }
        };
        let raw = buf.split_to(rsp_len).freeze();
        self.decode_need_message_bytes = 0;
        Ok(Some(ResponseData { raw, response }))
    }
}

impl<'a> Encoder<&'a Request<'a>> for ImapCodec {
    type Error = io::Error;
    fn encode(&mut self, msg: &Request, dst: &mut BytesMut) -> Result<(), io::Error> {
        dst.put(msg.0);
        dst.put_u8(b' ');
        dst.put_slice(msg.1);
        dst.put_slice(b"\r\n");
        Ok(())
    }
}

#[derive(Debug)]
pub struct ResponseData {
    raw: Bytes,
    // This reference is really scoped to the lifetime of the `raw`
    // member, but unfortunately Rust does not allow that yet. It
    // is transmuted to `'static` by the `Decoder`, instead, and
    // references returned to callers of `ResponseData` are limited
    // to the lifetime of the `ResponseData` struct.
    //
    // `raw` is never mutated during the lifetime of `ResponseData`,
    // and `Response` does not not implement any specific drop glue.
    response: Response<'static>,
}

impl ResponseData {
    pub fn request_id(&self) -> Option<&RequestId> {
        match self.response {
            Response::Done { ref tag, .. } => Some(tag),
            _ => None,
        }
    }

    #[allow(clippy::needless_lifetimes)]
    pub fn parsed<'a>(&'a self) -> &'a Response<'a> {
        &self.response
    }
}
<|endoftext|>


<commit_before>// Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Very basic syntax detection.

use std::borrow::Borrow;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use config::Table;

/// The canonical identifier for a particular `LanguageDefinition`.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct LanguageId(Arc<String>);

/// Describes a `LanguageDefinition`. Although these are provided by plugins,
/// they are a fundamental concept in core, used to determine things like
/// plugin activations and active user config tables.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageDefinition {
    pub name: LanguageId,
    pub extensions: Vec<String>,
    pub first_line_match: Option<String>,
    pub scope: String,
    #[serde(skip)]
    pub default_config: Option<Table>,
}

/// A repository of all loaded `LanguageDefinition`s.
#[derive(Debug, Default)]
pub struct Languages {
    named: HashMap<LanguageId, Arc<LanguageDefinition>>,
    extensions: HashMap<String, Arc<LanguageDefinition>>,
}

impl Languages {
    pub fn new(language_defs: &[LanguageDefinition]) -> Self {
        let mut named = HashMap::new();
        let mut extensions = HashMap::new();
        for lang in language_defs.iter() {
            let lang_arc = Arc::new(lang.clone());
            named.insert(lang.name.clone(), lang_arc.clone());
            for ext in lang.extensions.iter() {
                extensions.insert(ext.clone(), lang_arc.clone());
            }
        }
        Languages { named, extensions }
    }

    pub fn language_for_path(&self, path: &Path) -> Option<Arc<LanguageDefinition>> {
        path.extension()
            .and_then(|ext| self.extensions.get(ext.to_str().unwrap_or_default()))
            .map(Arc::clone)
    }

    pub fn language_for_name<S>(&self, name: S) -> Option<Arc<LanguageDefinition>>
        where S: AsRef<str>
    {
        self.named.get(name.as_ref()).map(Arc::clone)
    }

    /// Returns a Vec of any `LanguageDefinition`s which exist
    /// in `self` but not `other`.
    pub fn difference(&self, other: &Languages) -> Vec<Arc<LanguageDefinition>> {
        self.named.iter()
            .filter(|(k, _)| !other.named.contains_key(*k))
            .map(|(_, v)| v.clone())
            .collect()
    }

    pub fn iter<'a>(&'a self) -> impl Iterator<Item=&'a Arc<LanguageDefinition>> {
        self.named.values()
    }
}

impl AsRef<str> for LanguageId {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

// let's us use &str to query a HashMap with `LanguageId` keys
impl Borrow<str> for LanguageId {
    fn borrow(&self) -> &str {
        &self.0.as_ref()
    }
}

impl<'a> From<&'a str> for LanguageId {
    fn from(src: &'a str) -> LanguageId {
        LanguageId(Arc::new(src.into()))
    }
}

// for testing
#[cfg(test)]
impl LanguageDefinition {
    pub(crate) fn simple(name: &str, exts: &[&str],
                         scope: &str, config: Option<Table>) -> Self
    {
        LanguageDefinition {
            name: name.into(),
            extensions: exts.iter().map(|s| (*s).into()).collect(),
            first_line_match: None,
            scope: scope.into(),
            default_config: config,
        }
    }
}
<commit_msg>use BTreeMap to sort languages alphabetically by name<commit_after>// Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Very basic syntax detection.

use std::borrow::Borrow;
use std::collections::{HashMap, BTreeMap};
use std::path::Path;
use std::sync::Arc;

use config::Table;

/// The canonical identifier for a particular `LanguageDefinition`.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LanguageId(Arc<String>);

/// Describes a `LanguageDefinition`. Although these are provided by plugins,
/// they are a fundamental concept in core, used to determine things like
/// plugin activations and active user config tables.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageDefinition {
    pub name: LanguageId,
    pub extensions: Vec<String>,
    pub first_line_match: Option<String>,
    pub scope: String,
    #[serde(skip)]
    pub default_config: Option<Table>,
}

/// A repository of all loaded `LanguageDefinition`s.
#[derive(Debug, Default)]
pub struct Languages {
    named: BTreeMap<LanguageId, Arc<LanguageDefinition>>,
    extensions: HashMap<String, Arc<LanguageDefinition>>,
}

impl Languages {
    pub fn new(language_defs: &[LanguageDefinition]) -> Self {
        let mut named = BTreeMap::new();
        let mut extensions = HashMap::new();
        for lang in language_defs.iter() {
            let lang_arc = Arc::new(lang.clone());
            named.insert(lang.name.clone(), lang_arc.clone());
            for ext in lang.extensions.iter() {
                extensions.insert(ext.clone(), lang_arc.clone());
            }
        }
        Languages { named, extensions }
    }

    pub fn language_for_path(&self, path: &Path) -> Option<Arc<LanguageDefinition>> {
        path.extension()
            .and_then(|ext| self.extensions.get(ext.to_str().unwrap_or_default()))
            .map(Arc::clone)
    }

    pub fn language_for_name<S>(&self, name: S) -> Option<Arc<LanguageDefinition>>
        where S: AsRef<str>
    {
        self.named.get(name.as_ref()).map(Arc::clone)
    }

    /// Returns a Vec of any `LanguageDefinition`s which exist
    /// in `self` but not `other`.
    pub fn difference(&self, other: &Languages) -> Vec<Arc<LanguageDefinition>> {
        self.named.iter()
            .filter(|(k, _)| !other.named.contains_key(*k))
            .map(|(_, v)| v.clone())
            .collect()
    }

    pub fn iter<'a>(&'a self) -> impl Iterator<Item=&'a Arc<LanguageDefinition>> {
        self.named.values()
    }
}

impl AsRef<str> for LanguageId {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

// let's us use &str to query a HashMap with `LanguageId` keys
impl Borrow<str> for LanguageId {
    fn borrow(&self) -> &str {
        &self.0.as_ref()
    }
}

impl<'a> From<&'a str> for LanguageId {
    fn from(src: &'a str) -> LanguageId {
        LanguageId(Arc::new(src.into()))
    }
}

// for testing
#[cfg(test)]
impl LanguageDefinition {
    pub(crate) fn simple(name: &str, exts: &[&str],
                         scope: &str, config: Option<Table>) -> Self
    {
        LanguageDefinition {
            name: name.into(),
            extensions: exts.iter().map(|s| (*s).into()).collect(),
            first_line_match: None,
            scope: scope.into(),
            default_config: config,
        }
    }
}
<|endoftext|>


<commit_before>extern crate rosc;

use rosc::{address, OscError};

#[test]
fn test_validate_method_address() {
    // Valid addresses
    address::validate_method_address(&String::from("/"));
    address::validate_method_address(&String::from("/a"));

    // Invalid addresses
    match address::validate_method_address(&String::from("/foo\0")).err().expect("") {
        OscError::BadAddress("Address may only contain printable ASCII characters") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_method_address(&String::from("öäü")).err().expect("") {
        OscError::BadAddress("Address must only contain ASCII characters") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_method_address(&String::from("")).err().expect("") {
        OscError::BadAddress("Address must be at least 1 character long") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_method_address(&String::from("foo")).err().expect("") {
        OscError::BadAddress("Address must start with '/'") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_method_address(&String::from("/ illegal#*,?[]{}")).err().expect("") {
        OscError::BadAddress("Address may not contain any of the following characters: ' #*,?[]{}'") => assert!(true),
        _ => assert!(false)
    }
}

#[test]
fn test_validate_message_address() {
    // Valid addresses
    address::validate_message_address(&String::from("/a"));

    // Invalid addresses
    match address::validate_message_address(&String::from("/foo\0")).err().expect("") {
        OscError::BadAddress("Address may only contain printable ASCII characters") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_message_address(&String::from("öäü")).err().expect("") {
        OscError::BadAddress("Address must only contain ASCII characters") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_message_address(&String::from("")).err().expect("") {
        OscError::BadAddress("Address must be at least 1 character long") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_message_address(&String::from("foo")).err().expect("") {
        OscError::BadAddress("Address must start with '/'") => assert!(true),
        _ => assert!(false)
    }

    // Square brackets open and never close
    match address::validate_message_address(&String::from("/[a/b")).err().expect("") {
        OscError::BadAddress("Character range (square brackets) was started but not closed before the next address part started") => assert!(true),
        _ => assert!(false)
    }
    // Square brackets contains /
    match address::validate_message_address(&String::from("/[a/]b")).err().expect("") {
        OscError::BadAddress("Character range (square brackets) was started but not closed before the next address part started") => assert!(true),
        _ => assert!(false)
    }
    // Square brackets open but don't close before the address ends
    match address::validate_message_address(&String::from("/[a")).err().expect("") {
        OscError::BadAddress("Character range (square brackets) was started but not closed before the end of the address") => assert!(true),
        _ => assert!(false)
    }

    // Curly brakcets open and never close
    match address::validate_message_address(&String::from("/{a/b")).err().expect("") {
        OscError::BadAddress("String list (curly brackets) was started but not closed before the next address part started") => assert!(true),
        _ => assert!(false)
    }
    // Curly brackets contains /
    match address::validate_message_address(&String::from("/{a/}b")).err().expect("") {
        OscError::BadAddress("String list (curly brackets) was started but not closed before the next address part started") => assert!(true),
        _ => assert!(false)
    }
    // Curly brackets open but don't close before the address ends
    match address::validate_message_address(&String::from("/{a")).err().expect("") {
        OscError::BadAddress("String list (curly brackets) was started but not closed before the end of the address") => assert!(true),
        _ => assert!(false)
    }

    // Curly brackets open but don't close before the address ends
    match address::validate_message_address(&String::from("/{a[foo]}/")).err().expect("") {
        OscError::BadAddress("Can not start a character range (square brackets) within string list (curly brackets)") => assert!(true),
        _ => assert!(false)
    }

    // Square brackets within curly brackets
    match address::validate_message_address(&String::from("/[a{foo}]/")).err().expect("") {
        OscError::BadAddress("Can not start a string list (curly brackets) within character range (square brackets)") => assert!(true),
        _ => assert!(false)
    }
}<commit_msg>Add missing expects<commit_after>extern crate rosc;

use rosc::{address, OscError};

#[test]
fn test_validate_method_address() {
    // Valid addresses
    address::validate_method_address(&String::from("/")).expect("");
    address::validate_method_address(&String::from("/a")).expect("");

    // Invalid addresses
    match address::validate_method_address(&String::from("/foo\0")).err().expect("") {
        OscError::BadAddress("Address may only contain printable ASCII characters") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_method_address(&String::from("öäü")).err().expect("") {
        OscError::BadAddress("Address must only contain ASCII characters") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_method_address(&String::from("")).err().expect("") {
        OscError::BadAddress("Address must be at least 1 character long") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_method_address(&String::from("foo")).err().expect("") {
        OscError::BadAddress("Address must start with '/'") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_method_address(&String::from("/ illegal#*,?[]{}")).err().expect("") {
        OscError::BadAddress("Address may not contain any of the following characters: ' #*,?[]{}'") => assert!(true),
        _ => assert!(false)
    }
}

#[test]
fn test_validate_message_address() {
    // Valid addresses
    address::validate_message_address(&String::from("/a")).expect("");

    // Invalid addresses
    match address::validate_message_address(&String::from("/foo\0")).err().expect("") {
        OscError::BadAddress("Address may only contain printable ASCII characters") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_message_address(&String::from("öäü")).err().expect("") {
        OscError::BadAddress("Address must only contain ASCII characters") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_message_address(&String::from("")).err().expect("") {
        OscError::BadAddress("Address must be at least 1 character long") => assert!(true),
        _ => assert!(false)
    }
    match address::validate_message_address(&String::from("foo")).err().expect("") {
        OscError::BadAddress("Address must start with '/'") => assert!(true),
        _ => assert!(false)
    }

    // Square brackets open and never close
    match address::validate_message_address(&String::from("/[a/b")).err().expect("") {
        OscError::BadAddress("Character range (square brackets) was started but not closed before the next address part started") => assert!(true),
        _ => assert!(false)
    }
    // Square brackets contains /
    match address::validate_message_address(&String::from("/[a/]b")).err().expect("") {
        OscError::BadAddress("Character range (square brackets) was started but not closed before the next address part started") => assert!(true),
        _ => assert!(false)
    }
    // Square brackets open but don't close before the address ends
    match address::validate_message_address(&String::from("/[a")).err().expect("") {
        OscError::BadAddress("Character range (square brackets) was started but not closed before the end of the address") => assert!(true),
        _ => assert!(false)
    }

    // Curly brakcets open and never close
    match address::validate_message_address(&String::from("/{a/b")).err().expect("") {
        OscError::BadAddress("String list (curly brackets) was started but not closed before the next address part started") => assert!(true),
        _ => assert!(false)
    }
    // Curly brackets contains /
    match address::validate_message_address(&String::from("/{a/}b")).err().expect("") {
        OscError::BadAddress("String list (curly brackets) was started but not closed before the next address part started") => assert!(true),
        _ => assert!(false)
    }
    // Curly brackets open but don't close before the address ends
    match address::validate_message_address(&String::from("/{a")).err().expect("") {
        OscError::BadAddress("String list (curly brackets) was started but not closed before the end of the address") => assert!(true),
        _ => assert!(false)
    }

    // Curly brackets open but don't close before the address ends
    match address::validate_message_address(&String::from("/{a[foo]}/")).err().expect("") {
        OscError::BadAddress("Can not start a character range (square brackets) within string list (curly brackets)") => assert!(true),
        _ => assert!(false)
    }

    // Square brackets within curly brackets
    match address::validate_message_address(&String::from("/[a{foo}]/")).err().expect("") {
        OscError::BadAddress("Can not start a string list (curly brackets) within character range (square brackets)") => assert!(true),
        _ => assert!(false)
    }
}<|endoftext|>


<commit_before><commit_msg>Change `while` to `for`<commit_after><|endoftext|>


<commit_before>extern crate bio;
extern crate csv;
extern crate itertools;
#[macro_use]
extern crate quick_error;

use std::io::Error as StdIoError;

pub use bio::utils::Strand;
use csv::Error as CsvError;

mod feature;
pub mod io_refflat;

pub use feature::{Feature, FeatureError, FeatureKind,
                  EBuilder, Exon, ExonFeature, ExonFeatureKind,
                  TBuilder, Transcript, TranscriptFeature, TranscriptFeatureKind,
                  GBuilder, Gene, GeneFeature, GeneFeatureKind};

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        Feature(err: FeatureError) {
            description(err.description())
            from()
            cause(err)
        }
        RefFlat(string: &'static str) {
            description(string)
        }
        Csv(err: CsvError) {
            description(err.description())
            from()
            cause(err)
        }
        Io(err: StdIoError) {
            description(err.description())
            from()
            cause(err)
        }
    }
}

// Helper type for raw coordinates
type Coord<T> = (T, T);
<commit_msg>Export refflat io<commit_after>extern crate bio;
extern crate csv;
extern crate itertools;
#[macro_use]
extern crate quick_error;

use std::io::Error as StdIoError;

pub use bio::utils::Strand;
use csv::Error as CsvError;

mod feature;
pub use feature::{Feature, FeatureError, FeatureKind,
                  EBuilder, Exon, ExonFeature, ExonFeatureKind,
                  TBuilder, Transcript, TranscriptFeature, TranscriptFeatureKind,
                  GBuilder, Gene, GeneFeature, GeneFeatureKind};

mod io_refflat;
pub use io_refflat::{Reader as RefFlatReader, RefFlatRow, RefFlatRecord,
                     RefFlatRecords, RefFlatTranscripts, RefFlatGenes};

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        Feature(err: FeatureError) {
            description(err.description())
            from()
            cause(err)
        }
        RefFlat(string: &'static str) {
            description(string)
        }
        Csv(err: CsvError) {
            description(err.description())
            from()
            cause(err)
        }
        Io(err: StdIoError) {
            description(err.description())
            from()
            cause(err)
        }
    }
}

// Helper type for raw coordinates
type Coord<T> = (T, T);
<|endoftext|>