<commit_before>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::util::{byte_to_ascii_hex_lower, parse_byte_from_ascii_str_at};
use crate::GuidFromStrError;
use core::fmt::{self, Display, Formatter};
use core::str::{self, FromStr};

#[cfg(feature = "serde")]
use {
    serde::de::{self, Visitor},
    serde::{Deserialize, Deserializer, Serialize, Serializer},
};

#[cfg(feature = "bytemuck")]
use bytemuck::{Pod, Zeroable};

/// Macro replacement for the `?` operator, which cannot be used in
/// const functions.
macro_rules! mtry {
    ($expr:expr $(,)?) => {
        match $expr {
            Ok(val) => val,
            Err(err) => {
                return Err(err);
            }
        }
    };
}

/// Define a GUID struct and its impls. This is used to create structs
/// that are the same but for alignment.
macro_rules! guid_impl {
    ($struct_name:ident,
     // Struct alignment.
     $struct_alignment:literal,
     $deserializer_name:ident) => {
        /// Globally-unique identifier.
        ///
        /// The format is described in Appendix A of the UEFI
        /// Specification. Note that the first three fields are little-endian.
        #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
        #[cfg_attr(feature = "bytemuck", derive(Pod, Zeroable))]
        #[repr(C)]
        #[repr(align($struct_alignment))]
        pub struct $struct_name {
            /// The little-endian low field of the timestamp.
            pub time_low: [u8; 4],

            /// The little-endian middle field of the timestamp.
            pub time_mid: [u8; 2],

            /// The little-endian high field of the timestamp multiplexed with
            /// the version number.
            pub time_high_and_version: [u8; 2],

            /// The high field of the clock sequence multiplexed with the
            /// variant.
            pub clock_seq_high_and_reserved: u8,

            /// The low field of the clock sequence.
            pub clock_seq_low: u8,

            /// The spatially unique node identifier.
            pub node: [u8; 6],
        }

        impl $struct_name {
            /// GUID with all fields set to zero.
            pub const ZERO: Self =
                Self::new([0, 0, 0, 0], [0, 0], [0, 0], 0, 0, [0, 0, 0, 0, 0, 0]);

            /// Create a new GUID.
            #[must_use]
            pub const fn new(
                time_low: [u8; 4],
                time_mid: [u8; 2],
                time_high_and_version: [u8; 2],
                clock_seq_high_and_reserved: u8,
                clock_seq_low: u8,
                node: [u8; 6],
            ) -> Self {
                Self {
                    time_low,
                    time_mid,
                    time_high_and_version,
                    clock_seq_high_and_reserved,
                    clock_seq_low,
                    node,
                }
            }

            /// Parse a GUID from a string.
            ///
            /// This is functionally the same as [`Guid::from_str`], but is
            /// exposed separately to provide a `const` method for parsing.
            pub const fn try_parse(s: &str) -> Result<Self, GuidFromStrError> {
                // Treat input as ASCII.
                let s = s.as_bytes();

                if s.len() != 36 {
                    return Err(GuidFromStrError::Length);
                }

                let sep = b'-';
                if s[8] != sep {
                    return Err(GuidFromStrError::Separator(8));
                }
                if s[13] != sep {
                    return Err(GuidFromStrError::Separator(13));
                }
                if s[18] != sep {
                    return Err(GuidFromStrError::Separator(18));
                }
                if s[23] != sep {
                    return Err(GuidFromStrError::Separator(23));
                }

                Ok(Self {
                    time_low: [
                        mtry!(parse_byte_from_ascii_str_at(s, 6)),
                        mtry!(parse_byte_from_ascii_str_at(s, 4)),
                        mtry!(parse_byte_from_ascii_str_at(s, 2)),
                        mtry!(parse_byte_from_ascii_str_at(s, 0)),
                    ],
                    time_mid: [
                        mtry!(parse_byte_from_ascii_str_at(s, 11)),
                        mtry!(parse_byte_from_ascii_str_at(s, 9)),
                    ],
                    time_high_and_version: [
                        mtry!(parse_byte_from_ascii_str_at(s, 16)),
                        mtry!(parse_byte_from_ascii_str_at(s, 14)),
                    ],
                    clock_seq_high_and_reserved: mtry!(parse_byte_from_ascii_str_at(
                        s, 19
                    )),
                    clock_seq_low: mtry!(parse_byte_from_ascii_str_at(s, 21)),
                    node: [
                        mtry!(parse_byte_from_ascii_str_at(s, 24)),
                        mtry!(parse_byte_from_ascii_str_at(s, 26)),
                        mtry!(parse_byte_from_ascii_str_at(s, 28)),
                        mtry!(parse_byte_from_ascii_str_at(s, 30)),
                        mtry!(parse_byte_from_ascii_str_at(s, 32)),
                        mtry!(parse_byte_from_ascii_str_at(s, 34)),
                    ],
                })
            }

            /// Create a GUID from a 16-byte array. No changes to byte order are made.
            #[must_use]
            pub const fn from_bytes(bytes: [u8; 16]) -> Self {
                Self {
                    time_low: [bytes[0], bytes[1], bytes[2], bytes[3]],
                    time_mid: [bytes[4], bytes[5]],
                    time_high_and_version: [bytes[6], bytes[7]],
                    clock_seq_high_and_reserved: bytes[8],
                    clock_seq_low: bytes[9],
                    node: [
                        bytes[10], bytes[11], bytes[12], bytes[13], bytes[14],
                        bytes[15],
                    ],
                }
            }

            /// Convert to a 16-byte array.
            #[must_use]
            pub const fn to_bytes(self) -> [u8; 16] {
                [
                    self.time_low[0],
                    self.time_low[1],
                    self.time_low[2],
                    self.time_low[3],
                    self.time_mid[0],
                    self.time_mid[1],
                    self.time_high_and_version[0],
                    self.time_high_and_version[1],
                    self.clock_seq_high_and_reserved,
                    self.clock_seq_low,
                    self.node[0],
                    self.node[1],
                    self.node[2],
                    self.node[3],
                    self.node[4],
                    self.node[5],
                ]
            }

            /// Convert to a lower-case hex ASCII string.
            ///
            /// The output is in "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" format.
            #[must_use]
            pub const fn to_ascii_hex_lower(self) -> [u8; 36] {
                let mut buf = [0; 36];
                (buf[0], buf[1]) = byte_to_ascii_hex_lower(self.time_low[3]);
                (buf[2], buf[3]) = byte_to_ascii_hex_lower(self.time_low[2]);
                (buf[4], buf[5]) = byte_to_ascii_hex_lower(self.time_low[1]);
                (buf[6], buf[7]) = byte_to_ascii_hex_lower(self.time_low[0]);
                buf[8] = b'-';
                (buf[9], buf[10]) = byte_to_ascii_hex_lower(self.time_mid[1]);
                (buf[11], buf[12]) = byte_to_ascii_hex_lower(self.time_mid[0]);
                buf[13] = b'-';
                (buf[14], buf[15]) =
                    byte_to_ascii_hex_lower(self.time_high_and_version[1]);
                (buf[16], buf[17]) =
                    byte_to_ascii_hex_lower(self.time_high_and_version[0]);
                buf[18] = b'-';
                (buf[19], buf[20]) =
                    byte_to_ascii_hex_lower(self.clock_seq_high_and_reserved);
                (buf[21], buf[22]) = byte_to_ascii_hex_lower(self.clock_seq_low);
                buf[23] = b'-';
                (buf[24], buf[25]) = byte_to_ascii_hex_lower(self.node[0]);
                (buf[26], buf[27]) = byte_to_ascii_hex_lower(self.node[1]);
                (buf[28], buf[29]) = byte_to_ascii_hex_lower(self.node[2]);
                (buf[30], buf[31]) = byte_to_ascii_hex_lower(self.node[3]);
                (buf[32], buf[33]) = byte_to_ascii_hex_lower(self.node[4]);
                (buf[34], buf[35]) = byte_to_ascii_hex_lower(self.node[5]);
                buf
            }
        }

        impl Default for $struct_name {
            fn default() -> Self {
                Self::ZERO
            }
        }

        impl Display for $struct_name {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                let ascii = self.to_ascii_hex_lower();
                // OK to unwrap since the ascii output is valid utf-8.
                let s = str::from_utf8(&ascii).unwrap();
                f.write_str(s)
            }
        }

        impl FromStr for $struct_name {
            type Err = GuidFromStrError;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                Self::try_parse(s)
            }
        }

        #[cfg(feature = "serde")]
        impl Serialize for $struct_name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                let ascii = self.to_ascii_hex_lower();
                // OK to unwrap since the ascii output is valid utf-8.
                let s = str::from_utf8(&ascii).unwrap();
                serializer.serialize_str(s)
            }
        }

        #[cfg(feature = "serde")]
        struct $deserializer_name;

        #[cfg(feature = "serde")]
        impl<'de> Visitor<'de> for $deserializer_name {
            type Value = $struct_name;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str(
                    "a string in the format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
                )
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                $struct_name::try_parse(value).map_err(E::custom)
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> Deserialize<'de> for $struct_name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                deserializer.deserialize_str($deserializer_name)
            }
        }
    }
}

guid_impl!(Guid, 1, GuidDeserializeVisitor);
guid_impl!(AlignedGuid, 8, AlignedGuidDeserializeVisitor);
<commit_msg>uguid: Improve struct docstrings<commit_after>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::util::{byte_to_ascii_hex_lower, parse_byte_from_ascii_str_at};
use crate::GuidFromStrError;
use core::fmt::{self, Display, Formatter};
use core::str::{self, FromStr};

#[cfg(feature = "serde")]
use {
    serde::de::{self, Visitor},
    serde::{Deserialize, Deserializer, Serialize, Serializer},
};

