<commit_before>//! `assists` crate provides a bunch of code assists, also known as code
//! actions (in LSP) or intentions (in IntelliJ).
//!
//! An assist is a micro-refactoring, which is automatically activated in
//! certain context. For example, if the cursor is over `,`, a "swap `,`" assist
//! becomes available.

#[allow(unused)]
macro_rules! eprintln {
    ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
}

mod assist_config;
mod assist_context;
#[cfg(test)]
mod tests;
pub mod utils;

use hir::Semantics;
use ide_db::{base_db::FileRange, RootDatabase};
use syntax::TextRange;

pub(crate) use crate::assist_context::{AssistContext, Assists};

pub use assist_config::AssistConfig;
pub use ide_db::assists::{
    Assist, AssistId, AssistKind, AssistResolveStrategy, GroupLabel, SingleResolve,
};

/// Return all the assists applicable at the given position.
pub fn assists(
    db: &RootDatabase,
    config: &AssistConfig,
    resolve: AssistResolveStrategy,
    range: FileRange,
) -> Vec<Assist> {
    let sema = Semantics::new(db);
    let ctx = AssistContext::new(sema, config, range);
    let mut acc = Assists::new(&ctx, resolve);
    handlers::all().iter().for_each(|handler| {
        handler(&mut acc, &ctx);
    });
    acc.finish()
}

mod handlers {
    use crate::{AssistContext, Assists};

    pub(crate) type Handler = fn(&mut Assists, &AssistContext) -> Option<()>;

    mod add_explicit_type;
    mod add_lifetime_to_type;
    mod add_missing_impl_members;
    mod add_turbo_fish;
    mod apply_demorgan;
    mod auto_import;
    mod change_visibility;
    mod convert_bool_then;
    mod convert_comment_block;
    mod convert_integer_literal;
    mod convert_into_to_from;
    mod convert_iter_for_each_to_for;
    mod convert_tuple_struct_to_named_struct;
    mod convert_to_guarded_return;
    mod destructure_tuple_binding;
    mod expand_glob_import;
    mod extract_function;
    mod extract_struct_from_enum_variant;
    mod extract_type_alias;
    mod extract_variable;
    mod fill_match_arms;
    mod fix_visibility;
    mod flip_binexpr;
    mod flip_comma;
    mod flip_trait_bound;
    mod generate_default_from_enum_variant;
    mod generate_default_from_new;
    mod generate_deref;
    mod generate_derive;
    mod generate_enum_is_method;
    mod generate_enum_projection_method;
    mod generate_from_impl_for_enum;
    mod generate_function;
    mod generate_getter;
    mod generate_impl;
    mod generate_is_empty_from_len;
    mod generate_new;
    mod generate_setter;
    mod infer_function_return_type;
    mod inline_call;
    mod inline_local_variable;
    mod introduce_named_lifetime;
    mod invert_if;
    mod merge_imports;
    mod merge_match_arms;
    mod move_bounds;
    mod move_guard;
    mod move_module_to_file;
    mod pull_assignment_up;
    mod qualify_path;
    mod raw_string;
    mod remove_dbg;
    mod remove_mut;
    mod remove_unused_param;
    mod reorder_fields;
    mod reorder_impl;
    mod replace_derive_with_manual_impl;
    mod replace_for_loop_with_for_each;
    mod replace_if_let_with_match;
    mod replace_impl_trait_with_generic;
    mod replace_let_with_if_let;
    mod replace_qualified_name_with_use;
    mod replace_string_with_char;
    mod split_import;
    mod sort_items;
    mod toggle_ignore;
    mod unmerge_use;
    mod unwrap_block;
    mod wrap_return_type_in_result;

    pub(crate) fn all() -> &'static [Handler] {
        &[
            // These are alphabetic for the foolish consistency
            add_explicit_type::add_explicit_type,
            add_lifetime_to_type::add_lifetime_to_type,
            add_turbo_fish::add_turbo_fish,
            apply_demorgan::apply_demorgan,
            auto_import::auto_import,
            change_visibility::change_visibility,
            convert_bool_then::convert_bool_then_to_if,
            convert_bool_then::convert_if_to_bool_then,
            convert_comment_block::convert_comment_block,
            convert_integer_literal::convert_integer_literal,
            convert_into_to_from::convert_into_to_from,
            convert_iter_for_each_to_for::convert_iter_for_each_to_for,
            convert_to_guarded_return::convert_to_guarded_return,
            convert_tuple_struct_to_named_struct::convert_tuple_struct_to_named_struct,
            destructure_tuple_binding::destructure_tuple_binding,
            expand_glob_import::expand_glob_import,
            extract_struct_from_enum_variant::extract_struct_from_enum_variant,
            extract_type_alias::extract_type_alias,
            fill_match_arms::fill_match_arms,
            fix_visibility::fix_visibility,
            flip_binexpr::flip_binexpr,
            flip_comma::flip_comma,
            flip_trait_bound::flip_trait_bound,
            generate_default_from_enum_variant::generate_default_from_enum_variant,
            generate_default_from_new::generate_default_from_new,
            generate_deref::generate_deref,
            generate_derive::generate_derive,
            generate_enum_is_method::generate_enum_is_method,
            generate_enum_projection_method::generate_enum_as_method,
            generate_enum_projection_method::generate_enum_try_into_method,
            generate_from_impl_for_enum::generate_from_impl_for_enum,
            generate_function::generate_function,
            generate_impl::generate_impl,
            generate_is_empty_from_len::generate_is_empty_from_len,
            generate_new::generate_new,
            infer_function_return_type::infer_function_return_type,
            inline_call::inline_call,
            inline_local_variable::inline_local_variable,
            introduce_named_lifetime::introduce_named_lifetime,
            invert_if::invert_if,
            merge_imports::merge_imports,
            merge_match_arms::merge_match_arms,
            move_bounds::move_bounds_to_where_clause,
            move_guard::move_arm_cond_to_match_guard,
            move_guard::move_guard_to_arm_body,
            move_module_to_file::move_module_to_file,
            pull_assignment_up::pull_assignment_up,
            qualify_path::qualify_path,
            raw_string::add_hash,
            raw_string::make_usual_string,
            raw_string::remove_hash,
            remove_dbg::remove_dbg,
            remove_mut::remove_mut,
            remove_unused_param::remove_unused_param,
            reorder_fields::reorder_fields,
            reorder_impl::reorder_impl,
            replace_derive_with_manual_impl::replace_derive_with_manual_impl,
            replace_for_loop_with_for_each::replace_for_loop_with_for_each,
            replace_if_let_with_match::replace_if_let_with_match,
            replace_if_let_with_match::replace_match_with_if_let,
            replace_impl_trait_with_generic::replace_impl_trait_with_generic,
            replace_let_with_if_let::replace_let_with_if_let,
            replace_qualified_name_with_use::replace_qualified_name_with_use,
            sort_items::sort_items,
            split_import::split_import,
            toggle_ignore::toggle_ignore,
            unmerge_use::unmerge_use,
            unwrap_block::unwrap_block,
            wrap_return_type_in_result::wrap_return_type_in_result,
            // These are manually sorted for better priorities. By default,
            // priority is determined by the size of the target range (smaller
            // target wins). If the ranges are equal, position in this list is
            // used as a tie-breaker.
            add_missing_impl_members::add_missing_impl_members,
            add_missing_impl_members::add_missing_default_members,
            //
            replace_string_with_char::replace_string_with_char,
            replace_string_with_char::replace_char_with_string,
            raw_string::make_raw_string,
            //
            extract_variable::extract_variable,
            extract_function::extract_function,
            //
            generate_getter::generate_getter,
            generate_getter::generate_getter_mut,
            generate_setter::generate_setter,
            // Are you sure you want to add new assist here, and not to the
            // sorted list above?
        ]
    }
}
<commit_msg>internal: document tribal knowledge of how to assist<commit_after>//! `assists` crate provides a bunch of code assists, also known as code actions
//! (in LSP) or intentions (in IntelliJ).
//!
//! An assist is a micro-refactoring, which is automatically activated in
//! certain context. For example, if the cursor is over `,`, a "swap `,`" assist
//! becomes available.
//!
//! ## Assists Guidelines
//!
//! Assists are the main mechanism to deliver advanced IDE features to the user,
//! so we should pay extra attention to the UX.
//!
//! The power of assists comes from their context-awareness. The main problem
//! with IDE features is that there are a lot of them, and it's hard to teach
//! the user what's available. Assists solve this problem nicely: 💡 signifies
//! that *something* is possible, and clicking on it reveals a *short* list of
//! actions. Contrast it with Emacs `M-x`, which just spits an infinite list of
//! all the features.
//!
//! Here are some considerations when creating a new assist:
//!
//! * It's good to preserve semantics, and it's good to keep the code compiling,
//!   but it isn't necessary. Example: "flip binary operation" might change
//!   semantics.
//! * Assist shouldn't necessary make the code "better". A lot of assist come in
//!   pairs: "if let <-> match".
//! * Assists should have as narrow scope as possible. Each new assists greatly
//!   improves UX for cases where the user actually invokes it, but it makes UX
//!   worse for every case where the user clicks 💡 to invoke some *other*
//!   assist. So, a rarely useful assist which is always applicable can be a net
//!   negative.
//! * Rarely useful actions are tricky. Sometimes there are features which are
//!   clearly useful to some users, but are just noise most of the time. We
//!   don't have a good solution here, our current approach is to make this
//!   functionality available only if assist is applicable to the whole
//!   selection. Example: `sort_items` sorts items alphabetically. Naively, it
//!   should be available more or less everywhere, which isn't useful. So
//!   instead we only show it if the user *selects* the items they want to sort.
//! * Consider grouping related assists together (see [`Assists::add_group`]).
//! * Make assists robust. If the assist depends on results of type-inference to
//!   much, it might only fire in fully-correct code. This makes assist less
//!   useful and (worse) less predictable. The user should have a clear
//!   intuition when each particular assist is available.
//! * Make small assists, which compose. Example: rather than auto-importing
//!   enums in `fill_match_arms`, we use fully-qualified names. There's a
//!   separate assist to shorten a fully-qualified name.
//! * Distinguish between assists and fixits for diagnostics. Internally, fixits
//!   and assists are equivalent. They have the same "show a list + invoke a
//!   single element" workflow, and both use [`Assist`] data structure. The main
//!   difference is in the UX: while 💡 looks only at the cursor position,
//!   diagnostics squigglies and fixits are calculated for the whole file and
//!   are presented to the user eagerly. So, diagnostics should be fixable
//!   errors, while assists can be just suggestions for an alternative way to do
//!   something. If something *could* be a diagnostic, it should be a
//!   diagnostic. Conversely, it might be valuable to turn a diagnostic with a
//!   lot of false errors into an assist.
//! *
//!
//! See also this post:
//! <https://rust-analyzer.github.io/blog/2020/09/28/how-to-make-a-light-bulb.html>
#[allow(unused)]
macro_rules! eprintln {
    ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
}

