<commit_before>pub type XMM_SAVE_AREA32 = XSAVE_FORMAT;

s_no_extra_traits! {
    #[repr(align(16))]
    pub union __c_anonymous_CONTEXT_FP {
        pub FltSave: ::XMM_SAVE_AREA32,
        pub Xmm: __c_anonymous_CONTEXT_XMM,
    }
}

cfg_if! {
    if #[cfg(feature = "extra_traits")] {
        impl PartialEq for __c_anonymous_CONTEXT_FP {
            fn eq(&self, other: &__c_anonymous_CONTEXT_FP) -> bool {
                unsafe {
                    self.FltSave == other.FltSave ||
                        self.Xmm == other.Xmm
                }
            }
        }
        impl Eq for __c_anonymous_CONTEXT_FP {}
        impl ::fmt::Debug for __c_anonymous_CONTEXT_FP {
            fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
                unsafe {
                    f.debug_struct("__c_anonymous_CONTEXT_FP")
                        .field("FltSave", &self.FltSave)
                        .finish()
                }
            }
        }
        impl ::hash::Hash for __c_anonymous_CONTEXT_FP {
            fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
                unsafe {
                    self.FltSave.hash(state);
                    self.Xmm.hash(state);
                }
            }
        }
    }
}

s! {
    #[repr(align(16))]
    pub struct M128A {
        pub Low: ::c_ulonglong,
        pub High: ::c_longlong,
    }

    #[repr(align(16))]
    pub struct XSAVE_FORMAT {
        pub ControlWord: ::c_ushort,
        pub StatusWord: ::c_ushort,
        pub TagWord: ::c_uchar,
        _Reserved1: ::c_uchar,
        pub ErrorOpcode: ::c_ushort,
        pub ErrorOffset: ::c_ulong,
        pub ErrorSelector: ::c_ushort,
        _Reserved2: ::c_ushort,
        pub DataOffset: ::c_ulong,
        pub DataSelector: ::c_ushort,
        _Reserved3: ::c_ushort,
        pub MxCsr: ::c_ulong,
        pub MxCsr_Mask: ::c_ulong,
        pub FloatRegisters: [M128A; 8],
        pub XmmRegisters: [M128A; 16],
        _Reserved4: [[::c_uchar; 16]; 6],
    }

    #[repr(align(16))]
    pub struct __c_anonymous_CONTEXT_XMM {
        pub Header: [M128A; 2],
        pub Legacy: [M128A; 8],
        pub Xmm0: M128A,
        pub Xmm1: M128A,
        pub Xmm2: M128A,
        pub Xmm3: M128A,
        pub Xmm4: M128A,
        pub Xmm5: M128A,
        pub Xmm6: M128A,
        pub Xmm7: M128A,
        pub Xmm8: M128A,
        pub Xmm9: M128A,
        pub Xmm10: M128A,
        pub Xmm11: M128A,
        pub Xmm12: M128A,
        pub Xmm13: M128A,
        pub Xmm14: M128A,
        pub Xmm15: M128A,
    }

    #[repr(align(16))]
    pub struct CONTEXT {
        pub P1Home: u64,
        pub P2Home: u64,
        pub P3Home: u64,
        pub P4Home: u64,
        pub P5Home: u64,
        pub P6Home: u64,
        pub ContextFlags: ::c_ulong,
        pub MxCsr: ::c_ulong,
        pub SegCs: ::c_ushort,
        pub SegDs: ::c_ushort,
        pub SegEs: ::c_ushort,
        pub SegFs: ::c_ushort,
        pub SegGs: ::c_ushort,
        pub SegSs: ::c_ushort,
        pub EFlags: ::c_ulong,
        pub Dr0: u64,
        pub Dr1: u64,
        pub Dr2: u64,
        pub Dr3: u64,
        pub Dr6: u64,
        pub Dr7: u64,
        pub Rax: u64,
        pub Rcx: u64,
        pub Rdx: u64,
        pub Rbx: u64,
        pub Rsp: u64,
        pub Rbp: u64,
        pub Rsi: u64,
        pub Rdi: u64,
        pub R8: u64,
        pub R9: u64,
        pub R10: u64,
        pub R11: u64,
        pub R12: u64,
        pub R13: u64,
        pub R14: u64,
        pub R15: u64,
        pub Rip: u64,
        pub Fp: __c_anonymous_CONTEXT_FP,
        pub VectorRegister: [M128A; 26],
        pub VectorControl: u64,
        pub DebugControl: u64,
        pub LastBranchToRip: u64,
        pub LastBranchFromRip: u64,
        pub LastExceptionToRip: u64,
        pub LastExceptionFromRip: u64,
    }
}
<commit_msg>Auto merge of #2457 - devnexen:win32_deprecate_context, r=JohnTitor<commit_after>#[allow(deprecated)]
pub type XMM_SAVE_AREA32 = XSAVE_FORMAT;

s_no_extra_traits! {
    #[repr(align(16))]
    pub union __c_anonymous_CONTEXT_FP {
        pub FltSave: ::XMM_SAVE_AREA32,
        pub Xmm: __c_anonymous_CONTEXT_XMM,
    }
}

cfg_if! {
    if #[cfg(feature = "extra_traits")] {
        impl PartialEq for __c_anonymous_CONTEXT_FP {
            fn eq(&self, other: &__c_anonymous_CONTEXT_FP) -> bool {
                unsafe {
                    self.FltSave == other.FltSave ||
                        self.Xmm == other.Xmm
                }
            }
        }
        impl Eq for __c_anonymous_CONTEXT_FP {}
        impl ::fmt::Debug for __c_anonymous_CONTEXT_FP {
            fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
                unsafe {
                    f.debug_struct("__c_anonymous_CONTEXT_FP")
                        .field("FltSave", &self.FltSave)
                        .finish()
                }
            }
        }
        impl ::hash::Hash for __c_anonymous_CONTEXT_FP {
            fn hash<H: ::hash::Hasher>(&self, state: &mut H) {
                unsafe {
                    self.FltSave.hash(state);
                    self.Xmm.hash(state);
                }
            }
        }
    }
}

s! {
    #[doc(hidden)]
    #[deprecated(since = "0.2.104", note = "use the `winapi` crate instead; we're going to
remove it in a future release")]
    #[repr(align(16))]
    pub struct M128A {
        pub Low: ::c_ulonglong,
        pub High: ::c_longlong,
    }

    #[doc(hidden)]
    #[deprecated(since = "0.2.104", note = "use the `winapi` crate instead; we're going to
remove it in a future release")]
    #[repr(align(16))]
    pub struct XSAVE_FORMAT {
        pub ControlWord: ::c_ushort,
        pub StatusWord: ::c_ushort,
        pub TagWord: ::c_uchar,
        _Reserved1: ::c_uchar,
        pub ErrorOpcode: ::c_ushort,
        pub ErrorOffset: ::c_ulong,
        pub ErrorSelector: ::c_ushort,
        _Reserved2: ::c_ushort,
        pub DataOffset: ::c_ulong,
        pub DataSelector: ::c_ushort,
        _Reserved3: ::c_ushort,
        pub MxCsr: ::c_ulong,
        pub MxCsr_Mask: ::c_ulong,
        pub FloatRegisters: [M128A; 8],
        pub XmmRegisters: [M128A; 16],
        _Reserved4: [[::c_uchar; 16]; 6],
    }

    #[repr(align(16))]
    pub struct __c_anonymous_CONTEXT_XMM {
        pub Header: [M128A; 2],
        pub Legacy: [M128A; 8],
        pub Xmm0: M128A,
        pub Xmm1: M128A,
        pub Xmm2: M128A,
        pub Xmm3: M128A,
        pub Xmm4: M128A,
        pub Xmm5: M128A,
        pub Xmm6: M128A,
        pub Xmm7: M128A,
        pub Xmm8: M128A,
        pub Xmm9: M128A,
        pub Xmm10: M128A,
        pub Xmm11: M128A,
        pub Xmm12: M128A,
        pub Xmm13: M128A,
        pub Xmm14: M128A,
        pub Xmm15: M128A,
    }

    #[doc(hidden)]
    #[deprecated(since = "0.2.104", note = "use the `winapi` crate instead; we're going to
remove it in a future release")]
    #[repr(align(16))]
    pub struct CONTEXT {
        pub P1Home: u64,
        pub P2Home: u64,
        pub P3Home: u64,
        pub P4Home: u64,
        pub P5Home: u64,
        pub P6Home: u64,
        pub ContextFlags: ::c_ulong,
        pub MxCsr: ::c_ulong,
        pub SegCs: ::c_ushort,
        pub SegDs: ::c_ushort,
        pub SegEs: ::c_ushort,
        pub SegFs: ::c_ushort,
        pub SegGs: ::c_ushort,
        pub SegSs: ::c_ushort,
        pub EFlags: ::c_ulong,
        pub Dr0: u64,
        pub Dr1: u64,
        pub Dr2: u64,
        pub Dr3: u64,
        pub Dr6: u64,
        pub Dr7: u64,
        pub Rax: u64,
        pub Rcx: u64,
        pub Rdx: u64,
        pub Rbx: u64,
        pub Rsp: u64,
        pub Rbp: u64,
        pub Rsi: u64,
        pub Rdi: u64,
        pub R8: u64,
        pub R9: u64,
        pub R10: u64,
        pub R11: u64,
        pub R12: u64,
        pub R13: u64,
        pub R14: u64,
        pub R15: u64,
        pub Rip: u64,
        pub Fp: __c_anonymous_CONTEXT_FP,
        pub VectorRegister: [M128A; 26],
        pub VectorControl: u64,
        pub DebugControl: u64,
        pub LastBranchToRip: u64,
        pub LastBranchFromRip: u64,
        pub LastExceptionToRip: u64,
        pub LastExceptionFromRip: u64,
    }
}
<|endoftext|>


<commit_before>//! Common types used across the crate.

pub use hyper::Method as RequestMethod;
pub use hyper::StatusCode;
pub use url::Url;

use bytes::Bytes;
use std::fmt::{self, Display, Formatter};
use std::ops::Deref;
use std::str::{self, Utf8Error};

string_enums! {
    /// Represents the `filter_level` parameter in API requests.
    #[derive(Clone, Debug)]
    pub enum FilterLevel {
        :None("none"),
        :Low("low"),
        :Medium("medium");
        :Custom(_),
    }

    /// A value for `with` parameter for User and Site Streams.
    #[derive(Clone, Debug)]
    pub enum With {
        /// Instruct the stream to send messages only from the user associated with that stream.
        /// The default for Site Streams.
        :User("user"),
        /// Instruct the stream to send messages from accounts the user follows as well, equivalent
        /// to the user’s home timeline. The default for User Streams.
        :Following("following");
        /// Custom value.
        :Custom(_),
    }
}

/// A string type returned by `TwitterStream`.
// It is basically a wrapper type over `Bytes` that gurantees the contained bytes are valid UTF8 string.
// Inspired by hyper::http::str::ByteStr.
#[derive(Clone, PartialEq, PartialOrd, Ord, Eq, Debug, Hash)]
pub struct JsonStr {
    inner: Bytes,
}

impl JsonStr {
    #[doc(hidden)]
    pub fn from_utf8(v: Bytes) -> Result<Self, Utf8Error> {
        str::from_utf8(&v)?;
        unsafe { Ok(JsonStr::from_utf8_unchecked(v)) }
    }

    pub fn from_static(s: &'static str) -> Self {
        JsonStr {
            inner: Bytes::from_static(s.as_ref()),
        }
    }