#[cfg(feature = "bytemuck")]
use bytemuck::{Pod, Zeroable};

/// Macro replacement for the `?` operator, which cannot be used in
/// const functions.
macro_rules! mtry {
    ($expr:expr $(,)?) => {
        match $expr {
            Ok(val) => val,
            Err(err) => {
                return Err(err);
            }
        }
    };
}

/// Define a GUID struct and its impls. This is used to create structs
/// that are the same but for alignment.
macro_rules! guid_impl {
    (
        // Name of the GUID struct.
        $struct_name:ident,
        // Struct alignment.
        $struct_alignment:literal,
        // Internal name of the struct for implementing deserialization.
        $deserializer_name:ident,
        // Struct docstring.
        $struct_doc:literal) => {
        #[doc = $struct_doc]
        #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
        #[cfg_attr(feature = "bytemuck", derive(Pod, Zeroable))]
        #[repr(C)]
        #[repr(align($struct_alignment))]
        pub struct $struct_name {
            /// The little-endian low field of the timestamp.
            pub time_low: [u8; 4],

            /// The little-endian middle field of the timestamp.
            pub time_mid: [u8; 2],

            /// The little-endian high field of the timestamp multiplexed with
            /// the version number.
            pub time_high_and_version: [u8; 2],

            /// The high field of the clock sequence multiplexed with the
            /// variant.
            pub clock_seq_high_and_reserved: u8,

            /// The low field of the clock sequence.
            pub clock_seq_low: u8,

            /// The spatially unique node identifier.
            pub node: [u8; 6],
        }

        impl $struct_name {
            /// GUID with all fields set to zero.
            pub const ZERO: Self =
                Self::new([0, 0, 0, 0], [0, 0], [0, 0], 0, 0, [0, 0, 0, 0, 0, 0]);

            /// Create a new GUID.
            #[must_use]
            pub const fn new(
                time_low: [u8; 4],
                time_mid: [u8; 2],
                time_high_and_version: [u8; 2],
                clock_seq_high_and_reserved: u8,
                clock_seq_low: u8,
                node: [u8; 6],
            ) -> Self {
                Self {
                    time_low,
                    time_mid,
                    time_high_and_version,
                    clock_seq_high_and_reserved,
                    clock_seq_low,
                    node,
                }
            }

            /// Parse a GUID from a string.
            ///
            /// This is functionally the same as [`Guid::from_str`], but is
            /// exposed separately to provide a `const` method for parsing.
            pub const fn try_parse(s: &str) -> Result<Self, GuidFromStrError> {
                // Treat input as ASCII.
                let s = s.as_bytes();

                if s.len() != 36 {
                    return Err(GuidFromStrError::Length);
                }

                let sep = b'-';
                if s[8] != sep {
                    return Err(GuidFromStrError::Separator(8));
                }
                if s[13] != sep {
                    return Err(GuidFromStrError::Separator(13));
                }
                if s[18] != sep {
                    return Err(GuidFromStrError::Separator(18));
                }
                if s[23] != sep {
                    return Err(GuidFromStrError::Separator(23));
                }

                Ok(Self {
                    time_low: [
                        mtry!(parse_byte_from_ascii_str_at(s, 6)),
                        mtry!(parse_byte_from_ascii_str_at(s, 4)),
                        mtry!(parse_byte_from_ascii_str_at(s, 2)),
                        mtry!(parse_byte_from_ascii_str_at(s, 0)),
                    ],
                    time_mid: [
                        mtry!(parse_byte_from_ascii_str_at(s, 11)),
                        mtry!(parse_byte_from_ascii_str_at(s, 9)),
                    ],
                    time_high_and_version: [
                        mtry!(parse_byte_from_ascii_str_at(s, 16)),
                        mtry!(parse_byte_from_ascii_str_at(s, 14)),
                    ],
                    clock_seq_high_and_reserved: mtry!(parse_byte_from_ascii_str_at(
                        s, 19
                    )),
                    clock_seq_low: mtry!(parse_byte_from_ascii_str_at(s, 21)),
                    node: [
                        mtry!(parse_byte_from_ascii_str_at(s, 24)),
                        mtry!(parse_byte_from_ascii_str_at(s, 26)),
                        mtry!(parse_byte_from_ascii_str_at(s, 28)),
                        mtry!(parse_byte_from_ascii_str_at(s, 30)),
                        mtry!(parse_byte_from_ascii_str_at(s, 32)),
                        mtry!(parse_byte_from_ascii_str_at(s, 34)),
                    ],
                })
            }

            /// Create a GUID from a 16-byte array. No changes to byte order are made.
            #[must_use]
            pub const fn from_bytes(bytes: [u8; 16]) -> Self {
                Self {
                    time_low: [bytes[0], bytes[1], bytes[2], bytes[3]],
                    time_mid: [bytes[4], bytes[5]],
                    time_high_and_version: [bytes[6], bytes[7]],
                    clock_seq_high_and_reserved: bytes[8],
                    clock_seq_low: bytes[9],
                    node: [
                        bytes[10], bytes[11], bytes[12], bytes[13], bytes[14],
                        bytes[15],
                    ],
                }
            }

            /// Convert to a 16-byte array.
            #[must_use]
            pub const fn to_bytes(self) -> [u8; 16] {
                [
                    self.time_low[0],
                    self.time_low[1],
                    self.time_low[2],
                    self.time_low[3],
                    self.time_mid[0],
                    self.time_mid[1],
                    self.time_high_and_version[0],
                    self.time_high_and_version[1],
                    self.clock_seq_high_and_reserved,
                    self.clock_seq_low,
                    self.node[0],
                    self.node[1],
                    self.node[2],
                    self.node[3],
                    self.node[4],
                    self.node[5],
                ]
            }

            /// Convert to a lower-case hex ASCII string.
            ///
            /// The output is in "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" format.
            #[must_use]
            pub const fn to_ascii_hex_lower(self) -> [u8; 36] {
                let mut buf = [0; 36];
                (buf[0], buf[1]) = byte_to_ascii_hex_lower(self.time_low[3]);
                (buf[2], buf[3]) = byte_to_ascii_hex_lower(self.time_low[2]);
                (buf[4], buf[5]) = byte_to_ascii_hex_lower(self.time_low[1]);
                (buf[6], buf[7]) = byte_to_ascii_hex_lower(self.time_low[0]);
                buf[8] = b'-';
                (buf[9], buf[10]) = byte_to_ascii_hex_lower(self.time_mid[1]);
                (buf[11], buf[12]) = byte_to_ascii_hex_lower(self.time_mid[0]);
                buf[13] = b'-';
                (buf[14], buf[15]) =
                    byte_to_ascii_hex_lower(self.time_high_and_version[1]);
                (buf[16], buf[17]) =
                    byte_to_ascii_hex_lower(self.time_high_and_version[0]);
                buf[18] = b'-';
                (buf[19], buf[20]) =
                    byte_to_ascii_hex_lower(self.clock_seq_high_and_reserved);
                (buf[21], buf[22]) = byte_to_ascii_hex_lower(self.clock_seq_low);
                buf[23] = b'-';
                (buf[24], buf[25]) = byte_to_ascii_hex_lower(self.node[0]);
                (buf[26], buf[27]) = byte_to_ascii_hex_lower(self.node[1]);
                (buf[28], buf[29]) = byte_to_ascii_hex_lower(self.node[2]);
                (buf[30], buf[31]) = byte_to_ascii_hex_lower(self.node[3]);
                (buf[32], buf[33]) = byte_to_ascii_hex_lower(self.node[4]);
                (buf[34], buf[35]) = byte_to_ascii_hex_lower(self.node[5]);
                buf
            }
        }

        impl Default for $struct_name {
            fn default() -> Self {
                Self::ZERO
            }
        }

        impl Display for $struct_name {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                let ascii = self.to_ascii_hex_lower();
                // OK to unwrap since the ascii output is valid utf-8.
                let s = str::from_utf8(&ascii).unwrap();
                f.write_str(s)
            }
        }

        impl FromStr for $struct_name {
            type Err = GuidFromStrError;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                Self::try_parse(s)
            }
        }

        #[cfg(feature = "serde")]
        impl Serialize for $struct_name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                let ascii = self.to_ascii_hex_lower();
                // OK to unwrap since the ascii output is valid utf-8.
                let s = str::from_utf8(&ascii).unwrap();
                serializer.serialize_str(s)
            }
        }

        #[cfg(feature = "serde")]
        struct $deserializer_name;

        #[cfg(feature = "serde")]
        impl<'de> Visitor<'de> for $deserializer_name {
            type Value = $struct_name;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str(
                    "a string in the format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
                )
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                $struct_name::try_parse(value).map_err(E::custom)
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> Deserialize<'de> for $struct_name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                deserializer.deserialize_str($deserializer_name)
            }
        }
    }
}

guid_impl!(
    Guid,
    1,
    GuidDeserializeVisitor,
    "Globally-unique identifier (byte aligned).

The format is described in Appendix A of the UEFI
Specification. Note that the first three fields are little-endian."
);

guid_impl!(
    AlignedGuid,
    8,
    AlignedGuidDeserializeVisitor,
    "Globally-unique identifier (8-byte aligned).

The format is described in Appendix A of the UEFI
Specification. Note that the first three fields are little-endian."
);
<|endoftext|>


<commit_before>use std::io::{Cursor, Read};
use std::error::Error;

// TODO: do not remove if in passage name, monospace etc.