mod assist_config;
mod assist_context;
#[cfg(test)]
mod tests;
pub mod utils;

use hir::Semantics;
use ide_db::{base_db::FileRange, RootDatabase};
use syntax::TextRange;

pub(crate) use crate::assist_context::{AssistContext, Assists};

pub use assist_config::AssistConfig;
pub use ide_db::assists::{
    Assist, AssistId, AssistKind, AssistResolveStrategy, GroupLabel, SingleResolve,
};

/// Return all the assists applicable at the given position.
///
// NOTE: We don't have a `Feature: ` section for assists, they are special-cased
// in the manual.
pub fn assists(
    db: &RootDatabase,
    config: &AssistConfig,
    resolve: AssistResolveStrategy,
    range: FileRange,
) -> Vec<Assist> {
    let sema = Semantics::new(db);
    let ctx = AssistContext::new(sema, config, range);
    let mut acc = Assists::new(&ctx, resolve);
    handlers::all().iter().for_each(|handler| {
        handler(&mut acc, &ctx);
    });
    acc.finish()
}

mod handlers {
    use crate::{AssistContext, Assists};

    pub(crate) type Handler = fn(&mut Assists, &AssistContext) -> Option<()>;

    mod add_explicit_type;
    mod add_lifetime_to_type;
    mod add_missing_impl_members;
    mod add_turbo_fish;
    mod apply_demorgan;
    mod auto_import;
    mod change_visibility;
    mod convert_bool_then;
    mod convert_comment_block;
    mod convert_integer_literal;
    mod convert_into_to_from;
    mod convert_iter_for_each_to_for;
    mod convert_tuple_struct_to_named_struct;
    mod convert_to_guarded_return;
    mod destructure_tuple_binding;
    mod expand_glob_import;
    mod extract_function;
    mod extract_struct_from_enum_variant;
    mod extract_type_alias;
    mod extract_variable;
    mod fill_match_arms;
    mod fix_visibility;
    mod flip_binexpr;
    mod flip_comma;
    mod flip_trait_bound;
    mod generate_default_from_enum_variant;
    mod generate_default_from_new;
    mod generate_deref;
    mod generate_derive;
    mod generate_enum_is_method;
    mod generate_enum_projection_method;
    mod generate_from_impl_for_enum;
    mod generate_function;
    mod generate_getter;
    mod generate_impl;
    mod generate_is_empty_from_len;
    mod generate_new;
    mod generate_setter;
    mod infer_function_return_type;
    mod inline_call;
    mod inline_local_variable;
    mod introduce_named_lifetime;
    mod invert_if;
    mod merge_imports;
    mod merge_match_arms;
    mod move_bounds;
    mod move_guard;
    mod move_module_to_file;
    mod pull_assignment_up;
    mod qualify_path;
    mod raw_string;
    mod remove_dbg;
    mod remove_mut;
    mod remove_unused_param;
    mod reorder_fields;
    mod reorder_impl;
    mod replace_derive_with_manual_impl;
    mod replace_for_loop_with_for_each;
    mod replace_if_let_with_match;
    mod replace_impl_trait_with_generic;
    mod replace_let_with_if_let;
    mod replace_qualified_name_with_use;
    mod replace_string_with_char;
    mod split_import;
    mod sort_items;
    mod toggle_ignore;
    mod unmerge_use;
    mod unwrap_block;
    mod wrap_return_type_in_result;

    pub(crate) fn all() -> &'static [Handler] {
        &[
            // These are alphabetic for the foolish consistency
            add_explicit_type::add_explicit_type,
            add_lifetime_to_type::add_lifetime_to_type,
            add_turbo_fish::add_turbo_fish,
            apply_demorgan::apply_demorgan,
            auto_import::auto_import,
            change_visibility::change_visibility,
            convert_bool_then::convert_bool_then_to_if,
            convert_bool_then::convert_if_to_bool_then,
            convert_comment_block::convert_comment_block,
            convert_integer_literal::convert_integer_literal,
            convert_into_to_from::convert_into_to_from,
            convert_iter_for_each_to_for::convert_iter_for_each_to_for,
            convert_to_guarded_return::convert_to_guarded_return,
            convert_tuple_struct_to_named_struct::convert_tuple_struct_to_named_struct,
            destructure_tuple_binding::destructure_tuple_binding,
            expand_glob_import::expand_glob_import,
            extract_struct_from_enum_variant::extract_struct_from_enum_variant,
            extract_type_alias::extract_type_alias,
            fill_match_arms::fill_match_arms,
            fix_visibility::fix_visibility,
            flip_binexpr::flip_binexpr,
            flip_comma::flip_comma,
            flip_trait_bound::flip_trait_bound,
            generate_default_from_enum_variant::generate_default_from_enum_variant,
            generate_default_from_new::generate_default_from_new,
            generate_deref::generate_deref,
            generate_derive::generate_derive,
            generate_enum_is_method::generate_enum_is_method,
            generate_enum_projection_method::generate_enum_as_method,
            generate_enum_projection_method::generate_enum_try_into_method,
            generate_from_impl_for_enum::generate_from_impl_for_enum,
            generate_function::generate_function,
            generate_impl::generate_impl,
            generate_is_empty_from_len::generate_is_empty_from_len,
            generate_new::generate_new,
            infer_function_return_type::infer_function_return_type,
            inline_call::inline_call,
            inline_local_variable::inline_local_variable,
            introduce_named_lifetime::introduce_named_lifetime,
            invert_if::invert_if,
            merge_imports::merge_imports,
            merge_match_arms::merge_match_arms,
            move_bounds::move_bounds_to_where_clause,
            move_guard::move_arm_cond_to_match_guard,
            move_guard::move_guard_to_arm_body,
            move_module_to_file::move_module_to_file,
            pull_assignment_up::pull_assignment_up,
            qualify_path::qualify_path,
            raw_string::add_hash,
            raw_string::make_usual_string,
            raw_string::remove_hash,
            remove_dbg::remove_dbg,
            remove_mut::remove_mut,
            remove_unused_param::remove_unused_param,
            reorder_fields::reorder_fields,
            reorder_impl::reorder_impl,
            replace_derive_with_manual_impl::replace_derive_with_manual_impl,
            replace_for_loop_with_for_each::replace_for_loop_with_for_each,
            replace_if_let_with_match::replace_if_let_with_match,
            replace_if_let_with_match::replace_match_with_if_let,
            replace_impl_trait_with_generic::replace_impl_trait_with_generic,
            replace_let_with_if_let::replace_let_with_if_let,
            replace_qualified_name_with_use::replace_qualified_name_with_use,
            sort_items::sort_items,
            split_import::split_import,
            toggle_ignore::toggle_ignore,
            unmerge_use::unmerge_use,
            unwrap_block::unwrap_block,
            wrap_return_type_in_result::wrap_return_type_in_result,
            // These are manually sorted for better priorities. By default,
            // priority is determined by the size of the target range (smaller
            // target wins). If the ranges are equal, position in this list is
            // used as a tie-breaker.
            add_missing_impl_members::add_missing_impl_members,
            add_missing_impl_members::add_missing_default_members,
            //
            replace_string_with_char::replace_string_with_char,
            replace_string_with_char::replace_char_with_string,
            raw_string::make_raw_string,
            //
            extract_variable::extract_variable,
            extract_function::extract_function,
            //
            generate_getter::generate_getter,
            generate_getter::generate_getter_mut,
            generate_setter::generate_setter,
            // Are you sure you want to add new assist here, and not to the
            // sorted list above?
        ]
    }
}
<|endoftext|>


<commit_before>//! Types for the *m.tag* event.

use std::{collections::BTreeMap, error::Error, fmt, str::FromStr};