    #[doc(hidden)]
    pub unsafe fn from_utf8_unchecked(v: Bytes) -> Self {
        JsonStr {
            inner: v,
        }
    }

    pub fn as_str(&self) -> &str {
        unsafe { str::from_utf8_unchecked(&self.inner) }
    }
}

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

impl Deref for JsonStr {
    type Target = str;

    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl Display for JsonStr {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl From<String> for JsonStr {
    fn from(s: String) -> Self {
        JsonStr {
            inner: s.into_bytes().into(),
        }
    }
}

impl<'a> From<&'a str> for JsonStr {
    fn from(s: &'a str) -> Self {
        JsonStr {
            inner: s.into(),
        }
    }
}

impl From<JsonStr> for Bytes {
    fn from(s: JsonStr) -> Self {
        s.inner
    }
}

impl ::std::default::Default for FilterLevel {
    fn default() -> Self {
        FilterLevel::None
    }
}
<commit_msg>Add `#[derive(Default)]` to `JsonStr`<commit_after>//! Common types used across the crate.

pub use hyper::Method as RequestMethod;
pub use hyper::StatusCode;
pub use url::Url;

use bytes::Bytes;
use std::fmt::{self, Display, Formatter};
use std::ops::Deref;
use std::str::{self, Utf8Error};

string_enums! {
    /// Represents the `filter_level` parameter in API requests.
    #[derive(Clone, Debug)]
    pub enum FilterLevel {
        :None("none"),
        :Low("low"),
        :Medium("medium");
        :Custom(_),
    }

    /// A value for `with` parameter for User and Site Streams.
    #[derive(Clone, Debug)]
    pub enum With {
        /// Instruct the stream to send messages only from the user associated with that stream.
        /// The default for Site Streams.
        :User("user"),
        /// Instruct the stream to send messages from accounts the user follows as well, equivalent
        /// to the user’s home timeline. The default for User Streams.
        :Following("following");
        /// Custom value.
        :Custom(_),
    }
}

/// A string type returned by `TwitterStream`.
// It is basically a wrapper type over `Bytes` that gurantees the contained bytes are valid UTF8 string.
// Inspired by hyper::http::str::ByteStr.
#[derive(Clone, Default, PartialEq, PartialOrd, Ord, Eq, Debug, Hash)]
pub struct JsonStr {
    inner: Bytes,
}

impl JsonStr {
    #[doc(hidden)]
    pub fn from_utf8(v: Bytes) -> Result<Self, Utf8Error> {
        str::from_utf8(&v)?;
        unsafe { Ok(JsonStr::from_utf8_unchecked(v)) }
    }

    pub fn from_static(s: &'static str) -> Self {
        JsonStr {
            inner: Bytes::from_static(s.as_ref()),
        }
    }

    #[doc(hidden)]
    pub unsafe fn from_utf8_unchecked(v: Bytes) -> Self {
        JsonStr {
            inner: v,
        }
    }

    pub fn as_str(&self) -> &str {
        unsafe { str::from_utf8_unchecked(&self.inner) }
    }
}

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

impl Deref for JsonStr {
    type Target = str;

    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl Display for JsonStr {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl From<String> for JsonStr {
    fn from(s: String) -> Self {
        JsonStr {
            inner: s.into_bytes().into(),
        }
    }
}

impl<'a> From<&'a str> for JsonStr {
    fn from(s: &'a str) -> Self {
        JsonStr {
            inner: s.into(),
        }
    }
}

impl From<JsonStr> for Bytes {
    fn from(s: JsonStr) -> Self {
        s.inner
    }
}

impl ::std::default::Default for FilterLevel {
    fn default() -> Self {
        FilterLevel::None
    }
}
<|endoftext|>


<commit_before>use std::fmt;
use std::net::{Ipv4Addr, SocketAddrV4};

use super::ipv4_header::Protocol;
use super::ipv4_packet::IPv4Packet;
use super::net;
use super::selector::Selector;

const LOCALHOST_FORWARD: u32 = 0x0A000202;

pub trait Connection {
    fn id(&self) -> &ConnectionId;
    fn send_to_network(&mut self, selector: &mut Selector, ipv4_packet: &IPv4Packet);
    fn disconnect(&mut self, selector: &mut Selector);
    fn is_expired(&self) -> bool;
}

pub fn rewritten_destination(ipv4: u32, port: u16) -> SocketAddrV4  {
    let addr = if ipv4 == LOCALHOST_FORWARD {
        Ipv4Addr::new(127, 0, 0, 1)
    } else {
        net::to_addr(ipv4)
    };
    SocketAddrV4::new(addr, port)
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConnectionId {
    protocol: Protocol,
    source_ip: u32,
    source_port: u16,
    destination_ip: u32,
    destination_port: u16,
}

impl ConnectionId {
    pub fn new(protocol: Protocol, source_ip: u32, source_port: u16, destination_ip: u32, destination_port: u16) -> Self {
        Self {
            protocol: protocol,
            source_ip: source_ip,
            source_port: source_port,
            destination_ip: destination_ip,
            destination_port: destination_port,
        }
    }

    pub fn from_packet(reference_packet: &IPv4Packet) -> Self {
        let ipv4_header = reference_packet.ipv4_header();
        let transport_header = reference_packet.transport_header().as_ref().expect("Packet without transport header");
        Self {
            protocol: ipv4_header.protocol(),
            source_ip: ipv4_header.source(),
            source_port: transport_header.source_port(),
            destination_ip: ipv4_header.destination(),
            destination_port: transport_header.destination_port(),
        }
    }

    pub fn protocol(&self) -> Protocol {
        self.protocol
    }

    pub fn source_ip(&self) -> u32 {
        self.source_ip
    }

    pub fn source_port(&self) -> u16 {
        self.source_port
    }

    pub fn destination_ip(&self) -> u32 {
        self.destination_ip
    }

    pub fn destination_port(&self) -> u16 {
        self.destination_port
    }

    pub fn source(&self) -> SocketAddrV4 {
        net::to_socket_addr(self.source_ip, self.source_port)
    }

    pub fn destination(&self) -> SocketAddrV4 {
        net::to_socket_addr(self.destination_ip, self.destination_port)
    }
}

impl fmt::Display for ConnectionId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} -> {}", self.source(), self.destination())
    }
}
<commit_msg>Remove unused ConnectionId::new()<commit_after>use std::fmt;
use std::net::{Ipv4Addr, SocketAddrV4};

use super::ipv4_header::Protocol;
use super::ipv4_packet::IPv4Packet;
use super::net;
use super::selector::Selector;

const LOCALHOST_FORWARD: u32 = 0x0A000202;

pub trait Connection {
    fn id(&self) -> &ConnectionId;
    fn send_to_network(&mut self, selector: &mut Selector, ipv4_packet: &IPv4Packet);
    fn disconnect(&mut self, selector: &mut Selector);
    fn is_expired(&self) -> bool;
}

pub fn rewritten_destination(ipv4: u32, port: u16) -> SocketAddrV4  {
    let addr = if ipv4 == LOCALHOST_FORWARD {
        Ipv4Addr::new(127, 0, 0, 1)
    } else {
        net::to_addr(ipv4)
    };
    SocketAddrV4::new(addr, port)
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConnectionId {
    protocol: Protocol,
    source_ip: u32,
    source_port: u16,
    destination_ip: u32,
    destination_port: u16,
}

impl ConnectionId {
    pub fn from_packet(reference_packet: &IPv4Packet) -> Self {
        let ipv4_header = reference_packet.ipv4_header();
        let transport_header = reference_packet.transport_header().as_ref().expect("Packet without transport header");
        Self {
            protocol: ipv4_header.protocol(),
            source_ip: ipv4_header.source(),
            source_port: transport_header.source_port(),
            destination_ip: ipv4_header.destination(),
            destination_port: transport_header.destination_port(),
        }
    }

    pub fn protocol(&self) -> Protocol {
        self.protocol
    }

    pub fn source_ip(&self) -> u32 {
        self.source_ip
    }

    pub fn source_port(&self) -> u16 {
        self.source_port
    }

    pub fn destination_ip(&self) -> u32 {
        self.destination_ip
    }

    pub fn destination_port(&self) -> u16 {
        self.destination_port
    }

    pub fn source(&self) -> SocketAddrV4 {
        net::to_socket_addr(self.source_ip, self.source_port)
    }

    pub fn destination(&self) -> SocketAddrV4 {
        net::to_socket_addr(self.destination_ip, self.destination_port)
    }
}

impl fmt::Display for ConnectionId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} -> {}", self.source(), self.destination())
    }
}
<|endoftext|>


<commit_before>use super::ipv4header::IPv4Header;

pub struct IPv4Packet<'a> {
    raw: &'a mut [u8],
    header: IPv4Header,
}

impl<'a> IPv4Packet<'a> {
    fn new(raw: &'a mut [u8]) -> IPv4Packet<'a> {
        let header = IPv4Header::parse(raw);
        IPv4Packet {
            raw: raw,
            header: header,
        }
    }
}

<commit_msg>Rename header to ipv4_header<commit_after>use super::ipv4header::IPv4Header;

pub struct IPv4Packet<'a> {
    raw: &'a mut [u8],
    ipv4_header: IPv4Header,
}

impl<'a> IPv4Packet<'a> {
    fn new(raw: &'a mut [u8]) -> IPv4Packet<'a> {
        let ipv4_header = IPv4Header::parse(raw);
        IPv4Packet {
            raw: raw,
            ipv4_header: ipv4_header,
        }
    }
}

<|endoftext|>


<commit_before>use std::path::{Path, PathBuf};
use std::{env, fs};
use std::vec::Vec;

fn main() {
    if let Some(git_sha) = read_git_sha() {
        println!("cargo:rustc-env={}={}", "BUILD_SHA", git_sha);
    }

    if wasm_files_present() {
        println!("cargo:rustc-cfg={}", "TREE_SITTER_EMBED_WASM_BINDING");
    }

    println!(
        "cargo:rustc-env=BUILD_TARGET={}",
        std::env::var("TARGET").unwrap()
    );
}

fn wasm_files_present() -> bool {
    let paths = [
        "../lib/binding_web/tree-sitter.js",
        "../lib/binding_web/tree-sitter.wasm",
    ];

    return paths.iter().all(|p| Path::new(p).exists())
}

fn read_git_sha() -> Option<String> {
    let mut repo_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());

    let mut git_path;
    loop {
        git_path = repo_path.join(".git");
        if git_path.exists() {
            break;
        } else if !repo_path.pop() {
            return None;
        }
    }

    let git_dir_path;
    if git_path.is_dir() {
        git_dir_path = git_path;
    } else if let Ok(git_path_content) = fs::read_to_string(&git_path) {
        git_dir_path = repo_path.join(git_path_content.get("gitdir: ".len()..).unwrap().trim_end());
    } else {
        return None;
    }
    let git_head_path = git_dir_path.join("HEAD");
    if let Some(path) = git_head_path.to_str() {
        println!("cargo:rerun-if-changed={}", path);
    }
    if let Ok(mut head_content) = fs::read_to_string(&git_head_path) {
        if head_content.ends_with("\n") {
            head_content.pop();
        }

        // If we're on a branch, read the SHA from the ref file.
        if head_content.starts_with("ref: ") {
            head_content.replace_range(0.."ref: ".len(), "");
            let ref_filename = git_dir_path.join(&head_content);
            if let Some(path) = ref_filename.to_str() {
                println!("cargo:rerun-if-changed={}", path);
            }
            return fs::read_to_string(&ref_filename).ok();
        }
        // If we're on a detached commit, then the `HEAD` file itself contains the sha.
        else if head_content.len() == 40 {
            return Some(head_content);
        }
    }

