<commit_before>use std::collections::HashMap;
use std::path::Path;

#[derive(Debug)]
pub struct LanguageSpec {
    pub reserved_words: HashMap<String, String>,
    pub hash_comment: bool,
    pub c_style_comments: bool,
    pub backtick_strings: bool,
    pub regexp_literals: bool,
    pub triple_quote_literals: bool,
    pub c_preprocessor: bool,
    // Rust is mostly C-like, with a couple of differences.
    pub rust_tweaks: bool,
}

fn make_reserved(v: &[&str]) -> HashMap<String, String> {
    let mut reserved_words = HashMap::new();
    for word in v {
        reserved_words.insert(word.to_string(), "class=\"syn_reserved\" ".to_string());
    }
    reserved_words
}

lazy_static! {
    static ref RESERVED_WORDS_JS : Vec<&'static str> = vec![
        "abstract", "else", "instanceof", "super",
        "boolean", "enum", "int", "switch",
        "break", "export", "interface", "synchronized",
        "byte", "extends", "let", "this",
        "case", "false", "long", "throw",
        "catch", "final", "native", "throws",
        "char", "finally", "new", "transient",
        "class", "float", "null", "true",
        "const", "for", "package", "try",
        "continue", "function", "private", "typeof",
        "debugger", "goto", "protected", "var",
        "default", "if", "public", "void",
        "delete", "implements", "return", "volatile",
        "do", "import", "short", "while",
        "double", "in", "static", "with",
        "get", "set",
    ];

    static ref RESERVED_WORDS_CPP : Vec<&'static str> = vec![
        "alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel",
        "atomic_commit", "atomic_noexcept", "auto", "bitand", "bitor", "bool", "break",
        "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "concept",
        "const", "constexpr", "const_cast", "continue", "decltype", "default", "delete",
        "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false",
        "float", "for", "friend", "goto", "if", "inline", "int", "import", "long", "module",
        "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr",
        // Don't mark "operator" as a keyword so that people can click
        // on it.
        //"operator",
        "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast",
        "requires", "return", "short", "signed", "sizeof", "static", "static_assert",
        "static_cast", "struct", "switch", "synchronized", "template", "this", "thread_local",
        "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned",
        "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq",
        "#if", "#ifdef", "#ifndef", "#else", "#elif", "#endif", "#define", "#undef",
        "#include", "#error", "defined",
    ];

    static ref RESERVED_WORDS_IPDL : Vec<&'static str> = vec![
        "answer", "as", "async", "both", "bridges", "call", "child", "class",
        "compress", "compressall", "__delete__", "delete", "from", "goto", "high",
        "include", "intr", "manager", "manages", "namespace", "normal", "nullable",
        "opens", "or", "parent", "prio", "protocol", "recv", "returns", "send",
        "spawns", "start", "state", "struct", "sync", "union", "upto", "urgent",
        "using",
    ];

    static ref RESERVED_WORDS_IDL : Vec<&'static str> = vec![
        "const", "interface", "in", "inout", "out", "attribute", "raises",
        "readonly", "native", "typedef",
        "array", "shared", "iid_is", "size_is", "retval",
        "boolean", "void", "octet", "short", "long", "long",
        "unsigned", "float", "double", "char", "string", "wchar", "wstring",
        "nsid", "domstring", "utf8string", "cstring", "astring", "jsval",
        "uuid", "scriptable", "builtinclass", "function", "noscript", "deprecated",
        "object", "main_process_scriptable_only",
    ];

    static ref RESERVED_WORDS_WEBIDL : Vec<&'static str> = vec![
        "module", "interface", "partial", "dictionary", "exception", "enum", "callback",
        "typedef", "implements", "const", "null", "true", "false", "serializer",
        "stringifier", "jsonifier", "unrestricted", "attribute", "readonly", "inherit",
        "static", "getter", "setter", "creator", "deleter", "legacycaller", "optional",
        "Date", "DOMString", "ByteString", "USVString", "any", "boolean", "byte",
        "double", "float", "long", "object", "octet", "Promise", "required", "sequence",
        "MozMap", "short", "unsigned", "void", "ArrayBuffer", "SharedArrayBuffer", "or",
        "maplike", "setlike", "iterable",
        "Exposed", "ChromeOnly", "ChromeConstructor", "Pref", "Func", "AvailableIn",
        "CheckAnyPermissions", "CheckAllPermissions", "JSImplementation", "HeaderFile",
        "NavigatorProperty", "AvailableIn", "Func", "CheckAnyPermissions", "CheckAllPermissions",
        "Deprecated", "NeedResolve", "OverrideBuiltins", "ChromeOnly", "Unforgeable",
        "UnsafeInPrerendering", "LegacyEventInit", "ProbablyShortLivingObject", "ArrayClass",
        "Clamp", "Constructor", "EnforceRange", "ExceptionClass", "Exposed", "ImplicitThis",
        "Global", "PrimaryGlobal", "LegacyArrayClass", "LegacyUnenumerableNamedProperties",
        "LenientSetter", "LenientThis", "NamedConstructor", "NewObject", "NoInterfaceObject",
        "OverrideBuiltins", "PutForwards", "Replaceable", "SameObject", "SecureContext",
        "Throws", "TreatNonObjectAsNull", "TreatNullAs", "Unforgeable", "Unscopable",
    ];

    static ref RESERVED_WORDS_PYTHON : Vec<&'static str> = vec![
        "and", "del", "from", "not", "while",
        "as", "elif", "global", "or", "with",
        "assert", "else", "if", "pass", "yield",
        "break", "except", "import", "print",
        "class", "exec", "in", "raise", "continue",
        "finally", "is", "return",
        "def", "for", "lambda", "try",
    ];

    // List of Rust reserved words pulled from
    // https://github.com/rust-lang/rust/blob/master/src/libsyntax/symbol.rs
    static ref RESERVED_WORDS_RUST : Vec<&'static str> = vec![
        "as", "box", "break", "const", "continue", "crate",
        "else", "enum", "extern", "false", "fn", "for", "if",
        "impl", "in", "let", "loop", "match", "mod", "move",
        "mut", "pub", "ref", "return", "self", "Self", "static",
        "struct", "super", "trait", "true", "type", "unsafe",
        "use", "where", "while",

        "abstract", "alignof", "become", "do", "final", "macro",
        "offsetof", "override", "priv", "proc", "pure", "sizeof",
        "typeof", "unsized", "virtual", "yield",

        "default", "union",
    ];

    static ref RESERVED_WORDS_JAVA : Vec<&'static str> = vec![
        "abstract", "continue", "for", "new", "switch", "assert", "default",
        "goto", "package", "synchronized", "boolean", "do", "if", "private",
        "this", "break", "double", "implements", "protected", "throw", "byte",
        "else", "import", "public", "throws", "case", "enum", "instanceof",
        "return", "transient", "catch", "extends", "int", "short", "try",
        "char", "final", "interface", "static", "void", "class", "finally",
        "long", "strictfp", "volatile", "const", "float", "native", "super",
        "while", "null", "true", "false",
    ];

    static ref JS_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_JS),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: true,
        regexp_literals: true,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref CPP_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_CPP),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: true,
        rust_tweaks: false,
    };

    static ref IPDL_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_IPDL),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref IDL_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_IDL),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref WEBIDL_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_WEBIDL),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref PYTHON_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_PYTHON),
        hash_comment: true,
        c_style_comments: false,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: true,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref RUST_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_RUST),
        hash_comment: true, // for now, for attributes
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: true,
    };

    static ref JAVA_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_JAVA),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };
}

#[derive(Debug)]
pub enum DocType {
    Markdown,
    ReStructuredText,
}

#[derive(Debug)]
pub enum FormatAs {
    FormatCLike(&'static LanguageSpec),
    FormatTagLike(&'static LanguageSpec),
    FormatDoc(DocType),
    Plain,
    Binary,
}

pub fn select_formatting(filename: &str) -> FormatAs {
    let ext = match Path::new(filename).extension() {
        Some(ext) => ext.to_str().unwrap(),
        None => "",
    };
    match ext {
        "c" | "cc" | "cpp" | "h" | "hh" | "mm" => FormatAs::FormatCLike(&*CPP_SPEC),
        "ipdl" | "ipdlh" => FormatAs::FormatCLike(&*IPDL_SPEC),
        "idl" => FormatAs::FormatCLike(&*IDL_SPEC),
        "webidl" => FormatAs::FormatCLike(&*WEBIDL_SPEC),
        "js" | "jsm" | "json" | "sjs" => FormatAs::FormatCLike(&*JS_SPEC),
        "py" | "build" | "configure" => FormatAs::FormatCLike(&*PYTHON_SPEC),
        "rs" => FormatAs::FormatCLike(&*RUST_SPEC),
        "java" => FormatAs::FormatCLike(&*JAVA_SPEC),

        "html" | "htm" | "xhtml" | "xml" | "xul" => FormatAs::FormatTagLike(&*JS_SPEC),

        "ogg" | "ttf" | "xpi" | "png" | "bcmap" |
        "gif" | "ogv" | "jpg" | "bmp" | "icns" | "ico" |
        "mp4" | "sqlite" | "jar" | "webm" | "woff" |
        "class" | "m4s" | "mgif" | "wav" | "opus" |
        "mp3" | "otf" => FormatAs::Binary,

        "md" => FormatAs::FormatDoc(DocType::Markdown),
        "rst" => FormatAs::FormatDoc(DocType::ReStructuredText),

        _ => FormatAs::Plain,
    }
}
<commit_msg>Bug 1420219 - Treat .jpeg files as binary also<commit_after>use std::collections::HashMap;
use std::path::Path;

#[derive(Debug)]
pub struct LanguageSpec {
    pub reserved_words: HashMap<String, String>,
    pub hash_comment: bool,
    pub c_style_comments: bool,
    pub backtick_strings: bool,
    pub regexp_literals: bool,
    pub triple_quote_literals: bool,
    pub c_preprocessor: bool,
    // Rust is mostly C-like, with a couple of differences.
    pub rust_tweaks: bool,
}

fn make_reserved(v: &[&str]) -> HashMap<String, String> {
    let mut reserved_words = HashMap::new();
    for word in v {
        reserved_words.insert(word.to_string(), "class=\"syn_reserved\" ".to_string());
    }
    reserved_words
}

lazy_static! {
    static ref RESERVED_WORDS_JS : Vec<&'static str> = vec![
        "abstract", "else", "instanceof", "super",
        "boolean", "enum", "int", "switch",
        "break", "export", "interface", "synchronized",
        "byte", "extends", "let", "this",
        "case", "false", "long", "throw",
        "catch", "final", "native", "throws",
        "char", "finally", "new", "transient",
        "class", "float", "null", "true",
        "const", "for", "package", "try",
        "continue", "function", "private", "typeof",
        "debugger", "goto", "protected", "var",
        "default", "if", "public", "void",
        "delete", "implements", "return", "volatile",
        "do", "import", "short", "while",
        "double", "in", "static", "with",
        "get", "set",
    ];

    static ref RESERVED_WORDS_CPP : Vec<&'static str> = vec![
        "alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel",
        "atomic_commit", "atomic_noexcept", "auto", "bitand", "bitor", "bool", "break",
        "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "concept",
        "const", "constexpr", "const_cast", "continue", "decltype", "default", "delete",
        "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false",
        "float", "for", "friend", "goto", "if", "inline", "int", "import", "long", "module",
        "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr",
        // Don't mark "operator" as a keyword so that people can click
        // on it.
        //"operator",
        "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast",
        "requires", "return", "short", "signed", "sizeof", "static", "static_assert",
        "static_cast", "struct", "switch", "synchronized", "template", "this", "thread_local",
        "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned",
        "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq",
        "#if", "#ifdef", "#ifndef", "#else", "#elif", "#endif", "#define", "#undef",
        "#include", "#error", "defined",
    ];