use ruma_events_macros::EventContent;
use ruma_serde::deserialize_cow_str;
use serde::{Deserialize, Serialize};

use crate::RoomAccountDataEvent;

/// Informs the client of tags on a room.
pub type TagEvent = RoomAccountDataEvent<TagEventContent>;

/// Map of tag names to tag info.
pub type Tags = BTreeMap<TagName, TagInfo>;

/// The payload for `TagEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.tag", kind = RoomAccountData)]
pub struct TagEventContent {
    /// A map of tag names to tag info.
    pub tags: Tags,
}

impl TagEventContent {
    /// Creates a new `TagEventContent` with the given `Tags`.
    pub fn new(tags: Tags) -> Self {
        Self { tags }
    }
}

impl From<Tags> for TagEventContent {
    fn from(tags: Tags) -> Self {
        Self::new(tags)
    }
}

/// A user-defined tag name.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct UserTagName {
    name: String,
}

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

impl FromStr for UserTagName {
    type Err = InvalidUserTagName;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.starts_with("u.") {
            Ok(Self { name: s.into() })
        } else {
            Err(InvalidUserTagName)
        }
    }
}

/// An error returned when attempting to create a UserTagName with a string that would make it
/// invalid.
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct InvalidUserTagName;

impl fmt::Display for InvalidUserTagName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "missing 'u.' prefix in UserTagName")
    }
}

impl Error for InvalidUserTagName {}

/// The name of a tag.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub enum TagName {
    /// `m.favourite`: The user's favourite rooms. These should be shown with higher precedence
    /// than other rooms.
    Favorite,

    /// `m.lowpriority`: These should be shown with lower precedence than others.
    LowPriority,

    /// `m.server_notice`: Used to identify
    /// [Server Notice Rooms](https://matrix.org/docs/spec/client_server/r0.6.1#module-server-notices).
    ServerNotice,

    /// `u.*`: User-defined tag
    User(UserTagName),

    /// A custom tag
    #[doc(hidden)]
    _Custom(String),
}

impl TagName {
    /// Returns the display name of the tag.
    ///
    /// That means the string after `m.` or `u.` for spec- and user-defined tag names, and the
    /// string after the last dot for custom tags. If no dot is found, returns the whole string.
    pub fn display_name(&self) -> &str {
        match self {
            Self::_Custom(s) => {
                let start = s.rfind('.').map(|p| p + 1).unwrap_or(0);
                &self.as_ref()[start..]
            }
            _ => &self.as_ref()[2..],
        }
    }
}

impl AsRef<str> for TagName {
    fn as_ref(&self) -> &str {
        match self {
            Self::Favorite => "m.favourite",
            Self::LowPriority => "m.lowpriority",
            Self::ServerNotice => "m.server_notice",
            Self::User(tag) => tag.as_ref(),
            Self::_Custom(s) => s,
        }
    }
}

impl<T> From<T> for TagName
where
    T: AsRef<str> + Into<String>,
{
    fn from(s: T) -> TagName {
        match s.as_ref() {
            "m.favourite" => Self::Favorite,
            "m.lowpriority" => Self::LowPriority,
            "m.server_notice" => Self::ServerNotice,
            s if s.starts_with("u.") => Self::User(UserTagName { name: s.into() }),
            s => Self::_Custom(s.into()),
        }
    }
}

impl fmt::Display for TagName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_ref())
    }
}

impl<'de> Deserialize<'de> for TagName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let cow = deserialize_cow_str(deserializer)?;
        Ok(cow.into())
    }
}

impl Serialize for TagName {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_ref())
    }
}

/// Information about a tag.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct TagInfo {
    /// Value to use for lexicographically ordering rooms with this tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order: Option<f64>,
}

impl TagInfo {
    /// Creates an empty `TagInfo`.
    pub fn new() -> Self {
        Default::default()
    }
}

#[cfg(test)]
mod tests {
    use maplit::btreemap;
    use serde_json::{json, to_value as to_json_value};

    use super::{TagEventContent, TagInfo, TagName};

    #[test]
    fn serialization() {
        let tags = btreemap! {
            TagName::Favorite => TagInfo::new(),
            TagName::LowPriority => TagInfo::new(),
            TagName::ServerNotice => TagInfo::new(),
            "u.custom".to_owned().into() => TagInfo { order: Some(0.9) }
        };

        let content = TagEventContent { tags };

        assert_eq!(
            to_json_value(content).unwrap(),
            json!({
                "tags": {
                    "m.favourite": {},
                    "m.lowpriority": {},
                    "m.server_notice": {},
                    "u.custom": {
                        "order": 0.9
                    }
                },
            })
        );
    }

    #[test]
    fn display_name() {
        assert_eq!(TagName::Favorite.display_name(), "favourite");
        assert_eq!(TagName::LowPriority.display_name(), "lowpriority");
        assert_eq!(TagName::ServerNotice.display_name(), "server_notice");
        assert_eq!(TagName::from("u.Work").display_name(), "Work");
        assert_eq!(TagName::from("rs.conduit.rules").display_name(), "rules");
        assert_eq!(TagName::from("Play").display_name(), "Play");
    }
}
<commit_msg>Fix typo favourite -> favorite<commit_after>//! Types for the *m.tag* event.

use std::{collections::BTreeMap, error::Error, fmt, str::FromStr};

use ruma_events_macros::EventContent;
use ruma_serde::deserialize_cow_str;
use serde::{Deserialize, Serialize};

use crate::RoomAccountDataEvent;

/// Informs the client of tags on a room.
pub type TagEvent = RoomAccountDataEvent<TagEventContent>;

/// Map of tag names to tag info.
pub type Tags = BTreeMap<TagName, TagInfo>;

/// The payload for `TagEvent`.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.tag", kind = RoomAccountData)]
pub struct TagEventContent {
    /// A map of tag names to tag info.
    pub tags: Tags,
}

impl TagEventContent {
    /// Creates a new `TagEventContent` with the given `Tags`.
    pub fn new(tags: Tags) -> Self {
        Self { tags }
    }
}

impl From<Tags> for TagEventContent {
    fn from(tags: Tags) -> Self {
        Self::new(tags)
    }
}

/// A user-defined tag name.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct UserTagName {
    name: String,
}

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

impl FromStr for UserTagName {
    type Err = InvalidUserTagName;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.starts_with("u.") {
            Ok(Self { name: s.into() })
        } else {
            Err(InvalidUserTagName)
        }
    }
}

/// An error returned when attempting to create a UserTagName with a string that would make it
/// invalid.
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct InvalidUserTagName;

impl fmt::Display for InvalidUserTagName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "missing 'u.' prefix in UserTagName")
    }
}

impl Error for InvalidUserTagName {}

/// The name of a tag.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub enum TagName {
    /// `m.favourite`: The user's favorite rooms. These should be shown with higher precedence
    /// than other rooms.
    Favorite,

    /// `m.lowpriority`: These should be shown with lower precedence than others.
    LowPriority,

    /// `m.server_notice`: Used to identify
    /// [Server Notice Rooms](https://matrix.org/docs/spec/client_server/r0.6.1#module-server-notices).
    ServerNotice,

    /// `u.*`: User-defined tag
    User(UserTagName),

    /// A custom tag
    #[doc(hidden)]
    _Custom(String),
}

impl TagName {
    /// Returns the display name of the tag.
    ///
    /// That means the string after `m.` or `u.` for spec- and user-defined tag names, and the
    /// string after the last dot for custom tags. If no dot is found, returns the whole string.
    pub fn display_name(&self) -> &str {
        match self {
            Self::_Custom(s) => {
                let start = s.rfind('.').map(|p| p + 1).unwrap_or(0);
                &self.as_ref()[start..]
            }
            _ => &self.as_ref()[2..],
        }
    }
}

impl AsRef<str> for TagName {
    fn as_ref(&self) -> &str {
        match self {
            Self::Favorite => "m.favourite",
            Self::LowPriority => "m.lowpriority",
            Self::ServerNotice => "m.server_notice",
            Self::User(tag) => tag.as_ref(),
            Self::_Custom(s) => s,
        }
    }
}

impl<T> From<T> for TagName
where
    T: AsRef<str> + Into<String>,
{
    fn from(s: T) -> TagName {
        match s.as_ref() {
            "m.favourite" => Self::Favorite,
            "m.lowpriority" => Self::LowPriority,
            "m.server_notice" => Self::ServerNotice,
            s if s.starts_with("u.") => Self::User(UserTagName { name: s.into() }),
            s => Self::_Custom(s.into()),
        }
    }
}

impl fmt::Display for TagName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_ref())
    }
}

impl<'de> Deserialize<'de> for TagName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let cow = deserialize_cow_str(deserializer)?;
        Ok(cow.into())
    }
}

impl Serialize for TagName {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_ref())
    }
}

/// Information about a tag.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct TagInfo {
    /// Value to use for lexicographically ordering rooms with this tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order: Option<f64>,
}

impl TagInfo {
    /// Creates an empty `TagInfo`.
    pub fn new() -> Self {
        Default::default()
    }
}

#[cfg(test)]
mod tests {
    use maplit::btreemap;
    use serde_json::{json, to_value as to_json_value};

    use super::{TagEventContent, TagInfo, TagName};