pub fn screen<R: Read>(input: &mut R) -> Cursor<Vec<u8>> {

    let mut content = String::new();
    match input.read_to_string(&mut content) {
        Err(why) => panic!("could not read from input: {}", Error::description(&why)),
        Ok(_) => debug!("read input to buffer"),
    };

    let mut comment = false;
	let mut suspect_start = false;
	let mut suspect_end = false;
	let mut processed = String::new();

    //I really would have loved to use the chars iterator and filter or scan to perform this operation.
    //Sadly the comment blocks pervent this, as they depend on more then one chars to start
    //"fold" would have been possible, but is not more efficient then this old-school variant.
	for c in content.chars() {
		if !comment && !suspect_start && c == '/' {
			suspect_start = true;
			continue;
		}

		if suspect_start {
			if c == '%' {
				comment = true;
				suspect_start = false;
			} else {
				suspect_start = false;
				processed.push('/');
				processed.push(c);
			}

			continue;
		}

		if c == '%' && comment {
			suspect_end = true;
			continue;
		}

		if suspect_end {
			if c == '/' {
				comment = false;
				suspect_end = false;
			} else {
				suspect_end = false;
			}
			continue;
		}

		if !comment {
			processed.push(c);
		}
	}

    Cursor::new(processed.into_bytes())
}
<commit_msg>Iterators in the Screener!<commit_after>use std::io::{Cursor, Read};
use std::error::Error;
use utils::extensions::{QueuedScanExtension, QueuedScan};

// TODO: do not remove if in passage name, monospace etc.

struct ScanState {
    comment: bool,
    suspect_start: bool,
    suspect_end: bool,
}

pub fn screen<R: Read>(input: &mut R) -> Cursor<Vec<u8>> {

    let mut content = String::new();
    match input.read_to_string(&mut content) {
        Err(why) => panic!("could not read from input: {}", Error::description(&why)),
        Ok(_) => debug!("read input to buffer"),
    };

    let mut comment = false;
	let mut suspect_start = false;
	let mut suspect_end = false;
	let mut processed = String::new();

    Cursor::new(content.chars().queued_scan(
        ScanState {
            comment: false,
            suspect_start: false,
            suspect_end: false
        },
        |&mut state, maybe_char, queue| {
            match maybe_char {
                Some(c) => {
                    if !state.comment && !state.suspect_start && c == '/' {
                        state.suspect_start = true;
            			return true;
            		}

            		if state.suspect_start {
            			if c == '%' {
                            state.comment = true;
                            state.suspect_start = false;
            			} else {
                            state.suspect_start = false;
            				queue.push_back('/');
                            queue.push_back(c);
            			}
                        return true;
            		}

            		if c == '%' && state.comment {
                        state.suspect_end = true;
                        return true;
            		}

            		if state.suspect_end {
            			if c == '/' {
                            state.comment = false;
                            state.suspect_end = false;
            			} else {
                            state.suspect_end = false;
            			}
                        return true;
            		}

            		if !state.comment {
                        queue.push_back(c);
            		}

                    true
                },
                None => false
            }
        }
    ).map(|x: char| {x as u8}).collect())
}
<|endoftext|>


<commit_before>use num::Complex;

pub fn butterfly_2(input: &[Complex<f32>],
               input_stride: usize,
               output: &mut [Complex<f32>],
               output_stride: usize,
               twiddles: &[Complex<f32>],
               num_rows: usize) {
    let mut out_idx_1 = 0us;
    let mut out_idx_2 = num_rows * output_stride;
    let mut twiddle_idx = 0us;
    let mut row = input.as_ptr();
    let input_stride = input_stride as isize;
    for _ in range(0, num_rows) {
        unsafe {
            let twiddle = twiddles.get_unchecked(twiddle_idx);
            *output.get_unchecked_mut(out_idx_1) =
                *row.offset(0) + *row.offset(input_stride) * twiddle;
            *output.get_unchecked_mut(out_idx_2) =
                *row.offset(0) - *row.offset(input_stride) * twiddle;
        }
        out_idx_1 += output_stride;
        out_idx_2 += output_stride;
        twiddle_idx += input_stride as usize;
        row = unsafe { row.offset(2 * input_stride) };
    }
}
<commit_msg>Store multiplication to avoid two multiplications. Small performance improvement<commit_after>use num::Complex;

pub fn butterfly_2(input: &[Complex<f32>],
               input_stride: usize,
               output: &mut [Complex<f32>],
               output_stride: usize,
               twiddles: &[Complex<f32>],
               num_rows: usize) {
    let mut out_idx_1 = 0us;
    let mut out_idx_2 = num_rows * output_stride;
    let mut twiddle_idx = 0us;
    let mut row = input.as_ptr();
    let input_stride = input_stride as isize;
    for _ in range(0, num_rows) {
        unsafe {
            let twiddle = twiddles.get_unchecked(twiddle_idx);
            let prod = *row.offset(input_stride) * twiddle;
            *output.get_unchecked_mut(out_idx_1) =
                *row.offset(0) + prod;
            *output.get_unchecked_mut(out_idx_2) =
                *row.offset(0) - prod;
        }
        out_idx_1 += output_stride;
        out_idx_2 += output_stride;
        twiddle_idx += input_stride as usize;
        row = unsafe { row.offset(2 * input_stride) };
    }
}
<|endoftext|>


<commit_before>use clap::{Arg, ArgGroup, App, SubCommand};

pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
    app
        .subcommand(SubCommand::with_name("internal")
                    .about("Add, remove and list internal links")
                    .version("0.1")
                    .subcommand(SubCommand::with_name("add")
                                .about("Add link from one entry to another (and vice-versa)")
                                .version("0.1")
                                .arg(Arg::with_name("from")
                                     .long("from")
                                     .short("f")
                                     .takes_value(true)
                                     .required(true)
                                     .help("Link from this entry"))
                                .arg(Arg::with_name("to")
                                     .long("to")
                                     .short("t")
                                     .takes_value(true)
                                     .required(true)
                                     .multiple(true)
                                     .help("Link to this entries"))
                                )

                    .subcommand(SubCommand::with_name("remove")
                            .about("Remove a link between two or more entries")
                            .version("0.1")
                            .arg(Arg::with_name("from")
                                 .long("from")
                                 .short("f")
                                 .takes_value(true)
                                 .required(true)
                                 .help("Remove Link from this entry"))
                            .arg(Arg::with_name("to")
                                 .long("to")
                                 .short("t")
                                 .takes_value(true)
                                 .required(true)
                                 .multiple(true)
                                 .help("Remove links to these entries"))
                            )

                    .arg(Arg::with_name("list")
                         .long("list")
                         .short("l")
                         .takes_value(true)
                         .required(false)
                         .help("List links to this entry"))
                    )
        .subcommand(SubCommand::with_name("external")
                    .about("Add and remove external links")
                    .version("0.1")

                    .arg(Arg::with_name("id")
                         .long("id")
                         .short("i")
                         .takes_value(true)
                         .required(true)
                         .help("Modify external link of this entry"))

                    .arg(Arg::with_name("add")
                         .long("add")
                         .short("a")
                         .takes_value(true)
                         .required(false)
                         .help("Add this URI as external link"))

                    .arg(Arg::with_name("remove")
                         .long("remove")
                         .short("r")
                         .takes_value(false)
                         .required(false)
                         .help("Remove one external link"))

                    .arg(Arg::with_name("set")
                         .long("set")
                         .short("s")
                         .takes_value(true)
                         .required(false)
                         .help("Set these URIs as external link (seperate by comma)"))

                    .arg(Arg::with_name("list")
                         .long("list")
                         .short("l")
                         .takes_value(false)
                         .required(false)
                         .help("List external links"))

                    .group(ArgGroup::with_name("external-link-group")
                           .args(&["add", "remove", "set", "list"])
                           .required(true))

                    )
}

<commit_msg>Add value_name() call in ui specification code<commit_after>use clap::{Arg, ArgGroup, App, SubCommand};

pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
    app
        .subcommand(SubCommand::with_name("internal")
                    .about("Add, remove and list internal links")
                    .version("0.1")
                    .subcommand(SubCommand::with_name("add")
                                .about("Add link from one entry to another (and vice-versa)")
                                .version("0.1")
                                .arg(Arg::with_name("from")
                                     .long("from")
                                     .short("f")
                                     .takes_value(true)
                                     .required(true)
                                     .help("Link from this entry")
                                     .value_name("ENTRY"))
                                .arg(Arg::with_name("to")
                                     .long("to")
                                     .short("t")
                                     .takes_value(true)
                                     .required(true)
                                     .multiple(true)
                                     .help("Link to this entries")
                                     .value_name("ENTRIES"))
                                )

                    .subcommand(SubCommand::with_name("remove")
                            .about("Remove a link between two or more entries")
                            .version("0.1")
                            .arg(Arg::with_name("from")
                                 .long("from")
                                 .short("f")
                                 .takes_value(true)
                                 .required(true)
                                 .help("Remove Link from this entry")
                                 .value_name("ENTRY"))
                            .arg(Arg::with_name("to")
                                 .long("to")
                                 .short("t")
                                 .takes_value(true)
                                 .required(true)
                                 .multiple(true)
                                 .help("Remove links to these entries")
                                 .value_name("ENTRIES"))
                            )

                    .arg(Arg::with_name("list")
                         .long("list")
                         .short("l")
                         .takes_value(true)
                         .required(false)
                         .help("List links to this entry")
                         .value_name("ENTRY"))
                    )
        .subcommand(SubCommand::with_name("external")
                    .about("Add and remove external links")
                    .version("0.1")

                    .arg(Arg::with_name("id")
                         .long("id")
                         .short("i")
                         .takes_value(true)
                         .required(true)
                         .help("Modify external link of this entry")
                         .value_name("ENTRY"))

                    .arg(Arg::with_name("add")
                         .long("add")
                         .short("a")
                         .takes_value(true)
                         .required(false)
                         .help("Add this URI as external link")
                         .value_name("URI"))

                    .arg(Arg::with_name("remove")
                         .long("remove")
                         .short("r")
                         .takes_value(false)
                         .required(false)
                         .help("Remove one external link"))

                    .arg(Arg::with_name("set")
                         .long("set")
                         .short("s")
                         .takes_value(true)
                         .required(false)
                         .help("Set these URIs as external link (seperate by comma)")
                         .value_name("URIs"))

                    .arg(Arg::with_name("list")
                         .long("list")
                         .short("l")
                         .takes_value(false)
                         .required(false)
                         .help("List external links"))

                    .group(ArgGroup::with_name("external-link-group")
                           .args(&["add", "remove", "set", "list"])
                           .required(true))

                    )
}
<|endoftext|>