    static ref RESERVED_WORDS_IPDL : Vec<&'static str> = vec![
        "answer", "as", "async", "both", "bridges", "call", "child", "class",
        "compress", "compressall", "__delete__", "delete", "from", "goto", "high",
        "include", "intr", "manager", "manages", "namespace", "normal", "nullable",
        "opens", "or", "parent", "prio", "protocol", "recv", "returns", "send",
        "spawns", "start", "state", "struct", "sync", "union", "upto", "urgent",
        "using",
    ];

    static ref RESERVED_WORDS_IDL : Vec<&'static str> = vec![
        "const", "interface", "in", "inout", "out", "attribute", "raises",
        "readonly", "native", "typedef",
        "array", "shared", "iid_is", "size_is", "retval",
        "boolean", "void", "octet", "short", "long", "long",
        "unsigned", "float", "double", "char", "string", "wchar", "wstring",
        "nsid", "domstring", "utf8string", "cstring", "astring", "jsval",
        "uuid", "scriptable", "builtinclass", "function", "noscript", "deprecated",
        "object", "main_process_scriptable_only",
    ];

    static ref RESERVED_WORDS_WEBIDL : Vec<&'static str> = vec![
        "module", "interface", "partial", "dictionary", "exception", "enum", "callback",
        "typedef", "implements", "const", "null", "true", "false", "serializer",
        "stringifier", "jsonifier", "unrestricted", "attribute", "readonly", "inherit",
        "static", "getter", "setter", "creator", "deleter", "legacycaller", "optional",
        "Date", "DOMString", "ByteString", "USVString", "any", "boolean", "byte",
        "double", "float", "long", "object", "octet", "Promise", "required", "sequence",
        "MozMap", "short", "unsigned", "void", "ArrayBuffer", "SharedArrayBuffer", "or",
        "maplike", "setlike", "iterable",
        "Exposed", "ChromeOnly", "ChromeConstructor", "Pref", "Func", "AvailableIn",
        "CheckAnyPermissions", "CheckAllPermissions", "JSImplementation", "HeaderFile",
        "NavigatorProperty", "AvailableIn", "Func", "CheckAnyPermissions", "CheckAllPermissions",
        "Deprecated", "NeedResolve", "OverrideBuiltins", "ChromeOnly", "Unforgeable",
        "UnsafeInPrerendering", "LegacyEventInit", "ProbablyShortLivingObject", "ArrayClass",
        "Clamp", "Constructor", "EnforceRange", "ExceptionClass", "Exposed", "ImplicitThis",
        "Global", "PrimaryGlobal", "LegacyArrayClass", "LegacyUnenumerableNamedProperties",
        "LenientSetter", "LenientThis", "NamedConstructor", "NewObject", "NoInterfaceObject",
        "OverrideBuiltins", "PutForwards", "Replaceable", "SameObject", "SecureContext",
        "Throws", "TreatNonObjectAsNull", "TreatNullAs", "Unforgeable", "Unscopable",
    ];

    static ref RESERVED_WORDS_PYTHON : Vec<&'static str> = vec![
        "and", "del", "from", "not", "while",
        "as", "elif", "global", "or", "with",
        "assert", "else", "if", "pass", "yield",
        "break", "except", "import", "print",
        "class", "exec", "in", "raise", "continue",
        "finally", "is", "return",
        "def", "for", "lambda", "try",
    ];

    // List of Rust reserved words pulled from
    // https://github.com/rust-lang/rust/blob/master/src/libsyntax/symbol.rs
    static ref RESERVED_WORDS_RUST : Vec<&'static str> = vec![
        "as", "box", "break", "const", "continue", "crate",
        "else", "enum", "extern", "false", "fn", "for", "if",
        "impl", "in", "let", "loop", "match", "mod", "move",
        "mut", "pub", "ref", "return", "self", "Self", "static",
        "struct", "super", "trait", "true", "type", "unsafe",
        "use", "where", "while",

        "abstract", "alignof", "become", "do", "final", "macro",
        "offsetof", "override", "priv", "proc", "pure", "sizeof",
        "typeof", "unsized", "virtual", "yield",

        "default", "union",
    ];

    static ref RESERVED_WORDS_JAVA : Vec<&'static str> = vec![
        "abstract", "continue", "for", "new", "switch", "assert", "default",
        "goto", "package", "synchronized", "boolean", "do", "if", "private",
        "this", "break", "double", "implements", "protected", "throw", "byte",
        "else", "import", "public", "throws", "case", "enum", "instanceof",
        "return", "transient", "catch", "extends", "int", "short", "try",
        "char", "final", "interface", "static", "void", "class", "finally",
        "long", "strictfp", "volatile", "const", "float", "native", "super",
        "while", "null", "true", "false",
    ];

    static ref JS_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_JS),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: true,
        regexp_literals: true,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref CPP_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_CPP),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: true,
        rust_tweaks: false,
    };

    static ref IPDL_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_IPDL),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref IDL_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_IDL),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref WEBIDL_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_WEBIDL),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref PYTHON_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_PYTHON),
        hash_comment: true,
        c_style_comments: false,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: true,
        c_preprocessor: false,
        rust_tweaks: false,
    };

    static ref RUST_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_RUST),
        hash_comment: true, // for now, for attributes
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: true,
    };

    static ref JAVA_SPEC : LanguageSpec = LanguageSpec {
        reserved_words: make_reserved(&*RESERVED_WORDS_JAVA),
        hash_comment: false,
        c_style_comments: true,
        backtick_strings: false,
        regexp_literals: false,
        triple_quote_literals: false,
        c_preprocessor: false,
        rust_tweaks: false,
    };
}

#[derive(Debug)]
pub enum DocType {
    Markdown,
    ReStructuredText,
}

#[derive(Debug)]
pub enum FormatAs {
    FormatCLike(&'static LanguageSpec),
    FormatTagLike(&'static LanguageSpec),
    FormatDoc(DocType),
    Plain,
    Binary,
}

pub fn select_formatting(filename: &str) -> FormatAs {
    let ext = match Path::new(filename).extension() {
        Some(ext) => ext.to_str().unwrap(),
        None => "",
    };
    match ext {
        "c" | "cc" | "cpp" | "h" | "hh" | "mm" => FormatAs::FormatCLike(&*CPP_SPEC),
        "ipdl" | "ipdlh" => FormatAs::FormatCLike(&*IPDL_SPEC),
        "idl" => FormatAs::FormatCLike(&*IDL_SPEC),
        "webidl" => FormatAs::FormatCLike(&*WEBIDL_SPEC),
        "js" | "jsm" | "json" | "sjs" => FormatAs::FormatCLike(&*JS_SPEC),
        "py" | "build" | "configure" => FormatAs::FormatCLike(&*PYTHON_SPEC),
        "rs" => FormatAs::FormatCLike(&*RUST_SPEC),
        "java" => FormatAs::FormatCLike(&*JAVA_SPEC),

        "html" | "htm" | "xhtml" | "xml" | "xul" => FormatAs::FormatTagLike(&*JS_SPEC),

        "ogg" | "ttf" | "xpi" | "png" | "bcmap" |
        "gif" | "ogv" | "jpg" | "jpeg" | "bmp" | "icns" | "ico" |
        "mp4" | "sqlite" | "jar" | "webm" | "woff" |
        "class" | "m4s" | "mgif" | "wav" | "opus" |
        "mp3" | "otf" => FormatAs::Binary,

        "md" => FormatAs::FormatDoc(DocType::Markdown),
        "rst" => FormatAs::FormatDoc(DocType::ReStructuredText),

        _ => FormatAs::Plain,
    }
}
<|endoftext|>


<commit_before>// Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! DNS Service Discovery
#![cfg(feature = "mdns")]

use std::borrow::Cow;
use std::collections::HashMap;

use futures::{Async, Future, Poll};

use trust_dns_proto::rr::{IntoName, Name, RecordType};
use trust_dns_proto::xfer::DnsRequestOptions;

use error::*;
use lookup::{
    LookupFuture, LookupFuture, ReverseLookup, ReverseLookupFuture, ReverseLookupIter, TxtLookup,
    TxtLookupFuture,
};
use resolver_future::ResolverFuture;

/// An extension for the Resolver to perform DNS Service Discovery
pub trait DnsSdFuture {
    /// List all services available
    ///
    /// https://tools.ietf.org/html/rfc6763#section-4.1
    ///
    /// For registered service types, see: https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
    fn list_services<N: IntoName>(&self, name: N) -> ListServicesFuture;

    /// Retrieve service information
    ///
    /// https://tools.ietf.org/html/rfc6763#section-6
    fn service_info<N: IntoName>(&self, name: N) -> ServiceInfoFuture;
}

impl DnsSdFuture for ResolverFuture {
    fn list_services<N: IntoName>(&self, name: N) -> ListServicesFuture {
        let options = DnsRequestOptions {
            expects_multiple_responses: true,
            ..Default::default()
        };
        let name: Name = match name.into_name() {
            Ok(name) => name,
            Err(err) => {
                return ListServicesFuture(ReverseLookupFuture::from(LookupFuture::error(
                    self.client_cache.clone(),
                    err,
                )));
            }
        };

        let ptr_future: LookupFuture = self.inner_lookup(name, RecordType::PTR, options);
        let ptr_future: ReverseLookupFuture = ptr_future.into();

        ListServicesFuture(ptr_future)
    }

    fn service_info<N: IntoName>(&self, name: N) -> ServiceInfoFuture {
        let txt_future: TxtLookupFuture = self.txt_lookup(name);
        ServiceInfoFuture(txt_future)
    }
}

/// A DNS Service Discovery future of Services discovered through the list operation
pub struct ListServicesFuture(ReverseLookupFuture);

impl Future for ListServicesFuture {
    type Item = ListServices;
    type Error = ResolveError;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.0.poll() {
            Ok(Async::Ready(lookup)) => Ok(Async::Ready(ListServices(lookup))),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(e) => Err(e),
        }
    }
}

/// The list of Services discovered
pub struct ListServices(ReverseLookup);

impl ListServices {
    /// Returns an iterator over the list of returned names of services.
    ///
    /// Each name can be queried for additional information. To lookup service entries see `ResolverFuture::srv_lookup`. To get parameters associated with the service, see `DnsSdFuture::service_info`.
    pub fn iter(&self) -> ListServicesIter {
        ListServicesIter(self.0.iter())
    }
}

/// An iterator over the Lookup type
pub struct ListServicesIter<'i>(ReverseLookupIter<'i>);

impl<'i> Iterator for ListServicesIter<'i> {
    type Item = &'i Name;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

/// A Future that resolves to the TXT information for a service
pub struct ServiceInfoFuture(TxtLookupFuture);

impl Future for ServiceInfoFuture {
    type Item = ServiceInfo;
    type Error = ResolveError;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.0.poll() {
            Ok(Async::Ready(lookup)) => Ok(Async::Ready(ServiceInfo(lookup))),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(e) => Err(e),
        }
    }
}

/// The list of Services discovered
pub struct ServiceInfo(TxtLookup);