    #[test]
    fn serialization() {
        let tags = btreemap! {
            TagName::Favorite => TagInfo::new(),
            TagName::LowPriority => TagInfo::new(),
            TagName::ServerNotice => TagInfo::new(),
            "u.custom".to_owned().into() => TagInfo { order: Some(0.9) }
        };

        let content = TagEventContent { tags };

        assert_eq!(
            to_json_value(content).unwrap(),
            json!({
                "tags": {
                    "m.favourite": {},
                    "m.lowpriority": {},
                    "m.server_notice": {},
                    "u.custom": {
                        "order": 0.9
                    }
                },
            })
        );
    }

    #[test]
    fn display_name() {
        assert_eq!(TagName::Favorite.display_name(), "favourite");
        assert_eq!(TagName::LowPriority.display_name(), "lowpriority");
        assert_eq!(TagName::ServerNotice.display_name(), "server_notice");
        assert_eq!(TagName::from("u.Work").display_name(), "Work");
        assert_eq!(TagName::from("rs.conduit.rules").display_name(), "rules");
        assert_eq!(TagName::from("Play").display_name(), "Play");
    }
}
<|endoftext|>


<commit_before>extern crate rsoundio;
extern crate rb;

use rb::{RB, SpscRb, RbProducer, RbConsumer};
use std::f32::consts::PI as PI32;
use std::thread;
use std::time::Duration;

const BUF_SIZE: usize = 2048;

fn main() {
    let rb = SpscRb::new(BUF_SIZE);
    let (producer, consumer) = (rb.producer(), rb.consumer());
    // create an audio context
    let mut sio = rsoundio::SoundIo::default();
    sio.set_name("rsoundio-example").unwrap();
    // connect to the default audio backend
    sio.connect().unwrap();
    let backend = sio.current_backend().unwrap();
    println!("Connected to backend: {}", backend);
    sio.flush_events();
    // get default output device
    let dev = sio.default_output_device().unwrap();
    assert!(dev.probe_error().is_none());
    println!("Using output device: {}", dev);
    // create output stream
    let mut out = dev.create_outstream().unwrap();
    assert!(out.set_name("sine").is_ok());
    out.set_format(rsoundio::SioFormat::Float32LE).unwrap();
    println!("Output format: {}", out.format().unwrap());

    thread::spawn(move || {
        const LEN: usize = BUF_SIZE/16;
        let mut pos = 0;
        loop {
            const F: f32 = 440.0;
            const W: f32 = 2.0 * F * PI32 / 48_000.0;
            const A: f32 = 0.6;
            const CYCLE: usize = (48_000f32 / F) as usize;

            let samples: Vec<f32> = (0..LEN)
                                        .map(|i| (W * (i + pos) as f32).sin() * A)
                                        .collect();
            producer.write_blocking(&samples).unwrap();
            pos = (pos + LEN) % CYCLE;
        }
    });

    // register callbacks
    out.register_write_callback(|out: rsoundio::OutStream,
                                 min_frame_count: u32,
                                 max_frame_count: u32| {
        let mut data = vec![0.0f32; BUF_SIZE];
        let len = if backend != rsoundio::SioBackend::PulseAudio {
            ::std::cmp::min(BUF_SIZE, max_frame_count as usize)
        } else {
            BUF_SIZE
        };
        consumer.read_blocking(&mut data[..len]);
        let frames = vec![data[..len].iter().cloned().collect(),
                          data[..len].iter().cloned().collect()];
        out.write_stream_f32(min_frame_count, &frames).unwrap();
    });
    out.register_underflow_callback(|out: rsoundio::OutStream| {
        println!("Underflow in {} occured!", out.name().unwrap())
    });
    out.register_error_callback(|out: rsoundio::OutStream, err: rsoundio::SioError| {
        println!("{} error: {}", out.name().unwrap(), err)
    });

    // open output stream
    out.open().unwrap();
    let sample_rate = out.sample_rate();
    println!("Sample rate: {}", sample_rate);

    match out.latency() {
        Ok(latency) => println!("SW latency: {}", latency),
        Err(err) => println!("err: {}", err),
    }
    let layout = out.layout();
    println!("Output channel layout: {}", layout);
    // start audio output (now the `write_callback` will be called periodically)
    out.start().unwrap();
    thread::sleep(Duration::new(3, 0));
    println!("Pause for 1s");
    out.pause();
    thread::sleep(Duration::new(1, 0));
    println!("Unpausing");
    out.unpause();
    thread::sleep(Duration::new(3, 0));
}
<commit_msg>Set latency to `sample-rate / buffer-size`<commit_after>extern crate rsoundio;
extern crate rb;

use rb::{RB, SpscRb, RbProducer, RbConsumer};
use std::f32::consts::PI as PI32;
use std::thread;
use std::time::Duration;

const BUF_SIZE: usize = 2048;

fn main() {
    let rb = SpscRb::new(BUF_SIZE);
    let (producer, consumer) = (rb.producer(), rb.consumer());
    // create an audio context
    let mut sio = rsoundio::SoundIo::default();
    sio.set_name("rsoundio-example").unwrap();
    // connect to the default audio backend
    sio.connect().unwrap();
    let backend = sio.current_backend().unwrap();
    println!("Connected to backend: {}", backend);
    sio.flush_events();
    // get default output device
    let dev = sio.default_output_device().unwrap();
    assert!(dev.probe_error().is_none());
    println!("Using output device: {}", dev);
    // create output stream
    let mut out = dev.create_outstream().unwrap();
    assert!(out.set_name("sine").is_ok());
    out.set_format(rsoundio::SioFormat::Float32LE).unwrap();
    println!("Output format: {}", out.format().unwrap());

    thread::spawn(move || {
        const LEN: usize = BUF_SIZE/16;
        let mut pos = 0;
        loop {
            const F: f32 = 440.0;
            const W: f32 = 2.0 * F * PI32 / 48_000.0;
            const A: f32 = 0.6;
            const CYCLE: usize = (48_000f32 / F) as usize;

            let samples: Vec<f32> = (0..LEN)
                                        .map(|i| (W * (i + pos) as f32).sin() * A)
                                        .collect();
            producer.write_blocking(&samples).unwrap();
            pos = (pos + LEN) % CYCLE;
        }
    });

    // register callbacks
    out.register_write_callback(|out: rsoundio::OutStream,
                                 min_frame_count: u32,
                                 max_frame_count: u32| {
        let mut data = vec![0.0f32; BUF_SIZE];
        let len = if backend != rsoundio::SioBackend::PulseAudio {
            ::std::cmp::min(BUF_SIZE, max_frame_count as usize)
        } else {
            BUF_SIZE
        };
        consumer.read_blocking(&mut data[..len]);
        let frames = vec![data[..len].iter().cloned().collect(),
                          data[..len].iter().cloned().collect()];
        out.write_stream_f32(min_frame_count, &frames).unwrap();
    });
    out.register_underflow_callback(|out: rsoundio::OutStream| {
        println!("Underflow in {} occured!", out.name().unwrap())
    });
    out.register_error_callback(|out: rsoundio::OutStream, err: rsoundio::SioError| {
        println!("{} error: {}", out.name().unwrap(), err)
    });

    // open output stream
    out.open().unwrap();
    let sample_rate = out.sample_rate();
    println!("Sample rate: {}", sample_rate);

    out.set_latency(sample_rate as f64/BUF_SIZE as f64);
    match out.latency() {
        Ok(latency) => println!("SW latency: {}", latency),
        Err(err) => println!("err: {}", err),
    }
    let layout = out.layout();
    println!("Output channel layout: {}", layout);
    // start audio output (now the `write_callback` will be called periodically)
    out.start().unwrap();
    thread::sleep(Duration::new(3, 0));
    println!("Pause for 1s");
    out.pause();
    thread::sleep(Duration::new(1, 0));
    println!("Unpausing");
    out.unpause();
    thread::sleep(Duration::new(3, 0));
}
<|endoftext|>


<commit_before>use std::collections::{HashMap, BinaryHeap, VecDeque};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::iter::repeat;
use std::cmp::Ordering;
use std::usize;

type Node = usize;
type Cost = usize;
type Edge = (Node, Node);

/// The `DistPair` struct is for the priority queue.
#[derive(Eq, PartialEq, PartialOrd)]
struct DistPair(Node, Cost);
impl Ord for DistPair {
    fn cmp(&self, other: &DistPair) -> Ordering {
        let DistPair(_, dist_a) = *self;
        let DistPair(_, dist_b) = *other;
        dist_b.cmp(&dist_a) //Intentionally reversed
    }
}

/// Graph structure, represented as an adjacency List.
struct Graph<'a> {
    vertices: Vec<&'a str>,
    adj_list: Vec<Vec<Node>>,
    costs: HashMap<Edge, Cost>,
}

impl<'a> Graph<'a> {
    fn new() -> Graph<'a> {
        let vertices: Vec<&str> = Vec::new();
        let adj_list: Vec<Vec<Node>> = Vec::new();
        let costs: HashMap<Edge, Cost> = HashMap::new();