<commit_before>use clap::{Arg, App, ArgGroup, SubCommand};

pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
    app
        .arg(Arg::with_name("id")
            .long("id")
            .short("i")
            .takes_value(true)
            .required(true)
            .help("View this entry at this store path")
            .value_name("ID"))

        .arg(Arg::with_name("version")
            .long("version")
            .short("V")
            .takes_value(true)
            .required(false)
            .help("View this version (youngest if not specified)")
            .value_name("VERSION"))

        .arg(Arg::with_name("versions")
            .long("versions")
            .takes_value(false)
            .required(false)
            .help("Only print available versions for this file"))

        .arg(Arg::with_name("view-header")
            .long("header")
            .short("h")
            .takes_value(false)
            .required(false)
            .help("View header"))
        .arg(Arg::with_name("view-content")
            .long("content")
            .short("C")
            .takes_value(false)
            .required(false)
            .help("View content"))

        .arg(Arg::with_name("view-copy")
            .long("copy")
            .takes_value(false)
            .required(false)
            .help("Copy before opening (copies to /tmp/) and removes the file after viewing."))

        .arg(Arg::with_name("keep-copy")
            .long("keep-copy")
            .short("k")
            .takes_value(false)
            .required(false)
            .help("If --copy was passed, keep the copy after viewing."))

        .subcommand(SubCommand::with_name("view-in")
                   .about("View the entry in ...")
                   .version("0.1")

                   .arg(Arg::with_name("view-in-stdout")
                        .long("stdout")
                        .short("s")
                        .takes_value(false)
                        .required(false)
                        .help("View by printing to stdout"))

                   .arg(Arg::with_name("view-in-ui")
                        .long("ui")
                        .short("u")
                        .takes_value(false)
                        .required(false)
                        .help("View by opening own curses-like UI (default)"))

                   .arg(Arg::with_name("view-in-browser")
                        .long("browser")
                        .short("b")
                        .takes_value(true) // optional, which browser
                        .required(false)
                        .help("View content in $BROWSER (fails if no env variable $BROWSER)")
                        .value_name("BROWSER"))

                   .arg(Arg::with_name("view-in-texteditor")
                        .long("editor")
                        .short("e")
                        .takes_value(true) // optional, which editor
                        .required(false)
                        .help("View content in $EDITOR")
                        .value_name("EDITOR"))

                   .arg(Arg::with_name("view-in-custom")
                        .long("custom")
                        .short("c")
                        .takes_value(true) // non-optional, call-string
                        .required(false)
                        .help("View content in custom program, for example 'libreoffice %e', replace '%e' with entry path")
                        .value_name("PROGRAM"))

                   .group(ArgGroup::with_name("viewer")
                          .args(&["view-in-stdout",
                                  "view-in-ui",
                                  "view-in-browser",
                                  "view-in-texteditor",
                                  "view-in-custom",
                          ])
                          .required(false))
                   )

        .subcommand(SubCommand::with_name("compile")
                   .about("Compile content to other format for viewing, implies that the entry gets copied to /tmp")
                   .version("0.1")
                   .arg(Arg::with_name("from")
                        .long("from")
                        .short("f")
                        .takes_value(true) // "markdown" or "textile" or "restructuredtex"
                        .required(true)
                        .help("Compile from")
                        .value_name("FORMAT"))

                   .arg(Arg::with_name("to")
                        .long("to")
                        .short("t")
                        .takes_value(true) // "html" or "HTML" or ... json maybe?
                        .required(true)
                        .help("Compile to")
                        .value_name("FORMAT"))
                   )
}
<commit_msg>Version part should be enforced<commit_after>use clap::{Arg, App, ArgGroup, SubCommand};

pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
    app
        .arg(Arg::with_name("id")
            .long("id")
            .short("i")
            .takes_value(true)
            .required(true)
            .help("View this entry at this store path")
            .value_name("ID"))

        .arg(Arg::with_name("version")
            .long("version")
            .short("V")
            .takes_value(true)
            .required(true)
            .help("View this version (youngest if not specified)")
            .value_name("VERSION"))

        .arg(Arg::with_name("versions")
            .long("versions")
            .takes_value(false)
            .required(false)
            .help("Only print available versions for this file"))

        .arg(Arg::with_name("view-header")
            .long("header")
            .short("h")
            .takes_value(false)
            .required(false)
            .help("View header"))
        .arg(Arg::with_name("view-content")
            .long("content")
            .short("C")
            .takes_value(false)
            .required(false)
            .help("View content"))

        .arg(Arg::with_name("view-copy")
            .long("copy")
            .takes_value(false)
            .required(false)
            .help("Copy before opening (copies to /tmp/) and removes the file after viewing."))

        .arg(Arg::with_name("keep-copy")
            .long("keep-copy")
            .short("k")
            .takes_value(false)
            .required(false)
            .help("If --copy was passed, keep the copy after viewing."))

        .subcommand(SubCommand::with_name("view-in")
                   .about("View the entry in ...")
                   .version("0.1")

                   .arg(Arg::with_name("view-in-stdout")
                        .long("stdout")
                        .short("s")
                        .takes_value(false)
                        .required(false)
                        .help("View by printing to stdout"))

                   .arg(Arg::with_name("view-in-ui")
                        .long("ui")
                        .short("u")
                        .takes_value(false)
                        .required(false)
                        .help("View by opening own curses-like UI (default)"))

                   .arg(Arg::with_name("view-in-browser")
                        .long("browser")
                        .short("b")
                        .takes_value(true) // optional, which browser
                        .required(false)
                        .help("View content in $BROWSER (fails if no env variable $BROWSER)")
                        .value_name("BROWSER"))

                   .arg(Arg::with_name("view-in-texteditor")
                        .long("editor")
                        .short("e")
                        .takes_value(true) // optional, which editor
                        .required(false)
                        .help("View content in $EDITOR")
                        .value_name("EDITOR"))

                   .arg(Arg::with_name("view-in-custom")
                        .long("custom")
                        .short("c")
                        .takes_value(true) // non-optional, call-string
                        .required(false)
                        .help("View content in custom program, for example 'libreoffice %e', replace '%e' with entry path")
                        .value_name("PROGRAM"))

                   .group(ArgGroup::with_name("viewer")
                          .args(&["view-in-stdout",
                                  "view-in-ui",
                                  "view-in-browser",
                                  "view-in-texteditor",
                                  "view-in-custom",
                          ])
                          .required(false))
                   )

        .subcommand(SubCommand::with_name("compile")
                   .about("Compile content to other format for viewing, implies that the entry gets copied to /tmp")
                   .version("0.1")
                   .arg(Arg::with_name("from")
                        .long("from")
                        .short("f")
                        .takes_value(true) // "markdown" or "textile" or "restructuredtex"
                        .required(true)
                        .help("Compile from")
                        .value_name("FORMAT"))

                   .arg(Arg::with_name("to")
                        .long("to")
                        .short("t")
                        .takes_value(true) // "html" or "HTML" or ... json maybe?
                        .required(true)
                        .help("Compile to")
                        .value_name("FORMAT"))
                   )
}
<|endoftext|>


<commit_before>use std::env;
use std::fs;

use protobuf_codegen_pure::Customize;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();

    // We generate descriptors twice: with pure rust codegen
    // and with codegen depending on `protoc` binary.
    // This is for demonstration purposes; in practice you'd need either of them.
    //
    // Note there's a third option: using `protoc` binary directly and `protoc-gen-rust`
    // plugin, this is a canonical way to generate protobuf sources.
    // This is not possible to do with Cargo (since Cargo cannot depend on binaries)
    // but can be used with some other build system.

    let generated_with_pure_dir = format!("{}/generated_with_pure", out_dir);
    let generated_with_native_dir = format!("{}/generated_with_native", out_dir);

    fs::remove_dir_all(&generated_with_pure_dir).unwrap();
    fs::remove_dir_all(&generated_with_native_dir).unwrap();
    fs::create_dir(&generated_with_pure_dir).unwrap();
    fs::create_dir(&generated_with_native_dir).unwrap();

    protobuf_codegen_pure::Codegen::new()
        .customize(Customize {
            gen_mod_rs: Some(true),
            ..Default::default()
        })
        .out_dir(generated_with_pure_dir)
        .input("src/protos/example.proto")
        .include("src/protos")
        .run()
        .expect("protoc");

    protoc_rust::Codegen::new()
        .customize(Customize {
            gen_mod_rs: Some(true),
            ..Default::default()
        })
        .out_dir(generated_with_native_dir)
        .input("src/protos/example.proto")
        .include("src/protos")
        .run()
        .expect("protoc");
}
<commit_msg>Fix build when directory exists<commit_after>use std::env;
use std::fs;