impl ServiceInfo {
    /// Returns this as a map, this allocates a new hashmap
    ///
    /// This converts the DNS-SD TXT record into a map following the rules specified in https://tools.ietf.org/html/rfc6763#section-6.4
    pub fn to_map<'s>(&'s self) -> HashMap<Cow<'s, str>, Option<Cow<'s, str>>> {
        self.0
            .iter()
            .flat_map(|txt| txt.iter())
            .filter_map(|bytes| {
                let mut split = bytes.split(|byte| *byte == b'=');

                let key = split.next().map(String::from_utf8_lossy);
                let value = split.next().map(String::from_utf8_lossy);

                if let Some(key) = key {
                    Some((key, value))
                } else {
                    None
                }
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use tokio::runtime::current_thread::Runtime;

    use config::*;

    use super::*;

    #[test]
    #[ignore]
    fn test_list_services() {
        let mut io_loop = Runtime::new().unwrap();
        let resolver = ResolverFuture::new(
            ResolverConfig::default(),
            ResolverOpts {
                ip_strategy: LookupIpStrategy::Ipv6thenIpv4,
                ..ResolverOpts::default()
            },
        );

        let resolver = io_loop
            .block_on(resolver)
            .expect("failed to create resolver");
        let response = io_loop
            .block_on(resolver.list_services("_http._tcp.local."))
            .expect("failed to run lookup");

        for name in response.iter() {
            println!("service: {}", name);
            let srvs = io_loop
                .block_on(resolver.lookup_srv(name))
                .expect("failed to lookup name");

            for srv in srvs.iter() {
                println!("service: {:#?}", srv);

                let info = io_loop
                    .block_on(resolver.service_info(name))
                    .expect("info failed");
                let info = info.to_map();
                println!("info: {:#?}", info);
            }

            for ip in srvs.ip_iter() {
                println!("ip: {}", ip);
            }
        }
    }
}
<commit_msg>remove extra use<commit_after>// Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! DNS Service Discovery
#![cfg(feature = "mdns")]

use std::borrow::Cow;
use std::collections::HashMap;

use futures::{Async, Future, Poll};

use trust_dns_proto::rr::{IntoName, Name, RecordType};
use trust_dns_proto::xfer::DnsRequestOptions;

use error::*;
use lookup::{
    LookupFuture, ReverseLookup, ReverseLookupFuture, ReverseLookupIter, TxtLookup, TxtLookupFuture,
};
use resolver_future::ResolverFuture;

/// An extension for the Resolver to perform DNS Service Discovery
pub trait DnsSdFuture {
    /// List all services available
    ///
    /// https://tools.ietf.org/html/rfc6763#section-4.1
    ///
    /// For registered service types, see: https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
    fn list_services<N: IntoName>(&self, name: N) -> ListServicesFuture;

    /// Retrieve service information
    ///
    /// https://tools.ietf.org/html/rfc6763#section-6
    fn service_info<N: IntoName>(&self, name: N) -> ServiceInfoFuture;
}

impl DnsSdFuture for ResolverFuture {
    fn list_services<N: IntoName>(&self, name: N) -> ListServicesFuture {
        let options = DnsRequestOptions {
            expects_multiple_responses: true,
            ..Default::default()
        };
        let name: Name = match name.into_name() {
            Ok(name) => name,
            Err(err) => {
                return ListServicesFuture(ReverseLookupFuture::from(LookupFuture::error(
                    self.client_cache.clone(),
                    err,
                )));
            }
        };

        let ptr_future: LookupFuture = self.inner_lookup(name, RecordType::PTR, options);
        let ptr_future: ReverseLookupFuture = ptr_future.into();

        ListServicesFuture(ptr_future)
    }

    fn service_info<N: IntoName>(&self, name: N) -> ServiceInfoFuture {
        let txt_future: TxtLookupFuture = self.txt_lookup(name);
        ServiceInfoFuture(txt_future)
    }
}

/// A DNS Service Discovery future of Services discovered through the list operation
pub struct ListServicesFuture(ReverseLookupFuture);

impl Future for ListServicesFuture {
    type Item = ListServices;
    type Error = ResolveError;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.0.poll() {
            Ok(Async::Ready(lookup)) => Ok(Async::Ready(ListServices(lookup))),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(e) => Err(e),
        }
    }
}

/// The list of Services discovered
pub struct ListServices(ReverseLookup);

impl ListServices {
    /// Returns an iterator over the list of returned names of services.
    ///
    /// Each name can be queried for additional information. To lookup service entries see `ResolverFuture::srv_lookup`. To get parameters associated with the service, see `DnsSdFuture::service_info`.
    pub fn iter(&self) -> ListServicesIter {
        ListServicesIter(self.0.iter())
    }
}

/// An iterator over the Lookup type
pub struct ListServicesIter<'i>(ReverseLookupIter<'i>);

impl<'i> Iterator for ListServicesIter<'i> {
    type Item = &'i Name;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

/// A Future that resolves to the TXT information for a service
pub struct ServiceInfoFuture(TxtLookupFuture);

impl Future for ServiceInfoFuture {
    type Item = ServiceInfo;
    type Error = ResolveError;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.0.poll() {
            Ok(Async::Ready(lookup)) => Ok(Async::Ready(ServiceInfo(lookup))),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(e) => Err(e),
        }
    }
}

/// The list of Services discovered
pub struct ServiceInfo(TxtLookup);