        Graph {
            vertices: vertices,
            adj_list: adj_list,
            costs: costs,
        }
    }

    /// Returns the index of the vertex, or `None` if vertex not found.
    fn vertex_index(&self, vertex: &str) -> Option<Node> {
        for (idx, &v) in self.vertices.iter().enumerate() {
            if v == vertex {
                return Some(idx);
            }
        }
        None
    }

    /// Returns the index of the vertex. If vertex is not found, inserts the vertex.
    fn get_or_insert_vertex(&mut self, vertex: &'a str) -> Node {
        self.vertex_index(vertex)
            .unwrap_or_else(|| {
                self.adj_list.push(Vec::new());
                self.vertices.push(vertex);
                self.vertices.len() - 1
            })
    }

    /// Adds the given edge to the graph.
    fn add_edge(&mut self, from: &'a str, to: &'a str, cost: usize) {
        let from_idx = self.get_or_insert_vertex(from);
        let to_idx = self.get_or_insert_vertex(to);

        match self.costs.entry((from_idx, to_idx)) {
            Vacant(entry) => {
                self.adj_list[from_idx].push(to_idx);
                entry.insert(cost);
            }
            Occupied(entry) => {
                *entry.into_mut() = cost;
            }
        };
    }

    /// Implements Dijkstra's algorithm. This uses a priority queue to determine which vertex to
    /// visit first. Terminates on discovering the target vertex.
    ///
    /// Returns vector of vertices representing the path, or an empty vector if there's no path, or
    /// if the source or target is not in the graph.
    fn dijkstra(&'a self, source: &str, target: &str) -> Vec<&str> {
        let num_vert = self.vertices.len();
        let mut dist: Vec<usize> = repeat(usize::MAX)
            .take(num_vert)
            .collect(); //Close enough to infinity
        let mut prev: HashMap<Node, Node> = HashMap::new();
        let mut queue: BinaryHeap<DistPair> = BinaryHeap::new();

        let source_idx = match self.vertex_index(source) {
            Some(idx) => idx,
            None => return Vec::new(), // Source not in graph, return empty path.
        };

        let target_idx = match self.vertex_index(target) {
            Some(idx) => idx,
            None => return Vec::new(), // Target not in graph, return empty path.
        };

        dist[source_idx] = 0;
        queue.push(DistPair(source_idx, dist[source_idx]));

        loop {
            match queue.pop() {
                None => break,
                Some(DistPair(u, dist_u)) => {
                    for &v in &(self.adj_list[u]) {
                        let cost_uv = match self.costs.get(&(u, v)) {
                            Some(&x) => x,
                            None => usize::MAX,
                        };
                        let alt = dist_u + cost_uv;
                        if alt < dist[v] {
                            match prev.entry(v) {
                                Vacant(entry) => {
                                    entry.insert(u);
                                }
                                Occupied(entry) => {
                                    *entry.into_mut() = u;
                                }
                            }
                            dist[v] = alt;
                            queue.push(DistPair(v, dist[v]));
                        }
                        if v == target_idx {
                            break;
                        }
                    }
                }
            };
        }

        let mut temp_path: VecDeque<&str> = VecDeque::new();
        let mut curr = target_idx;
        temp_path.push_front(self.vertices[curr]);
        loop {
            match prev.get(&curr) {
                Some(&parent) => {
                    curr = parent;
                    temp_path.push_front(self.vertices[curr]);
                    if curr == source_idx {
                        break;
                    }
                }
                None => return Vec::new(),
            }
        }
        temp_path.into_iter().collect()
    }
}

impl<'a> Default for Graph<'a> {
    fn default() -> Self {
        Self::new()
    }
}

#[test]
fn test_dijkstras() {
    let mut graph = Graph::new();
    graph.add_edge("a", "b", 7);
    graph.add_edge("b", "c", 10);
    graph.add_edge("c", "d", 5);
    graph.add_edge("a", "d", 30);
    graph.add_edge("y", "z", 10); //Disconnected from the rest

    assert_eq!(graph.dijkstra("a", "d"), vec!["a", "b", "c", "d"]);
    assert!(graph.dijkstra("a", "y").is_empty());
    assert!(graph.dijkstra("e", "y").is_empty());
    assert!(graph.dijkstra("a", "e").is_empty());
}

fn main() {
    let mut graph = Graph::new();
    graph.add_edge("a", "b", 7);
    graph.add_edge("a", "c", 9);
    graph.add_edge("a", "f", 14);
    graph.add_edge("b", "c", 10);
    graph.add_edge("b", "d", 15);
    graph.add_edge("c", "d", 11);
    graph.add_edge("c", "f", 2);
    graph.add_edge("d", "e", 6);
    graph.add_edge("e", "f", 9);

    let path = graph.dijkstra("a", "e");
    println!("Path is: {:?}", path);
}
<commit_msg>cleanup Dijkstra's<commit_after>use std::collections::{BinaryHeap, HashMap, VecDeque};
use std::cmp::Ordering;
use std::usize;

type Node = usize;
type Cost = usize;
type Edge = (Node, Node);

/// The `DistPair` struct is for the priority queue.
#[derive(Eq, PartialEq, PartialOrd)]
struct DistPair(Node, Cost);
impl Ord for DistPair {
    fn cmp(&self, other: &DistPair) -> Ordering {
        let DistPair(_, dist_a) = *self;
        let DistPair(_, dist_b) = *other;
        dist_b.cmp(&dist_a) // Intentionally reversed
    }
}

/// Graph structure, represented as an adjacency List.
struct Graph<'a> {
    vertices: Vec<&'a str>,
    adj_list: Vec<Vec<Node>>,
    costs: HashMap<Edge, Cost>,
}

impl<'a> Graph<'a> {
    fn new() -> Graph<'a> {
        Graph {
            vertices: Vec::new(),
            adj_list: Vec::new(),
            costs: HashMap::new(),
        }
    }

    /// Returns the index of the vertex, or `None` if vertex not found.
    fn vertex_index(&self, vertex: &str) -> Option<Node> {
        self.vertices.iter().position(|&v| v == vertex)
    }

    /// Returns the index of the vertex. If vertex is not found, inserts the vertex.
    fn get_or_insert_vertex(&mut self, vertex: &'a str) -> Node {
        self.vertex_index(vertex).unwrap_or_else(|| {
            self.adj_list.push(Vec::new());
            self.vertices.push(vertex);
            self.vertices.len() - 1
        })
    }

    /// Adds the given edge to the graph.
    fn add_edge(&mut self, from: &'a str, to: &'a str, cost: usize) {
        let from_idx = self.get_or_insert_vertex(from);
        let to_idx = self.get_or_insert_vertex(to);

        // Insert, and then if the insertion added a new key-value pair...
        if self.costs.insert((from_idx, to_idx), cost).is_none() {
            self.adj_list[from_idx].push(to_idx);
        }
    }

    /// Implements Dijkstra's algorithm. This uses a priority queue to determine which vertex to
    /// visit first. Terminates on discovering the target vertex.
    ///
    /// Returns vector of vertices representing the path, or an empty vector if there's no path, or
    /// if the source or target is not in the graph.
    fn dijkstra(&self, source: &str, target: &str) -> Vec<&str> {
        let num_vert = self.vertices.len();
        let mut dist = vec![usize::MAX; num_vert]; // Close enough to infinity
        let mut prev: HashMap<Node, Node> = HashMap::new();
        let mut queue: BinaryHeap<DistPair> = BinaryHeap::new();

        let source_idx = match self.vertex_index(source) {
            Some(idx) => idx,
            None => return Vec::new(), // Source not in graph, return empty path.
        };

        let target_idx = match self.vertex_index(target) {
            Some(idx) => idx,
            None => return Vec::new(), // Target not in graph, return empty path.
        };

        dist[source_idx] = 0;
        queue.push(DistPair(source_idx, dist[source_idx]));

        while let Some(DistPair(u, dist_u)) = queue.pop() {
            for &v in &(self.adj_list[u]) {
                let cost_uv = self.costs.get(&(u, v)).unwrap_or(&usize::MAX);
                let alt = dist_u + cost_uv;
                if alt < dist[v] {
                    prev.insert(v, u);
                    dist[v] = alt;
                    queue.push(DistPair(v, dist[v]));
                }
                if v == target_idx {
                    break;
                }
            }
        }

        let mut temp_path: VecDeque<&str> = VecDeque::new();
        let mut curr = target_idx;
        temp_path.push_front(self.vertices[curr]);
        while let Some(&parent) = prev.get(&curr) {
            curr = parent;
            temp_path.push_front(self.vertices[curr]);
            if curr == source_idx {
                return Vec::from(temp_path);
            }
        }
        Vec::new()
    }
}

impl<'a> Default for Graph<'a> {
    fn default() -> Self {
        Self::new()
    }
}

fn main() {
    let mut graph = Graph::new();
    graph.add_edge("a", "b", 7);
    graph.add_edge("a", "c", 9);
    graph.add_edge("a", "f", 14);
    graph.add_edge("b", "c", 10);
    graph.add_edge("b", "d", 15);
    graph.add_edge("c", "d", 11);
    graph.add_edge("c", "f", 2);
    graph.add_edge("d", "e", 6);
    graph.add_edge("e", "f", 9);

    let path = graph.dijkstra("a", "e");
    println!("Path is: {:?}", path);
}