use protobuf_codegen_pure::Customize;
use std::path::Path;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();

    // We generate descriptors twice: with pure rust codegen
    // and with codegen depending on `protoc` binary.
    // This is for demonstration purposes; in practice you'd need either of them.
    //
    // Note there's a third option: using `protoc` binary directly and `protoc-gen-rust`
    // plugin, this is a canonical way to generate protobuf sources.
    // This is not possible to do with Cargo (since Cargo cannot depend on binaries)
    // but can be used with some other build system.

    let generated_with_pure_dir = format!("{}/generated_with_pure", out_dir);
    let generated_with_native_dir = format!("{}/generated_with_native", out_dir);

    if Path::new(&generated_with_pure_dir).exists() {
        fs::remove_dir_all(&generated_with_pure_dir).unwrap();
    }
    if Path::new(&generated_with_native_dir).exists() {
        fs::remove_dir_all(&generated_with_native_dir).unwrap();
    }
    fs::create_dir(&generated_with_pure_dir).unwrap();
    fs::create_dir(&generated_with_native_dir).unwrap();

    protobuf_codegen_pure::Codegen::new()
        .customize(Customize {
            gen_mod_rs: Some(true),
            ..Default::default()
        })
        .out_dir(generated_with_pure_dir)
        .input("src/protos/example.proto")
        .include("src/protos")
        .run()
        .expect("protoc");

    protoc_rust::Codegen::new()
        .customize(Customize {
            gen_mod_rs: Some(true),
            ..Default::default()
        })
        .out_dir(generated_with_native_dir)
        .input("src/protos/example.proto")
        .include("src/protos")
        .run()
        .expect("protoc");
}
<|endoftext|>


<commit_before>use na::{DefaultAllocator, RealField};

use crate::aliases::{TVec, TVec3};
use crate::traits::{Alloc, Dimension, Number};

/// The cross product of two vectors.
pub fn cross<N: Number, D: Dimension>(x: &TVec3<N>, y: &TVec3<N>) -> TVec3<N> {
    x.cross(y)
}

/// The distance between two points.
///
/// # See also:
///
/// * [`distance2`](fn.distance2.html)
pub fn distance<N: RealField, D: Dimension>(p0: &TVec<N, D>, p1: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
    (p1 - p0).norm()
}

/// The dot product of two vectors.
pub fn dot<N: Number, D: Dimension>(x: &TVec<N, D>, y: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
    x.dot(y)
}

/// If `dot(nref, i) < 0.0`, return `n`, otherwise, return `-n`.
pub fn faceforward<N: Number, D: Dimension>(
    n: &TVec<N, D>,
    i: &TVec<N, D>,
    nref: &TVec<N, D>,
) -> TVec<N, D>
where
    DefaultAllocator: Alloc<N, D>,
{
    if nref.dot(i) < N::zero() {
        n.clone()
    } else {
        -n.clone()
    }
}

/// The magnitude of a vector.
///
/// A synonym for [`magnitude`](fn.magnitude.html).
///
/// # See also:
///
/// * [`length2`](fn.length2.html)
/// * [`magnitude`](fn.magnitude.html)
/// * [`magnitude2`](fn.magnitude2.html)
pub fn length<N: RealField, D: Dimension>(x: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
    x.norm()
}

/// The magnitude of a vector.
///
/// A wrapper around [`nalgebra::norm`](../nalgebra/fn.norm.html).
///
/// # See also:
///
/// * [`length`](fn.length.html)
/// * [`magnitude2`](fn.magnitude2.html)
/// * [`nalgebra::norm`](../nalgebra/fn.norm.html)
pub fn magnitude<N: RealField, D: Dimension>(x: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
    x.norm()
}

/// Normalizes a vector.
pub fn normalize<N: RealField, D: Dimension>(x: &TVec<N, D>) -> TVec<N, D>
where DefaultAllocator: Alloc<N, D> {
    x.normalize()
}

/// For the incident vector `i` and surface orientation `n`, returns the reflection direction : `result = i - 2.0 * dot(n, i) * n`.
pub fn reflect_vec<N: Number, D: Dimension>(i: &TVec<N, D>, n: &TVec<N, D>) -> TVec<N, D>
where DefaultAllocator: Alloc<N, D> {
    let _2 = N::one() + N::one();
    i - n * (n.dot(i) * _2)
}

/// For the incident vector `i` and surface normal `n`, and the ratio of indices of refraction `eta`, return the refraction vector.
pub fn refract_vec<N: RealField, D: Dimension>(i: &TVec<N, D>, n: &TVec<N, D>, eta: N) -> TVec<N, D>
where DefaultAllocator: Alloc<N, D> {
    let ni = n.dot(i);
    let k = N::one() - eta * eta * (N::one() - ni * ni);

    if k < N::zero() {
        TVec::<_, D>::zeros()
    } else {
        i * eta - n * (eta * dot(n, i) + k.sqrt())
    }
}
<commit_msg>Fixes #637: removes not used parameter from cross<commit_after>use na::{DefaultAllocator, RealField};

use crate::aliases::{TVec, TVec3};
use crate::traits::{Alloc, Dimension, Number};

/// The cross product of two vectors.
pub fn cross<N: Number>(x: &TVec3<N>, y: &TVec3<N>) -> TVec3<N> {
    x.cross(y)
}

/// The distance between two points.
///
/// # See also:
///
/// * [`distance2`](fn.distance2.html)
pub fn distance<N: RealField, D: Dimension>(p0: &TVec<N, D>, p1: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
    (p1 - p0).norm()
}

/// The dot product of two vectors.
pub fn dot<N: Number, D: Dimension>(x: &TVec<N, D>, y: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
    x.dot(y)
}

/// If `dot(nref, i) < 0.0`, return `n`, otherwise, return `-n`.
pub fn faceforward<N: Number, D: Dimension>(
    n: &TVec<N, D>,
    i: &TVec<N, D>,
    nref: &TVec<N, D>,
) -> TVec<N, D>
where
    DefaultAllocator: Alloc<N, D>,
{
    if nref.dot(i) < N::zero() {
        n.clone()
    } else {
        -n.clone()
    }
}

/// The magnitude of a vector.
///
/// A synonym for [`magnitude`](fn.magnitude.html).
///
/// # See also:
///
/// * [`length2`](fn.length2.html)
/// * [`magnitude`](fn.magnitude.html)
/// * [`magnitude2`](fn.magnitude2.html)
pub fn length<N: RealField, D: Dimension>(x: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
    x.norm()
}

/// The magnitude of a vector.
///
/// A wrapper around [`nalgebra::norm`](../nalgebra/fn.norm.html).
///
/// # See also:
///
/// * [`length`](fn.length.html)
/// * [`magnitude2`](fn.magnitude2.html)
/// * [`nalgebra::norm`](../nalgebra/fn.norm.html)
pub fn magnitude<N: RealField, D: Dimension>(x: &TVec<N, D>) -> N
where DefaultAllocator: Alloc<N, D> {
    x.norm()
}

/// Normalizes a vector.
pub fn normalize<N: RealField, D: Dimension>(x: &TVec<N, D>) -> TVec<N, D>
where DefaultAllocator: Alloc<N, D> {
    x.normalize()
}

/// For the incident vector `i` and surface orientation `n`, returns the reflection direction : `result = i - 2.0 * dot(n, i) * n`.
pub fn reflect_vec<N: Number, D: Dimension>(i: &TVec<N, D>, n: &TVec<N, D>) -> TVec<N, D>
where DefaultAllocator: Alloc<N, D> {
    let _2 = N::one() + N::one();
    i - n * (n.dot(i) * _2)
}

/// For the incident vector `i` and surface normal `n`, and the ratio of indices of refraction `eta`, return the refraction vector.
pub fn refract_vec<N: RealField, D: Dimension>(i: &TVec<N, D>, n: &TVec<N, D>, eta: N) -> TVec<N, D>
where DefaultAllocator: Alloc<N, D> {
    let ni = n.dot(i);
    let k = N::one() - eta * eta * (N::one() - ni * ni);

    if k < N::zero() {
        TVec::<_, D>::zeros()
    } else {
        i * eta - n * (eta * dot(n, i) + k.sqrt())
    }
}
<|endoftext|>


<commit_before>//! Applies pooling to the input.
//!
//! This layers looks at adjectant values of the input and then computes a
//! simple pooling operation over them (e.g. taking their maximum or average value).
//! *See [PoolingMode][pooling_mode]*
//!
//! [pooling_mode]: ./enum.PoolingMode.html
//!
//! ## Input Data
//!
//! The layer expects the input to be in either 4D NCHW (2 spatial dimensions)
//! or 5D NCDHW (3 spatial dimensions) format.

use super::FilterLayer;
use capnp_util::*;
use co::{IBackend, SharedTensor};
use conn;
use layer::*;
use juice_capnp::PoolingMode as CapnpPoolingMode;
use juice_capnp::pooling_config as capnp_config;
use std::rc::Rc;
use util::{ArcLock, cast_vec_usize_to_i32};

#[derive(Debug, Clone)]
/// [Pooling](./index.html) Layer
pub struct Pooling<T, B: conn::Pooling<T>> {
    mode: PoolingMode,

    filter_shape: Vec<usize>,
    stride: Vec<usize>,
    padding: Vec<usize>,

    pooling_configs: Vec<Rc<B::CPOOL>>,
}

impl<T, B: conn::Pooling<T>> Pooling<T, B> {
    /// Create a Pooling layer from a PoolingConfig.
    pub fn from_config(config: &PoolingConfig) -> Pooling<T, B> {
        Pooling {
            mode: config.mode,

            filter_shape: config.filter_shape.clone(),
            stride: config.stride.clone(),
            padding: config.padding.clone(),

            pooling_configs: vec![],
        }
    }
}

impl<T, B: conn::Pooling<T>> FilterLayer for Pooling<T, B> {
    /// Calculates the number of spatial dimensions for the pooling operation.
    fn num_spatial_dims(&self, input_shape: &[usize]) -> usize {
        match input_shape.len() {
            4 => 2,
            5 => 3,
            _ => panic!("A pooling layer currently only supports 4D or 5D input."),
        }
    }