    None
}
<commit_msg>fix warning and use implicit return here<commit_after>use std::path::{Path, PathBuf};
use std::{env, fs};

fn main() {
    if let Some(git_sha) = read_git_sha() {
        println!("cargo:rustc-env={}={}", "BUILD_SHA", git_sha);
    }

    if wasm_files_present() {
        println!("cargo:rustc-cfg={}", "TREE_SITTER_EMBED_WASM_BINDING");
    }

    println!(
        "cargo:rustc-env=BUILD_TARGET={}",
        std::env::var("TARGET").unwrap()
    );
}

fn wasm_files_present() -> bool {
    let paths = [
        "../lib/binding_web/tree-sitter.js",
        "../lib/binding_web/tree-sitter.wasm",
    ];

    paths.iter().all(|p| Path::new(p).exists())
}

fn read_git_sha() -> Option<String> {
    let mut repo_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());

    let mut git_path;
    loop {
        git_path = repo_path.join(".git");
        if git_path.exists() {
            break;
        } else if !repo_path.pop() {
            return None;
        }
    }

    let git_dir_path;
    if git_path.is_dir() {
        git_dir_path = git_path;
    } else if let Ok(git_path_content) = fs::read_to_string(&git_path) {
        git_dir_path = repo_path.join(git_path_content.get("gitdir: ".len()..).unwrap().trim_end());
    } else {
        return None;
    }
    let git_head_path = git_dir_path.join("HEAD");
    if let Some(path) = git_head_path.to_str() {
        println!("cargo:rerun-if-changed={}", path);
    }
    if let Ok(mut head_content) = fs::read_to_string(&git_head_path) {
        if head_content.ends_with("\n") {
            head_content.pop();
        }

        // If we're on a branch, read the SHA from the ref file.
        if head_content.starts_with("ref: ") {
            head_content.replace_range(0.."ref: ".len(), "");
            let ref_filename = git_dir_path.join(&head_content);
            if let Some(path) = ref_filename.to_str() {
                println!("cargo:rerun-if-changed={}", path);
            }
            return fs::read_to_string(&ref_filename).ok();
        }
        // If we're on a detached commit, then the `HEAD` file itself contains the sha.
        else if head_content.len() == 40 {
            return Some(head_content);
        }
    }

    None
}
<|endoftext|>


<commit_before>extern crate num;

use std::f32::consts;

use num::complex::{Complex, Complex32};

fn main() {
    let degree = 3;

    for root in &roots_of_unity(degree) {
        println!("{}", root);
    }
}

fn roots_of_unity(degree: usize) -> Vec<Complex32> {
    (0..degree)
        .map(|el| {
            Complex::<f32>::from_polar(&1f32, &(2f32 * consts::PI * (el as f32) / (degree as f32)))
        })
        .collect::<Vec<Complex32>>()
}

#[test]
fn test_result() {
    let expected = vec![
        Complex::new(1f32, 0.),
        Complex::new(-0.5, 0.866025),
        Complex::new(-0.5, -0.866025),
    ];

    for (root, &exp) in roots_of_unity(3).iter().zip(expected.iter()) {
        assert!((*root - exp).norm() < 1e-6);
    }
}
<commit_msg>roots-of-unity: do not collect into Vec<commit_after>extern crate num;

use std::f32::consts;

use num::complex::{Complex, Complex32};

fn main() {
    let degree = 3;

    for root in roots_of_unity(degree) {
        println!("{}", root);
    }
}

fn roots_of_unity(degree: usize) -> impl Iterator<Item=Complex32> {
    (0..degree)
        .map(move |el| {
            Complex::<f32>::from_polar(&1f32, &(2f32 * consts::PI * (el as f32) / (degree as f32)))
        })
}

#[test]
fn test_result() {
    let expected = vec![
        Complex::new(1f32, 0.),
        Complex::new(-0.5, 0.866025),
        Complex::new(-0.5, -0.866025),
    ];

    for (root, exp) in roots_of_unity(3).zip(expected.iter()) {
        assert!((root - exp).norm() < 1e-6);
    }
}
<|endoftext|>