#[test]
fn test_dijkstras() {
    let mut graph = Graph::new();
    graph.add_edge("a", "b", 7);
    graph.add_edge("b", "c", 10);
    graph.add_edge("c", "d", 5);
    graph.add_edge("a", "d", 30);
    graph.add_edge("y", "z", 10); //Disconnected from the rest

    assert_eq!(graph.dijkstra("a", "d"), ["a", "b", "c", "d"]);
    assert!(graph.dijkstra("a", "y").is_empty());
    assert!(graph.dijkstra("e", "y").is_empty());
    assert!(graph.dijkstra("a", "e").is_empty());

    let mut graph = Graph::new();
    graph.add_edge("a", "b", 7);
    graph.add_edge("a", "c", 9);
    graph.add_edge("a", "f", 14);
    graph.add_edge("b", "c", 10);
    graph.add_edge("b", "d", 15);
    graph.add_edge("c", "d", 11);
    graph.add_edge("c", "f", 2);
    graph.add_edge("d", "e", 6);
    graph.add_edge("e", "f", 9);

    assert_eq!(graph.dijkstra("a", "e"), ["a", "c", "d", "e"]);
}
<|endoftext|>


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

use std::ptr;
use std::slice;
use std::ffi;

use htslib;

pub struct Record {
    pub inner: *mut htslib::vcf::bcf1_t,
    pub header: *mut htslib::vcf::bcf_hdr_t,
    buffer: *mut ::libc::c_void,
}

impl Record {
    pub fn new() -> Self {
        let inner = unsafe { htslib::vcf::bcf_init() };
        Record { inner: inner, header: ptr::null_mut(), buffer: ptr::null_mut() }
    }

    #[inline]
    fn inner(&self) -> htslib::vcf::bcf1_t {
        unsafe { *self.inner }
    }

    pub fn rid(&self) -> Option<u32> {
        match self.inner().rid {
            -1  => None,
            rid => Some(rid as u32)
        }
    }

    // 0-based position.
    pub fn pos(&self) -> u32 {
        self.inner().pos as u32
    }

    pub fn alleles(&self) -> Vec<&[u8]> {
        unsafe { htslib::vcf::bcf_unpack(self.inner, htslib::vcf::BCF_UN_STR) };
        let n = self.inner().n_allele as usize;
        let dec = self.inner().d;
        let alleles = unsafe { slice::from_raw_parts(dec.allele, n) };
        (0..n).map(|i| unsafe { ffi::CStr::from_ptr(alleles[i]).to_bytes() }).collect()
    }

    pub fn qual(&self) -> f32 {
        self.inner().qual
    }

    /// Get the value of the given info tag.
    pub fn info<'a>(&'a mut self, tag: &'a [u8]) -> Info {
        Info { record: self, tag: tag }
    }

    pub fn sample_count(&self) -> u32 {
        self.inner().n_fmt_n_sample & 0xffffff
    }

    pub fn allele_count(&self) -> u16 {
        self.inner().n_allele
    }

    /// Get the value of the given format tag for each sample.
    pub fn format<'a>(&'a mut self, tag: &'a [u8]) -> Format {
        Format::new(self, tag)
    }

    /// Add an integer format tag. Data is a two dimensional array of integers.
    /// The first dimension contains one array for each sample.
    pub fn push_format_integer(&mut self, tag: &[u8], data: &[&[i32]]) -> Result<(), ()> {
        self.push_format(tag, data)
    }

    /// Add a float format tag. Data is a two dimensional array of floats.
    /// The first dimension contains one array for each sample.
    pub fn push_format_float(&mut self, tag: &[u8], data: &[&[f32]]) -> Result<(), ()> {
        self.push_format(tag, data)
    }

    /// Add a format tag. Data is a two dimensional array.
    /// The first dimension contains one array for each sample.
    fn push_format<T>(&mut self, tag: &[u8], data: &[&[T]]) -> Result<(), ()> {
        assert!(data.len() != 0 && data[0].len() != 0);
        unsafe {
            if htslib::vcf::bcf_update_format(
                self.header,
                self.inner,
                ffi::CString::new(tag).unwrap().as_ptr() as *mut i8,
                data.as_ptr() as *mut ::libc::c_void,
                (data.len() * data[0].len()) as i32,
                htslib::vcf::BCF_HT_INT
            ) == 0 {
                Ok(())
            }
            else {
                Err(())
            }
        }
    }

    pub fn set_qual(&mut self, qual: f32) {
        self.inner().qual = qual;
    }
}

impl Drop for Record {
    fn drop(&mut self) {
        if !self.buffer.is_null() {
            unsafe { ::libc::free(self.buffer) };
        }
        unsafe { htslib::vcf::bcf_destroy(self.inner) };
    }
}

unsafe impl Send for Record {}

pub struct Info<'a> {
    record: &'a mut Record,
    tag: &'a [u8],
}

impl<'a> Info<'a> {
    fn data(&mut self, data_type: i32) -> Result<(usize, i32), TagError> {
        let mut n: i32 = 0;
        match unsafe {
            htslib::vcf::bcf_get_info_values(
                self.record.header,
                self.record.inner,
                ffi::CString::new(self.tag).unwrap().as_ptr() as *mut i8,
                &mut self.record.buffer,
                &mut n,
                data_type
            )
        } {
            -1 => Err(TagError::UndefinedTag),
            -2 => Err(TagError::UnexpectedType),
            -3 => Err(TagError::MissingTag),
            ret  => Ok((n as usize, ret)),
        }
    }

    pub fn integer(&mut self) -> Result<&mut [i32], TagError> {
        self.data(htslib::vcf::BCF_HT_INT).map(|(n, _)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut i32, n) }
        })
    }

    pub fn float(&mut self) -> Result<&mut [f32], TagError> {
        self.data(htslib::vcf::BCF_HT_REAL).map(|(n, _)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut f32, n) }
        })
    }

    pub fn flag(&mut self) -> Result<bool, TagError> {
        self.data(htslib::vcf::BCF_HT_FLAG).map(|(_, ret)| {
            ret == 1
        })
    }

    pub fn string(&mut self) -> Result<&mut [u8], TagError> {
        self.data(htslib::vcf::BCF_HT_STR).map(|(_, ret)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut u8, ret as usize) }
        })
    }
}

// TODO implement format.
pub struct Format<'a> {
    record: &'a mut Record,
    tag: &'a [u8],
    inner: *mut htslib::vcf::bcf_fmt_t,
}

impl<'a> Format<'a> {
    fn new(record: &'a mut Record, tag: &'a [u8]) -> Format<'a> {
        let inner = unsafe { htslib::vcf::bcf_get_fmt(
            record.header,
            record.inner,
            ffi::CString::new(tag).unwrap().as_ptr() as *mut i8
        ) };
        Format { record: record, tag: tag, inner: inner }
    }

    fn values_per_sample(&self) -> usize {
        unsafe { (*self.inner).n as usize }
    }

    fn data(&mut self, data_type: i32) -> Result<(usize, i32), TagError> {
        let mut n: i32 = 0;
        match unsafe {
            htslib::vcf::bcf_get_format_values(
                self.record.header,
                self.record.inner,
                ffi::CString::new(self.tag).unwrap().as_ptr() as *mut i8,
                &mut self.record.buffer,
                &mut n,
                data_type
            )
        } {
            -1 => Err(TagError::UndefinedTag),
            -2 => Err(TagError::UnexpectedType),
            -3 => Err(TagError::MissingTag),
            ret  => Ok((n as usize, ret)),
        }
    }

    pub fn integer(&mut self) -> Result<Vec<&mut [i32]>, TagError> {
        self.data(htslib::vcf::BCF_HT_INT).map(|(n, _)| {
            unsafe {
                slice::from_raw_parts_mut(self.record.buffer as *mut i32, n)
            }.chunks_mut(self.values_per_sample()).collect()
        })
    }

    pub fn float(&mut self) -> Result<Vec<&mut [f32]>, TagError> {
        self.data(htslib::vcf::BCF_HT_REAL).map(|(n, _)| {
            unsafe {
                slice::from_raw_parts_mut(self.record.buffer as *mut f32, n)
            }.chunks_mut(self.values_per_sample()).collect()
        })
    }
}

pub enum TagError {
    UndefinedTag,
    UnexpectedType,
    MissingTag,
}
<commit_msg>Fixed push_format_tag.<commit_after>// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

use std::ptr;
use std::slice;
use std::ffi;

use htslib;

pub struct Record {
    pub inner: *mut htslib::vcf::bcf1_t,
    pub header: *mut htslib::vcf::bcf_hdr_t,
    buffer: *mut ::libc::c_void,
}

impl Record {
    pub fn new() -> Self {
        let inner = unsafe { htslib::vcf::bcf_init() };
        Record { inner: inner, header: ptr::null_mut(), buffer: ptr::null_mut() }
    }

    #[inline]
    fn inner(&self) -> htslib::vcf::bcf1_t {
        unsafe { *self.inner }
    }

    pub fn rid(&self) -> Option<u32> {
        match self.inner().rid {
            -1  => None,
            rid => Some(rid as u32)
        }
    }

    // 0-based position.
    pub fn pos(&self) -> u32 {
        self.inner().pos as u32
    }

    pub fn alleles(&self) -> Vec<&[u8]> {
        unsafe { htslib::vcf::bcf_unpack(self.inner, htslib::vcf::BCF_UN_STR) };
        let n = self.inner().n_allele as usize;
        let dec = self.inner().d;
        let alleles = unsafe { slice::from_raw_parts(dec.allele, n) };
        (0..n).map(|i| unsafe { ffi::CStr::from_ptr(alleles[i]).to_bytes() }).collect()
    }