    fn calculate_output_shape(&self, input_shape: &[usize]) -> Vec<usize> {
        let num_spatial_dims = self.num_spatial_dims(input_shape);
        let filter = self.spatial_filter_dims(num_spatial_dims);
        let padding = self.padding_dims(num_spatial_dims);
        let stride = self.stride_dims(num_spatial_dims);
        let mut output_shape = Vec::new();
        for dim in &input_shape[0..2].to_vec() {
            output_shape.push(*dim);
        }
        for spatial_dim in Self::calculate_spatial_output_dims(&input_shape[2..], &filter, &padding, &stride) {
            output_shape.push(spatial_dim);
        }

        output_shape
    }

    fn filter_shape(&self) -> &[usize] {
        &self.filter_shape
    }

    fn stride(&self) -> &[usize] {
        &self.stride
    }

    fn padding(&self) -> &[usize] {
        &self.padding
    }
}

impl<B: IBackend + conn::Pooling<f32>> ILayer<B> for Pooling<f32, B> {
    impl_ilayer_common!();

    fn reshape(&mut self,
               backend: ::std::rc::Rc<B>,
               input_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
               input_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
               weights_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
               weights_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
               output_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
               output_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>) {
        for i in 0..input_data.len() {
            let inp = input_data[0].read().unwrap();
            let input_shape = inp.desc();
            let output_shape = self.calculate_output_shape(input_shape);
            output_data[0].write().unwrap().resize(&output_shape).unwrap();
            output_gradient[0].write().unwrap().resize(&output_shape).unwrap();

            let num_spatial_dims = self.num_spatial_dims(inp.desc());
            let filter = cast_vec_usize_to_i32(self.spatial_filter_dims(num_spatial_dims));
            let stride = cast_vec_usize_to_i32(self.stride_dims(num_spatial_dims));
            let padding = cast_vec_usize_to_i32(self.padding_dims(num_spatial_dims));

            let config = backend.new_pooling_config(&filter, &padding, &stride).unwrap();
            self.pooling_configs.push(Rc::new(config));
        }
    }
}

impl<B: IBackend + conn::Pooling<f32>> ComputeOutput<f32, B> for Pooling<f32, B> {
    fn compute_output(&self,
                      backend: &B,
                      weights: &[&SharedTensor<f32>],
                      input_data: &[&SharedTensor<f32>],
                      output_data: &mut [&mut SharedTensor<f32>]) {
        let config = &self.pooling_configs[0];
        match self.mode {
            PoolingMode::Max => {
                backend.pooling_max(input_data[0], output_data[0], &*config)
                    .unwrap()
            }
            PoolingMode::Average => {
                backend.pooling_avg(input_data[0], output_data[0], &*config)
                    .unwrap()
            }
            _ => panic!("Unknown Parameter {:?} for PoolingMode", self.mode),
        }
    }
}

impl<B: IBackend + conn::Pooling<f32>> ComputeInputGradient<f32, B> for Pooling<f32, B> {
    fn compute_input_gradient(&self,
                              backend: &B,
                              _weights_data: &[&SharedTensor<f32>],
                              output_data: &[&SharedTensor<f32>],
                              output_gradients: &[&SharedTensor<f32>],
                              input_data: &[&SharedTensor<f32>],
                              input_gradients: &mut [&mut SharedTensor<f32>]) {
        let config = &self.pooling_configs[0];
        match self.mode {
            PoolingMode::Max => {
                backend.pooling_max_grad(output_data[0],
                                      output_gradients[0],
                                      input_data[0],
                                      input_gradients[0],
                                      config)
                    .unwrap()
            }
            PoolingMode::Average => {
                backend.pooling_avg_grad(output_data[0],
                                      output_gradients[0],
                                      input_data[0],
                                      input_gradients[0],
                                      config)
                    .unwrap()
            }
            _ => panic!("Unknown parameter {:?} for PoolingMode", self.mode),
        }
    }
}

impl<B: IBackend + conn::Pooling<f32>> ComputeParametersGradient<f32, B> for Pooling<f32, B> {}

#[derive(Debug, Clone)]
/// Specifies configuration parameters for a Pooling Layer.
pub struct PoolingConfig {
    /// The PoolingMode to use
    pub mode: PoolingMode,
    /// The shape of the filter
    pub filter_shape: Vec<usize>,
    /// The stride size
    pub stride: Vec<usize>,
    /// The padding size
    pub padding: Vec<usize>,
}

impl Into<LayerType> for PoolingConfig {
    fn into(self) -> LayerType {
        LayerType::Pooling(self)
    }
}

impl<'a> CapnpWrite<'a> for PoolingConfig {
    type Builder = capnp_config::Builder<'a>;

    /// Write the PoolingConfig into a capnp message.
    fn write_capnp(&self, builder: &mut Self::Builder) {
        builder.borrow().set_mode(self.mode.to_capnp());
        {
            let mut filter_shape = builder.borrow().init_filter_shape(self.filter_shape.len() as u32);
            for (i, dim) in self.filter_shape.iter().enumerate() {
                filter_shape.set(i as u32, *dim as u64);
            }
        }
        {
            let mut stride = builder.borrow().init_stride(self.stride.len() as u32);
            for (i, dim) in self.stride.iter().enumerate() {
                stride.set(i as u32, *dim as u64);
            }
        }
        {
            let mut padding = builder.borrow().init_padding(self.padding.len() as u32);
            for (i, dim) in self.padding.iter().enumerate() {
                padding.set(i as u32, *dim as u64);
            }
        }
    }
}

impl<'a> CapnpRead<'a> for PoolingConfig {
    type Reader = capnp_config::Reader<'a>;

    fn read_capnp(reader: Self::Reader) -> Self {
        let mode = PoolingMode::from_capnp(reader.get_mode().unwrap());

        let read_filter_shape = reader.get_filter_shape().unwrap();
        let mut filter_shape = Vec::new();
        for i in 0..read_filter_shape.len() {
            filter_shape.push(read_filter_shape.get(i) as usize)
        }
        let read_stride = reader.get_stride().unwrap();
        let mut stride = Vec::new();
        for i in 0..read_stride.len() {
            stride.push(read_stride.get(i) as usize)
        }
        let read_padding = reader.get_padding().unwrap();
        let mut padding = Vec::new();
        for i in 0..read_padding.len() {
            padding.push(read_padding.get(i) as usize)
        }

        PoolingConfig {
            mode: mode,
            filter_shape: filter_shape,
            stride: stride,
            padding: padding,
        }
    }
}

#[derive(Debug, Copy, Clone)]
/// The different modes of pooling that can be calculated.
pub enum PoolingMode {
    /// The maximum value inside the pooling window will be used as result.
    Max,
    /// The average of all values inside the pooling window will be used as result.
    Average,
}

impl PoolingMode {
    /// Return the corresponding Cap'n Proto value.
    fn to_capnp(&self) -> CapnpPoolingMode {
        match *self {
            PoolingMode::Max => CapnpPoolingMode::Max,
            PoolingMode::Average => CapnpPoolingMode::Average,
        }
    }

    /// Return the enum value for a Cap'n Proto value.
    fn from_capnp(value: CapnpPoolingMode) -> Self {
        match value {
            CapnpPoolingMode::Max => PoolingMode::Max,
            CapnpPoolingMode::Average => PoolingMode::Average,
        }
    }
}
<commit_msg>fix/layers: fixed regression in pooling layer signature change<commit_after>//! Applies pooling to the input.
//!
//! This layers looks at adjacent values of the input and then computes a
//! simple pooling operation over them (e.g. taking their maximum or average value).
//! *See [PoolingMode][pooling_mode]*
//!
//! [pooling_mode]: ./enum.PoolingMode.html
//!
//! ## Input Data
//!
//! The layer expects the input to be in either 4D NCHW (2 spatial dimensions)
//! or 5D NCDHW (3 spatial dimensions) format.

use super::FilterLayer;
use capnp_util::*;
use co::{IBackend, SharedTensor};
use conn;
use layer::*;
use juice_capnp::PoolingMode as CapnpPoolingMode;
use juice_capnp::pooling_config as capnp_config;
use std::rc::Rc;
use util::{ArcLock, cast_vec_usize_to_i32};

#[derive(Debug, Clone)]
/// [Pooling](./index.html) Layer
pub struct Pooling<T, B: conn::Pooling<T>> {
    mode: PoolingMode,

    filter_shape: Vec<usize>,
    stride: Vec<usize>,
    padding: Vec<usize>,

    pooling_configs: Vec<Rc<B::CPOOL>>,
}

impl<T, B: conn::Pooling<T>> Pooling<T, B> {
    /// Create a Pooling layer from a PoolingConfig.
    pub fn from_config(config: &PoolingConfig) -> Pooling<T, B> {
        Pooling {
            mode: config.mode,

            filter_shape: config.filter_shape.clone(),
            stride: config.stride.clone(),
            padding: config.padding.clone(),

            pooling_configs: vec![],
        }
    }
}

impl<T, B: conn::Pooling<T>> FilterLayer for Pooling<T, B> {
    /// Calculates the number of spatial dimensions for the pooling operation.
    fn num_spatial_dims(&self, input_shape: &[usize]) -> usize {
        match input_shape.len() {
            4 => 2,
            5 => 3,
            _ => panic!("A pooling layer currently only supports 4D or 5D input."),
        }
    }

    fn calculate_output_shape(&self, input_shape: &[usize]) -> Vec<usize> {
        let num_spatial_dims = self.num_spatial_dims(input_shape);
        let filter = self.spatial_filter_dims(num_spatial_dims);
        let padding = self.padding_dims(num_spatial_dims);
        let stride = self.stride_dims(num_spatial_dims);
        let mut output_shape = Vec::new();
        for dim in &input_shape[0..2].to_vec() {
            output_shape.push(*dim);
        }
        for spatial_dim in Self::calculate_spatial_output_dims(&input_shape[2..], &filter, &padding, &stride) {
            output_shape.push(spatial_dim);
        }

        output_shape
    }