impl ServiceInfo {
    /// Returns this as a map, this allocates a new hashmap
    ///
    /// This converts the DNS-SD TXT record into a map following the rules specified in https://tools.ietf.org/html/rfc6763#section-6.4
    pub fn to_map<'s>(&'s self) -> HashMap<Cow<'s, str>, Option<Cow<'s, str>>> {
        self.0
            .iter()
            .flat_map(|txt| txt.iter())
            .filter_map(|bytes| {
                let mut split = bytes.split(|byte| *byte == b'=');

                let key = split.next().map(String::from_utf8_lossy);
                let value = split.next().map(String::from_utf8_lossy);

                if let Some(key) = key {
                    Some((key, value))
                } else {
                    None
                }
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use tokio::runtime::current_thread::Runtime;

    use config::*;

    use super::*;

    #[test]
    #[ignore]
    fn test_list_services() {
        let mut io_loop = Runtime::new().unwrap();
        let resolver = ResolverFuture::new(
            ResolverConfig::default(),
            ResolverOpts {
                ip_strategy: LookupIpStrategy::Ipv6thenIpv4,
                ..ResolverOpts::default()
            },
        );

        let resolver = io_loop
            .block_on(resolver)
            .expect("failed to create resolver");
        let response = io_loop
            .block_on(resolver.list_services("_http._tcp.local."))
            .expect("failed to run lookup");

        for name in response.iter() {
            println!("service: {}", name);
            let srvs = io_loop
                .block_on(resolver.lookup_srv(name))
                .expect("failed to lookup name");

            for srv in srvs.iter() {
                println!("service: {:#?}", srv);

                let info = io_loop
                    .block_on(resolver.service_info(name))
                    .expect("info failed");
                let info = info.to_map();
                println!("info: {:#?}", info);
            }

            for ip in srvs.ip_iter() {
                println!("ip: {}", ip);
            }
        }
    }
}
<|endoftext|>


<commit_before>pub fn is_leap_year(year: i32) -> bool {
    let has_factor = |&:n| year % n == 0;
    has_factor(4) && (!has_factor(100) || has_factor(400))
}
<commit_msg>update leap year syntax<commit_after>pub fn is_leap_year(year: i32) -> bool {
    let has_factor = |n| year % n == 0;
    has_factor(4) && (!has_factor(100) || has_factor(400))
}
<|endoftext|>


<commit_before>#![feature(collections)]

extern crate opencl;

use opencl::mem::CLBuffer;
use std::fmt;

fn main()
{
    let ker = include_str!("demo.ocl");
    println!("ker {}", ker);

    let vec_a = vec![0isize, 1, 2, -3, 4, 5, 6, 7];
    let vec_b = vec![-7isize, -6, 5, -4, 0, -1, 2, 3];

    let ref platform = opencl::hl::get_platforms()[0];
    let devices = platform.get_devices();
    let ctx = opencl::hl::Context::create_context(&devices[..]);
    let queues: Vec<opencl::hl::CommandQueue> = devices.iter()
        .map(|d| ctx.create_command_queue(d)).collect();

    for (device, queue) in devices.iter().zip(queues.iter()) {
        println!("{}", device.name());

        let a: CLBuffer<isize> = ctx.create_buffer(vec_a.len(), opencl::cl::CL_MEM_READ_ONLY);
        let b: CLBuffer<isize> = ctx.create_buffer(vec_a.len(), opencl::cl::CL_MEM_READ_ONLY);
        let c: CLBuffer<isize> = ctx.create_buffer(vec_a.len(), opencl::cl::CL_MEM_WRITE_ONLY);

        queue.write(&a, &&vec_a[..], ());
        queue.write(&b, &&vec_b[..], ());

        let program = ctx.create_program_from_source(ker);
        program.build(&device).ok().expect("Couldn't build program.");

        let kernel = program.create_kernel("vector_add");

        kernel.set_arg(0, &a);
        kernel.set_arg(1, &b);
        kernel.set_arg(2, &c);

        let event = queue.enqueue_async_kernel(&kernel, vec_a.len(), None, ());

        let vec_c: Vec<isize> = queue.get(&c, &event);

        println!("  {}", string_from_slice(&vec_a[..]));
        println!("+ {}", string_from_slice(&vec_b[..]));
        println!("= {}", string_from_slice(&vec_c[..]));
    }
}

fn string_from_slice<T: fmt::Display>(slice: &[T]) -> String {
    let mut st = String::from_str("[");
    let mut first = true;

    for i in slice.iter() {
        if !first {
            st.push_str(", ");
        }
        else {
            first = false;
        }
        st.push_str(&*i.to_string())
    }

    st.push_str("]");
    return st
}
<commit_msg>changed multidevice demo to test CommandQueue::device<commit_after>#![feature(collections)]

extern crate opencl;

use opencl::mem::CLBuffer;
use std::fmt;

fn main()
{
    let ker = include_str!("demo.ocl");
    println!("ker {}", ker);

    let vec_a = vec![0isize, 1, 2, -3, 4, 5, 6, 7];
    let vec_b = vec![-7isize, -6, 5, -4, 0, -1, 2, 3];

    let ref platform = opencl::hl::get_platforms()[0];
    let devices = platform.get_devices();
    let ctx = opencl::hl::Context::create_context(&devices[..]);
    let queues: Vec<opencl::hl::CommandQueue> = devices.iter()
        .map(|d| ctx.create_command_queue(d)).collect();

    for (device, queue) in devices.iter().zip(queues.iter()) {
        println!("{}", queue.device().name());

        let a: CLBuffer<isize> = ctx.create_buffer(vec_a.len(), opencl::cl::CL_MEM_READ_ONLY);
        let b: CLBuffer<isize> = ctx.create_buffer(vec_a.len(), opencl::cl::CL_MEM_READ_ONLY);
        let c: CLBuffer<isize> = ctx.create_buffer(vec_a.len(), opencl::cl::CL_MEM_WRITE_ONLY);

        queue.write(&a, &&vec_a[..], ());
        queue.write(&b, &&vec_b[..], ());

        let program = ctx.create_program_from_source(ker);
        program.build(&device).ok().expect("Couldn't build program.");

        let kernel = program.create_kernel("vector_add");

        kernel.set_arg(0, &a);
        kernel.set_arg(1, &b);
        kernel.set_arg(2, &c);

        let event = queue.enqueue_async_kernel(&kernel, vec_a.len(), None, ());

        let vec_c: Vec<isize> = queue.get(&c, &event);

        println!("  {}", string_from_slice(&vec_a[..]));
        println!("+ {}", string_from_slice(&vec_b[..]));
        println!("= {}", string_from_slice(&vec_c[..]));
    }
}

fn string_from_slice<T: fmt::Display>(slice: &[T]) -> String {
    let mut st = String::from_str("[");
    let mut first = true;

    for i in slice.iter() {
        if !first {
            st.push_str(", ");
        }
        else {
            first = false;
        }
        st.push_str(&*i.to_string())
    }

    st.push_str("]");
    return st
}
<|endoftext|>


<commit_before>#![feature(plugin)]
#![feature(collections)]
#![plugin(interpolate_idents)]

#[macro_use]
extern crate apache2;

use apache2::{HookOrder, Request, Status};

apache2_module!(https_www, b"mod_https_www\0", handlers {
   https_www_handler, translate_name, HookOrder::MIDDLE
});

fn https_www_handler(r: &mut Request) -> Result<Status, ()> {
   let scheme = try!(r.http_scheme());
   let hostname = try!(r.hostname());

   let already_www = &hostname[..4] == "www.";
   let already_https = scheme == "https";

   if already_www && already_https {
      return Ok(Status::DECLINED);
   };

   let full_hostname = if already_www {
      String::from_str(hostname)
   } else {
      format!("www.{}", hostname)
   };

   let uri = try!(r.unparsed_uri());

   let location = format!("https://{}{}", full_hostname, uri);

   try!(
      try!(r.headers_out()).set("Location", location)
   );

   r.set_status(apache2::Status::HTTP_MOVED_PERMANENTLY);

   Ok(Status::DONE)
}
<commit_msg>Fixing compilation error.<commit_after>#![feature(plugin)]
#![feature(collections)]
#![plugin(interpolate_idents)]

#[macro_use]
extern crate apache2;

use apache2::{HookOrder, Request, Status};

apache2_module!(https_www, b"mod_https_www\0", handlers {
   (https_www_handler, translate_name, HookOrder::MIDDLE)
});

fn https_www_handler(r: &mut Request) -> Result<Status, ()> {
   let scheme = try!(r.http_scheme());
   let hostname = try!(r.hostname());

   let already_www = &hostname[..4] == "www.";
   let already_https = scheme == "https";

   if already_www && already_https {
      return Ok(Status::DECLINED);
   };

   let full_hostname = if already_www {
      String::from_str(hostname)
   } else {
      format!("www.{}", hostname)
   };

   let uri = try!(r.unparsed_uri());

   let location = format!("https://{}{}", full_hostname, uri);

   try!(
      try!(r.headers_out()).set("Location", location)
   );

   r.set_status(apache2::Status::HTTP_MOVED_PERMANENTLY);

   Ok(Status::DONE)
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/// A struct that makes it easier to print out a pretty tree of data, which
/// can be visually scanned more easily.
pub struct PrintTree {
    /// The current level of recursion.
    level: u32,

    /// An item which is queued up, so that we can determine if we need
    /// a mid-tree prefix or a branch ending prefix.
    queued_item: Option<String>,
}

/// A trait that makes it easy to describe a pretty tree of data,
/// regardless of the printing destination, to either print it
/// directly to stdout, or serialize it as in the debugger
pub trait PrintTreePrinter {
    fn new_level(&mut self, title: String);
    fn end_level(&mut self);
    fn add_item(&mut self, text: String);
}

impl PrintTree {
    pub fn new(title: &str) -> PrintTree {
        println!("\u{250c} {}", title);
        PrintTree {
            level: 1,
            queued_item: None,
        }
    }

    fn print_level_prefix(&self) {
        for _ in 0 .. self.level {
            print!("\u{2502}  ");
        }
    }

    fn flush_queued_item(&mut self, prefix: &str) {
        if let Some(queued_item) = self.queued_item.take() {
            self.print_level_prefix();
            println!("{} {}", prefix, queued_item);
        }
    }
}

// The default `println!` based printer
impl PrintTreePrinter for PrintTree {
    /// Descend one level in the tree with the given title.
    fn new_level(&mut self, title: String) {
        self.flush_queued_item("\u{251C}\u{2500}");

        self.print_level_prefix();
        println!("\u{251C}\u{2500} {}", title);

        self.level = self.level + 1;
    }

    /// Ascend one level in the tree.
    fn end_level(&mut self) {
        self.flush_queued_item("\u{2514}\u{2500}");
        self.level = self.level - 1;
    }

    /// Add an item to the current level in the tree.
    fn add_item(&mut self, text: String) {
        self.flush_queued_item("\u{251C}\u{2500}");
        self.queued_item = Some(text);
    }
}

impl Drop for PrintTree {
    fn drop(&mut self) {
        self.flush_queued_item("\u{9492}\u{9472}");
    }
}
<commit_msg>Bug 1519175 - Allow creating PrintTree instances with other sinks. r=kvark<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use std::io::{stdout, Stdout, Write};

/// A struct that makes it easier to print out a pretty tree of data, which
/// can be visually scanned more easily.
pub struct PrintTree<W>
where
    W: Write
{
    /// The current level of recursion.
    level: u32,

    /// An item which is queued up, so that we can determine if we need
    /// a mid-tree prefix or a branch ending prefix.
    queued_item: Option<String>,

    /// The sink to print to.
    sink: W,
}

/// A trait that makes it easy to describe a pretty tree of data,
/// regardless of the printing destination, to either print it
/// directly to stdout, or serialize it as in the debugger
pub trait PrintTreePrinter {
    fn new_level(&mut self, title: String);
    fn end_level(&mut self);
    fn add_item(&mut self, text: String);
}

impl PrintTree<Stdout> {
    pub fn new(title: &str) -> Self {
        PrintTree::new_with_sink(title, stdout())
    }
}

impl<W> PrintTree<W>
where
    W: Write
{
    pub fn new_with_sink(title: &str, mut sink: W) -> Self {
        writeln!(sink, "\u{250c} {}", title).unwrap();
        PrintTree {
            level: 1,
            queued_item: None,
            sink,
        }
    }

    fn print_level_prefix(&mut self) {
        for _ in 0 .. self.level {
            write!(self.sink, "\u{2502}  ").unwrap();
        }
    }

    fn flush_queued_item(&mut self, prefix: &str) {
        if let Some(queued_item) = self.queued_item.take() {
            self.print_level_prefix();
            writeln!(self.sink, "{} {}", prefix, queued_item).unwrap();
        }
    }
}

// The default `println!` based printer
impl<W> PrintTreePrinter for PrintTree<W>
where
    W: Write
{
    /// Descend one level in the tree with the given title.
    fn new_level(&mut self, title: String) {
        self.flush_queued_item("\u{251C}\u{2500}");

        self.print_level_prefix();
        writeln!(self.sink, "\u{251C}\u{2500} {}", title).unwrap();

        self.level = self.level + 1;
    }

    /// Ascend one level in the tree.
    fn end_level(&mut self) {
        self.flush_queued_item("\u{2514}\u{2500}");
        self.level = self.level - 1;
    }

    /// Add an item to the current level in the tree.
    fn add_item(&mut self, text: String) {
        self.flush_queued_item("\u{251C}\u{2500}");
        self.queued_item = Some(text);
    }
}

impl<W> Drop for PrintTree<W>
where
    W: Write
{
    fn drop(&mut self) {
        self.flush_queued_item("\u{9492}\u{9472}");
    }
}
<|endoftext|>


<commit_before>#![allow(unreachable_pub)]

xflags::args_parser! {
    /// Run custom build command.
    cmd xtask {
        default cmd help {
            /// Print help information.
            optional -h, --help
        }

        /// Install rust-analyzer server or editor plugin.
        cmd install {
            /// Install only VS Code plugin.
            optional --client
            /// One of 'code', 'code-exploration', 'code-insiders', 'codium', or 'code-oss'.
            optional --code-bin name: String

            /// Install only the language server.
            optional --server
            /// Use mimalloc allocator for server
            optional --mimalloc
            /// Use jemalloc allocator for server
            optional --jemalloc
        }

        cmd codegen {
            optional --features
        }

        cmd lint {}
        cmd fuzz-tests {}
        cmd pre-cache {}

        cmd release {
            optional --dry-run
        }
        cmd promote {
            optional --dry-run
        }
        cmd dist {
            optional --nightly
            optional --client version: String
        }
        cmd metrics {
            optional --dry-run
        }
        /// Builds a benchmark version of rust-analyzer and puts it into `./target`.
        cmd bb
            required suffix : String
        {}
    }
}

// generated start
// The following code is generated by `xflags` macro.
// Run `env XFLAGS_DUMP= cargo build` to regenerate.
#[derive(Debug)]
pub struct Xtask {
    pub subcommand: XtaskCmd,
}

#[derive(Debug)]
pub enum XtaskCmd {
    Help(Help),
    Install(Install),
    Codegen(Codegen),
    Lint(Lint),
    FuzzTests(FuzzTests),
    PreCache(PreCache),
    Release(Release),
    Promote(Promote),
    Dist(Dist),
    Metrics(Metrics),
    Bb(Bb),
}

#[derive(Debug)]
pub struct Help {
    pub help: bool,
}

#[derive(Debug)]
pub struct Install {
    pub client: bool,
    pub code_bin: Option<String>,
    pub server: bool,
    pub mimalloc: bool,
    pub jemalloc: bool,
}

#[derive(Debug)]
pub struct Codegen {
    pub features: bool,
}

#[derive(Debug)]
pub struct Lint {}

#[derive(Debug)]
pub struct FuzzTests {}

#[derive(Debug)]
pub struct PreCache {}

#[derive(Debug)]
pub struct Release {
    pub dry_run: bool,
}

#[derive(Debug)]
pub struct Promote {
    pub dry_run: bool,
}

#[derive(Debug)]
pub struct Dist {
    pub nightly: bool,
    pub client: Option<String>,
}

#[derive(Debug)]
pub struct Metrics {
    pub dry_run: bool,
}

#[derive(Debug)]
pub struct Bb {
    pub suffix: String,
}

impl Xtask {
    pub const HELP: &'static str = Self::_HELP;

    pub fn from_env() -> xflags::Result<Self> {
        let mut p = xflags::rt::Parser::new_from_env();
        Self::_parse(&mut p)
    }
}
// generated end
<commit_msg>Update xtask/src/flags.rs<commit_after>#![allow(unreachable_pub)]

xflags::args_parser! {
    /// Run custom build command.
    cmd xtask {
        default cmd help {
            /// Print help information.
            optional -h, --help
        }

        /// Install rust-analyzer server or editor plugin.
        cmd install {
            /// Install only VS Code plugin.
            optional --client
            /// One of 'code', 'code-exploration', 'code-insiders', 'codium', or 'code-oss'.
            optional --code-bin name: String

            /// Install only the language server.
            optional --server
            /// Use mimalloc allocator for server
            optional --mimalloc
            /// Use jemalloc allocator for server
            optional --jemalloc
        }

        cmd codegen {
            optional --features
        }

        cmd lint {}
        cmd fuzz-tests {}
        cmd pre-cache {}

        cmd release {
            optional --dry-run
        }
        cmd promote {
            optional --dry-run
        }
        cmd dist {
            optional --nightly
            optional --client version: String
        }
        cmd metrics {
            optional --dry-run
        }
        /// Builds a benchmark version of rust-analyzer and puts it into `./target`.
        cmd bb
            required suffix: String
        {}
    }
}

// generated start
// The following code is generated by `xflags` macro.
// Run `env XFLAGS_DUMP= cargo build` to regenerate.
#[derive(Debug)]
pub struct Xtask {
    pub subcommand: XtaskCmd,
}

#[derive(Debug)]
pub enum XtaskCmd {
    Help(Help),
    Install(Install),
    Codegen(Codegen),
    Lint(Lint),
    FuzzTests(FuzzTests),
    PreCache(PreCache),
    Release(Release),
    Promote(Promote),
    Dist(Dist),
    Metrics(Metrics),
    Bb(Bb),
}

#[derive(Debug)]
pub struct Help {
    pub help: bool,
}

#[derive(Debug)]
pub struct Install {
    pub client: bool,
    pub code_bin: Option<String>,
    pub server: bool,
    pub mimalloc: bool,
    pub jemalloc: bool,
}

#[derive(Debug)]
pub struct Codegen {
    pub features: bool,
}

#[derive(Debug)]
pub struct Lint {}

#[derive(Debug)]
pub struct FuzzTests {}

#[derive(Debug)]
pub struct PreCache {}

#[derive(Debug)]
pub struct Release {
    pub dry_run: bool,
}

#[derive(Debug)]
pub struct Promote {
    pub dry_run: bool,
}

#[derive(Debug)]
pub struct Dist {
    pub nightly: bool,
    pub client: Option<String>,
}

#[derive(Debug)]
pub struct Metrics {
    pub dry_run: bool,
}

#[derive(Debug)]
pub struct Bb {
    pub suffix: String,
}

impl Xtask {
    pub const HELP: &'static str = Self::_HELP;

    pub fn from_env() -> xflags::Result<Self> {
        let mut p = xflags::rt::Parser::new_from_env();
        Self::_parse(&mut p)
    }
}
// generated end
<|endoftext|>


<commit_before>mod foreign_types_map {
    #![foreigner_type="void"]
    #![rust_type="()"]
    #![foreigner_type="boolean"]
    #![rust_type="jboolean"]
    #![foreigner_type="byte"]
    #![rust_type="jbyte"]
    #![foreigner_type="short"]
    #![rust_type="jshort"]
    #![foreigner_type="int"]
    #![rust_type="jint"]
    #![foreigner_type="long"]
    #![rust_type="jlong"]
    #![foreigner_type="String"]
    #![rust_type="jstring"]
    #![foreigner_type="float"]
    #![rust_type="jfloat"]
    #![foreigner_type="double"]
    #![rust_type="jdouble"]
    #![foreigner_type="Object"]
    #![rust_type_not_unique="jobject"]
    #![foreigner_type="java.util.Date"]
    #![rust_type_not_unique="jobject"]
}

#[cfg(target_pointer_width = "32")]
unsafe fn jlong_to_pointer<T>(val: jlong) -> *mut T {
    ::std::mem::transmute::<u32, *mut T>(val as u32)
}

#[cfg(target_pointer_width = "64")]
unsafe fn jlong_to_pointer<T>(val: jlong) -> *mut T {
    ::std::mem::transmute::<jlong, *mut T>(val)
}

#[allow(dead_code)]
struct JavaString {
    string: jstring,
    chars: *const ::std::os::raw::c_char,
    env: *mut JNIEnv,
}
#[allow(dead_code)]
impl JavaString {
    fn new(env: *mut JNIEnv, js: jstring) -> JavaString {
        let chars = unsafe { (**env).GetStringUTFChars.unwrap()(env, js, ::std::ptr::null_mut()) };
        JavaString {
            string: js,
            chars: chars,
            env: env,
        }
    }
    fn to_str(&self) -> &str {
        let s = unsafe { ::std::ffi::CStr::from_ptr(self.chars) };
        s.to_str().unwrap()
    }
}

#[allow(dead_code)]
impl Drop for JavaString {
    fn drop(&mut self) {
        assert!(self.env != ::std::ptr::null_mut() && self.chars != ::std::ptr::null_mut());
        unsafe { (**self.env).ReleaseStringUTFChars.unwrap()(self.env, self.string, self.chars) };
        self.env = ::std::ptr::null_mut();
        self.chars = ::std::ptr::null_mut();
    }
}

impl ::std::ops::Deref for JavaString {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.to_str()
    }
}

#[allow(dead_code)]
fn jni_throw(env: *mut JNIEnv, class_name: &'static str, message: &str) {
    let class_name_c = ::std::ffi::CString::new(class_name).unwrap();

    let ex_class = unsafe { (**env).FindClass.unwrap()(env, class_name_c.as_ptr()) };
    if ex_class.is_null() {
        error!("throw_exception: can not find exp class {}, msg {}",
               class_name,
               message);
        return;
    }
    let c_message = ::std::ffi::CString::new(message).unwrap();
    let res = unsafe { (**env).ThrowNew.unwrap()(env, ex_class, c_message.as_ptr()) };
    if res != 0 {
        error!("ThrowNew({}) for class {} failed", message, class_name);
    }
}

#[allow(dead_code)]
fn jni_throw_exception(env: *mut JNIEnv, message: &str) {
    jni_throw(env, "java/lang/Exception", message)
}

#[allow(dead_code)]
fn object_to_jobject<T>(obj: T, full_class_name: &str, env: *mut JNIEnv) -> jobject {
    let class_id = ::std::ffi::CString::new(full_class_name).unwrap();
    let jcls: jclass = unsafe { (**env).FindClass.unwrap()(env, class_id.as_ptr()) };
    assert!(!jcls.is_null());
    let jobj: jobject = unsafe { (**env).AllocObject.unwrap()(env, jcls) };
    assert!(!jobj.is_null());
    let field_id = ::std::ffi::CString::new("mNativeObj").unwrap();
    let type_id = ::std::ffi::CString::new("J").unwrap();
    let field_id: jfieldID =
        unsafe { (**env).GetFieldID.unwrap()(env, jcls, field_id.as_ptr(), type_id.as_ptr()) };
    assert!(!field_id.is_null());
    let b: Box<T> = Box::new(obj);
    let ret = Box::into_raw(b) as jlong;
    unsafe {
        (**env).SetLongField.unwrap()(env, jobj, field_id, ret);
        if (**env).ExceptionCheck.unwrap()(env) != 0 {
            panic!("Can not mNativeObj field: catch exception");
        }
    }
    jobj
}

#[allow(dead_code)]
fn vec_of_objects_to_jobject_array<T>(mut arr: Vec<T>,
                                      full_class_name: &str,
                                      env: *mut JNIEnv)
                                      -> jobjectArray {
    let class_id = ::std::ffi::CString::new(full_class_name).unwrap();
    let jcls: jclass = unsafe { (**env).FindClass.unwrap()(env, class_id.as_ptr()) };
    assert!(!jcls.is_null());
    let obj_arr: jobjectArray = unsafe {
        (**env).NewObjectArray.unwrap()(env, arr.len() as jsize, jcls, ::std::ptr::null_mut())
    };
    assert!(!obj_arr.is_null());

    let field_id = ::std::ffi::CString::new("mNativeObj").unwrap();
    let type_id = ::std::ffi::CString::new("J").unwrap();
    let field_id: jfieldID =
        unsafe { (**env).GetFieldID.unwrap()(env, jcls, field_id.as_ptr(), type_id.as_ptr()) };
    assert!(!field_id.is_null());

    for (i, r_obj) in arr.drain(..).enumerate() {
        let jobj: jobject = unsafe { (**env).AllocObject.unwrap()(env, jcls) };
        assert!(!jobj.is_null());

        let r_obj = Box::into_raw(Box::new(r_obj)) as jlong;
        unsafe {
            (**env).SetLongField.unwrap()(env, jobj, field_id, r_obj);
            if (**env).ExceptionCheck.unwrap()(env) != 0 {
                panic!("Can not mNativeObj field: catch exception");
            }
            (**env).SetObjectArrayElement.unwrap()(env, obj_arr, i as jsize, jobj);
            if (**env).ExceptionCheck.unwrap()(env) != 0 {
                panic!("SetObjectArrayElement({}) failed", i);
            }
            (**env).DeleteLocalRef.unwrap()(env, jobj);
        }
    }
    obj_arr
}

#[allow(dead_code)]
macro_rules! jni_unpack_return {
    ($result_value:expr, $default_value:expr, $env:ident) => {
        {
            let ret = match $result_value {
                Ok(x) => x,
                Err(msg) => {
                    jni_throw_exception($env, &msg);
                    return $default_value;
                }
            };
            ret
        }
    }
}

#[allow(dead_code)]
trait SwigInto<T> {
    fn swig_into(self, env: *mut JNIEnv) -> T;
}

#[allow(dead_code)]
trait SwigFrom<T> {
    fn swig_from(T, env: *mut JNIEnv) -> Self;
}

impl SwigInto<bool> for jboolean {
    fn swig_into(self, _: *mut JNIEnv) -> bool {
        self != 0
    }
}

impl SwigFrom<bool> for jboolean {
    fn swig_from(x: bool, _: *mut JNIEnv) -> Self {
        if x { 1 as jboolean } else { 0 as jboolean }
    }
}

impl SwigFrom<i8> for jbyte {
    fn swig_from(x: i8, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigInto<i8> for jbyte {
    fn swig_into(self, _: *mut JNIEnv) -> i8 {
        self
    }
}

impl SwigFrom<u8> for jshort {
    fn swig_from(x: u8, _: *mut JNIEnv) -> Self {
        x as jshort
    }
}

impl SwigInto<u8> for jshort {
    fn swig_into(self, _: *mut JNIEnv) -> u8 {
        if self < 0 || self > (::std::u8::MAX as jshort) {
            panic!("Expect self from 0 to {}, got {}", ::std::u8::MAX, self);
        }
        self as u8
    }
}

impl SwigInto<i16> for jshort {
    fn swig_into(self, _: *mut JNIEnv) -> i16 {
        self
    }
}

impl SwigFrom<i16> for jshort {
    fn swig_from(x: i16, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigFrom<u16> for jint {
    fn swig_from(x: u16, _: *mut JNIEnv) -> Self {
        x as jint
    }
}

impl SwigInto<u16> for jint {
    fn swig_into(self, _: *mut JNIEnv) -> u16 {
        if self < 0 || self > (::std::u16::MAX as jint) {
            panic!("Expect self from 0 to {}, got {}", ::std::u16::MAX, self);
        }
        self as u16
    }
}

impl SwigInto<i32> for jint {
    fn swig_into(self, _: *mut JNIEnv) -> i32 {
        self
    }
}

impl SwigFrom<i32> for jint {
    fn swig_from(x: i32, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigFrom<u32> for jlong {
    fn swig_from(x: u32, _: *mut JNIEnv) -> Self {
        x as jlong
    }
}

impl SwigInto<u32> for jlong {
    fn swig_into(self, _: *mut JNIEnv) -> u32 {
        if self < 0 || self > (::std::u32::MAX as jlong) {
            panic!("Expect self from 0 to {}, got {}", ::std::u32::MAX, self);
        }
        self as u32
    }
}

impl SwigInto<i64> for jlong {
    fn swig_into(self, _: *mut JNIEnv) -> i64 {
        self
    }
}

impl SwigFrom<i64> for jlong {
    fn swig_from(x: i64, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigInto<u64> for jlong {
    fn swig_into(self, _: *mut JNIEnv) -> u64 {
        if self < 0 {
            panic!("Expect self to be positive, got {}", self);
        }
        self as u64
    }
}

impl SwigFrom<u64> for jlong {
    fn swig_from(x: u64, _: *mut JNIEnv) -> Self {
        if (::std::i64::MAX as u64) < x {
            error!("u64->jlong type overflow: {}", x);
            ::std::i64::MAX
        } else {
            x as i64
        }
    }
}

impl SwigInto<f32> for jfloat {
    fn swig_into(self, _: *mut JNIEnv) -> f32 {
        self
    }
}

impl SwigFrom<f32> for jfloat {
    fn swig_from(x: f32, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigInto<f64> for jdouble {
    fn swig_into(self, _: *mut JNIEnv) -> f64 {
        self
    }
}

impl SwigFrom<f64> for jdouble {
    fn swig_from(x: f64, _: *mut JNIEnv) -> Self {
        x
    }
}

impl<'a> SwigFrom<&'a str> for jstring {
    fn swig_from(x: &'a str, env: *mut JNIEnv) -> Self {
        let x = ::std::ffi::CString::new(x).unwrap();
        unsafe { (**env).NewStringUTF.unwrap()(env, x.as_ptr()) }
    }
}

impl SwigInto<JavaString> for jstring {
    fn swig_into(self, env: *mut JNIEnv) -> JavaString {
        JavaString::new(env, self)
    }
}

impl SwigFrom<String> for jstring {
    fn swig_from(x: String, env: *mut JNIEnv) -> Self {
        let x = x.into_bytes();
        let x = unsafe { ::std::ffi::CString::from_vec_unchecked(x) };
        unsafe { (**env).NewStringUTF.unwrap()(env, x.as_ptr()) }
    }
}

#[to_foreigner_hint = "java.util.Date"]
impl SwigFrom<SystemTime> for jobject {
    fn swig_from(x: SystemTime, env: *mut JNIEnv) -> Self {
        let since_unix_epoch = x.duration_since(::std::time::UNIX_EPOCH).unwrap();
        let mills: jlong = (since_unix_epoch.as_secs() * 1_000 +
                            (since_unix_epoch.subsec_nanos() / 1_000_000) as u64) as
                           jlong;
        let class_name_c = ::std::ffi::CString::new("java/util/Date").unwrap();
        let date_class: jclass = unsafe { (**env).FindClass.unwrap()(env, class_name_c.as_ptr()) };
        assert!(!date_class.is_null());
        let init_name_c = ::std::ffi::CString::new("<init>").unwrap();
        let method_args_c = ::std::ffi::CString::new("(J)V").unwrap();
        let init: jmethodID = unsafe {
            (**env).GetMethodID.unwrap()(env,
                                         date_class,
                                         init_name_c.as_ptr(),
                                         method_args_c.as_ptr())
        };
        assert!(!init.is_null());
        let x = unsafe { (**env).NewObject.unwrap()(env, date_class, init, mills) };
        assert!(!x.is_null());
        x
    }
}

impl SwigInto<usize> for i64 {
    fn swig_into(self, _: *mut JNIEnv) -> usize {
        if self < 0 {
            panic!("{}:{} expect self to be positive, got {}",
                   file!(),
                   line!(),
                   self);
        } else if (self as u64) > (::std::usize::MAX as u64) {
            panic!("{}:{} too big value for usize {}", self);
        } else {
            self as usize
        }
    }
}

// &str -> &Path
impl<'a> SwigInto<&'a Path> for &'a str {
    fn swig_into(self, _: *mut JNIEnv) -> &'a Path {
        Path::new(self)
    }
}
<commit_msg>fixes warning in generated code<commit_after>mod foreign_types_map {
    #![foreigner_type="void"]
    #![rust_type="()"]
    #![foreigner_type="boolean"]
    #![rust_type="jboolean"]
    #![foreigner_type="byte"]
    #![rust_type="jbyte"]
    #![foreigner_type="short"]
    #![rust_type="jshort"]
    #![foreigner_type="int"]
    #![rust_type="jint"]
    #![foreigner_type="long"]
    #![rust_type="jlong"]
    #![foreigner_type="String"]
    #![rust_type="jstring"]
    #![foreigner_type="float"]
    #![rust_type="jfloat"]
    #![foreigner_type="double"]
    #![rust_type="jdouble"]
    #![foreigner_type="Object"]
    #![rust_type_not_unique="jobject"]
    #![foreigner_type="java.util.Date"]
    #![rust_type_not_unique="jobject"]
}

#[cfg(target_pointer_width = "32")]
unsafe fn jlong_to_pointer<T>(val: jlong) -> *mut T {
    ::std::mem::transmute::<u32, *mut T>(val as u32)
}

#[cfg(target_pointer_width = "64")]
unsafe fn jlong_to_pointer<T>(val: jlong) -> *mut T {
    ::std::mem::transmute::<jlong, *mut T>(val)
}

#[allow(dead_code)]
struct JavaString {
    string: jstring,
    chars: *const ::std::os::raw::c_char,
    env: *mut JNIEnv,
}
#[allow(dead_code)]
impl JavaString {
    fn new(env: *mut JNIEnv, js: jstring) -> JavaString {
        let chars = unsafe { (**env).GetStringUTFChars.unwrap()(env, js, ::std::ptr::null_mut()) };
        JavaString {
            string: js,
            chars: chars,
            env: env,
        }
    }
    fn to_str(&self) -> &str {
        let s = unsafe { ::std::ffi::CStr::from_ptr(self.chars) };
        s.to_str().unwrap()
    }
}

#[allow(dead_code)]
impl Drop for JavaString {
    fn drop(&mut self) {
        assert!(self.env != ::std::ptr::null_mut() && self.chars != ::std::ptr::null_mut());
        unsafe { (**self.env).ReleaseStringUTFChars.unwrap()(self.env, self.string, self.chars) };
        self.env = ::std::ptr::null_mut();
        self.chars = ::std::ptr::null_mut();
    }
}

impl ::std::ops::Deref for JavaString {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.to_str()
    }
}

#[allow(dead_code)]
fn jni_throw(env: *mut JNIEnv, class_name: &'static str, message: &str) {
    let class_name_c = ::std::ffi::CString::new(class_name).unwrap();

    let ex_class = unsafe { (**env).FindClass.unwrap()(env, class_name_c.as_ptr()) };
    if ex_class.is_null() {
        error!("throw_exception: can not find exp class {}, msg {}",
               class_name,
               message);
        return;
    }
    let c_message = ::std::ffi::CString::new(message).unwrap();
    let res = unsafe { (**env).ThrowNew.unwrap()(env, ex_class, c_message.as_ptr()) };
    if res != 0 {
        error!("ThrowNew({}) for class {} failed", message, class_name);
    }
}

#[allow(dead_code)]
fn jni_throw_exception(env: *mut JNIEnv, message: &str) {
    jni_throw(env, "java/lang/Exception", message)
}

#[allow(dead_code)]
fn object_to_jobject<T>(obj: T, full_class_name: &str, env: *mut JNIEnv) -> jobject {
    let class_id = ::std::ffi::CString::new(full_class_name).unwrap();
    let jcls: jclass = unsafe { (**env).FindClass.unwrap()(env, class_id.as_ptr()) };
    assert!(!jcls.is_null());
    let jobj: jobject = unsafe { (**env).AllocObject.unwrap()(env, jcls) };
    assert!(!jobj.is_null());
    let field_id = ::std::ffi::CString::new("mNativeObj").unwrap();
    let type_id = ::std::ffi::CString::new("J").unwrap();
    let field_id: jfieldID =
        unsafe { (**env).GetFieldID.unwrap()(env, jcls, field_id.as_ptr(), type_id.as_ptr()) };
    assert!(!field_id.is_null());
    let b: Box<T> = Box::new(obj);
    let ret = Box::into_raw(b) as jlong;
    unsafe {
        (**env).SetLongField.unwrap()(env, jobj, field_id, ret);
        if (**env).ExceptionCheck.unwrap()(env) != 0 {
            panic!("Can not mNativeObj field: catch exception");
        }
    }
    jobj
}

#[allow(dead_code)]
fn vec_of_objects_to_jobject_array<T>(mut arr: Vec<T>,
                                      full_class_name: &str,
                                      env: *mut JNIEnv)
                                      -> jobjectArray {
    let class_id = ::std::ffi::CString::new(full_class_name).unwrap();
    let jcls: jclass = unsafe { (**env).FindClass.unwrap()(env, class_id.as_ptr()) };
    assert!(!jcls.is_null());
    let obj_arr: jobjectArray = unsafe {
        (**env).NewObjectArray.unwrap()(env, arr.len() as jsize, jcls, ::std::ptr::null_mut())
    };
    assert!(!obj_arr.is_null());

    let field_id = ::std::ffi::CString::new("mNativeObj").unwrap();
    let type_id = ::std::ffi::CString::new("J").unwrap();
    let field_id: jfieldID =
        unsafe { (**env).GetFieldID.unwrap()(env, jcls, field_id.as_ptr(), type_id.as_ptr()) };
    assert!(!field_id.is_null());

    for (i, r_obj) in arr.drain(..).enumerate() {
        let jobj: jobject = unsafe { (**env).AllocObject.unwrap()(env, jcls) };
        assert!(!jobj.is_null());

        let r_obj = Box::into_raw(Box::new(r_obj)) as jlong;
        unsafe {
            (**env).SetLongField.unwrap()(env, jobj, field_id, r_obj);
            if (**env).ExceptionCheck.unwrap()(env) != 0 {
                panic!("Can not mNativeObj field: catch exception");
            }
            (**env).SetObjectArrayElement.unwrap()(env, obj_arr, i as jsize, jobj);
            if (**env).ExceptionCheck.unwrap()(env) != 0 {
                panic!("SetObjectArrayElement({}) failed", i);
            }
            (**env).DeleteLocalRef.unwrap()(env, jobj);
        }
    }
    obj_arr
}

#[allow(unused_macros)]
macro_rules! jni_unpack_return {
    ($result_value:expr, $default_value:expr, $env:ident) => {
        {
            let ret = match $result_value {
                Ok(x) => x,
                Err(msg) => {
                    jni_throw_exception($env, &msg);
                    return $default_value;
                }
            };
            ret
        }
    }
}

#[allow(dead_code)]
trait SwigInto<T> {
    fn swig_into(self, env: *mut JNIEnv) -> T;
}

#[allow(dead_code)]
trait SwigFrom<T> {
    fn swig_from(T, env: *mut JNIEnv) -> Self;
}

impl SwigInto<bool> for jboolean {
    fn swig_into(self, _: *mut JNIEnv) -> bool {
        self != 0
    }
}

impl SwigFrom<bool> for jboolean {
    fn swig_from(x: bool, _: *mut JNIEnv) -> Self {
        if x { 1 as jboolean } else { 0 as jboolean }
    }
}

impl SwigFrom<i8> for jbyte {
    fn swig_from(x: i8, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigInto<i8> for jbyte {
    fn swig_into(self, _: *mut JNIEnv) -> i8 {
        self
    }
}

impl SwigFrom<u8> for jshort {
    fn swig_from(x: u8, _: *mut JNIEnv) -> Self {
        x as jshort
    }
}

impl SwigInto<u8> for jshort {
    fn swig_into(self, _: *mut JNIEnv) -> u8 {
        if self < 0 || self > (::std::u8::MAX as jshort) {
            panic!("Expect self from 0 to {}, got {}", ::std::u8::MAX, self);
        }
        self as u8
    }
}

impl SwigInto<i16> for jshort {
    fn swig_into(self, _: *mut JNIEnv) -> i16 {
        self
    }
}

impl SwigFrom<i16> for jshort {
    fn swig_from(x: i16, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigFrom<u16> for jint {
    fn swig_from(x: u16, _: *mut JNIEnv) -> Self {
        x as jint
    }
}

impl SwigInto<u16> for jint {
    fn swig_into(self, _: *mut JNIEnv) -> u16 {
        if self < 0 || self > (::std::u16::MAX as jint) {
            panic!("Expect self from 0 to {}, got {}", ::std::u16::MAX, self);
        }
        self as u16
    }
}

impl SwigInto<i32> for jint {
    fn swig_into(self, _: *mut JNIEnv) -> i32 {
        self
    }
}

impl SwigFrom<i32> for jint {
    fn swig_from(x: i32, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigFrom<u32> for jlong {
    fn swig_from(x: u32, _: *mut JNIEnv) -> Self {
        x as jlong
    }
}

impl SwigInto<u32> for jlong {
    fn swig_into(self, _: *mut JNIEnv) -> u32 {
        if self < 0 || self > (::std::u32::MAX as jlong) {
            panic!("Expect self from 0 to {}, got {}", ::std::u32::MAX, self);
        }
        self as u32
    }
}

impl SwigInto<i64> for jlong {
    fn swig_into(self, _: *mut JNIEnv) -> i64 {
        self
    }
}

impl SwigFrom<i64> for jlong {
    fn swig_from(x: i64, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigInto<u64> for jlong {
    fn swig_into(self, _: *mut JNIEnv) -> u64 {
        if self < 0 {
            panic!("Expect self to be positive, got {}", self);
        }
        self as u64
    }
}

impl SwigFrom<u64> for jlong {
    fn swig_from(x: u64, _: *mut JNIEnv) -> Self {
        if (::std::i64::MAX as u64) < x {
            error!("u64->jlong type overflow: {}", x);
            ::std::i64::MAX
        } else {
            x as i64
        }
    }
}

impl SwigInto<f32> for jfloat {
    fn swig_into(self, _: *mut JNIEnv) -> f32 {
        self
    }
}

impl SwigFrom<f32> for jfloat {
    fn swig_from(x: f32, _: *mut JNIEnv) -> Self {
        x
    }
}

impl SwigInto<f64> for jdouble {
    fn swig_into(self, _: *mut JNIEnv) -> f64 {
        self
    }
}

impl SwigFrom<f64> for jdouble {
    fn swig_from(x: f64, _: *mut JNIEnv) -> Self {
        x
    }
}

impl<'a> SwigFrom<&'a str> for jstring {
    fn swig_from(x: &'a str, env: *mut JNIEnv) -> Self {
        let x = ::std::ffi::CString::new(x).unwrap();
        unsafe { (**env).NewStringUTF.unwrap()(env, x.as_ptr()) }
    }
}

impl SwigInto<JavaString> for jstring {
    fn swig_into(self, env: *mut JNIEnv) -> JavaString {
        JavaString::new(env, self)
    }
}

impl SwigFrom<String> for jstring {
    fn swig_from(x: String, env: *mut JNIEnv) -> Self {
        let x = x.into_bytes();
        let x = unsafe { ::std::ffi::CString::from_vec_unchecked(x) };
        unsafe { (**env).NewStringUTF.unwrap()(env, x.as_ptr()) }
    }
}

#[to_foreigner_hint = "java.util.Date"]
impl SwigFrom<SystemTime> for jobject {
    fn swig_from(x: SystemTime, env: *mut JNIEnv) -> Self {
        let since_unix_epoch = x.duration_since(::std::time::UNIX_EPOCH).unwrap();
        let mills: jlong = (since_unix_epoch.as_secs() * 1_000 +
                            (since_unix_epoch.subsec_nanos() / 1_000_000) as u64) as
                           jlong;
        let class_name_c = ::std::ffi::CString::new("java/util/Date").unwrap();
        let date_class: jclass = unsafe { (**env).FindClass.unwrap()(env, class_name_c.as_ptr()) };
        assert!(!date_class.is_null());
        let init_name_c = ::std::ffi::CString::new("<init>").unwrap();
        let method_args_c = ::std::ffi::CString::new("(J)V").unwrap();
        let init: jmethodID = unsafe {
            (**env).GetMethodID.unwrap()(env,
                                         date_class,
                                         init_name_c.as_ptr(),
                                         method_args_c.as_ptr())
        };
        assert!(!init.is_null());
        let x = unsafe { (**env).NewObject.unwrap()(env, date_class, init, mills) };
        assert!(!x.is_null());
        x
    }
}

impl SwigInto<usize> for i64 {
    fn swig_into(self, _: *mut JNIEnv) -> usize {
        if self < 0 {
            panic!("{}:{} expect self to be positive, got {}",
                   file!(),
                   line!(),
                   self);
        } else if (self as u64) > (::std::usize::MAX as u64) {
            panic!("{}:{} too big value for usize {}", self);
        } else {
            self as usize
        }
    }
}

// &str -> &Path
impl<'a> SwigInto<&'a Path> for &'a str {
    fn swig_into(self, _: *mut JNIEnv) -> &'a Path {
        Path::new(self)
    }
}
<|endoftext|>


<commit_before>// This is a test which attempts to blow out the system limit with how many
// arguments can be passed to a process. This'll successively call rustc with
// larger and larger argument lists in an attempt to find one that's way too
// big for the system at hand. This file itself is then used as a "linker" to
// detect when the process creation succeeds.
//
// Eventually we should see an argument that looks like `@` as we switch from
// passing literal arguments to passing everything in the file.

use std::collections::HashSet;
use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

fn write_test_case(file: &Path, n: usize) -> HashSet<String> {
    let mut libs = HashSet::new();
    let mut f = BufWriter::new(File::create(&file).unwrap());
    let mut prefix = String::new();
    for _ in 0..n {
        prefix.push_str("foo");
    }
    for i in 0..n {
        writeln!(f, "#[link(name = \"S{}{}S\")]", prefix, i).unwrap();
        libs.insert(format!("{}{}", prefix, i));
    }
    writeln!(f, "extern {{}}\nfn main() {{}}").unwrap();
    f.into_inner().unwrap();

    libs
}

fn read_linker_args(path: &Path) -> String {
    let contents = fs::read(path).unwrap();
    if cfg!(target_env = "msvc") {
        let mut i = contents.chunks(2).map(|c| {
            c[0] as u16 | ((c[1] as u16) << 8)
        });
        assert_eq!(i.next(), Some(0xfeff), "Expected UTF-16 BOM");
        String::from_utf16(&i.collect::<Vec<u16>>()).unwrap()
    } else {
        String::from_utf8(contents).unwrap()
    }
}

fn main() {
    let tmpdir = PathBuf::from(env::var_os("TMPDIR").unwrap());
    let ok = tmpdir.join("ok");
    if env::var("YOU_ARE_A_LINKER").is_ok() {
        if let Some(file) = env::args_os().find(|a| a.to_string_lossy().contains("@")) {
            let file = file.to_str().expect("non-utf8 file argument");
            fs::copy(&file[1..], &ok).unwrap();
        }
        return
    }

    let rustc = env::var_os("RUSTC").unwrap_or("rustc".into());
    let me_as_linker = format!("linker={}", env::current_exe().unwrap().display());
    for i in (1..).map(|i| i * 100) {
        println!("attempt: {}", i);
        let file = tmpdir.join("bar.rs");
        let mut expected_libs = write_test_case(&file, i);

        drop(fs::remove_file(&ok));
        let output = Command::new(&rustc)
            .arg(&file)
            .arg("-C").arg(&me_as_linker)
            .arg("--out-dir").arg(&tmpdir)
            .env("YOU_ARE_A_LINKER", "1")
            .output()
            .unwrap();

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            panic!("status: {}\nstdout:\n{}\nstderr:\n{}",
                   output.status,
                   String::from_utf8_lossy(&output.stdout),
                   stderr.lines().map(|l| {
                       if l.len() > 200 {
                           format!("{}...\n", &l[..200])
                       } else {
                           format!("{}\n", l)
                       }
                   }).collect::<String>());
        }

        if !ok.exists() {
            continue
        }

        let linker_args = read_linker_args(&ok);
        for mut arg in linker_args.split('S') {
            expected_libs.remove(arg);
        }

        assert!(
            expected_libs.is_empty(),
            "expected but missing libraries: {:#?}\nlinker arguments: \n{}",
            expected_libs,
            linker_args,
        );

        break
    }
}
<commit_msg>Remove unused mut from long-linker-command-lines test<commit_after>// This is a test which attempts to blow out the system limit with how many
// arguments can be passed to a process. This'll successively call rustc with
// larger and larger argument lists in an attempt to find one that's way too
// big for the system at hand. This file itself is then used as a "linker" to
// detect when the process creation succeeds.
//
// Eventually we should see an argument that looks like `@` as we switch from
// passing literal arguments to passing everything in the file.

use std::collections::HashSet;
use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

fn write_test_case(file: &Path, n: usize) -> HashSet<String> {
    let mut libs = HashSet::new();
    let mut f = BufWriter::new(File::create(&file).unwrap());
    let mut prefix = String::new();
    for _ in 0..n {
        prefix.push_str("foo");
    }
    for i in 0..n {
        writeln!(f, "#[link(name = \"S{}{}S\")]", prefix, i).unwrap();
        libs.insert(format!("{}{}", prefix, i));
    }
    writeln!(f, "extern {{}}\nfn main() {{}}").unwrap();
    f.into_inner().unwrap();

    libs
}

fn read_linker_args(path: &Path) -> String {
    let contents = fs::read(path).unwrap();
    if cfg!(target_env = "msvc") {
        let mut i = contents.chunks(2).map(|c| {
            c[0] as u16 | ((c[1] as u16) << 8)
        });
        assert_eq!(i.next(), Some(0xfeff), "Expected UTF-16 BOM");
        String::from_utf16(&i.collect::<Vec<u16>>()).unwrap()
    } else {
        String::from_utf8(contents).unwrap()
    }
}

fn main() {
    let tmpdir = PathBuf::from(env::var_os("TMPDIR").unwrap());
    let ok = tmpdir.join("ok");
    if env::var("YOU_ARE_A_LINKER").is_ok() {
        if let Some(file) = env::args_os().find(|a| a.to_string_lossy().contains("@")) {
            let file = file.to_str().expect("non-utf8 file argument");
            fs::copy(&file[1..], &ok).unwrap();
        }
        return
    }

    let rustc = env::var_os("RUSTC").unwrap_or("rustc".into());
    let me_as_linker = format!("linker={}", env::current_exe().unwrap().display());
    for i in (1..).map(|i| i * 100) {
        println!("attempt: {}", i);
        let file = tmpdir.join("bar.rs");
        let mut expected_libs = write_test_case(&file, i);

        drop(fs::remove_file(&ok));
        let output = Command::new(&rustc)
            .arg(&file)
            .arg("-C").arg(&me_as_linker)
            .arg("--out-dir").arg(&tmpdir)
            .env("YOU_ARE_A_LINKER", "1")
            .output()
            .unwrap();

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            panic!("status: {}\nstdout:\n{}\nstderr:\n{}",
                   output.status,
                   String::from_utf8_lossy(&output.stdout),
                   stderr.lines().map(|l| {
                       if l.len() > 200 {
                           format!("{}...\n", &l[..200])
                       } else {
                           format!("{}\n", l)
                       }
                   }).collect::<String>());
        }

        if !ok.exists() {
            continue
        }

        let linker_args = read_linker_args(&ok);
        for arg in linker_args.split('S') {
            expected_libs.remove(arg);
        }

        assert!(
            expected_libs.is_empty(),
            "expected but missing libraries: {:#?}\nlinker arguments: \n{}",
            expected_libs,
            linker_args,
        );

        break
    }
}
<|endoftext|>


<commit_before>#[derive(Debug,PartialEq)]
pub enum RleComponent {
    Run(usize, u8),
    Literal(Vec<u8>)
}

pub fn encode(input: &str) -> Vec<RleComponent> {
    let mut last : u8 = input.bytes().nth(0).unwrap();
    let mut counter : usize = 0;
    let mut encoded = vec!();

    for bv in input.bytes() {
        if bv == last {
            counter += 1;
        } else {
            if counter == 1 {
                // TODO: Combine adjacent literals.
                encoded.push(RleComponent::Literal(vec![last]));
            } else {
                encoded.push(RleComponent::Run(counter, last));
            }

            counter = 1;
            last = bv;
        }
    }
    // TODO: This repeated code isn't ideal.
    if counter == 1 {
        encoded.push(RleComponent::Literal(vec![last]));
    } else {
        encoded.push(RleComponent::Run(counter, last));
    }

    encoded//.to_vec()
}

pub fn decode(input: Vec<RleComponent>) -> String {
    let mut decoded = vec!();

    for component in input {
        let tv = match component {
            RleComponent::Run(length, byte) => vec![byte;length],
            RleComponent::Literal(bytes) => bytes,
        };
        decoded.extend(tv);
    }

    String::from_utf8(decoded).unwrap()
}

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

    #[test]
    fn basic_encode() {
        assert_eq!(
            encode("hello"),
            [
                RleComponent::Literal(vec![104]),
                RleComponent::Literal(vec![101]),
                RleComponent::Run(2, 108),
                RleComponent::Literal(vec![111])
            ]
        );
    }

    #[test]
    fn with_trailing_run() {
        assert_eq!(
            encode("helloo"),
            [
                RleComponent::Literal(vec![104]),
                RleComponent::Literal(vec![101]),
                RleComponent::Run(2, 108),
                RleComponent::Run(2, 111),
            ]
        );
    }

    #[test]
    fn moretests() {
        assert_eq!(
            encode("aaaaaab"),
            [
                RleComponent::Run(6, 97),
                RleComponent::Literal(vec![98]),
            ]
        );
    }

    #[test]
    fn basic_decode() {
        assert_eq!(
            decode(encode("aabb")),
            "aabb"
        );
    }

    #[test]
    fn basic_decode_only_literal() {
        assert_eq!(
            decode(encode("ab")),
            "ab"
        );
    }
}
<commit_msg>Rename variable<commit_after>#[derive(Debug,PartialEq)]
pub enum RleComponent {
    Run(usize, u8),
    Literal(Vec<u8>)
}

pub fn encode(input: &str) -> Vec<RleComponent> {
    let mut last : u8 = input.bytes().nth(0).unwrap();
    let mut counter : usize = 0;
    let mut encoded = vec!();

    for bv in input.bytes() {
        if bv == last {
            counter += 1;
        } else {
            if counter == 1 {
                // TODO: Combine adjacent literals.
                encoded.push(RleComponent::Literal(vec![last]));
            } else {
                encoded.push(RleComponent::Run(counter, last));
            }

            counter = 1;
            last = bv;
        }
    }
    // TODO: This repeated code isn't ideal.
    if counter == 1 {
        encoded.push(RleComponent::Literal(vec![last]));
    } else {
        encoded.push(RleComponent::Run(counter, last));
    }

    encoded//.to_vec()
}

pub fn decode(input: Vec<RleComponent>) -> String {
    let mut decoded = vec!();

    for component in input {
        let next_sequence = match component {
            RleComponent::Run(length, byte) => vec![byte;length],
            RleComponent::Literal(bytes) => bytes,
        };
        decoded.extend(next_sequence);
    }

    String::from_utf8(decoded).unwrap()
}

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

    #[test]
    fn basic_encode() {
        assert_eq!(
            encode("hello"),
            [
                RleComponent::Literal(vec![104]),
                RleComponent::Literal(vec![101]),
                RleComponent::Run(2, 108),
                RleComponent::Literal(vec![111])
            ]
        );
    }

    #[test]
    fn with_trailing_run() {
        assert_eq!(
            encode("helloo"),
            [
                RleComponent::Literal(vec![104]),
                RleComponent::Literal(vec![101]),
                RleComponent::Run(2, 108),
                RleComponent::Run(2, 111),
            ]
        );
    }

    #[test]
    fn moretests() {
        assert_eq!(
            encode("aaaaaab"),
            [
                RleComponent::Run(6, 97),
                RleComponent::Literal(vec![98]),
            ]
        );
    }

    #[test]
    fn basic_decode() {
        assert_eq!(
            decode(encode("aabb")),
            "aabb"
        );
    }

    #[test]
    fn basic_decode_only_literal() {
        assert_eq!(
            decode(encode("ab")),
            "ab"
        );
    }
}
<|endoftext|>


<commit_before>use screen::*;
use piston_window;
use conrod::{self, Widget, Frameable, Positionable, Sizeable, Labelable};
use conrod::color::Colorable;

pub struct MainMenuScreen {
    ui: conrod::Ui<piston_window::Glyphs>,
    new_game: bool,
    exit: bool,
}

impl MainMenuScreen {
    pub fn new(window: &piston_window::PistonWindow, context: &mut Context) -> MainMenuScreen {
        MainMenuScreen { ui: create_ui(&window, &context.assets_path), new_game: false, exit: false, }
    }
}

impl Screen for MainMenuScreen {
    fn on_input(&mut self,
                input: &piston_window::Input,
                window: &piston_window::PistonWindow,
                context: &mut Context)
                -> InputResults {
        use piston_window::{Input, Button, MouseButton};

        let mut result = Vec::new();

        match input {
            &Input::Press(Button::Mouse(MouseButton::Left)) => {
                result.push(InputResult::PopScreen);
                result.push(InputResult::PushScreen(Box::new(BattleScreen::new(&window, context))));
            }
            _ => {}
        }

        result
    }

    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow) {
        self.ui.handle_event(window);
        window.draw_2d(|context, graphics| self.ui.draw_if_changed(context, graphics));
    }

    fn on_update(&mut self, args: &piston_window::UpdateArgs) {
        handle_on_update(&mut self.ui, &mut self.new_game, &mut self.exit);
    }
}

widget_ids! {
    CANVAS,
    TITLE,
    NEW_GAME_BUTTON,
    EXIT_BUTTON,
}

fn create_ui(window: &piston_window::PistonWindow,
             assets_path: &::std::path::Path)
             -> conrod::Ui<piston_window::Glyphs> {
    let font_path = assets_path.join("NotoSans-Regular.ttf");
    let theme = conrod::Theme::default();
    let glyph_cache = piston_window::Glyphs::new(&font_path, window.factory.borrow().clone());
    conrod::Ui::new(glyph_cache.unwrap(), theme)
}

fn handle_on_update(ui: &mut conrod::Ui<piston_window::Glyphs>, new_game: &mut bool, exit: &mut bool) {
    ui.set_widgets(|ui| {
        conrod::Canvas::new()
            .pad(30.)
            .color(conrod::color::rgb(0.2, 0.35, 0.45))
            .scroll_kids()
            .set(CANVAS, ui);

        conrod::Button::new()
            .w_h(200.0, 50.0)
            .mid_left_of(CANVAS)
            .rgb(0.4, 0.75, 0.6)
            .label("New game")
            .react(|| *new_game = true)
            .set(NEW_GAME_BUTTON, ui);

        conrod::Button::new()
            .w_h(200.0, 50.0)
            .mid_left_of(CANVAS)
            .down_from(NEW_GAME_BUTTON, 45.0)
            .rgb(0.4, 0.75, 0.6)
            .label("Exit")
            .react(|| *exit = true)
            .set(EXIT_BUTTON, ui);
    });
}
<commit_msg>TITLE id has been removed<commit_after>use screen::*;
use piston_window;
use conrod::{self, Widget, Frameable, Positionable, Sizeable, Labelable};
use conrod::color::Colorable;

pub struct MainMenuScreen {
    ui: conrod::Ui<piston_window::Glyphs>,
    new_game: bool,
    exit: bool,
}

impl MainMenuScreen {
    pub fn new(window: &piston_window::PistonWindow, context: &mut Context) -> MainMenuScreen {
        MainMenuScreen { ui: create_ui(&window, &context.assets_path), new_game: false, exit: false, }
    }
}

impl Screen for MainMenuScreen {
    fn on_input(&mut self,
                input: &piston_window::Input,
                window: &piston_window::PistonWindow,
                context: &mut Context)
                -> InputResults {
        use piston_window::{Input, Button, MouseButton};

        let mut result = Vec::new();

        match input {
            &Input::Press(Button::Mouse(MouseButton::Left)) => {
                result.push(InputResult::PopScreen);
                result.push(InputResult::PushScreen(Box::new(BattleScreen::new(&window, context))));
            }
            _ => {}
        }

        result
    }

    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow) {
        self.ui.handle_event(window);
        window.draw_2d(|context, graphics| self.ui.draw_if_changed(context, graphics));
    }

    fn on_update(&mut self, args: &piston_window::UpdateArgs) {
        handle_on_update(&mut self.ui, &mut self.new_game, &mut self.exit);
    }
}

widget_ids! {
    CANVAS,
    NEW_GAME_BUTTON,
    EXIT_BUTTON,
}

fn create_ui(window: &piston_window::PistonWindow,
             assets_path: &::std::path::Path)
             -> conrod::Ui<piston_window::Glyphs> {
    let font_path = assets_path.join("NotoSans-Regular.ttf");
    let theme = conrod::Theme::default();
    let glyph_cache = piston_window::Glyphs::new(&font_path, window.factory.borrow().clone());
    conrod::Ui::new(glyph_cache.unwrap(), theme)
}

fn handle_on_update(ui: &mut conrod::Ui<piston_window::Glyphs>, new_game: &mut bool, exit: &mut bool) {
    ui.set_widgets(|ui| {
        conrod::Canvas::new()
            .pad(30.)
            .color(conrod::color::rgb(0.2, 0.35, 0.45))
            .scroll_kids()
            .set(CANVAS, ui);

        conrod::Button::new()
            .w_h(200.0, 50.0)
            .mid_left_of(CANVAS)
            .rgb(0.4, 0.75, 0.6)
            .label("New game")
            .react(|| *new_game = true)
            .set(NEW_GAME_BUTTON, ui);

        conrod::Button::new()
            .w_h(200.0, 50.0)
            .mid_left_of(CANVAS)
            .down_from(NEW_GAME_BUTTON, 45.0)
            .rgb(0.4, 0.75, 0.6)
            .label("Exit")
            .react(|| *exit = true)
            .set(EXIT_BUTTON, ui);
    });
}
<|endoftext|>