    pub fn qual(&self) -> f32 {
        self.inner().qual
    }

    /// Get the value of the given info tag.
    pub fn info<'a>(&'a mut self, tag: &'a [u8]) -> Info {
        Info { record: self, tag: tag }
    }

    pub fn sample_count(&self) -> u32 {
        self.inner().n_fmt_n_sample & 0xffffff
    }

    pub fn allele_count(&self) -> u16 {
        self.inner().n_allele
    }

    /// Get the value of the given format tag for each sample.
    pub fn format<'a>(&'a mut self, tag: &'a [u8]) -> Format {
        Format::new(self, tag)
    }

    /// Add an integer format tag. Data is a flattened two-dimensional array.
    /// The first dimension contains one array for each sample.
    pub fn push_format_integer(&mut self, tag: &[u8], data: &[i32]) -> Result<(), ()> {
        self.push_format(tag, data)
    }

    /// Add a float format tag. Data is a flattened two-dimensional array.
    /// The first dimension contains one array for each sample.
    pub fn push_format_float(&mut self, tag: &[u8], data: &[f32]) -> Result<(), ()> {
        self.push_format(tag, data)
    }

    /// Add a format tag. Data is a flattened two-dimensional array.
    /// The first dimension contains one array for each sample.
    fn push_format<T>(&mut self, tag: &[u8], data: &[T]) -> Result<(), ()> {
        assert!(data.len() > 0);
        unsafe {
            if htslib::vcf::bcf_update_format(
                self.header,
                self.inner,
                ffi::CString::new(tag).unwrap().as_ptr() as *mut i8,
                data.as_ptr() as *mut ::libc::c_void,
                data.len() as i32,
                htslib::vcf::BCF_HT_INT
            ) == 0 {
                Ok(())
            }
            else {
                Err(())
            }
        }
    }

    pub fn set_qual(&mut self, qual: f32) {
        self.inner().qual = qual;
    }
}

impl Drop for Record {
    fn drop(&mut self) {
        if !self.buffer.is_null() {
            unsafe { ::libc::free(self.buffer) };
        }
        unsafe { htslib::vcf::bcf_destroy(self.inner) };
    }
}

unsafe impl Send for Record {}

pub struct Info<'a> {
    record: &'a mut Record,
    tag: &'a [u8],
}

impl<'a> Info<'a> {
    fn data(&mut self, data_type: i32) -> Result<(usize, i32), TagError> {
        let mut n: i32 = 0;
        match unsafe {
            htslib::vcf::bcf_get_info_values(
                self.record.header,
                self.record.inner,
                ffi::CString::new(self.tag).unwrap().as_ptr() as *mut i8,
                &mut self.record.buffer,
                &mut n,
                data_type
            )
        } {
            -1 => Err(TagError::UndefinedTag),
            -2 => Err(TagError::UnexpectedType),
            -3 => Err(TagError::MissingTag),
            ret  => Ok((n as usize, ret)),
        }
    }

    pub fn integer(&mut self) -> Result<&mut [i32], TagError> {
        self.data(htslib::vcf::BCF_HT_INT).map(|(n, _)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut i32, n) }
        })
    }

    pub fn float(&mut self) -> Result<&mut [f32], TagError> {
        self.data(htslib::vcf::BCF_HT_REAL).map(|(n, _)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut f32, n) }
        })
    }

    pub fn flag(&mut self) -> Result<bool, TagError> {
        self.data(htslib::vcf::BCF_HT_FLAG).map(|(_, ret)| {
            ret == 1
        })
    }

    pub fn string(&mut self) -> Result<&mut [u8], TagError> {
        self.data(htslib::vcf::BCF_HT_STR).map(|(_, ret)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut u8, ret as usize) }
        })
    }
}

// TODO implement format.
pub struct Format<'a> {
    record: &'a mut Record,
    tag: &'a [u8],
    inner: *mut htslib::vcf::bcf_fmt_t,
}

impl<'a> Format<'a> {
    fn new(record: &'a mut Record, tag: &'a [u8]) -> Format<'a> {
        let inner = unsafe { htslib::vcf::bcf_get_fmt(
            record.header,
            record.inner,
            ffi::CString::new(tag).unwrap().as_ptr() as *mut i8
        ) };
        Format { record: record, tag: tag, inner: inner }
    }

    fn values_per_sample(&self) -> usize {
        unsafe { (*self.inner).n as usize }
    }

    fn data(&mut self, data_type: i32) -> Result<(usize, i32), TagError> {
        let mut n: i32 = 0;
        match unsafe {
            htslib::vcf::bcf_get_format_values(
                self.record.header,
                self.record.inner,
                ffi::CString::new(self.tag).unwrap().as_ptr() as *mut i8,
                &mut self.record.buffer,
                &mut n,
                data_type
            )
        } {
            -1 => Err(TagError::UndefinedTag),
            -2 => Err(TagError::UnexpectedType),
            -3 => Err(TagError::MissingTag),
            ret  => Ok((n as usize, ret)),
        }
    }

    pub fn integer(&mut self) -> Result<Vec<&mut [i32]>, TagError> {
        self.data(htslib::vcf::BCF_HT_INT).map(|(n, _)| {
            unsafe {
                slice::from_raw_parts_mut(self.record.buffer as *mut i32, n)
            }.chunks_mut(self.values_per_sample()).collect()
        })
    }

    pub fn float(&mut self) -> Result<Vec<&mut [f32]>, TagError> {
        self.data(htslib::vcf::BCF_HT_REAL).map(|(n, _)| {
            unsafe {
                slice::from_raw_parts_mut(self.record.buffer as *mut f32, n)
            }.chunks_mut(self.values_per_sample()).collect()
        })
    }
}

pub enum TagError {
    UndefinedTag,
    UnexpectedType,
    MissingTag,
}
<|endoftext|>


<commit_before>use std::error::Error;
use std::io;
use std::str;
use std::io::Write;

use itertools::Itertools;
use rust_htslib::bcf;

pub struct Writer {
    inner: io::BufWriter<io::Stdout>,
    field_count: usize
}

impl Writer {
    fn new(inner: io::BufWriter<io::Stdout>) -> Self {
        Writer {
            inner: inner,
            field_count: 0
        }
    }

    fn write_integer(&mut self, value: i32) -> Result<(), Box<Error>> {
        self.write_field(format!("{}", value).as_bytes())
    }

    fn write_float(&mut self, value: f32) -> Result<(), Box<Error>> {
        self.write_field(format!("{}", value).as_bytes())
    }

    fn write_flag(&mut self, value: bool) -> Result<(), Box<Error>> {
        self.write_field(format!("{}", value).as_bytes())
    }

    fn write_field(&mut self, value: &[u8]) -> Result<(), Box<Error>> {
        if self.field_count > 0 {
            try!(self.inner.write(b"\t"));
        }
        try!(self.inner.write(value));
        self.field_count += 1;
        Ok(())
    }

    fn newline(&mut self) -> Result<(), Box<Error>> {
        try!(self.inner.write(b"\n"));
        self.field_count = 0;
        Ok(())
    }
}

const HEADER_COMMON: &'static [u8] = b"VARIANT";