    fn filter_shape(&self) -> &[usize] {
        &self.filter_shape
    }

    fn stride(&self) -> &[usize] {
        &self.stride
    }

    fn padding(&self) -> &[usize] {
        &self.padding
    }
}

impl<B: IBackend + conn::Pooling<f32>> ILayer<B> for Pooling<f32, B> {
    impl_ilayer_common!();

    fn reshape(&mut self,
               backend: ::std::rc::Rc<B>,
               input_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
               input_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
               weights_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
               weights_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>,
               output_data: &mut Vec<ArcLock<SharedTensor<f32>>>,
               output_gradient: &mut Vec<ArcLock<SharedTensor<f32>>>) {
        for i in 0..input_data.len() {
            let inp = input_data[0].read().unwrap();
            let input_shape = inp.desc();
            let output_shape = self.calculate_output_shape(input_shape);
            output_data[0].write().unwrap().resize(&output_shape).unwrap();
            output_gradient[0].write().unwrap().resize(&output_shape).unwrap();

            let num_spatial_dims = self.num_spatial_dims(inp.desc());
            let filter = cast_vec_usize_to_i32(self.spatial_filter_dims(num_spatial_dims));
            let stride = cast_vec_usize_to_i32(self.stride_dims(num_spatial_dims));
            let padding = cast_vec_usize_to_i32(self.padding_dims(num_spatial_dims));

            let config = backend.new_pooling_config(&filter, &stride, &padding).unwrap();
            self.pooling_configs.push(Rc::new(config));
        }
    }
}

impl<B: IBackend + conn::Pooling<f32>> ComputeOutput<f32, B> for Pooling<f32, B> {
    fn compute_output(&self,
                      backend: &B,
                      weights: &[&SharedTensor<f32>],
                      input_data: &[&SharedTensor<f32>],
                      output_data: &mut [&mut SharedTensor<f32>]) {
        let config = &self.pooling_configs[0];
        match self.mode {
            PoolingMode::Max => {
                backend.pooling_max(input_data[0], output_data[0], &*config)
                    .unwrap()
            }
            PoolingMode::Average => {
                backend.pooling_avg(input_data[0], output_data[0], &*config)
                    .unwrap()
            }
            _ => panic!("Unknown Parameter {:?} for PoolingMode", self.mode),
        }
    }
}

impl<B: IBackend + conn::Pooling<f32>> ComputeInputGradient<f32, B> for Pooling<f32, B> {
    fn compute_input_gradient(&self,
                              backend: &B,
                              _weights_data: &[&SharedTensor<f32>],
                              output_data: &[&SharedTensor<f32>],
                              output_gradients: &[&SharedTensor<f32>],
                              input_data: &[&SharedTensor<f32>],
                              input_gradients: &mut [&mut SharedTensor<f32>]) {
        let config = &self.pooling_configs[0];
        match self.mode {
            PoolingMode::Max => {
                backend.pooling_max_grad(output_data[0],
                                      output_gradients[0],
                                      input_data[0],
                                      input_gradients[0],
                                      config)
                    .unwrap()
            }
            PoolingMode::Average => {
                backend.pooling_avg_grad(output_data[0],
                                      output_gradients[0],
                                      input_data[0],
                                      input_gradients[0],
                                      config)
                    .unwrap()
            }
            _ => panic!("Unknown parameter {:?} for PoolingMode", self.mode),
        }
    }
}

impl<B: IBackend + conn::Pooling<f32>> ComputeParametersGradient<f32, B> for Pooling<f32, B> {}

#[derive(Debug, Clone)]
/// Specifies configuration parameters for a Pooling Layer.
pub struct PoolingConfig {
    /// The PoolingMode to use
    pub mode: PoolingMode,
    /// The shape of the filter
    pub filter_shape: Vec<usize>,
    /// The stride size
    pub stride: Vec<usize>,
    /// The padding size
    pub padding: Vec<usize>,
}

impl Into<LayerType> for PoolingConfig {
    fn into(self) -> LayerType {
        LayerType::Pooling(self)
    }
}

impl<'a> CapnpWrite<'a> for PoolingConfig {
    type Builder = capnp_config::Builder<'a>;

    /// Write the PoolingConfig into a capnp message.
    fn write_capnp(&self, builder: &mut Self::Builder) {
        builder.borrow().set_mode(self.mode.to_capnp());
        {
            let mut filter_shape = builder.borrow().init_filter_shape(self.filter_shape.len() as u32);
            for (i, dim) in self.filter_shape.iter().enumerate() {
                filter_shape.set(i as u32, *dim as u64);
            }
        }
        {
            let mut stride = builder.borrow().init_stride(self.stride.len() as u32);
            for (i, dim) in self.stride.iter().enumerate() {
                stride.set(i as u32, *dim as u64);
            }
        }
        {
            let mut padding = builder.borrow().init_padding(self.padding.len() as u32);
            for (i, dim) in self.padding.iter().enumerate() {
                padding.set(i as u32, *dim as u64);
            }
        }
    }
}

impl<'a> CapnpRead<'a> for PoolingConfig {
    type Reader = capnp_config::Reader<'a>;

    fn read_capnp(reader: Self::Reader) -> Self {
        let mode = PoolingMode::from_capnp(reader.get_mode().unwrap());

        let read_filter_shape = reader.get_filter_shape().unwrap();
        let mut filter_shape = Vec::new();
        for i in 0..read_filter_shape.len() {
            filter_shape.push(read_filter_shape.get(i) as usize)
        }
        let read_stride = reader.get_stride().unwrap();
        let mut stride = Vec::new();
        for i in 0..read_stride.len() {
            stride.push(read_stride.get(i) as usize)
        }
        let read_padding = reader.get_padding().unwrap();
        let mut padding = Vec::new();
        for i in 0..read_padding.len() {
            padding.push(read_padding.get(i) as usize)
        }

        PoolingConfig {
            mode: mode,
            filter_shape: filter_shape,
            stride: stride,
            padding: padding,
        }
    }
}

#[derive(Debug, Copy, Clone)]
/// The different modes of pooling that can be calculated.
pub enum PoolingMode {
    /// The maximum value inside the pooling window will be used as result.
    Max,
    /// The average of all values inside the pooling window will be used as result.
    Average,
}

impl PoolingMode {
    /// Return the corresponding Cap'n Proto value.
    fn to_capnp(&self) -> CapnpPoolingMode {
        match *self {
            PoolingMode::Max => CapnpPoolingMode::Max,
            PoolingMode::Average => CapnpPoolingMode::Average,
        }
    }