<commit_before>pub mod reader;
pub mod writer;

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub struct PresentationContextProposed {
    pub id: u8,
    pub abstract_syntax: String,
    pub transfer_syntaxes: Vec<String>,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub struct PresentationContextResult {
    pub id: u8,
    pub reason: PresentationContextResultReason,
    pub transfer_syntax: String,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum PresentationContextResultReason {
    Acceptance = 0,
    UserRejection = 1,
    NoReason = 2,
    AbstractSyntaxNotSupported = 3,
    TransferSyntaxesNotSupported = 4,
}

impl PresentationContextResultReason {
    fn from(reason: u8) -> Option<PresentationContextResultReason> {
        let result = match reason {
            0 => PresentationContextResultReason::Acceptance,
            1 => PresentationContextResultReason::UserRejection,
            2 => PresentationContextResultReason::NoReason,
            3 => PresentationContextResultReason::AbstractSyntaxNotSupported,
            4 => PresentationContextResultReason::TransferSyntaxesNotSupported,
            _ => {
                return None;
            }
        };

        Some(result)
    }
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJResult {
    Permanent,
    Transient,
}

impl AssociationRJResult {
    fn from(value: u8) -> Option<AssociationRJResult> {
        match value {
            0 => Some(AssociationRJResult::Permanent),
            1 => Some(AssociationRJResult::Transient),
            _ => None,
        }
    }
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJSource {
    ServiceUser(AssociationRJServiceUserReason),
    ServiceProviderASCE(AssociationRJServiceProviderASCEReason),
    ServiceProviderPresentation(AssociationRJServiceProviderPresentationReason),
}

impl AssociationRJSource {
    fn from(source: u8, reason: u8) -> Option<AssociationRJSource> {
        let result = match (source, reason) {
            (1, 1) => {
                AssociationRJSource::ServiceUser(AssociationRJServiceUserReason::NoReasonGiven)
            }
            (1, 2) => AssociationRJSource::ServiceUser(
                AssociationRJServiceUserReason::ApplicationContextNameNotSupported,
            ),
            (1, 3) => AssociationRJSource::ServiceUser(
                AssociationRJServiceUserReason::CallingAETitleNotRecognized,
            ),
            (1, x) if x == 4 || x == 5 || x == 6 => {
                AssociationRJSource::ServiceUser(AssociationRJServiceUserReason::Reserved(x))
            }
            (1, 7) => AssociationRJSource::ServiceUser(
                AssociationRJServiceUserReason::CalledAETitleNotRecognized,
            ),
            //(1, 8) | (1, 9) | (1, 10) => {
            (1, x) if x == 8 || x == 9 || x == 10 => {
                AssociationRJSource::ServiceUser(AssociationRJServiceUserReason::Reserved(x))
            }
            (1, _) => {
                return None;
            }
            (2, 1) => AssociationRJSource::ServiceProviderASCE(
                AssociationRJServiceProviderASCEReason::NoReasonGiven,
            ),
            (2, 2) => AssociationRJSource::ServiceProviderASCE(
                AssociationRJServiceProviderASCEReason::ProtocolVersionNotSupported,
            ),
            (2, _) => {
                return None;
            }
            (3, 0) => AssociationRJSource::ServiceProviderPresentation(
                AssociationRJServiceProviderPresentationReason::Reserved(0),
            ),
            (3, 1) => AssociationRJSource::ServiceProviderPresentation(
                AssociationRJServiceProviderPresentationReason::TemporaryCongestion,
            ),
            (3, 2) => AssociationRJSource::ServiceProviderPresentation(
                AssociationRJServiceProviderPresentationReason::LocalLimitExceeded,
            ),
            (3, x) if x == 3 || x == 4 || x == 5 || x == 6 || x == 7 => {
                AssociationRJSource::ServiceProviderPresentation(
                    AssociationRJServiceProviderPresentationReason::Reserved(x),
                )
            }
            _ => {
                return None;
            }
        };
        Some(result)
    }
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJServiceUserReason {
    NoReasonGiven,
    ApplicationContextNameNotSupported,
    CallingAETitleNotRecognized,
    CalledAETitleNotRecognized,
    Reserved(u8),
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJServiceProviderASCEReason {
    NoReasonGiven,
    ProtocolVersionNotSupported,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJServiceProviderPresentationReason {
    TemporaryCongestion,
    LocalLimitExceeded,
    Reserved(u8),
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub struct PDataValue {
    pub presentation_context_id: u8,
    pub value_type: PDataValueType,
    pub is_last: bool,
    pub data: Vec<u8>,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum PDataValueType {
    Command,
    Data,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AbortRQSource {
    ServiceUser,
    ServiceProvider(AbortRQServiceProviderReason),
    Reserved,
}

impl AbortRQSource {
    fn from(source: u8, reason: u8) -> Option<AbortRQSource> {
        let result = match (source, reason) {
            (0, _) => AbortRQSource::ServiceUser,
            (1, _) => AbortRQSource::Reserved,
            (2, 0) => AbortRQSource::ServiceProvider(
                AbortRQServiceProviderReason::ReasonNotSpecifiedUnrecognizedPdu,
            ),
            (2, 2) => AbortRQSource::ServiceProvider(AbortRQServiceProviderReason::UnexpectedPdu),
            (2, 3) => AbortRQSource::ServiceProvider(AbortRQServiceProviderReason::Reserved),
            (2, 4) => AbortRQSource::ServiceProvider(
                AbortRQServiceProviderReason::UnrecognizedPduParameter,
            ),
            (2, 5) => {
                AbortRQSource::ServiceProvider(AbortRQServiceProviderReason::UnexpectedPduParameter)
            }
            (2, 6) => {
                AbortRQSource::ServiceProvider(AbortRQServiceProviderReason::InvalidPduParameter)
            }
            (_, _) => {
                return None;
            }
        };

        Some(result)
    }
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AbortRQServiceProviderReason {
    ReasonNotSpecifiedUnrecognizedPdu,
    UnexpectedPdu,
    Reserved,
    UnrecognizedPduParameter,
    UnexpectedPduParameter,
    InvalidPduParameter,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum PduVariableItem {
    Unknown(u8),
    ApplicationContext(String),
    PresentationContextProposed(PresentationContextProposed),
    PresentationContextResult(PresentationContextResult),
    UserVariables(Vec<UserVariableItem>),
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum UserVariableItem {
    Unknown(u8, Vec<u8>),
    MaxLength(u32),
    ImplementationClassUID(String),
    ImplementationVersionName(String),
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum Pdu {
    Unknown {
        pdu_type: u8,
        data: Vec<u8>,
    },
    AssociationRQ {
        protocol_version: u16,
        calling_ae_title: String,
        called_ae_title: String,
        application_context_name: String,
        presentation_contexts: Vec<PresentationContextProposed>,
        user_variables: Vec<UserVariableItem>,
    },
    AssociationAC {
        protocol_version: u16,
        application_context_name: String,
        presentation_contexts: Vec<PresentationContextResult>,
        user_variables: Vec<UserVariableItem>,
    },
    AssociationRJ {
        result: AssociationRJResult,
        source: AssociationRJSource,
    },
    PData {
        data: Vec<PDataValue>,
    },
    ReleaseRQ,
    ReleaseRP,
    AbortRQ {
        source: AbortRQSource,
    },
}
<commit_msg>Fix AssociationRJResult::from<commit_after>pub mod reader;
pub mod writer;

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub struct PresentationContextProposed {
    pub id: u8,
    pub abstract_syntax: String,
    pub transfer_syntaxes: Vec<String>,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub struct PresentationContextResult {
    pub id: u8,
    pub reason: PresentationContextResultReason,
    pub transfer_syntax: String,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum PresentationContextResultReason {
    Acceptance = 0,
    UserRejection = 1,
    NoReason = 2,
    AbstractSyntaxNotSupported = 3,
    TransferSyntaxesNotSupported = 4,
}

impl PresentationContextResultReason {
    fn from(reason: u8) -> Option<PresentationContextResultReason> {
        let result = match reason {
            0 => PresentationContextResultReason::Acceptance,
            1 => PresentationContextResultReason::UserRejection,
            2 => PresentationContextResultReason::NoReason,
            3 => PresentationContextResultReason::AbstractSyntaxNotSupported,
            4 => PresentationContextResultReason::TransferSyntaxesNotSupported,
            _ => {
                return None;
            }
        };

        Some(result)
    }
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJResult {
    Permanent = 1,
    Transient = 2,
}

impl AssociationRJResult {
    fn from(value: u8) -> Option<AssociationRJResult> {
        match value {
            1 => Some(AssociationRJResult::Permanent),
            2 => Some(AssociationRJResult::Transient),
            _ => None,
        }
    }
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJSource {
    ServiceUser(AssociationRJServiceUserReason),
    ServiceProviderASCE(AssociationRJServiceProviderASCEReason),
    ServiceProviderPresentation(AssociationRJServiceProviderPresentationReason),
}

impl AssociationRJSource {
    fn from(source: u8, reason: u8) -> Option<AssociationRJSource> {
        let result = match (source, reason) {
            (1, 1) => {
                AssociationRJSource::ServiceUser(AssociationRJServiceUserReason::NoReasonGiven)
            }
            (1, 2) => AssociationRJSource::ServiceUser(
                AssociationRJServiceUserReason::ApplicationContextNameNotSupported,
            ),
            (1, 3) => AssociationRJSource::ServiceUser(
                AssociationRJServiceUserReason::CallingAETitleNotRecognized,
            ),
            (1, x) if x == 4 || x == 5 || x == 6 => {
                AssociationRJSource::ServiceUser(AssociationRJServiceUserReason::Reserved(x))
            }
            (1, 7) => AssociationRJSource::ServiceUser(
                AssociationRJServiceUserReason::CalledAETitleNotRecognized,
            ),
            //(1, 8) | (1, 9) | (1, 10) => {
            (1, x) if x == 8 || x == 9 || x == 10 => {
                AssociationRJSource::ServiceUser(AssociationRJServiceUserReason::Reserved(x))
            }
            (1, _) => {
                return None;
            }
            (2, 1) => AssociationRJSource::ServiceProviderASCE(
                AssociationRJServiceProviderASCEReason::NoReasonGiven,
            ),
            (2, 2) => AssociationRJSource::ServiceProviderASCE(
                AssociationRJServiceProviderASCEReason::ProtocolVersionNotSupported,
            ),
            (2, _) => {
                return None;
            }
            (3, 0) => AssociationRJSource::ServiceProviderPresentation(
                AssociationRJServiceProviderPresentationReason::Reserved(0),
            ),
            (3, 1) => AssociationRJSource::ServiceProviderPresentation(
                AssociationRJServiceProviderPresentationReason::TemporaryCongestion,
            ),
            (3, 2) => AssociationRJSource::ServiceProviderPresentation(
                AssociationRJServiceProviderPresentationReason::LocalLimitExceeded,
            ),
            (3, x) if x == 3 || x == 4 || x == 5 || x == 6 || x == 7 => {
                AssociationRJSource::ServiceProviderPresentation(
                    AssociationRJServiceProviderPresentationReason::Reserved(x),
                )
            }
            _ => {
                return None;
            }
        };
        Some(result)
    }
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJServiceUserReason {
    NoReasonGiven,
    ApplicationContextNameNotSupported,
    CallingAETitleNotRecognized,
    CalledAETitleNotRecognized,
    Reserved(u8),
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJServiceProviderASCEReason {
    NoReasonGiven,
    ProtocolVersionNotSupported,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AssociationRJServiceProviderPresentationReason {
    TemporaryCongestion,
    LocalLimitExceeded,
    Reserved(u8),
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub struct PDataValue {
    pub presentation_context_id: u8,
    pub value_type: PDataValueType,
    pub is_last: bool,
    pub data: Vec<u8>,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum PDataValueType {
    Command,
    Data,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AbortRQSource {
    ServiceUser,
    ServiceProvider(AbortRQServiceProviderReason),
    Reserved,
}

impl AbortRQSource {
    fn from(source: u8, reason: u8) -> Option<AbortRQSource> {
        let result = match (source, reason) {
            (0, _) => AbortRQSource::ServiceUser,
            (1, _) => AbortRQSource::Reserved,
            (2, 0) => AbortRQSource::ServiceProvider(
                AbortRQServiceProviderReason::ReasonNotSpecifiedUnrecognizedPdu,
            ),
            (2, 2) => AbortRQSource::ServiceProvider(AbortRQServiceProviderReason::UnexpectedPdu),
            (2, 3) => AbortRQSource::ServiceProvider(AbortRQServiceProviderReason::Reserved),
            (2, 4) => AbortRQSource::ServiceProvider(
                AbortRQServiceProviderReason::UnrecognizedPduParameter,
            ),
            (2, 5) => {
                AbortRQSource::ServiceProvider(AbortRQServiceProviderReason::UnexpectedPduParameter)
            }
            (2, 6) => {
                AbortRQSource::ServiceProvider(AbortRQServiceProviderReason::InvalidPduParameter)
            }
            (_, _) => {
                return None;
            }
        };

        Some(result)
    }
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum AbortRQServiceProviderReason {
    ReasonNotSpecifiedUnrecognizedPdu,
    UnexpectedPdu,
    Reserved,
    UnrecognizedPduParameter,
    UnexpectedPduParameter,
    InvalidPduParameter,
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum PduVariableItem {
    Unknown(u8),
    ApplicationContext(String),
    PresentationContextProposed(PresentationContextProposed),
    PresentationContextResult(PresentationContextResult),
    UserVariables(Vec<UserVariableItem>),
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum UserVariableItem {
    Unknown(u8, Vec<u8>),
    MaxLength(u32),
    ImplementationClassUID(String),
    ImplementationVersionName(String),
}

#[derive(Clone, Eq, PartialEq, PartialOrd, Hash, Debug)]
pub enum Pdu {
    Unknown {
        pdu_type: u8,
        data: Vec<u8>,
    },
    AssociationRQ {
        protocol_version: u16,
        calling_ae_title: String,
        called_ae_title: String,
        application_context_name: String,
        presentation_contexts: Vec<PresentationContextProposed>,
        user_variables: Vec<UserVariableItem>,
    },
    AssociationAC {
        protocol_version: u16,
        application_context_name: String,
        presentation_contexts: Vec<PresentationContextResult>,
        user_variables: Vec<UserVariableItem>,
    },
    AssociationRJ {
        result: AssociationRJResult,
        source: AssociationRJSource,
    },
    PData {
        data: Vec<PDataValue>,
    },
    ReleaseRQ,
    ReleaseRP,
    AbortRQ {
        source: AbortRQSource,
    },
}
<|endoftext|>


<commit_before>extern crate document;
extern crate xpath;

use std::io::File;

use std::collections::hashmap::HashMap;

use document::ToAny;
use document::parser::Parser;

use xpath::{XPathEvaluationContext,XPathFactory};
use xpath::expression::XPathExpression;

fn main() {
    let mut args = std::os::args();

    let filename = match args.remove(1) {
        Some(x) => x,
        None => { println!("File required"); return; },
    };

    let xpath_str = match args.remove(1) {
        Some(x) => x,
        None => { println!("XPath required"); return; },
    };

    let factory = XPathFactory::new();

    let expr = match factory.build(xpath_str.as_slice()) {
        Err(x) => { println!("Unable to compile XPath: {}", x); return; },
        Ok(None) => { println!("Unable to compile XPath"); return; },
        Ok(Some(x)) => x,
    };

    let p = Parser::new();

    let path = Path::new(filename);
    let mut file = File::open(&path);

    let data = match file.read_to_end() {
        Ok(x) => String::from_utf8(x),
        Err(x) => { println!("Can't read: {}", x); return; },
    };

    let data = data.ok().expect("Unable to convert to UTF-8");

    let d = p.parse(data.as_slice());

    let mut functions = HashMap::new();
    xpath::function::register_core_functions(& mut functions);
    let variables = HashMap::new();
    let mut context = XPathEvaluationContext::new(d.root().to_any(),
                                                  &functions,
                                                  &variables);
    context.next(d.root().to_any());

    let res = expr.evaluate(&context);

    println!("{}", res);
}
<commit_msg>Update the command line app to support XML parsing errors<commit_after>extern crate document;
extern crate xpath;

use std::cmp::min;
use std::collections::hashmap::HashMap;
use std::io::File;

use document::ToAny;
use document::parser::Parser;

use xpath::{XPathEvaluationContext,XPathFactory};
use xpath::expression::XPathExpression;

fn pretty_error(xml: &str, position: uint) -> &str {
    let s = xml.slice_from(position);
    let l = s.char_len();
    s.slice_chars(0, min(l, 15))
}

fn main() {
    let mut args = std::os::args();

    let filename = args.remove(1).expect("File required");
    let xpath_str = args.remove(1).expect("XPath required");

    let factory = XPathFactory::new();

    let expr = match factory.build(xpath_str.as_slice()) {
        Err(x) => fail!("Unable to compile XPath: {}", x),
        Ok(None) => fail!("Unable to compile XPath"),
        Ok(Some(x)) => x,
    };

    let p = Parser::new();

    let path = Path::new(filename);
    let mut file = File::open(&path);

    let data = match file.read_to_end() {
        Ok(x) => x,
        Err(x) => fail!("Can't read: {}", x),
    };

    let data = match String::from_utf8(data) {
        Ok(x) => x,
        Err(x) => fail!("Unable to convert to UTF-8: {}", x),
    };

    let d = match p.parse(data.as_slice()) {
        Ok(d) => d,
        Err(point) => fail!("Unable to parse: {}", pretty_error(data.as_slice(), point)),
    };

    let mut functions = HashMap::new();
    xpath::function::register_core_functions(& mut functions);
    let variables = HashMap::new();
    let mut context = XPathEvaluationContext::new(d.root().to_any(),
                                                  &functions,
                                                  &variables);
    context.next(d.root().to_any());

    let res = expr.evaluate(&context);

    println!("{}", res);
}
<|endoftext|>


<commit_before>use indicatif::{ProgressBar, ProgressIterator, ProgressStyle};

fn main() {
    // Default styling, attempt to use Iterator::size_hint to count input size
    for _ in (0..1000).progress() {
        // ...
    }

    // Provide explicit number of elements in iterator
    for _ in (0..1000).progress_count(1000) {
        // ...
    }

    // Provide a custom bar style
    let pb = ProgressBar::new(1000);
    pb.set_style(ProgressStyle::default_bar().template(
        "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] ({pos}/{len}, ETA {eta})",
    ));
    for _ in (0..1000).progress_with(pb) {
        // ...
    }
}
<commit_msg>Add sleep in iterator example to see bars<commit_after>use std::thread;
use std::time::Duration;

use indicatif::{ProgressBar, ProgressIterator, ProgressStyle};

fn main() {
    // Default styling, attempt to use Iterator::size_hint to count input size
    for _ in (0..1000).progress() {
        // ...
        thread::sleep(Duration::from_millis(5));
    }

    // Provide explicit number of elements in iterator
    for _ in (0..1000).progress_count(1000) {
        // ...
        thread::sleep(Duration::from_millis(5));
    }

    // Provide a custom bar style
    let pb = ProgressBar::new(1000);
    pb.set_style(ProgressStyle::default_bar().template(
        "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] ({pos}/{len}, ETA {eta})",
    ));
    for _ in (0..1000).progress_with(pb) {
        // ...
        thread::sleep(Duration::from_millis(5));
    }
}
<|endoftext|>


<commit_before>extern crate docopt;

use docopt::docopt;

static docstr: &'static str = "
Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
";

fn main() {
    let args = docopt(docstr);
    // If you invoke with:
    //
    //     no_macro ship Guardian move 100 150 --speed=15
    //
    // then you should get the following map:
    //
    //     --drifting  => Switch(false)
    //     -h, --help  => Switch(false)
    //     --moored    => Switch(false)
    //     --speed     => Plain(Some(15))
    //     --version   => Switch(false)
    //     <name>      => List([Guardian])
    //     <x>         => Plain(Some(100))
    //     <y>         => Plain(Some(150))
    //     mine        => Switch(false)
    //     move        => Switch(true)
    //     new         => Switch(false)
    //     remove      => Switch(false)
    //     set         => Switch(false)
    //     ship        => Switch(true)
    //     shoot       => Switch(false)
    println!("{}", args);
}
<commit_msg>Show a little more in the example.<commit_after>extern crate docopt;

use docopt::docopt;

static docstr: &'static str = "
Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
";

fn main() {
    let args = docopt(docstr);
    // If you invoke with:
    //
    //     no_macro ship Guardian move 100 150 --speed=15
    //
    // then you should get the following map:
    //
    //     --drifting  => Switch(false)
    //     -h, --help  => Switch(false)
    //     --moored    => Switch(false)
    //     --speed     => Plain(Some(15))
    //     --version   => Switch(false)
    //     <name>      => List([Guardian])
    //     <x>         => Plain(Some(100))
    //     <y>         => Plain(Some(150))
    //     mine        => Switch(false)
    //     move        => Switch(true)
    //     new         => Switch(false)
    //     remove      => Switch(false)
    //     set         => Switch(false)
    //     ship        => Switch(true)
    //     shoot       => Switch(false)
    println!("{}", args);

    // You can conveniently access values with `get_{bool,count,str,vec}`
    // functions. If the key doesn't exist (or if, e.g., you use `get_str` on
    // a switch), then a sensible default value is returned.
    println!("\nSome values:");
    println!("  Speed: {}", args.get_str("--speed"));
    println!("  Drifting? {}", args.get_bool("--drifting"));
    println!("  Names: {}", args.get_vec("<name>"));
}
<|endoftext|>


<commit_before>extern crate regex;

use crate::common::util::*;

extern crate stat;
pub use self::stat::*;

#[test]
fn test_scanners() {
    assert_eq!(Some((-5, 2)), "-5zxc".scan_num::<i32>());
    assert_eq!(Some((51, 2)), "51zxc".scan_num::<u32>());
    assert_eq!(Some((192, 4)), "+192zxc".scan_num::<i32>());
    assert_eq!(None, "z192zxc".scan_num::<i32>());

    assert_eq!(Some(('a', 3)), "141zxc".scan_char(8));
    assert_eq!(Some(('\n', 2)), "12qzxc".scan_char(8)); // spell-checker:disable-line
    assert_eq!(Some(('\r', 1)), "dqzxc".scan_char(16)); // spell-checker:disable-line
    assert_eq!(None, "z2qzxc".scan_char(8)); // spell-checker:disable-line
}

#[test]
fn test_group_num() {
    assert_eq!("12,379,821,234", group_num("12379821234"));
    assert_eq!("21,234", group_num("21234"));
    assert_eq!("821,234", group_num("821234"));
    assert_eq!("1,821,234", group_num("1821234"));
    assert_eq!("1,234", group_num("1234"));
    assert_eq!("234", group_num("234"));
    assert_eq!("24", group_num("24"));
    assert_eq!("4", group_num("4"));
    assert_eq!("", group_num(""));
}

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

    #[test]
    fn normal_format() {
        let s = "%'010.2ac%-#5.w\n";
        let expected = vec![
            Token::Directive {
                flag: F_GROUP | F_ZERO,
                width: 10,
                precision: 2,
                format: 'a',
            },
            Token::Char('c'),
            Token::Directive {
                flag: F_LEFT | F_ALTER,
                width: 5,
                precision: 0,
                format: 'w',
            },
            Token::Char('\n'),
        ];
        assert_eq!(&expected, &Stater::generate_tokens(s, false).unwrap());
    }

    #[test]
    fn printf_format() {
        let s = "%-# 15a\\r\\\"\\\\\\a\\b\\e\\f\\v%+020.-23w\\x12\\167\\132\\112\\n";
        let expected = vec![
            Token::Directive {
                flag: F_LEFT | F_ALTER | F_SPACE,
                width: 15,
                precision: -1,
                format: 'a',
            },
            Token::Char('\r'),
            Token::Char('"'),
            Token::Char('\\'),
            Token::Char('\x07'),
            Token::Char('\x08'),
            Token::Char('\x1B'),
            Token::Char('\x0C'),
            Token::Char('\x0B'),
            Token::Directive {
                flag: F_SIGN | F_ZERO,
                width: 20,
                precision: -1,
                format: 'w',
            },
            Token::Char('\x12'),
            Token::Char('w'),
            Token::Char('Z'),
            Token::Char('J'),
            Token::Char('\n'),
        ];
        assert_eq!(&expected, &Stater::generate_tokens(s, true).unwrap());
    }
}

#[test]
fn test_invalid_option() {
    new_ucmd!().arg("-w").arg("-q").arg("/").fails();
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
const NORMAL_FORMAT_STR: &str =
    "%a %A %b %B %d %D %f %F %g %G %h %i %m %n %o %s %u %U %x %X %y %Y %z %Z"; // avoid "%w %W" (birth/creation) due to `stat` limitations and linux kernel & rust version capability variations
#[cfg(any(target_os = "linux"))]
const DEV_FORMAT_STR: &str =
    "%a %A %b %B %d %D %f %F %g %G %h %i %m %n %o %s (%t/%T) %u %U %w %W %x %X %y %Y %z %Z";
#[cfg(target_os = "linux")]
const FS_FORMAT_STR: &str = "%b %c %i %l %n %s %S %t %T"; // avoid "%a %d %f" which can cause test failure due to race conditions

#[test]
#[cfg(target_os = "linux")]
fn test_terse_fs_format() {
    let args = ["-f", "-t", "/proc"];
    new_ucmd!()
        .args(&args)
        .run()
        .stdout_is(expected_result(&args));
}

#[test]
#[cfg(target_os = "linux")]
fn test_fs_format() {
    let args = ["-f", "-c", FS_FORMAT_STR, "/dev/shm"];
    new_ucmd!()
        .args(&args)
        .run()
        .stdout_is(expected_result(&args));
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn test_terse_normal_format() {
    // note: contains birth/creation date which increases test fragility
    // * results may vary due to built-in `stat` limitations as well as linux kernel and rust version capability variations
    let args = ["-t", "/"];
    let actual = new_ucmd!().args(&args).succeeds().stdout_move_str();
    let expect = expected_result(&args);
    println!("actual: {:?}", actual);
    println!("expect: {:?}", expect);
    let v_actual: Vec<&str> = actual.trim().split(' ').collect();
    let mut v_expect: Vec<&str> = expect.trim().split(' ').collect();
    assert!(!v_expect.is_empty());

    // uu_stat does not support selinux
    if v_actual.len() == v_expect.len() - 1 && v_expect[v_expect.len() - 1].contains(':') {
        // assume last element contains: `SELinux security context string`
        v_expect.pop();
    }

    // * allow for inequality if `stat` (aka, expect) returns "0" (unknown value)
    assert!(
        expect == "0"
            || expect == "0\n"
            || v_actual
                .iter()
                .zip(v_expect.iter())
                .all(|(a, e)| a == e || *e == "0" || *e == "0\n")
    );
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn test_format_created_time() {
    let args = ["-c", "%w", "/bin"];
    let actual = new_ucmd!().args(&args).succeeds().stdout_move_str();
    let expect = expected_result(&args);
    println!("actual: {:?}", actual);
    println!("expect: {:?}", expect);
    // note: using a regex instead of `split_whitespace()` in order to detect whitespace differences
    let re = regex::Regex::new(r"\s").unwrap();
    let v_actual: Vec<&str> = re.split(&actual).collect();
    let v_expect: Vec<&str> = re.split(&expect).collect();
    assert!(!v_expect.is_empty());
    // * allow for inequality if `stat` (aka, expect) returns "-" (unknown value)
    assert!(
        expect == "-"
            || expect == "-\n"
            || v_actual
                .iter()
                .zip(v_expect.iter())
                .all(|(a, e)| a == e || *e == "-" || *e == "-\n")
    );
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn test_format_created_seconds() {
    let args = ["-c", "%W", "/bin"];
    let actual = new_ucmd!().args(&args).succeeds().stdout_move_str();
    let expect = expected_result(&args);
    println!("actual: {:?}", actual);
    println!("expect: {:?}", expect);
    // note: using a regex instead of `split_whitespace()` in order to detect whitespace differences
    let re = regex::Regex::new(r"\s").unwrap();
    let v_actual: Vec<&str> = re.split(&actual).collect();
    let v_expect: Vec<&str> = re.split(&expect).collect();
    assert!(!v_expect.is_empty());
    // * allow for inequality if `stat` (aka, expect) returns "0" (unknown value)
    assert!(
        expect == "0"
            || expect == "0\n"
            || v_actual
                .iter()
                .zip(v_expect.iter())
                .all(|(a, e)| a == e || *e == "0" || *e == "0\n")
    );
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn test_normal_format() {
    let args = ["-c", NORMAL_FORMAT_STR, "/bin"];
    new_ucmd!()
        .args(&args)
        .succeeds()
        .stdout_is(expected_result(&args));
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn test_symlinks() {
    let scene = TestScenario::new(util_name!());
    let at = &scene.fixtures;

    let mut tested: bool = false;
    // arbitrarily chosen symlinks with hope that the CI environment provides at least one of them
    for file in &[
        "/bin/sh",
        "/bin/sudoedit",
        "/usr/bin/ex",
        "/etc/localtime",
        "/etc/aliases",
    ] {
        if at.file_exists(file) && at.is_symlink(file) {
            tested = true;
            let args = ["-c", NORMAL_FORMAT_STR, file];
            scene
                .ucmd()
                .args(&args)
                .succeeds()
                .stdout_is(expected_result(&args));
            // -L, --dereference    follow links
            let args = ["-L", "-c", NORMAL_FORMAT_STR, file];
            scene
                .ucmd()
                .args(&args)
                .succeeds()
                .stdout_is(expected_result(&args));
        }
    }
    if !tested {
        panic!("No symlink found to test in this environment");
    }
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn test_char() {
    // TODO: "(%t) (%x) (%w)" deviate from GNU stat for `character special file` on macOS
    // Diff < left / right > :
    // <"(f0000) (2021-05-20 23:08:03.442555000 +0200) (1970-01-01 01:00:00.000000000 +0100)\n"
    // >"(f) (2021-05-20 23:08:03.455598000 +0200) (-)\n"
    let args = [
        "-c",
        #[cfg(target_os = "linux")]
        DEV_FORMAT_STR,
        #[cfg(target_os = "linux")]
        "/dev/pts/ptmx",
        #[cfg(any(target_vendor = "apple"))]
        "%a %A %b %B %d %D %f %F %g %G %h %i %m %n %o %s (/%T) %u %U %W %X %y %Y %z %Z",
        #[cfg(any(target_vendor = "apple"))]
        "/dev/ptmx",
    ];
    new_ucmd!()
        .args(&args)
        .succeeds()
        .stdout_is(expected_result(&args));
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn test_multi_files() {
    let args = [
        "-c",
        NORMAL_FORMAT_STR,
        "/dev",
        "/usr/lib",
        #[cfg(target_os = "linux")]
        "/etc/fstab",
        "/var",
    ];
    new_ucmd!()
        .args(&args)
        .succeeds()
        .stdout_is(expected_result(&args));
}

#[cfg(any(target_vendor = "apple", target_os = "linux"))]
#[test]
fn test_printf() {
    let args = [
        "--printf=123%-# 15q\\r\\\"\\\\\\a\\b\\e\\f\\v%+020.23m\\x12\\167\\132\\112\\n",
        "/",
    ];
    new_ucmd!()
        .args(&args)
        .succeeds()
        .stdout_is(expected_result(&args));
}

#[cfg(any(target_vendor = "apple", target_os = "linux"))]
fn expected_result(args: &[&str]) -> String {
    #[cfg(target_os = "linux")]
    let util_name = util_name!();
    #[cfg(target_vendor = "apple")]
    let util_name = format!("g{}", util_name!());

    // note: clippy::needless_borrow *false positive*
    #[allow(clippy::needless_borrow)]
    TestScenario::new(&util_name)
        .cmd_keepenv(util_name)
        .env("LC_ALL", "C")
        .args(args)
        .succeeds()
        .stdout_move_str()
}
<commit_msg>test_stat: refactor use expected_result from common/util.rs<commit_after>extern crate regex;

use crate::common::util::*;

extern crate stat;
pub use self::stat::*;

#[test]
fn test_scanners() {
    assert_eq!(Some((-5, 2)), "-5zxc".scan_num::<i32>());
    assert_eq!(Some((51, 2)), "51zxc".scan_num::<u32>());
    assert_eq!(Some((192, 4)), "+192zxc".scan_num::<i32>());
    assert_eq!(None, "z192zxc".scan_num::<i32>());

    assert_eq!(Some(('a', 3)), "141zxc".scan_char(8));
    assert_eq!(Some(('\n', 2)), "12qzxc".scan_char(8)); // spell-checker:disable-line
    assert_eq!(Some(('\r', 1)), "dqzxc".scan_char(16)); // spell-checker:disable-line
    assert_eq!(None, "z2qzxc".scan_char(8)); // spell-checker:disable-line
}

#[test]
fn test_group_num() {
    assert_eq!("12,379,821,234", group_num("12379821234"));
    assert_eq!("21,234", group_num("21234"));
    assert_eq!("821,234", group_num("821234"));
    assert_eq!("1,821,234", group_num("1821234"));
    assert_eq!("1,234", group_num("1234"));
    assert_eq!("234", group_num("234"));
    assert_eq!("24", group_num("24"));
    assert_eq!("4", group_num("4"));
    assert_eq!("", group_num(""));
}

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

    #[test]
    fn normal_format() {
        let s = "%'010.2ac%-#5.w\n";
        let expected = vec![
            Token::Directive {
                flag: F_GROUP | F_ZERO,
                width: 10,
                precision: 2,
                format: 'a',
            },
            Token::Char('c'),
            Token::Directive {
                flag: F_LEFT | F_ALTER,
                width: 5,
                precision: 0,
                format: 'w',
            },
            Token::Char('\n'),
        ];
        assert_eq!(&expected, &Stater::generate_tokens(s, false).unwrap());
    }

    #[test]
    fn printf_format() {
        let s = "%-# 15a\\r\\\"\\\\\\a\\b\\e\\f\\v%+020.-23w\\x12\\167\\132\\112\\n";
        let expected = vec![
            Token::Directive {
                flag: F_LEFT | F_ALTER | F_SPACE,
                width: 15,
                precision: -1,
                format: 'a',
            },
            Token::Char('\r'),
            Token::Char('"'),
            Token::Char('\\'),
            Token::Char('\x07'),
            Token::Char('\x08'),
            Token::Char('\x1B'),
            Token::Char('\x0C'),
            Token::Char('\x0B'),
            Token::Directive {
                flag: F_SIGN | F_ZERO,
                width: 20,
                precision: -1,
                format: 'w',
            },
            Token::Char('\x12'),
            Token::Char('w'),
            Token::Char('Z'),
            Token::Char('J'),
            Token::Char('\n'),
        ];
        assert_eq!(&expected, &Stater::generate_tokens(s, true).unwrap());
    }
}

#[test]
fn test_invalid_option() {
    new_ucmd!().arg("-w").arg("-q").arg("/").fails();
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
const NORMAL_FORMAT_STR: &str =
    "%a %A %b %B %d %D %f %F %g %G %h %i %m %n %o %s %u %U %x %X %y %Y %z %Z"; // avoid "%w %W" (birth/creation) due to `stat` limitations and linux kernel & rust version capability variations
#[cfg(any(target_os = "linux"))]
const DEV_FORMAT_STR: &str =
    "%a %A %b %B %d %D %f %F %g %G %h %i %m %n %o %s (%t/%T) %u %U %w %W %x %X %y %Y %z %Z";
#[cfg(target_os = "linux")]
const FS_FORMAT_STR: &str = "%b %c %i %l %n %s %S %t %T"; // avoid "%a %d %f" which can cause test failure due to race conditions

#[test]
#[cfg(target_os = "linux")]
fn test_terse_fs_format() {
    let args = ["-f", "-t", "/proc"];
    let expected_stdout = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    new_ucmd!().args(&args).run().stdout_is(expected_stdout);
}

#[test]
#[cfg(target_os = "linux")]
fn test_fs_format() {
    let args = ["-f", "-c", FS_FORMAT_STR, "/dev/shm"];
    let expected_stdout = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    new_ucmd!().args(&args).run().stdout_is(expected_stdout);
}

#[cfg(unix)]
#[test]
fn test_terse_normal_format() {
    // note: contains birth/creation date which increases test fragility
    // * results may vary due to built-in `stat` limitations as well as linux kernel and rust version capability variations
    let args = ["-t", "/"];
    let actual = new_ucmd!().args(&args).succeeds().stdout_move_str();
    let expect = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    println!("actual: {:?}", actual);
    println!("expect: {:?}", expect);
    let v_actual: Vec<&str> = actual.trim().split(' ').collect();
    let mut v_expect: Vec<&str> = expect.trim().split(' ').collect();
    assert!(!v_expect.is_empty());

    // uu_stat does not support selinux
    if v_actual.len() == v_expect.len() - 1 && v_expect[v_expect.len() - 1].contains(':') {
        // assume last element contains: `SELinux security context string`
        v_expect.pop();
    }

    // * allow for inequality if `stat` (aka, expect) returns "0" (unknown value)
    assert!(
        expect == "0"
            || expect == "0\n"
            || v_actual
                .iter()
                .zip(v_expect.iter())
                .all(|(a, e)| a == e || *e == "0" || *e == "0\n")
    );
}

#[cfg(unix)]
#[test]
fn test_format_created_time() {
    let args = ["-c", "%w", "/bin"];
    let actual = new_ucmd!().args(&args).succeeds().stdout_move_str();
    let expect = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    println!("actual: {:?}", actual);
    println!("expect: {:?}", expect);
    // note: using a regex instead of `split_whitespace()` in order to detect whitespace differences
    let re = regex::Regex::new(r"\s").unwrap();
    let v_actual: Vec<&str> = re.split(&actual).collect();
    let v_expect: Vec<&str> = re.split(&expect).collect();
    assert!(!v_expect.is_empty());
    // * allow for inequality if `stat` (aka, expect) returns "-" (unknown value)
    assert!(
        expect == "-"
            || expect == "-\n"
            || v_actual
                .iter()
                .zip(v_expect.iter())
                .all(|(a, e)| a == e || *e == "-" || *e == "-\n")
    );
}

#[cfg(unix)]
#[test]
fn test_format_created_seconds() {
    let args = ["-c", "%W", "/bin"];
    let actual = new_ucmd!().args(&args).succeeds().stdout_move_str();
    let expect = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    println!("actual: {:?}", actual);
    println!("expect: {:?}", expect);
    // note: using a regex instead of `split_whitespace()` in order to detect whitespace differences
    let re = regex::Regex::new(r"\s").unwrap();
    let v_actual: Vec<&str> = re.split(&actual).collect();
    let v_expect: Vec<&str> = re.split(&expect).collect();
    assert!(!v_expect.is_empty());
    // * allow for inequality if `stat` (aka, expect) returns "0" (unknown value)
    assert!(
        expect == "0"
            || expect == "0\n"
            || v_actual
                .iter()
                .zip(v_expect.iter())
                .all(|(a, e)| a == e || *e == "0" || *e == "0\n")
    );
}

#[cfg(unix)]
#[test]
fn test_normal_format() {
    let args = ["-c", NORMAL_FORMAT_STR, "/bin"];
    let expected_stdout = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    new_ucmd!()
        .args(&args)
        .succeeds()
        .stdout_is(expected_stdout);
}

#[cfg(unix)]
#[test]
fn test_symlinks() {
    let scene = TestScenario::new(util_name!());
    let at = &scene.fixtures;

    let mut tested: bool = false;
    // arbitrarily chosen symlinks with hope that the CI environment provides at least one of them
    for file in &[
        "/bin/sh",
        "/bin/sudoedit",
        "/usr/bin/ex",
        "/etc/localtime",
        "/etc/aliases",
    ] {
        if at.file_exists(file) && at.is_symlink(file) {
            tested = true;
            let args = ["-c", NORMAL_FORMAT_STR, file];
            let expected_stdout =
                unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
            scene
                .ucmd()
                .args(&args)
                .succeeds()
                .stdout_is(expected_stdout);
            // -L, --dereference    follow links
            let args = ["-L", "-c", NORMAL_FORMAT_STR, file];
            let expected_stdout =
                unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
            scene
                .ucmd()
                .args(&args)
                .succeeds()
                .stdout_is(expected_stdout);
        }
    }
    if !tested {
        panic!("No symlink found to test in this environment");
    }
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn test_char() {
    // TODO: "(%t) (%x) (%w)" deviate from GNU stat for `character special file` on macOS
    // Diff < left / right > :
    // <"(f0000) (2021-05-20 23:08:03.442555000 +0200) (1970-01-01 01:00:00.000000000 +0100)\n"
    // >"(f) (2021-05-20 23:08:03.455598000 +0200) (-)\n"
    let args = [
        "-c",
        #[cfg(target_os = "linux")]
        DEV_FORMAT_STR,
        #[cfg(target_os = "linux")]
        "/dev/pts/ptmx",
        #[cfg(any(target_vendor = "apple"))]
        "%a %A %b %B %d %D %f %F %g %G %h %i %m %n %o %s (/%T) %u %U %W %X %y %Y %z %Z",
        #[cfg(any(target_vendor = "apple"))]
        "/dev/ptmx",
    ];
    let expected_stdout = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    new_ucmd!()
        .args(&args)
        .succeeds()
        .stdout_is(expected_stdout);
}

#[cfg(unix)]
#[test]
fn test_multi_files() {
    let args = [
        "-c",
        NORMAL_FORMAT_STR,
        "/dev",
        "/usr/lib",
        #[cfg(target_os = "linux")]
        "/etc/fstab",
        "/var",
    ];
    let expected_stdout = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    new_ucmd!()
        .args(&args)
        .succeeds()
        .stdout_is(expected_stdout);
}

#[cfg(unix)]
#[test]
fn test_printf() {
    let args = [
        "--printf=123%-# 15q\\r\\\"\\\\\\a\\b\\e\\f\\v%+020.23m\\x12\\167\\132\\112\\n",
        "/",
    ];
    let expected_stdout = unwrap_or_return!(expected_result(util_name!(), &args)).stdout_move_str();
    new_ucmd!()
        .args(&args)
        .succeeds()
        .stdout_is(expected_stdout);
}
<|endoftext|>


<commit_before>use super::{c32, c64};
use super::util::FFTW_MUTEX;
use ffi;

use num_traits::Zero;
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::os::raw::c_void;
use std::slice::{from_raw_parts, from_raw_parts_mut};

pub struct AlignedVec<T> {
    n: usize,
    data: *mut T,
}

pub trait AlignedAllocable {
    unsafe fn alloc(n: usize) -> *mut Self;
}

impl AlignedAllocable for f64 {
    unsafe fn alloc(n: usize) -> *mut Self {
        ffi::fftw_alloc_real(n)
    }
}

impl AlignedAllocable for f32 {
    unsafe fn alloc(n: usize) -> *mut Self {
        ffi::fftwf_alloc_real(n)
    }
}

impl AlignedAllocable for c64 {
    unsafe fn alloc(n: usize) -> *mut Self {
        ffi::fftw_alloc_complex(n)
    }
}

impl AlignedAllocable for c32 {
    unsafe fn alloc(n: usize) -> *mut Self {
        ffi::fftwf_alloc_complex(n)
    }
}

impl<T> AlignedVec<T> {
    pub fn as_slice(&self) -> &[T] {
        unsafe { from_raw_parts(self.data, self.n) }
    }
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { from_raw_parts_mut(self.data, self.n) }
    }
}

impl<T> Deref for AlignedVec<T> {
    type Target = [T];
    fn deref(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T> DerefMut for AlignedVec<T> {
    fn deref_mut(&mut self) -> &mut [T] {
        self.as_mut_slice()
    }
}

impl<T> Drop for AlignedVec<T> {
    fn drop(&mut self) {
        let lock = FFTW_MUTEX.lock().expect("Cannot get lock");
        unsafe { ffi::fftw_free(self.data as *mut c_void) };
        drop(lock);
    }
}

impl<T> AlignedVec<T>
where
    T: Zero + AlignedAllocable,
{
    pub fn new(n: usize) -> Self {
        let lock = FFTW_MUTEX.lock().expect("Cannot get lock");
        let ptr = unsafe { T::alloc(n) };
        drop(lock);
        let mut vec = AlignedVec { n: n, data: ptr };
        for v in vec.iter_mut() {
            *v = T::zero();
        }
        vec
    }
}

impl<T> Index<usize> for AlignedVec<T> {
    type Output = T;
    fn index(&self, index: usize) -> &Self::Output {
        unsafe { &*self.data.offset(index as isize) }
    }
}

impl<T> IndexMut<usize> for AlignedVec<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        unsafe { &mut *self.data.offset(index as isize) }
    }
}
<commit_msg>Add docstrings for AlignedVec<commit_after>use super::{c32, c64};
use super::util::FFTW_MUTEX;
use ffi;

use num_traits::Zero;
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::os::raw::c_void;
use std::slice::{from_raw_parts, from_raw_parts_mut};

/// Array with SIMD alignment
///
/// This wraps `fftw_alloc` and `fftw_free`for SIMD feature
/// http://www.fftw.org/fftw3_doc/SIMD-alignment-and-fftw_005fmalloc.html
pub struct AlignedVec<T> {
    n: usize,
    data: *mut T,
}

pub trait AlignedAllocable {
    unsafe fn alloc(n: usize) -> *mut Self;
}

impl AlignedAllocable for f64 {
    unsafe fn alloc(n: usize) -> *mut Self {
        ffi::fftw_alloc_real(n)
    }
}

impl AlignedAllocable for f32 {
    unsafe fn alloc(n: usize) -> *mut Self {
        ffi::fftwf_alloc_real(n)
    }
}

impl AlignedAllocable for c64 {
    unsafe fn alloc(n: usize) -> *mut Self {
        ffi::fftw_alloc_complex(n)
    }
}

impl AlignedAllocable for c32 {
    unsafe fn alloc(n: usize) -> *mut Self {
        ffi::fftwf_alloc_complex(n)
    }
}

impl<T> AlignedVec<T> {
    /// Recast to Rust's immutable slice
    pub fn as_slice(&self) -> &[T] {
        unsafe { from_raw_parts(self.data, self.n) }
    }
    /// Recast to Rust's mutable slice
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { from_raw_parts_mut(self.data, self.n) }
    }
}

impl<T> Deref for AlignedVec<T> {
    type Target = [T];
    fn deref(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T> DerefMut for AlignedVec<T> {
    fn deref_mut(&mut self) -> &mut [T] {
        self.as_mut_slice()
    }
}

impl<T> Drop for AlignedVec<T> {
    fn drop(&mut self) {
        let lock = FFTW_MUTEX.lock().expect("Cannot get lock");
        unsafe { ffi::fftw_free(self.data as *mut c_void) };
        drop(lock);
    }
}

impl<T> AlignedVec<T>
where
    T: Zero + AlignedAllocable,
{
    /// Create array with `fftw_malloc` (`fftw_free` is automatically called when the arrya is `Drop`-ed)
    pub fn new(n: usize) -> Self {
        let lock = FFTW_MUTEX.lock().expect("Cannot get lock");
        let ptr = unsafe { T::alloc(n) };
        drop(lock);
        let mut vec = AlignedVec { n: n, data: ptr };
        for v in vec.iter_mut() {
            *v = T::zero();
        }
        vec
    }
}

impl<T> Index<usize> for AlignedVec<T> {
    type Output = T;
    fn index(&self, index: usize) -> &Self::Output {
        unsafe { &*self.data.offset(index as isize) }
    }
}

impl<T> IndexMut<usize> for AlignedVec<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        unsafe { &mut *self.data.offset(index as isize) }
    }
}
<|endoftext|>


<commit_before>///! fff-lang
///!
///! util/date_time for Readonly UTC date time

use std::fmt;

/// Readonly UTC date time
#[derive(Clone, Eq, PartialEq)]
pub struct DateTime {
    m_year: u32,
    m_month: u32,
    m_day: u32,
    m_hour: u32,
    m_minute: u32,
    m_second: u32,
}
impl DateTime {

    /// Attention: no validate because I'm lazy
    pub fn with6(year: u32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> DateTime {
        DateTime{ m_year: year, m_month: month, m_day: day, m_hour: hour, m_minute: minute, m_second: second }
    }
    pub fn new() -> DateTime {
        DateTime::with6(1970, 1, 1, 0, 0, 0)
    }

    pub fn get_year(&self) -> u32 { self.m_year }
    pub fn get_month(&self) -> u32 { self.m_month }
    pub fn get_day(&self) -> u32 { self.m_day }
    pub fn get_hour(&self) -> u32 { self.m_hour }
    pub fn get_minute(&self) -> u32 { self.m_minute }
    pub fn get_second(&self) -> u32 { self.m_second }

    /// Currently only ISO8601 and UTC
    pub fn format(&self, _formatter : &str) -> String {
        format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", self.m_year, self.m_month, self.m_day, self.m_hour, self.m_minute, self.m_second)
    }
}
impl fmt::Debug for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.format("iso8601"))
    }
}

#[cfg(windows)]
mod native {
    use std::mem;
    use super::DateTime;

    #[repr(C, packed)]
    struct SystemTime {
        year: u16,
        month: u16,
        _day_of_week: u16, // not used here
        day: u16,
        hour: u16,
        minute: u16,
        second: u16,
        _milli_second: u16, // not used here
    }
    #[repr(C, packed)]
    struct FileTime {
        low_part: u32,
        high_part: u32,
    }

    #[link(name = "kernel32")] extern "stdcall" {
        fn GetSystemTime(retval: *mut SystemTime);
        fn SystemTimeToFileTime(systime: *const SystemTime, filetime: *mut FileTime);
        fn FileTimeToSystemTime(filetime: *const FileTime, systime: *mut SystemTime);
    }

    const FILETIME_TIMESTAMP_OFFSET: u64 = 11644473600u64;

    pub fn now() -> DateTime {
        unsafe {
            let mut ret_val = mem::uninitialized::<SystemTime>();
            GetSystemTime(&mut ret_val as *mut SystemTime);
            DateTime::with6(
                ret_val.year as u32, ret_val.month as u32, ret_val.day as u32,
                ret_val.hour as u32, ret_val.minute as u32, ret_val.second as u32)
        }
    }
    pub fn with_timestamp(timestamp: u64) -> DateTime {
        unsafe {
            timestamp += FILETIME_TIMESTAMP_OFFSET;
            timestamp *= 10_000_000u64;
            let filetime = FileTime{ low_part: (timestamp & 0xFFFFFFFF) as u32, high_part: (timestamp >> 32) as u32 };
            let mut systime = mem::uninitialized::<SystemTime>();
            FileTimeToSystemTime(&filetime as *const FileTime, &mut systime as *mut SystemTime);
            DateTime::with6(
                systime.year as u32, systime.month as u32, systime.day as u32,
                systime.hour as u32, systime.minute as u32, systime.second as u32)
        }
    }
    pub fn as_timestamp(this: &DateTime) -> u64 {
        unsafe {
            let systime = SystemTime{
                year: this.m_year as u16, month: this.m_month as u16, day: this.m_day as u16,
                hour: this.m_hour as u16, minute: this.m_minute as u16, second: this.m_second as u16,
                _day_of_week: 0, _milli_second: 0
            };
            let mut filetime = mem::uninitialized::<FileTime>();
            SystemTimeToFileTime(&systime as *const SystemTime, &mut filetime as *mut FileTime);
            (filetime.low_part as u64 + ((filetime.high_part as u64) << 32)) / 10_000_000u64 - FILETIME_TIMESTAMP_OFFSET
        }
    }
}
#[cfg(unix)]
mod native {
    use super::DateTime;

    #[repr(C, packed)]
    struct tm {
        second: i32,         // 0-60
        minute: i32,         // 0-59
        hour: i32,           // 0-23
        day_of_month: i32,   // 1-31
        month: i32,          // 0-11
        year: i32,           // 1900+
        _day_of_week: i32,   // Sunday as 0
        _day_of_year: i32,   // 0-365
        _is_daylight_saving_time: i32,
        _gmt_offset: i64,    // second from GMT   // currently only UTC so not used
        _zone: *mut u8,                           // not used, too
    }
    impl tm {
        fn into_datetime(&self) -> DateTime { // because you may not own a struct tm
            DateTime::with6(
                self.year as u32 + 1900, self.month as u32 + 1, self.day_of_month as u32,
                self.hour as u32, self.minute as u32, self.second as u32,
            )
        }
    }

    #[link(name = "c")] extern "cdecl" {
        fn time(stamp: *mut u64) -> u64;
        fn gmtime(stamp: *const u64) -> *const tm;
        fn timegm(t: *mut tm) -> u64;
    }

    pub fn now() -> DateTime {
        unsafe { tm::into_datetime(&*gmtime(&time(0 as *mut u64) as *const u64)) }
    }
    pub fn with_timestamp(timestamp: u64) -> DateTime {
        unsafe { tm::into_datetime(&*gmtime(&timestamp as *const u64)) }
    }
    pub fn as_timestamp(this: &DateTime) -> u64 {
        let mut zone = ['G' as u32 as u8, 'M' as u32 as u8, 'T' as u32 as u8, 0u8]; // C style `"GMT"`, 0 for null terminate
        unsafe { timegm(&mut tm {
            second: this.m_second as i32,
            minute: this.m_minute as i32,
            hour: this.m_hour as i32,
            day_of_month: this.m_day as i32,
            month: this.m_month as i32 - 1,
            year: this.m_year as i32 - 1900,
            _day_of_week: 0,  // mktime says ignored
            _day_of_year: 0,  // mktime says ignored
            _is_daylight_saving_time: -1, // auto
            _gmt_offset: 0,   // only UTC is used here
            _zone: &mut zone[0] as *mut u8,
        } as *mut tm)
    } }
}

impl DateTime {

    pub fn now() -> DateTime { self::native::now() }
    pub fn with_timestamp(timestamp: u64) -> DateTime { self::native::with_timestamp(timestamp) }
    pub fn as_timestamp(&self) -> u64 { self::native::as_timestamp(self) }
}

#[cfg(test)] #[test]
fn date_time_timestamp() {

    assert_eq!(DateTime::with6(2017, 3, 13, 6, 40, 40).as_timestamp(), 1489387240);
    assert_eq!(DateTime::with_timestamp(0), DateTime::new());
    assert_eq!(DateTime::with_timestamp(1489387240), DateTime::with6(2017, 3, 13, 6, 40, 40));
    assert_eq!(DateTime::with_timestamp(12345678).as_timestamp(), 12345678);
    assert_eq!(DateTime::new().format("iso8601"), "1970-01-01T00:00:00Z");
}<commit_msg>[util] fix compile error on Windows<commit_after>///! fff-lang
///!
///! util/date_time for Readonly UTC date time

use std::fmt;

/// Readonly UTC date time
#[derive(Clone, Eq, PartialEq)]
pub struct DateTime {
    m_year: u32,
    m_month: u32,
    m_day: u32,
    m_hour: u32,
    m_minute: u32,
    m_second: u32,
}
impl DateTime {

    /// Attention: no validate because I'm lazy
    pub fn with6(year: u32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> DateTime {
        DateTime{ m_year: year, m_month: month, m_day: day, m_hour: hour, m_minute: minute, m_second: second }
    }
    pub fn new() -> DateTime {
        DateTime::with6(1970, 1, 1, 0, 0, 0)
    }

    pub fn get_year(&self) -> u32 { self.m_year }
    pub fn get_month(&self) -> u32 { self.m_month }
    pub fn get_day(&self) -> u32 { self.m_day }
    pub fn get_hour(&self) -> u32 { self.m_hour }
    pub fn get_minute(&self) -> u32 { self.m_minute }
    pub fn get_second(&self) -> u32 { self.m_second }

    /// Currently only ISO8601 and UTC
    pub fn format(&self, _formatter : &str) -> String {
        format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", self.m_year, self.m_month, self.m_day, self.m_hour, self.m_minute, self.m_second)
    }
}
impl fmt::Debug for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.format("iso8601"))
    }
}

#[cfg(windows)]
mod native {
    use std::mem;
    use super::DateTime;

    #[repr(C, packed)]
    struct SystemTime {
        year: u16,
        month: u16,
        _day_of_week: u16, // not used here
        day: u16,
        hour: u16,
        minute: u16,
        second: u16,
        _milli_second: u16, // not used here
    }
    #[repr(C, packed)]
    struct FileTime {
        low_part: u32,
        high_part: u32,
    }

    #[link(name = "kernel32")] extern "stdcall" {
        fn GetSystemTime(retval: *mut SystemTime);
        fn SystemTimeToFileTime(systime: *const SystemTime, filetime: *mut FileTime);
        fn FileTimeToSystemTime(filetime: *const FileTime, systime: *mut SystemTime);
    }

    const FILETIME_TIMESTAMP_OFFSET: u64 = 11644473600u64;

    pub fn now() -> DateTime {
        unsafe {
            let mut ret_val = mem::uninitialized::<SystemTime>();
            GetSystemTime(&mut ret_val as *mut SystemTime);
            DateTime::with6(
                ret_val.year as u32, ret_val.month as u32, ret_val.day as u32,
                ret_val.hour as u32, ret_val.minute as u32, ret_val.second as u32)
        }
    }
    pub fn with_timestamp(timestamp: u64) -> DateTime {
        let mut timestamp = timestamp;
        unsafe {
            timestamp += FILETIME_TIMESTAMP_OFFSET;
            timestamp *= 10_000_000u64;
            let filetime = FileTime{ low_part: (timestamp & 0xFFFFFFFF) as u32, high_part: (timestamp >> 32) as u32 };
            let mut systime = mem::uninitialized::<SystemTime>();
            FileTimeToSystemTime(&filetime as *const FileTime, &mut systime as *mut SystemTime);
            DateTime::with6(
                systime.year as u32, systime.month as u32, systime.day as u32,
                systime.hour as u32, systime.minute as u32, systime.second as u32)
        }
    }
    pub fn as_timestamp(this: &DateTime) -> u64 {
        unsafe {
            let systime = SystemTime{
                year: this.m_year as u16, month: this.m_month as u16, day: this.m_day as u16,
                hour: this.m_hour as u16, minute: this.m_minute as u16, second: this.m_second as u16,
                _day_of_week: 0, _milli_second: 0
            };
            let mut filetime = mem::uninitialized::<FileTime>();
            SystemTimeToFileTime(&systime as *const SystemTime, &mut filetime as *mut FileTime);
            (filetime.low_part as u64 + ((filetime.high_part as u64) << 32)) / 10_000_000u64 - FILETIME_TIMESTAMP_OFFSET
        }
    }
}
#[cfg(unix)]
mod native {
    use super::DateTime;

    #[repr(C, packed)]
    struct tm {
        second: i32,         // 0-60
        minute: i32,         // 0-59
        hour: i32,           // 0-23
        day_of_month: i32,   // 1-31
        month: i32,          // 0-11
        year: i32,           // 1900+
        _day_of_week: i32,   // Sunday as 0
        _day_of_year: i32,   // 0-365
        _is_daylight_saving_time: i32,
        _gmt_offset: i64,    // second from GMT   // currently only UTC so not used
        _zone: *mut u8,                           // not used, too
    }
    impl tm {
        fn into_datetime(&self) -> DateTime { // because you may not own a struct tm
            DateTime::with6(
                self.year as u32 + 1900, self.month as u32 + 1, self.day_of_month as u32,
                self.hour as u32, self.minute as u32, self.second as u32,
            )
        }
    }

    #[link(name = "c")] extern "cdecl" {
        fn time(stamp: *mut u64) -> u64;
        fn gmtime(stamp: *const u64) -> *const tm;
        fn timegm(t: *mut tm) -> u64;
    }

    pub fn now() -> DateTime {
        unsafe { tm::into_datetime(&*gmtime(&time(0 as *mut u64) as *const u64)) }
    }
    pub fn with_timestamp(timestamp: u64) -> DateTime {
        unsafe { tm::into_datetime(&*gmtime(&timestamp as *const u64)) }
    }
    pub fn as_timestamp(this: &DateTime) -> u64 {
        let mut zone = ['G' as u32 as u8, 'M' as u32 as u8, 'T' as u32 as u8, 0u8]; // C style `"GMT"`, 0 for null terminate
        unsafe { timegm(&mut tm {
            second: this.m_second as i32,
            minute: this.m_minute as i32,
            hour: this.m_hour as i32,
            day_of_month: this.m_day as i32,
            month: this.m_month as i32 - 1,
            year: this.m_year as i32 - 1900,
            _day_of_week: 0,  // mktime says ignored
            _day_of_year: 0,  // mktime says ignored
            _is_daylight_saving_time: -1, // auto
            _gmt_offset: 0,   // only UTC is used here
            _zone: &mut zone[0] as *mut u8,
        } as *mut tm)
    } }
}

impl DateTime {

    pub fn now() -> DateTime { self::native::now() }
    pub fn with_timestamp(timestamp: u64) -> DateTime { self::native::with_timestamp(timestamp) }
    pub fn as_timestamp(&self) -> u64 { self::native::as_timestamp(self) }
}

#[cfg(test)] #[test]
fn date_time_timestamp() {

    assert_eq!(DateTime::with6(2017, 3, 13, 6, 40, 40).as_timestamp(), 1489387240);
    assert_eq!(DateTime::with_timestamp(0), DateTime::new());
    assert_eq!(DateTime::with_timestamp(1489387240), DateTime::with6(2017, 3, 13, 6, 40, 40));
    assert_eq!(DateTime::with_timestamp(12345678).as_timestamp(), 12345678);
    assert_eq!(DateTime::new().format("iso8601"), "1970-01-01T00:00:00Z");
}<|endoftext|>


<commit_before>use async_trait::async_trait;
use futures::channel::mpsc::UnboundedSender as Sender;
use crate::{
	gateway::InterMessage,
	model::{
	    id::{GuildId, UserId},
	    voice::VoiceState,
	},
};

/// FIXME: must be documented.
/// All these take read refs to allow struct to use its own concurrency access mechanisms.
#[async_trait]
pub trait VoiceGatewayManager: Send + Sync {
    async fn initialise(&self, shard_count: u64, user_id: UserId);

    async fn register_shard(&self, shard_id: u64, sender: Sender<InterMessage>);

    async fn deregister_shard(&self, shard_id: u64);

    async fn server_update(&self, guild_id: GuildId, endpoint: &Option<String>, token: &str);

    async fn state_update(&self, guild_id: GuildId, voice_state: &VoiceState);
}
<commit_msg>Document VoiceGatewayManager interface (#1167)<commit_after>use async_trait::async_trait;
use futures::channel::mpsc::UnboundedSender as Sender;
use crate::{
	gateway::InterMessage,
	model::{
	    id::{GuildId, UserId},
	    voice::VoiceState,
	},
};

/// Interface for any compatible voice plugin.
///
/// This interface covers several serenity-specific hooks, as well as
/// packet handlers for voice-specific gateway messages.
#[async_trait]
pub trait VoiceGatewayManager: Send + Sync {
	/// Performs initial setup at the start of a connection to Discord.
	///
	/// This will only occur once, and provides the bot's ID and shard count.
    async fn initialise(&self, shard_count: u64, user_id: UserId);

    /// Handler fired in response to a `Ready` event.
    ///
    /// This provides the voice plugin with a channel to send gateway messages to Discord,
    /// once per active shard.
    async fn register_shard(&self, shard_id: u64, sender: Sender<InterMessage>);

    /// Handler fired in response to a disconnect, reconnection, or rebalance.
    ///
    /// This event invalidates the last sender associated with `shard_id`.
    /// Unless the bot is fully disconnecting, this is often followed by a call
    /// to [`register_shard`]. Users may wish to buffer manually any gateway messages
    /// sent between these calls.
    ///
    /// [`register_shard`]: VoiceGatewayManager::register_shard
    async fn deregister_shard(&self, shard_id: u64);

    /// Handler for VOICE_SERVER_UPDATE messages.
    ///
    /// These contain the endpoint and token needed to form a voice connection session.
    async fn server_update(&self, guild_id: GuildId, endpoint: &Option<String>, token: &str);

    /// Handler for VOICE_STATE_UPDATE messages.
    ///
    /// These contain the session ID needed to form a voice connection session.
    async fn state_update(&self, guild_id: GuildId, voice_state: &VoiceState);
}
<|endoftext|>