pub fn to_txt(
    info_tags: &[&str],
    format_tags: &[&str],
    show_genotypes: bool
) -> Result<(), Box<Error>> {
    let reader = try!(bcf::Reader::new(&"-"));
    let mut writer = Writer::new(io::BufWriter::new(io::stdout()));

    let common_n = 5 + info_tags.len();
    try!(writer.write_field(HEADER_COMMON));
    for _ in 1..common_n {
        try!(writer.write_field(HEADER_COMMON));
    }
    for sample in reader.header.samples() {
        try!(writer.write_field(sample));
        for _ in 1..format_tags.len() + show_genotypes as usize {
            try!(writer.write_field(sample));
        }
    }
    try!(writer.newline());
    try!(writer.write_field(b"CHROM"));
    try!(writer.write_field(b"POS"));
    try!(writer.write_field(b"REF"));
    try!(writer.write_field(b"ALT"));
    try!(writer.write_field(b"QUAL"));
    for name in info_tags {
        try!(writer.write_field(name.as_bytes()));
    }
    for _ in 0..reader.header.sample_count() {
        if show_genotypes {
            try!(writer.write_field(b"GT"));
        }
        for name in format_tags {
            try!(writer.write_field(name.as_bytes()));
        }
    }
    try!(writer.newline());

    let mut record = bcf::Record::new();
    loop {
        if let Err(e) = reader.read(&mut record) {
            if e.is_eof() {
                break;
            } else {
                return Err(Box::new(e));
            }
        }

        let alleles = record.alleles().into_iter().map(|a| a.to_owned()).collect_vec();
        for (i, allele) in alleles[1..].iter().enumerate() {
            try!(writer.write_field(reader.header.rid2name(record.rid().unwrap())));
            try!(writer.write_integer(record.pos() as i32 + 1));
            try!(writer.write_field(&alleles[0]));
            try!(writer.write_field(allele));
            match record.qual() {
                q if q == bcf::record::MISSING_FLOAT => try!(writer.write_field(b"")),
                q => try!(writer.write_float(q))
            }

            for name in info_tags {
                let _name = name.as_bytes();
                let (tag_type, tag_length) = try!(reader.header.info_type(_name));
                let i = match tag_length {
                    bcf::header::TagLength::Fixed => {
                        0
                    },
                    bcf::header::TagLength::AltAlleles => {
                        i
                    },
                    _ => return Err(Box::new(ParseError::UnsupportedTagLength))
                };

                match tag_type {
                    bcf::header::TagType::Flag => {
                        try!(writer.write_flag(try!(record.info(_name).flag())));
                    },
                    bcf::header::TagType::Integer => {
                        if let Some(values) = try!(record.info(_name).integer()) {
                            try!(writer.write_integer(values[i]));
                        } else {
                            try!(writer.write_field(b""));
                        }
                    },
                    bcf::header::TagType::Float => {
                        if let Some(values) = try!(record.info(_name).float()) {
                            try!(writer.write_float(values[i]));
                        } else {
                            try!(writer.write_field(b""));
                        }
                    },
                    bcf::header::TagType::String => {
                        if let Some(values) = try!(record.info(_name).string()) {
                            try!(writer.write_field(values[i]));
                        } else {
                            try!(writer.write_field(b""));
                        }
                    }
                }
            }

            let genotypes = if show_genotypes {
                let genotypes = try!(record.genotypes());
                Some(
                    (0..reader.header.sample_count() as usize).map(|s| {
                        format!("{}", genotypes.get(s))
                    }).collect_vec()
                )
            } else {
                None
            };

            for s in 0..reader.header.sample_count() as usize {
                if let Some(ref genotypes) = genotypes {
                    try!(writer.write_field(genotypes[s].as_bytes()));
                }
                for name in format_tags {
                    let _name = name.as_bytes();
                    let (tag_type, tag_length) = try!(reader.header.format_type(_name));
                    let i = match tag_length {
                        bcf::header::TagLength::Fixed => {
                            0
                        },
                        bcf::header::TagLength::AltAlleles => {
                            i
                        },
                        _ => return Err(Box::new(ParseError::UnsupportedTagLength))
                    };

                    match tag_type {
                        bcf::header::TagType::Flag => {
                            panic!("there is no flag type for format");
                        },
                        bcf::header::TagType::Integer => {
                            try!(writer.write_field(format!("{}", try!(record.format(_name).integer())[s][i]).as_bytes()));
                        },
                        bcf::header::TagType::Float => {
                            try!(writer.write_field(format!("{}", try!(record.format(_name).float())[s][i]).as_bytes()));
                        },
                        bcf::header::TagType::String => {
                            try!(writer.write_field(try!(record.format(_name).string())[s]));
                        }
                    }
                }
            }
            try!(writer.newline());
        }
    }

    Ok(())
}

quick_error! {
    #[derive(Debug)]
    pub enum ParseError {
        UnsupportedTagLength {
            description("currently, only A and 1 are supported multiplicities of tags")
        }

    }
}
<commit_msg>Allow undefined tags.<commit_after>use std::error::Error;
use std::io;
use std::str;
use std::io::Write;

use itertools::Itertools;
use rust_htslib::bcf;

pub struct Writer {
    inner: io::BufWriter<io::Stdout>,
    field_count: usize
}

impl Writer {
    fn new(inner: io::BufWriter<io::Stdout>) -> Self {
        Writer {
            inner: inner,
            field_count: 0
        }
    }

    fn write_integer(&mut self, value: i32) -> Result<(), Box<Error>> {
        self.write_field(format!("{}", value).as_bytes())
    }

    fn write_float(&mut self, value: f32) -> Result<(), Box<Error>> {
        self.write_field(format!("{}", value).as_bytes())
    }

    fn write_flag(&mut self, value: bool) -> Result<(), Box<Error>> {
        self.write_field(format!("{}", value).as_bytes())
    }

    fn write_field(&mut self, value: &[u8]) -> Result<(), Box<Error>> {
        if self.field_count > 0 {
            try!(self.inner.write(b"\t"));
        }
        try!(self.inner.write(value));
        self.field_count += 1;
        Ok(())
    }

    fn newline(&mut self) -> Result<(), Box<Error>> {
        try!(self.inner.write(b"\n"));
        self.field_count = 0;
        Ok(())
    }
}

const HEADER_COMMON: &'static [u8] = b"VARIANT";

pub fn to_txt(
    info_tags: &[&str],
    format_tags: &[&str],
    show_genotypes: bool
) -> Result<(), Box<Error>> {
    let reader = try!(bcf::Reader::new(&"-"));
    let mut writer = Writer::new(io::BufWriter::new(io::stdout()));

    let common_n = 5 + info_tags.len();
    try!(writer.write_field(HEADER_COMMON));
    for _ in 1..common_n {
        try!(writer.write_field(HEADER_COMMON));
    }
    for sample in reader.header.samples() {
        try!(writer.write_field(sample));
        for _ in 1..format_tags.len() + show_genotypes as usize {
            try!(writer.write_field(sample));
        }
    }
    try!(writer.newline());
    try!(writer.write_field(b"CHROM"));
    try!(writer.write_field(b"POS"));
    try!(writer.write_field(b"REF"));
    try!(writer.write_field(b"ALT"));
    try!(writer.write_field(b"QUAL"));
    for name in info_tags {
        try!(writer.write_field(name.as_bytes()));
    }
    for _ in 0..reader.header.sample_count() {
        if show_genotypes {
            try!(writer.write_field(b"GT"));
        }
        for name in format_tags {
            try!(writer.write_field(name.as_bytes()));
        }
    }
    try!(writer.newline());

    let mut record = bcf::Record::new();
    loop {
        if let Err(e) = reader.read(&mut record) {
            if e.is_eof() {
                break;
            } else {
                return Err(Box::new(e));
            }
        }

        let alleles = record.alleles().into_iter().map(|a| a.to_owned()).collect_vec();
        for (i, allele) in alleles[1..].iter().enumerate() {
            try!(writer.write_field(reader.header.rid2name(record.rid().unwrap())));
            try!(writer.write_integer(record.pos() as i32 + 1));
            try!(writer.write_field(&alleles[0]));
            try!(writer.write_field(allele));
            match record.qual() {
                q if q == bcf::record::MISSING_FLOAT => try!(writer.write_field(b"")),
                q => try!(writer.write_float(q))
            }

            for name in info_tags {
                let _name = name.as_bytes();
                if let Ok((tag_type, tag_length)) = reader.header.info_type(_name) {
                    let i = match tag_length {
                        bcf::header::TagLength::Fixed => {
                            0
                        },
                        bcf::header::TagLength::AltAlleles => {
                            i
                        },
                        _ => return Err(Box::new(ParseError::UnsupportedTagLength))
                    };

                    match tag_type {
                        bcf::header::TagType::Flag => {
                            try!(writer.write_flag(try!(record.info(_name).flag())));
                        },
                        bcf::header::TagType::Integer => {
                            if let Some(values) = try!(record.info(_name).integer()) {
                                try!(writer.write_integer(values[i]));
                            } else {
                                try!(writer.write_field(b""));
                            }
                        },
                        bcf::header::TagType::Float => {
                            if let Some(values) = try!(record.info(_name).float()) {
                                try!(writer.write_float(values[i]));
                            } else {
                                try!(writer.write_field(b""));
                            }
                        },
                        bcf::header::TagType::String => {
                            if let Some(values) = try!(record.info(_name).string()) {
                                try!(writer.write_field(values[i]));
                            } else {
                                try!(writer.write_field(b""));
                            }
                        }
                    }
                } else {
                    // tag undefined, write NA
                    try!(writer.write_field(b""));
                }
            }

            let genotypes = if show_genotypes {
                let genotypes = try!(record.genotypes());
                Some(
                    (0..reader.header.sample_count() as usize).map(|s| {
                        format!("{}", genotypes.get(s))
                    }).collect_vec()
                )
            } else {
                None
            };

            for s in 0..reader.header.sample_count() as usize {
                if let Some(ref genotypes) = genotypes {
                    try!(writer.write_field(genotypes[s].as_bytes()));
                }
                for name in format_tags {
                    let _name = name.as_bytes();
                    if let Ok((tag_type, tag_length)) = reader.header.format_type(_name) {
                        let i = match tag_length {
                            bcf::header::TagLength::Fixed => {
                                0
                            },
                            bcf::header::TagLength::AltAlleles => {
                                i
                            },
                            _ => return Err(Box::new(ParseError::UnsupportedTagLength))
                        };

                        match tag_type {
                            bcf::header::TagType::Flag => {
                                panic!("there is no flag type for format");
                            },
                            bcf::header::TagType::Integer => {
                                try!(writer.write_field(format!("{}", try!(record.format(_name).integer())[s][i]).as_bytes()));
                            },
                            bcf::header::TagType::Float => {
                                try!(writer.write_field(format!("{}", try!(record.format(_name).float())[s][i]).as_bytes()));
                            },
                            bcf::header::TagType::String => {
                                try!(writer.write_field(try!(record.format(_name).string())[s]));
                            }
                        }
                    } else {
                        // tag undefined, write NA
                        try!(writer.write_field(b""));
                    }
                }
            }
            try!(writer.newline());
        }
    }

    Ok(())
}

quick_error! {
    #[derive(Debug)]
    pub enum ParseError {
        UnsupportedTagLength {
            description("currently, only A and 1 are supported multiplicities of tags")
        }

    }
}
<|endoftext|>