    /// Return the enum value for a Cap'n Proto value.
    fn from_capnp(value: CapnpPoolingMode) -> Self {
        match value {
            CapnpPoolingMode::Max => PoolingMode::Max,
            CapnpPoolingMode::Average => PoolingMode::Average,
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.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.

//! Some lints that are built in to the compiler.
//!
//! These are the built-in lints that are emitted direct in the main
//! compiler code, rather than using their own custom pass. Those
//! lints are all available in `rustc_lint::builtin`.

use lint::{LintPass, LateLintPass, LintArray};

declare_lint! {
    pub CONST_ERR,
    Warn,
    "constant evaluation detected erroneous expression"
}

declare_lint! {
    pub UNUSED_IMPORTS,
    Warn,
    "imports that are never used"
}

declare_lint! {
    pub UNUSED_EXTERN_CRATES,
    Allow,
    "extern crates that are never used"
}

declare_lint! {
    pub UNUSED_QUALIFICATIONS,
    Allow,
    "detects unnecessarily qualified names"
}

declare_lint! {
    pub UNKNOWN_LINTS,
    Warn,
    "unrecognized lint attribute"
}

declare_lint! {
    pub UNUSED_VARIABLES,
    Warn,
    "detect variables which are not used in any way"
}

declare_lint! {
    pub UNUSED_ASSIGNMENTS,
    Warn,
    "detect assignments that will never be read"
}

declare_lint! {
    pub DEAD_CODE,
    Warn,
    "detect unused, unexported items"
}

declare_lint! {
    pub UNREACHABLE_CODE,
    Warn,
    "detects unreachable code paths"
}

declare_lint! {
    pub WARNINGS,
    Warn,
    "mass-change the level for lints which produce warnings"
}

declare_lint! {
    pub UNUSED_FEATURES,
    Warn,
    "unused or unknown features found in crate-level #[feature] directives"
}

declare_lint! {
    pub STABLE_FEATURES,
    Warn,
    "stable features found in #[feature] directive"
}

declare_lint! {
    pub UNKNOWN_CRATE_TYPES,
    Deny,
    "unknown crate type found in #[crate_type] directive"
}

declare_lint! {
    pub FAT_PTR_TRANSMUTES,
    Allow,
    "detects transmutes of fat pointers"
}

declare_lint! {
    pub TRIVIAL_CASTS,
    Allow,
    "detects trivial casts which could be removed"
}

declare_lint! {
    pub TRIVIAL_NUMERIC_CASTS,
    Allow,
    "detects trivial casts of numeric types which could be removed"
}

declare_lint! {
    pub PRIVATE_IN_PUBLIC,
    Warn,
    "detect private items in public interfaces not caught by the old implementation"
}

declare_lint! {
    pub INACCESSIBLE_EXTERN_CRATE,
    Deny,
    "use of inaccessible extern crate erroneously allowed"
}

declare_lint! {
    pub INVALID_TYPE_PARAM_DEFAULT,
    Deny,
    "type parameter default erroneously allowed in invalid location"
}

declare_lint! {
    pub ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN,
    Deny,
    "floating-point constants cannot be used in patterns"
}

declare_lint! {
    pub ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN,
    Deny,
    "constants of struct or enum type can only be used in a pattern if \
     the struct or enum has `#[derive(PartialEq, Eq)]`"
}

declare_lint! {
    pub RAW_POINTER_DERIVE,
    Warn,
    "uses of #[derive] with raw pointers are rarely correct"
}

declare_lint! {
    pub TRANSMUTE_FROM_FN_ITEM_TYPES,
    Deny,
    "transmute from function item type to pointer-sized type erroneously allowed"
}

declare_lint! {
    pub HR_LIFETIME_IN_ASSOC_TYPE,
    Warn,
    "binding for associated type references higher-ranked lifetime \
     that does not appear in the trait input types"
}

declare_lint! {
    pub OVERLAPPING_INHERENT_IMPLS,
    Deny,
    "two overlapping inherent impls define an item with the same name were erroneously allowed"
}

declare_lint! {
    pub RENAMED_AND_REMOVED_LINTS,
    Warn,
    "lints that have been renamed or removed"
}

declare_lint! {
    pub SUPER_OR_SELF_IN_GLOBAL_PATH,
    Deny,
    "detects super or self keywords at the beginning of global path"
}

declare_lint! {
    pub LIFETIME_UNDERSCORE,
    Deny,
    "lifetimes or labels named `'_` were erroneously allowed"
}

declare_lint! {
    pub SAFE_EXTERN_STATICS,
    Warn,
    "safe access to extern statics was erroneously allowed"
}

declare_lint! {
    pub PATTERNS_IN_FNS_WITHOUT_BODY,
    Warn,
    "patterns in functions without body were erroneously allowed"
}

declare_lint! {
    pub EXTRA_REQUIREMENT_IN_IMPL,
    Warn,
    "detects extra requirements in impls that were erroneously allowed"
}

/// Does nothing as a lint pass, but registers some `Lint`s
/// which are used by other parts of the compiler.
#[derive(Copy, Clone)]
pub struct HardwiredLints;

impl LintPass for HardwiredLints {
    fn get_lints(&self) -> LintArray {
        lint_array!(
            UNUSED_IMPORTS,
            UNUSED_EXTERN_CRATES,
            UNUSED_QUALIFICATIONS,
            UNKNOWN_LINTS,
            UNUSED_VARIABLES,
            UNUSED_ASSIGNMENTS,
            DEAD_CODE,
            UNREACHABLE_CODE,
            WARNINGS,
            UNUSED_FEATURES,
            STABLE_FEATURES,
            UNKNOWN_CRATE_TYPES,
            FAT_PTR_TRANSMUTES,
            TRIVIAL_CASTS,
            TRIVIAL_NUMERIC_CASTS,
            PRIVATE_IN_PUBLIC,
            INACCESSIBLE_EXTERN_CRATE,
            INVALID_TYPE_PARAM_DEFAULT,
            ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN,
            ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN,
            CONST_ERR,
            RAW_POINTER_DERIVE,
            TRANSMUTE_FROM_FN_ITEM_TYPES,
            OVERLAPPING_INHERENT_IMPLS,
            RENAMED_AND_REMOVED_LINTS,
            SUPER_OR_SELF_IN_GLOBAL_PATH,
            HR_LIFETIME_IN_ASSOC_TYPE,
            LIFETIME_UNDERSCORE,
            SAFE_EXTERN_STATICS,
            PATTERNS_IN_FNS_WITHOUT_BODY,
            EXTRA_REQUIREMENT_IN_IMPL
        )
    }
}

impl LateLintPass for HardwiredLints {}
<commit_msg>make HR_LIFETIME_IN_ASSOC_TYPE deny-by-default<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.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.

//! Some lints that are built in to the compiler.
//!
//! These are the built-in lints that are emitted direct in the main
//! compiler code, rather than using their own custom pass. Those
//! lints are all available in `rustc_lint::builtin`.

use lint::{LintPass, LateLintPass, LintArray};

declare_lint! {
    pub CONST_ERR,
    Warn,
    "constant evaluation detected erroneous expression"
}

declare_lint! {
    pub UNUSED_IMPORTS,
    Warn,
    "imports that are never used"
}

declare_lint! {
    pub UNUSED_EXTERN_CRATES,
    Allow,
    "extern crates that are never used"
}

declare_lint! {
    pub UNUSED_QUALIFICATIONS,
    Allow,
    "detects unnecessarily qualified names"
}

declare_lint! {
    pub UNKNOWN_LINTS,
    Warn,
    "unrecognized lint attribute"
}

declare_lint! {
    pub UNUSED_VARIABLES,
    Warn,
    "detect variables which are not used in any way"
}

declare_lint! {
    pub UNUSED_ASSIGNMENTS,
    Warn,
    "detect assignments that will never be read"
}

declare_lint! {
    pub DEAD_CODE,
    Warn,
    "detect unused, unexported items"
}

declare_lint! {
    pub UNREACHABLE_CODE,
    Warn,
    "detects unreachable code paths"
}

declare_lint! {
    pub WARNINGS,
    Warn,
    "mass-change the level for lints which produce warnings"
}

declare_lint! {
    pub UNUSED_FEATURES,
    Warn,
    "unused or unknown features found in crate-level #[feature] directives"
}

declare_lint! {
    pub STABLE_FEATURES,
    Warn,
    "stable features found in #[feature] directive"
}

declare_lint! {
    pub UNKNOWN_CRATE_TYPES,
    Deny,
    "unknown crate type found in #[crate_type] directive"
}

declare_lint! {
    pub FAT_PTR_TRANSMUTES,
    Allow,
    "detects transmutes of fat pointers"
}

declare_lint! {
    pub TRIVIAL_CASTS,
    Allow,
    "detects trivial casts which could be removed"
}

declare_lint! {
    pub TRIVIAL_NUMERIC_CASTS,
    Allow,
    "detects trivial casts of numeric types which could be removed"
}

declare_lint! {
    pub PRIVATE_IN_PUBLIC,
    Warn,
    "detect private items in public interfaces not caught by the old implementation"
}

declare_lint! {
    pub INACCESSIBLE_EXTERN_CRATE,
    Deny,
    "use of inaccessible extern crate erroneously allowed"
}

declare_lint! {
    pub INVALID_TYPE_PARAM_DEFAULT,
    Deny,
    "type parameter default erroneously allowed in invalid location"
}

declare_lint! {
    pub ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN,
    Deny,
    "floating-point constants cannot be used in patterns"
}

declare_lint! {
    pub ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN,
    Deny,
    "constants of struct or enum type can only be used in a pattern if \
     the struct or enum has `#[derive(PartialEq, Eq)]`"
}

declare_lint! {
    pub RAW_POINTER_DERIVE,
    Warn,
    "uses of #[derive] with raw pointers are rarely correct"
}

declare_lint! {
    pub TRANSMUTE_FROM_FN_ITEM_TYPES,
    Deny,
    "transmute from function item type to pointer-sized type erroneously allowed"
}

declare_lint! {
    pub HR_LIFETIME_IN_ASSOC_TYPE,
    Deny,
    "binding for associated type references higher-ranked lifetime \
     that does not appear in the trait input types"
}

declare_lint! {
    pub OVERLAPPING_INHERENT_IMPLS,
    Deny,
    "two overlapping inherent impls define an item with the same name were erroneously allowed"
}

declare_lint! {
    pub RENAMED_AND_REMOVED_LINTS,
    Warn,
    "lints that have been renamed or removed"
}

declare_lint! {
    pub SUPER_OR_SELF_IN_GLOBAL_PATH,
    Deny,
    "detects super or self keywords at the beginning of global path"
}

declare_lint! {
    pub LIFETIME_UNDERSCORE,
    Deny,
    "lifetimes or labels named `'_` were erroneously allowed"
}

declare_lint! {
    pub SAFE_EXTERN_STATICS,
    Warn,
    "safe access to extern statics was erroneously allowed"
}

declare_lint! {
    pub PATTERNS_IN_FNS_WITHOUT_BODY,
    Warn,
    "patterns in functions without body were erroneously allowed"
}

declare_lint! {
    pub EXTRA_REQUIREMENT_IN_IMPL,
    Warn,
    "detects extra requirements in impls that were erroneously allowed"
}

/// Does nothing as a lint pass, but registers some `Lint`s
/// which are used by other parts of the compiler.
#[derive(Copy, Clone)]
pub struct HardwiredLints;

impl LintPass for HardwiredLints {
    fn get_lints(&self) -> LintArray {
        lint_array!(
            UNUSED_IMPORTS,
            UNUSED_EXTERN_CRATES,
            UNUSED_QUALIFICATIONS,
            UNKNOWN_LINTS,
            UNUSED_VARIABLES,
            UNUSED_ASSIGNMENTS,
            DEAD_CODE,
            UNREACHABLE_CODE,
            WARNINGS,
            UNUSED_FEATURES,
            STABLE_FEATURES,
            UNKNOWN_CRATE_TYPES,
            FAT_PTR_TRANSMUTES,
            TRIVIAL_CASTS,
            TRIVIAL_NUMERIC_CASTS,
            PRIVATE_IN_PUBLIC,
            INACCESSIBLE_EXTERN_CRATE,
            INVALID_TYPE_PARAM_DEFAULT,
            ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN,
            ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN,
            CONST_ERR,
            RAW_POINTER_DERIVE,
            TRANSMUTE_FROM_FN_ITEM_TYPES,
            OVERLAPPING_INHERENT_IMPLS,
            RENAMED_AND_REMOVED_LINTS,
            SUPER_OR_SELF_IN_GLOBAL_PATH,
            HR_LIFETIME_IN_ASSOC_TYPE,
            LIFETIME_UNDERSCORE,
            SAFE_EXTERN_STATICS,
            PATTERNS_IN_FNS_WITHOUT_BODY,
            EXTRA_REQUIREMENT_IN_IMPL
        )
    }
}

impl LateLintPass for HardwiredLints {}
<|endoftext|>