Bug 1878536 - Update bindgen to 0.69.4. r=glandium,supply-chain-reviewers

Differential Revision: https://phabricator.services.mozilla.com/D200580
This commit is contained in:
Emilio Cobos Álvarez 2024-02-09 15:49:55 +00:00
parent 63ba6c1626
commit 1f8082fd46
23 changed files with 192 additions and 469 deletions

32
Cargo.lock generated
View file

@ -418,21 +418,21 @@ dependencies = [
name = "bindgen"
version = "0.63.999"
dependencies = [
"bindgen 0.69.2",
"bindgen 0.69.4",
]
[[package]]
name = "bindgen"
version = "0.69.2"
version = "0.69.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4c69fae65a523209d34240b60abe0c42d33d1045d445c0839d8a4894a736e2d"
checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0"
dependencies = [
"bitflags 2.4.1",
"cexpr",
"clang-sys",
"itertools",
"lazy_static",
"lazycell",
"peeking_take_while",
"proc-macro2",
"quote",
"regex",
@ -570,7 +570,7 @@ dependencies = [
name = "builtins-static"
version = "0.1.0"
dependencies = [
"bindgen 0.69.2",
"bindgen 0.69.4",
"mozilla-central-workspace-hack",
"nom",
"pkcs11-bindings",
@ -893,7 +893,7 @@ version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3120ebb80a9de008e638ad833d4127d50ea3d3a960ea23ea69bc66d9358a028"
dependencies = [
"bindgen 0.69.2",
"bindgen 0.69.4",
]
[[package]]
@ -2036,7 +2036,7 @@ name = "gecko-profiler"
version = "0.1.0"
dependencies = [
"bincode",
"bindgen 0.69.2",
"bindgen 0.69.4",
"lazy_static",
"mozbuild",
"profiler-macros",
@ -2596,7 +2596,7 @@ name = "http3server"
version = "0.1.1"
dependencies = [
"base64 0.21.3",
"bindgen 0.69.2",
"bindgen 0.69.4",
"cfg-if 1.0.0",
"http",
"hyper",
@ -3714,7 +3714,7 @@ name = "mozilla-central-workspace-hack"
version = "0.1.0"
dependencies = [
"arrayvec",
"bindgen 0.69.2",
"bindgen 0.69.4",
"bitflags 2.4.1",
"bytes",
"cc",
@ -3885,7 +3885,7 @@ name = "neqo-crypto"
version = "0.7.0"
source = "git+https://github.com/mozilla/neqo?tag=v0.7.0#9489511f7c82786f55bc9c713cddbff825507ed7"
dependencies = [
"bindgen 0.69.2",
"bindgen 0.69.4",
"log",
"mozbuild",
"neqo-common",
@ -4029,7 +4029,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c17aec6d4e1822c023689899f09311592a36cbf6de8f85dfaf5f01976790d8d"
dependencies = [
"bindgen 0.69.2",
"bindgen 0.69.4",
"mozbuild",
"once_cell",
"pkcs11-bindings",
@ -4299,12 +4299,6 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "peeking_take_while"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"
[[package]]
name = "percent-encoding"
version = "2.3.1"
@ -4401,7 +4395,7 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0fabbdbe64b22820753da90995b3a73d02907eaeeac6f2414962a566aaa18ea"
dependencies = [
"bindgen 0.69.2",
"bindgen 0.69.4",
]
[[package]]
@ -5322,7 +5316,7 @@ dependencies = [
"app_units",
"arrayvec",
"atomic_refcell",
"bindgen 0.69.2",
"bindgen 0.69.4",
"bitflags 2.4.1",
"byteorder",
"cssparser",

View file

@ -776,6 +776,11 @@ who = "Mike Hommey <mh+mozilla@glandium.org>"
criteria = "safe-to-deploy"
delta = "0.69.1 -> 0.69.2"
[[audits.bindgen]]
who = "Emilio Cobos Álvarez <emilio@crisal.io>"
criteria = "safe-to-deploy"
delta = "0.69.2 -> 0.69.4"
[[audits.bit-set]]
who = "Aria Beingessner <a.beingessner@gmail.com>"
criteria = "safe-to-deploy"

File diff suppressed because one or more lines are too long

View file

@ -13,7 +13,7 @@
edition = "2018"
rust-version = "1.60.0"
name = "bindgen"
version = "0.69.2"
version = "0.69.4"
authors = [
"Jyun-Yan You <jyyou.tw@gmail.com>",
"Emilio Cobos Álvarez <emilio@crisal.io>",
@ -79,6 +79,10 @@ version = "0.6"
version = "1"
features = ["clang_6_0"]
[dependencies.itertools]
version = ">=0.10,<0.13"
default-features = false
[dependencies.lazy_static]
version = "1"
@ -89,9 +93,6 @@ version = "1"
version = "0.4"
optional = true
[dependencies.peeking_take_while]
version = "0.1.2"
[dependencies.prettyplease]
version = "0.2.7"
features = ["verbatim"]
@ -106,10 +107,10 @@ version = "1"
default-features = false
[dependencies.regex]
version = "1.5"
version = "1.5.1"
features = [
"std",
"unicode",
"unicode-perl",
]
default-features = false
@ -135,7 +136,7 @@ default-features = false
[features]
__cli = []
__testing_only_extra_assertions = []
__testing_only_libclang_5 = []
__testing_only_libclang_16 = []
__testing_only_libclang_9 = []
default = [
"logging",

View file

@ -2297,6 +2297,15 @@ impl Drop for EvalResult {
unsafe { clang_EvalResult_dispose(self.x) };
}
}
/// ABI kinds as defined in
/// <https://github.com/llvm/llvm-project/blob/ddf1de20a3f7db3bca1ef6ba7e6cbb90aac5fd2d/clang/include/clang/Basic/TargetCXXABI.def>
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub(crate) enum ABIKind {
/// All the regular targets like Linux, Mac, WASM, etc. implement the Itanium ABI
GenericItanium,
/// The ABI used when compiling for the MSVC target
Microsoft,
}
/// Target information obtained from libclang.
#[derive(Debug)]
@ -2305,6 +2314,8 @@ pub(crate) struct TargetInfo {
pub(crate) triple: String,
/// The width of the pointer _in bits_.
pub(crate) pointer_width: usize,
/// The ABI of the target
pub(crate) abi: ABIKind,
}
impl TargetInfo {
@ -2320,9 +2331,17 @@ impl TargetInfo {
}
assert!(pointer_width > 0);
assert_eq!(pointer_width % 8, 0);
let abi = if triple.contains("msvc") {
ABIKind::Microsoft
} else {
ABIKind::GenericItanium
};
TargetInfo {
triple,
pointer_width: pointer_width as usize,
abi,
}
}
}

View file

@ -232,6 +232,15 @@ pub(crate) mod ast_ty {
//
// Also, maybe this one shouldn't be the default?
match (fk, ctx.options().convert_floats) {
(FloatKind::Float16, _) => {
// TODO: do f16 when rust lands it
ctx.generated_bindgen_float16();
if ctx.options().enable_cxx_namespaces {
syn::parse_quote! { root::__BindgenFloat16 }
} else {
syn::parse_quote! { __BindgenFloat16 }
}
}
(FloatKind::Float, true) => syn::parse_quote! { f32 },
(FloatKind::Double, true) => syn::parse_quote! { f64 },
(FloatKind::Float, false) => raw_type(ctx, "c_float"),

View file

@ -578,6 +578,9 @@ impl CodeGenerator for Module {
if result.saw_incomplete_array {
utils::prepend_incomplete_array_types(ctx, &mut *result);
}
if ctx.need_bindgen_float16_type() {
utils::prepend_float16_type(&mut *result);
}
if ctx.need_bindgen_complex_type() {
utils::prepend_complex_type(&mut *result);
}
@ -1974,6 +1977,7 @@ impl CodeGenerator for CompInfo {
ty,
&canonical_name,
visibility,
packed,
);
if !is_opaque {
@ -2193,7 +2197,14 @@ impl CodeGenerator for CompInfo {
if let Some(comment) = item.comment(ctx) {
attributes.push(attributes::doc(comment));
}
if packed && !is_opaque {
// if a type has both a "packed" attribute and an "align(N)" attribute, then check if the
// "packed" attr is redundant, and do not include it if so.
if packed &&
!is_opaque &&
!(explicit_align.is_some() &&
self.already_packed(ctx).unwrap_or(false))
{
let n = layout.map_or(1, |l| l.align);
assert!(ctx.options().rust_features().repr_packed_n || n == 1);
let packed_repr = if n == 1 {
@ -5136,6 +5147,20 @@ pub(crate) mod utils {
result.extend(old_items);
}
pub(crate) fn prepend_float16_type(
result: &mut Vec<proc_macro2::TokenStream>,
) {
let float16_type = quote! {
#[derive(PartialEq, Copy, Clone, Hash, Debug, Default)]
#[repr(transparent)]
pub struct __BindgenFloat16(pub u16);
};
let items = vec![float16_type];
let old_items = mem::replace(result, items);
result.extend(old_items);
}
pub(crate) fn prepend_complex_type(
result: &mut Vec<proc_macro2::TokenStream>,
) {

View file

@ -270,6 +270,7 @@ impl<'a> CSerialize<'a> for Type {
write!(writer, "const ")?;
}
match float_kind {
FloatKind::Float16 => write!(writer, "_Float16")?,
FloatKind::Float => write!(writer, "float")?,
FloatKind::Double => write!(writer, "double")?,
FloatKind::LongDouble => write!(writer, "long double")?,
@ -281,6 +282,7 @@ impl<'a> CSerialize<'a> for Type {
write!(writer, "const ")?;
}
match float_kind {
FloatKind::Float16 => write!(writer, "_Float16 complex")?,
FloatKind::Float => write!(writer, "float complex")?,
FloatKind::Double => write!(writer, "double complex")?,
FloatKind::LongDouble => {

View file

@ -91,9 +91,9 @@ impl<'a> StructLayoutTracker<'a> {
ty: &'a Type,
name: &'a str,
visibility: FieldVisibilityKind,
is_packed: bool,
) -> Self {
let known_type_layout = ty.layout(ctx);
let is_packed = comp.is_packed(ctx, known_type_layout.as_ref());
let (is_rust_union, can_copy_union_fields) =
comp.is_rust_union(ctx, known_type_layout.as_ref(), name);
StructLayoutTracker {
@ -156,9 +156,7 @@ impl<'a> StructLayoutTracker<'a> {
self.latest_field_layout = Some(layout);
self.last_field_was_bitfield = true;
// NB: We intentionally don't update the max_field_align here, since our
// bitfields code doesn't necessarily guarantee it, so we need to
// actually generate the dummy alignment.
self.max_field_align = cmp::max(self.max_field_align, layout.align);
}
/// Returns a padding field if necessary for a given new field _before_
@ -214,7 +212,10 @@ impl<'a> StructLayoutTracker<'a> {
0
} else if !self.is_packed {
self.padding_bytes(field_layout)
} else if let Some(l) = self.known_type_layout {
} else if let Some(mut l) = self.known_type_layout {
if field_layout.align < l.align {
l.align = field_layout.align;
}
self.padding_bytes(l)
} else {
0

View file

@ -95,9 +95,9 @@ macro_rules! define_rust_targets {
// not stable.
define_rust_targets! {
Nightly => {
thiscall_abi: #42202,
vectorcall_abi,
},
Stable_1_73(73) => { thiscall_abi: #42202 },
Stable_1_71(71) => { c_unwind_abi: #106075 },
Stable_1_68(68) => { abi_efiapi: #105795 },
Stable_1_64(64) => { core_ffi_c: #94503 },

View file

@ -1,5 +1,7 @@
//! Compound types (unions and structs) in our intermediate representation.
use itertools::Itertools;
use super::analysis::Sizedness;
use super::annotations::Annotations;
use super::context::{BindgenContext, FunctionId, ItemId, TypeId, VarId};
@ -15,7 +17,6 @@ use crate::ir::derive::CanDeriveCopy;
use crate::parse::ParseError;
use crate::HashMap;
use crate::NonCopyUnionStyle;
use peeking_take_while::PeekableExt;
use std::cmp;
use std::io;
use std::mem;
@ -1641,6 +1642,26 @@ impl CompInfo {
false
}
/// Return true if a compound type is "naturally packed". This means we can exclude the
/// "packed" attribute without changing the layout.
/// This is useful for types that need an "align(N)" attribute since rustc won't compile
/// structs that have both of those attributes.
pub(crate) fn already_packed(&self, ctx: &BindgenContext) -> Option<bool> {
let mut total_size: usize = 0;
for field in self.fields().iter() {
let layout = field.layout(ctx)?;
if layout.align != 0 && total_size % layout.align != 0 {
return Some(false);
}
total_size += layout.size;
}
Some(true)
}
/// Returns true if compound type has been forward declared
pub(crate) fn is_forward_declaration(&self) -> bool {
self.is_forward_declaration

View file

@ -19,7 +19,7 @@ use super::module::{Module, ModuleKind};
use super::template::{TemplateInstantiation, TemplateParameters};
use super::traversal::{self, Edge, ItemTraversal};
use super::ty::{FloatKind, Type, TypeKind};
use crate::clang::{self, Cursor};
use crate::clang::{self, ABIKind, Cursor};
use crate::codegen::CodegenError;
use crate::BindgenOptions;
use crate::{Entry, HashMap, HashSet};
@ -386,6 +386,9 @@ pub(crate) struct BindgenContext {
/// Whether a bindgen complex was generated
generated_bindgen_complex: Cell<bool>,
/// Whether a bindgen float16 was generated
generated_bindgen_float16: Cell<bool>,
/// The set of `ItemId`s that are allowlisted. This the very first thing
/// computed after parsing our IR, and before running any of our analyses.
allowlisted: Option<ItemSet>,
@ -585,6 +588,7 @@ If you encounter an error missing from this list, please file an issue or a PR!"
target_info,
options,
generated_bindgen_complex: Cell::new(false),
generated_bindgen_float16: Cell::new(false),
allowlisted: None,
blocklisted_types_implement_traits: Default::default(),
codegen_items: None,
@ -622,6 +626,11 @@ If you encounter an error missing from this list, please file an issue or a PR!"
self.target_info.pointer_width / 8
}
/// Returns the ABI, which is mostly useful for determining the mangling kind.
pub(crate) fn abi_kind(&self) -> ABIKind {
self.target_info.abi
}
/// Get the stack of partially parsed types that we are in the middle of
/// parsing.
pub(crate) fn currently_parsed_types(&self) -> &[PartialType] {
@ -2005,6 +2014,7 @@ If you encounter an error missing from this list, please file an issue or a PR!"
CXType_ULongLong => TypeKind::Int(IntKind::ULongLong),
CXType_Int128 => TypeKind::Int(IntKind::I128),
CXType_UInt128 => TypeKind::Int(IntKind::U128),
CXType_Float16 | CXType_Half => TypeKind::Float(FloatKind::Float16),
CXType_Float => TypeKind::Float(FloatKind::Float),
CXType_Double => TypeKind::Float(FloatKind::Double),
CXType_LongDouble => TypeKind::Float(FloatKind::LongDouble),
@ -2013,6 +2023,7 @@ If you encounter an error missing from this list, please file an issue or a PR!"
let float_type =
ty.elem_type().expect("Not able to resolve complex type?");
let float_kind = match float_type.kind() {
CXType_Float16 | CXType_Half => FloatKind::Float16,
CXType_Float => FloatKind::Float,
CXType_Double => FloatKind::Double,
CXType_LongDouble => FloatKind::LongDouble,
@ -2528,6 +2539,16 @@ If you encounter an error missing from this list, please file an issue or a PR!"
self.generated_bindgen_complex.get()
}
/// Call if a bindgen float16 is generated
pub(crate) fn generated_bindgen_float16(&self) {
self.generated_bindgen_float16.set(true)
}
/// Whether we need to generate the bindgen float16 type
pub(crate) fn need_bindgen_float16_type(&self) -> bool {
self.generated_bindgen_float16.get()
}
/// Compute which `enum`s have an associated `typedef` definition.
fn compute_enum_typedef_combos(&mut self) {
let _t = self.timer("compute_enum_typedef_combos");

View file

@ -7,7 +7,7 @@ use super::item::Item;
use super::traversal::{EdgeKind, Trace, Tracer};
use super::ty::TypeKind;
use crate::callbacks::{ItemInfo, ItemKind};
use crate::clang::{self, Attribute};
use crate::clang::{self, ABIKind, Attribute};
use crate::parse::{ClangSubItemParser, ParseError, ParseResult};
use clang_sys::{self, CXCallingConv};
@ -303,6 +303,7 @@ fn get_abi(cc: CXCallingConv) -> ClangAbi {
CXCallingConv_X86VectorCall => ClangAbi::Known(Abi::Vectorcall),
CXCallingConv_AAPCS => ClangAbi::Known(Abi::Aapcs),
CXCallingConv_X86_64Win64 => ClangAbi::Known(Abi::Win64),
CXCallingConv_AArch64VectorCall => ClangAbi::Known(Abi::Vectorcall),
other => ClangAbi::Unknown(other),
}
}
@ -323,11 +324,12 @@ pub(crate) fn cursor_mangling(
return None;
}
let is_itanium_abi = ctx.abi_kind() == ABIKind::GenericItanium;
let is_destructor = cursor.kind() == clang_sys::CXCursor_Destructor;
if let Ok(mut manglings) = cursor.cxx_manglings() {
while let Some(m) = manglings.pop() {
// Only generate the destructor group 1, see below.
if is_destructor && !m.ends_with("D1Ev") {
if is_itanium_abi && is_destructor && !m.ends_with("D1Ev") {
continue;
}
@ -340,7 +342,7 @@ pub(crate) fn cursor_mangling(
return None;
}
if is_destructor {
if is_itanium_abi && is_destructor {
// With old (3.8-) libclang versions, and the Itanium ABI, clang returns
// the "destructor group 0" symbol, which means that it'll try to free
// memory, which definitely isn't what we want.
@ -503,10 +505,24 @@ impl FunctionSig {
Default::default()
};
// This looks easy to break but the clang parser keeps the type spelling clean even if
// other attributes are added.
is_divergent =
is_divergent || ty.spelling().contains("__attribute__((noreturn))");
// Check if the type contains __attribute__((noreturn)) outside of parentheses. This is
// somewhat fragile, but it seems to be the only way to get at this information as of
// libclang 9.
let ty_spelling = ty.spelling();
let has_attribute_noreturn = ty_spelling
.match_indices("__attribute__((noreturn))")
.any(|(i, _)| {
let depth = ty_spelling[..i]
.bytes()
.filter_map(|ch| match ch {
b'(' => Some(1),
b')' => Some(-1),
_ => None,
})
.sum::<isize>();
depth == 0
});
is_divergent = is_divergent || has_attribute_noreturn;
let is_method = kind == CXCursor_CXXMethod;
let is_constructor = kind == CXCursor_Constructor;

View file

@ -668,8 +668,11 @@ impl Item {
ItemKind::Function(..) => {
ctx.options().blocklisted_functions.matches(&name)
}
// TODO: Add constant / namespace blocklisting?
ItemKind::Var(..) | ItemKind::Module(..) => false,
ItemKind::Var(..) => {
ctx.options().blocklisted_vars.matches(&name)
}
// TODO: Add namespace blocklisting?
ItemKind::Module(..) => false,
}
}

View file

@ -558,6 +558,8 @@ impl TemplateParameters for TypeKind {
/// The kind of float this type represents.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum FloatKind {
/// A half (`_Float16` or `__fp16`)
Float16,
/// A `float`.
Float,
/// A `double`.

View file

@ -440,13 +440,14 @@ impl Builder {
impl BindgenOptions {
fn build(&mut self) {
const REGEX_SETS_LEN: usize = 28;
const REGEX_SETS_LEN: usize = 29;
let regex_sets: [_; REGEX_SETS_LEN] = [
&mut self.blocklisted_types,
&mut self.blocklisted_functions,
&mut self.blocklisted_items,
&mut self.blocklisted_files,
&mut self.blocklisted_vars,
&mut self.opaque_types,
&mut self.allowlisted_vars,
&mut self.allowlisted_types,
@ -483,6 +484,7 @@ impl BindgenOptions {
"--blocklist-function",
"--blocklist-item",
"--blocklist-file",
"--blocklist-var",
"--opaque-type",
"--allowlist-type",
"--allowlist-function",
@ -927,22 +929,24 @@ impl Bindings {
/// Write these bindings as source text to the given `Write`able.
pub fn write<'a>(&self, mut writer: Box<dyn Write + 'a>) -> io::Result<()> {
const NL: &str = if cfg!(windows) { "\r\n" } else { "\n" };
if !self.options.disable_header_comment {
let version =
option_env!("CARGO_PKG_VERSION").unwrap_or("(unknown version)");
let header = format!(
"/* automatically generated by rust-bindgen {version} */\n\n",
);
writer.write_all(header.as_bytes())?;
writeln!(
writer,
"/* automatically generated by rust-bindgen {version} */{NL}",
)?;
}
for line in self.options.raw_lines.iter() {
writer.write_all(line.as_bytes())?;
writer.write_all("\n".as_bytes())?;
writer.write_all(NL.as_bytes())?;
}
if !self.options.raw_lines.is_empty() {
writer.write_all("\n".as_bytes())?;
writer.write_all(NL.as_bytes())?;
}
match self.format_tokens(&self.module) {
@ -1237,7 +1241,7 @@ fn get_target_dependent_env_var(
/// use bindgen::builder;
/// let bindings = builder()
/// .header("path/to/input/header")
/// .parse_callbacks(Box::new(bindgen::CargoCallbacks))
/// .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
/// .generate();
/// ```
#[derive(Debug)]

View file

@ -222,6 +222,22 @@ options! {
},
as_args: "--blocklist-file",
},
/// Variables that have been blocklisted and should not appear in the generated code.
blocklisted_vars: RegexSet {
methods: {
regex_option! {
/// Do not generate any bindings for the given variable.
///
/// This option is not recursive, meaning that it will only block variables whose
/// names explicitly match the argument of this method.
pub fn blocklist_var<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.blocklisted_vars.insert(arg);
self
}
}
},
as_args: "--blocklist-var",
},
/// Types that should be treated as opaque structures in the generated code.
opaque_types: RegexSet {
methods: {

View file

@ -1 +0,0 @@
{"files":{"Cargo.toml":"caf1a07b54869ad1b35394c5b9262fe1e8f63b7ab85bf517ad6d59c1ad1d64bc","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.md":"9f7659439d3e98a3aae69562648a651e49eeac7152f489deb77dd09c0c8010d0","src/lib.rs":"699149181f71aa88dc6585bd047fc29c6f5baba2b8bf5fbd1c5612966322b379"},"package":"19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"}

View file

@ -1,14 +0,0 @@
[package]
authors = ["Nick Fitzgerald <fitzgen@gmail.com>"]
description = "Like `Iterator::take_while`, but calls the predicate on a peeked value. This allows you to use `Iterator::by_ref` and `Iterator::take_while` together, and still get the first value for which the `take_while` predicate returned false after dropping the `by_ref`."
categories = ["rust-patterns"]
keywords = ["iterator", "take_while", "peek", "by_ref"]
license = "Apache-2.0/MIT"
name = "peeking_take_while"
readme = "./README.md"
repository = "https://github.com/fitzgen/peeking_take_while"
version = "0.1.2"
[badges]
[badges.travis-ci]
repository = "fitzgen/peeking_take_while"

View file

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,25 +0,0 @@
Copyright (c) 2015 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -1,58 +0,0 @@
# `peeking_take_while`
[![Build Status](https://travis-ci.org/fitzgen/peeking_take_while.png?branch=master)](https://travis-ci.org/fitzgen/peeking_take_while)
Provides the `peeking_take_while` iterator adaptor method.
The `peeking_take_while` method is very similar to `take_while`, but behaves
differently when used with a borrowed iterator (perhaps returned by
`Iterator::by_ref`).
`peeking_take_while` peeks at the next item in the iterator and runs the
predicate on that peeked item. This avoids consuming the first item yielded by
the underlying iterator for which the predicate returns `false`. On the other
hand, `take_while` will consume that first item for which the predicate returns
`false`, and it will be lost.
```rust
extern crate peeking_take_while;
// Bring the `peeking_take_while` method for peekable iterators into
// scope.
use peeking_take_while::PeekableExt;
// Let's say we have two collections we want to iterate through: `xs` and
// `ys`. We want to perform one operation on all the leading contiguous
// elements that match some predicate, and a different thing with the rest of
// the elements. With the `xs`, we will use the normal `take_while`. With the
// `ys`, we will use `peeking_take_while`.
let xs: Vec<u8> = (0..100).collect();
let ys = xs.clone();
let mut iter_xs = xs.into_iter();
let mut iter_ys = ys.into_iter().peekable();
{
// Let's do one thing with all the items that are less than 10.
let xs_less_than_ten = iter_xs.by_ref().take_while(|x| *x < 10);
for x in xs_less_than_ten {
do_things_with(x);
}
let ys_less_than_ten = iter_ys.by_ref().peeking_take_while(|y| *y < 10);
for y in ys_less_than_ten {
do_things_with(y);
}
}
// And now we will do some other thing with the items that are greater than
// or equal to 10.
// ...except, when using plain old `take_while` we lost 10!
assert_eq!(iter_xs.next(), Some(11));
// However, when using `peeking_take_while` we did not! Great!
assert_eq!(iter_ys.next(), Some(10));
```

View file

@ -1,117 +0,0 @@
//! # `peeking_take_while`
//!
//! Provides the `peeking_take_while` iterator adaptor method.
//!
//! The `peeking_take_while` method is very similar to `take_while`, but behaves
//! differently when used with a borrowed iterator (perhaps returned by
//! `Iterator::by_ref`).
//!
//! `peeking_take_while` peeks at the next item in the iterator and runs the
//! predicate on that peeked item. This avoids consuming the first item yielded
//! by the underlying iterator for which the predicate returns `false`. On the
//! other hand, `take_while` will consume that first item for which the
//! predicate returns `false`, and it will be lost.
//!
//! ```
//! extern crate peeking_take_while;
//!
//! // Bring the `peeking_take_while` method for peekable iterators into
//! // scope.
//! use peeking_take_while::PeekableExt;
//!
//! # fn main() {
//! // Let's say we have two collections we want to iterate through: `xs` and
//! // `ys`. We want to perform one operation on all the leading contiguous
//! // elements that match some predicate, and a different thing with the rest of
//! // the elements. With the `xs`, we will use the normal `take_while`. With the
//! // `ys`, we will use `peeking_take_while`.
//!
//! let xs: Vec<u8> = (0..100).collect();
//! let ys = xs.clone();
//!
//! let mut iter_xs = xs.into_iter();
//! let mut iter_ys = ys.into_iter().peekable();
//!
//! {
//! // Let's do one thing with all the items that are less than 10.
//! # fn do_things_with<T>(_: T) {}
//!
//! let xs_less_than_ten = iter_xs.by_ref().take_while(|x| *x < 10);
//! for x in xs_less_than_ten {
//! do_things_with(x);
//! }
//!
//! let ys_less_than_ten = iter_ys.by_ref().peeking_take_while(|y| *y < 10);
//! for y in ys_less_than_ten {
//! do_things_with(y);
//! }
//! }
//!
//! // And now we will do some other thing with the items that are greater than
//! // or equal to 10.
//!
//! // ...except, when using plain old `take_while` we lost 10!
//! assert_eq!(iter_xs.next(), Some(11));
//!
//! // However, when using `peeking_take_while` we did not! Great!
//! assert_eq!(iter_ys.next(), Some(10));
//! # }
//! ```
use std::iter::Peekable;
/// The iterator returned by `peeking_take_while`.
///
/// See the [module documentation](./index.html) for details.
pub struct PeekingTakeWhile<'a, I, P>
where I: 'a + Iterator
{
iter: &'a mut Peekable<I>,
predicate: P,
}
impl<'a, I, P> Iterator for PeekingTakeWhile<'a, I, P>
where I: Iterator,
I::Item: ::std::fmt::Debug,
P: FnMut(&<I as Iterator>::Item) -> bool
{
type Item = <I as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item> {
let predicate = &mut self.predicate;
if self.iter.peek().map_or(false, |x| !(predicate)(x)) {
None
} else {
self.iter.next()
}
}
}
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
pub trait PeekableExt<'a, I>: Iterator
where I: 'a + Iterator
{
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
fn peeking_take_while<P>(&'a mut self, predicate: P) -> PeekingTakeWhile<'a, I, P>
where Self: Sized,
P: FnMut(&<Self as Iterator>::Item) -> bool;
}
impl<'a, I> PeekableExt<'a, I> for Peekable<I>
where I: 'a + Iterator
{
fn peeking_take_while<P>(&'a mut self, predicate: P) -> PeekingTakeWhile<I, P>
where P: FnMut(&<Self as Iterator>::Item) -> bool
{
PeekingTakeWhile {
iter: self,
predicate: predicate,
}
}
}