file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
bind-by-move-neither-can-live-while-the-other-survives-3.rs
// Copyright 2012 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.
error!("destructor runs"); } } enum double_option<T,U> { some2(T,U), none2 } fn main() { let x = some2(X { x: () }, X { x: () }); match x { some2(ref _y, _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern none2 => fail!() } }
struct X { x: (), } impl Drop for X { fn finalize(&self) {
random_line_split
bind-by-move-neither-can-live-while-the-other-survives-3.rs
// Copyright 2012 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. struct X { x: (), } impl Drop for X { fn
(&self) { error!("destructor runs"); } } enum double_option<T,U> { some2(T,U), none2 } fn main() { let x = some2(X { x: () }, X { x: () }); match x { some2(ref _y, _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern none2 => fail!() } }
finalize
identifier_name
challenge47_48.rs
use crate::errors::*; use rsa::Rsa; use bignum::OpensslBigNum as BigNum; use bignum::{BigNumExt, BigNumTrait}; use rand::Rng; use std::cmp; struct Server { rsa: Rsa<BigNum>, } // We do not need an oracle which checks for full PKCS#1v1.5 conformance. // It suffices that the oracle tells us whether the cleartext is of the form // 00 || 02 || another k - 2 bytes, // where k is the number of bytes in the RSA modulus. impl Server { fn new(rsa_bits: usize) -> Self { let rsa = Rsa::generate(rsa_bits); Server { rsa } } fn n(&self) -> &BigNum { self.rsa.n() } fn oracle(&self, ciphertext: &BigNum) -> bool { let cleartext = self.rsa.decrypt(ciphertext); cleartext.rsh(8 * (self.rsa.n().bytes() - 2)) == BigNum::from_u32(2) } fn get_ciphertext(&self) -> BigNum { let k = self.rsa.n().bytes() as usize; let cleartext = b"kick it, CC"; let cleartext_len = cleartext.len(); assert!(cleartext_len <= k - 11); let mut padded_cleartext = vec![2u8]; let mut rng = rand::thread_rng(); padded_cleartext.extend((0..(k - 3 - cleartext_len)).map(|_| rng.gen_range(1, 256) as u8)); padded_cleartext.push(0); padded_cleartext.extend_from_slice(cleartext); let m: BigNum = BigNumTrait::from_bytes_be(&padded_cleartext); self.rsa.encrypt(&m) } fn encrypt(&self, cleartext: &BigNum) -> BigNum { self.rsa.encrypt(cleartext) } } // We use the variable names from the paper #[allow(non_snake_case)] #[allow(clippy::just_underscores_and_digits)] #[allow(clippy::many_single_char_names)] pub fn run(rsa_bits: usize) -> Result<()> { let _0 = BigNum::zero(); let _1 = BigNum::one(); let _2 = BigNum::from_u32(2); let _3 = BigNum::from_u32(3); let server = Server::new(rsa_bits); let n = server.n(); let k = n.bytes() as usize; let B = _1.lsh(8 * (k - 2)); let _2B = &_2 * &B; let _3B = &_3 * &B; let c = server.get_ciphertext(); // We are only ever going to use `oracle` in the following way let wrapped_oracle = |s: &BigNum| -> bool { server.oracle(&(&c * &server.encrypt(s))) }; let mut M_prev = vec![(_2B.clone(), &_3B - &_1)]; let mut s_prev = _1.clone(); let mut i = 1; // We know that the cleartext corresponding to our ciphertext is PKCS conforming, so we can skip // Step 1 of the paper. loop { // Step 2 let mut si; if i == 1
else if M_prev.len() >= 2 { // Step 2.b si = &s_prev + &_1; while!wrapped_oracle(&si) { si = &si + &_1; } } else { // Step 2.c let (ref a, ref b) = M_prev[0]; let mut ri = (&_2 * &(&(b * &s_prev) - &_2B)).ceil_quotient(n); 'outer: loop { si = (&_2B + &(&ri * n)).ceil_quotient(b); let U = (&_3B + &(&ri * n)).ceil_quotient(a); while si < U { if wrapped_oracle(&si) { break 'outer; } si = &si + &_1; } ri = &ri + &_1; } } let mut Mi = Vec::new(); for &(ref a, ref b) in &M_prev { let mut r = (&(&(a * &si) - &_3B) + &_1).ceil_quotient(n); let U = (&(b * &si) - &_2B).floor_quotient(n); while r <= U { Mi.push(( cmp::max(a.clone(), (&_2B + &(&r * n)).ceil_quotient(&si)), cmp::min(b.clone(), (&(&_3B - &_1) + &(&r * n)).floor_quotient(&si)), )); r = &r + &_1; } } Mi.sort(); Mi.dedup(); if Mi.len() == 1 && Mi[0].0 == Mi[0].1 { // Verify that our cleartext encrypts to the ciphertext return compare_eq(&c, &server.encrypt(&Mi[0].0)); } i += 1; s_prev = si; M_prev = Mi; } }
{ // Step 2.a si = n.ceil_quotient(&_3B); while !wrapped_oracle(&si) { si = &si + &_1; } }
conditional_block
challenge47_48.rs
use crate::errors::*; use rsa::Rsa; use bignum::OpensslBigNum as BigNum; use bignum::{BigNumExt, BigNumTrait}; use rand::Rng; use std::cmp; struct Server { rsa: Rsa<BigNum>, } // We do not need an oracle which checks for full PKCS#1v1.5 conformance. // It suffices that the oracle tells us whether the cleartext is of the form // 00 || 02 || another k - 2 bytes, // where k is the number of bytes in the RSA modulus. impl Server { fn new(rsa_bits: usize) -> Self { let rsa = Rsa::generate(rsa_bits); Server { rsa } } fn
(&self) -> &BigNum { self.rsa.n() } fn oracle(&self, ciphertext: &BigNum) -> bool { let cleartext = self.rsa.decrypt(ciphertext); cleartext.rsh(8 * (self.rsa.n().bytes() - 2)) == BigNum::from_u32(2) } fn get_ciphertext(&self) -> BigNum { let k = self.rsa.n().bytes() as usize; let cleartext = b"kick it, CC"; let cleartext_len = cleartext.len(); assert!(cleartext_len <= k - 11); let mut padded_cleartext = vec![2u8]; let mut rng = rand::thread_rng(); padded_cleartext.extend((0..(k - 3 - cleartext_len)).map(|_| rng.gen_range(1, 256) as u8)); padded_cleartext.push(0); padded_cleartext.extend_from_slice(cleartext); let m: BigNum = BigNumTrait::from_bytes_be(&padded_cleartext); self.rsa.encrypt(&m) } fn encrypt(&self, cleartext: &BigNum) -> BigNum { self.rsa.encrypt(cleartext) } } // We use the variable names from the paper #[allow(non_snake_case)] #[allow(clippy::just_underscores_and_digits)] #[allow(clippy::many_single_char_names)] pub fn run(rsa_bits: usize) -> Result<()> { let _0 = BigNum::zero(); let _1 = BigNum::one(); let _2 = BigNum::from_u32(2); let _3 = BigNum::from_u32(3); let server = Server::new(rsa_bits); let n = server.n(); let k = n.bytes() as usize; let B = _1.lsh(8 * (k - 2)); let _2B = &_2 * &B; let _3B = &_3 * &B; let c = server.get_ciphertext(); // We are only ever going to use `oracle` in the following way let wrapped_oracle = |s: &BigNum| -> bool { server.oracle(&(&c * &server.encrypt(s))) }; let mut M_prev = vec![(_2B.clone(), &_3B - &_1)]; let mut s_prev = _1.clone(); let mut i = 1; // We know that the cleartext corresponding to our ciphertext is PKCS conforming, so we can skip // Step 1 of the paper. loop { // Step 2 let mut si; if i == 1 { // Step 2.a si = n.ceil_quotient(&_3B); while!wrapped_oracle(&si) { si = &si + &_1; } } else if M_prev.len() >= 2 { // Step 2.b si = &s_prev + &_1; while!wrapped_oracle(&si) { si = &si + &_1; } } else { // Step 2.c let (ref a, ref b) = M_prev[0]; let mut ri = (&_2 * &(&(b * &s_prev) - &_2B)).ceil_quotient(n); 'outer: loop { si = (&_2B + &(&ri * n)).ceil_quotient(b); let U = (&_3B + &(&ri * n)).ceil_quotient(a); while si < U { if wrapped_oracle(&si) { break 'outer; } si = &si + &_1; } ri = &ri + &_1; } } let mut Mi = Vec::new(); for &(ref a, ref b) in &M_prev { let mut r = (&(&(a * &si) - &_3B) + &_1).ceil_quotient(n); let U = (&(b * &si) - &_2B).floor_quotient(n); while r <= U { Mi.push(( cmp::max(a.clone(), (&_2B + &(&r * n)).ceil_quotient(&si)), cmp::min(b.clone(), (&(&_3B - &_1) + &(&r * n)).floor_quotient(&si)), )); r = &r + &_1; } } Mi.sort(); Mi.dedup(); if Mi.len() == 1 && Mi[0].0 == Mi[0].1 { // Verify that our cleartext encrypts to the ciphertext return compare_eq(&c, &server.encrypt(&Mi[0].0)); } i += 1; s_prev = si; M_prev = Mi; } }
n
identifier_name
challenge47_48.rs
use crate::errors::*; use rsa::Rsa; use bignum::OpensslBigNum as BigNum; use bignum::{BigNumExt, BigNumTrait}; use rand::Rng; use std::cmp; struct Server { rsa: Rsa<BigNum>, } // We do not need an oracle which checks for full PKCS#1v1.5 conformance. // It suffices that the oracle tells us whether the cleartext is of the form // 00 || 02 || another k - 2 bytes, // where k is the number of bytes in the RSA modulus. impl Server { fn new(rsa_bits: usize) -> Self { let rsa = Rsa::generate(rsa_bits); Server { rsa } } fn n(&self) -> &BigNum { self.rsa.n() } fn oracle(&self, ciphertext: &BigNum) -> bool { let cleartext = self.rsa.decrypt(ciphertext); cleartext.rsh(8 * (self.rsa.n().bytes() - 2)) == BigNum::from_u32(2) } fn get_ciphertext(&self) -> BigNum { let k = self.rsa.n().bytes() as usize; let cleartext = b"kick it, CC"; let cleartext_len = cleartext.len(); assert!(cleartext_len <= k - 11); let mut padded_cleartext = vec![2u8]; let mut rng = rand::thread_rng(); padded_cleartext.extend((0..(k - 3 - cleartext_len)).map(|_| rng.gen_range(1, 256) as u8)); padded_cleartext.push(0); padded_cleartext.extend_from_slice(cleartext); let m: BigNum = BigNumTrait::from_bytes_be(&padded_cleartext); self.rsa.encrypt(&m) } fn encrypt(&self, cleartext: &BigNum) -> BigNum { self.rsa.encrypt(cleartext) } } // We use the variable names from the paper #[allow(non_snake_case)] #[allow(clippy::just_underscores_and_digits)] #[allow(clippy::many_single_char_names)] pub fn run(rsa_bits: usize) -> Result<()>
let mut i = 1; // We know that the cleartext corresponding to our ciphertext is PKCS conforming, so we can skip // Step 1 of the paper. loop { // Step 2 let mut si; if i == 1 { // Step 2.a si = n.ceil_quotient(&_3B); while!wrapped_oracle(&si) { si = &si + &_1; } } else if M_prev.len() >= 2 { // Step 2.b si = &s_prev + &_1; while!wrapped_oracle(&si) { si = &si + &_1; } } else { // Step 2.c let (ref a, ref b) = M_prev[0]; let mut ri = (&_2 * &(&(b * &s_prev) - &_2B)).ceil_quotient(n); 'outer: loop { si = (&_2B + &(&ri * n)).ceil_quotient(b); let U = (&_3B + &(&ri * n)).ceil_quotient(a); while si < U { if wrapped_oracle(&si) { break 'outer; } si = &si + &_1; } ri = &ri + &_1; } } let mut Mi = Vec::new(); for &(ref a, ref b) in &M_prev { let mut r = (&(&(a * &si) - &_3B) + &_1).ceil_quotient(n); let U = (&(b * &si) - &_2B).floor_quotient(n); while r <= U { Mi.push(( cmp::max(a.clone(), (&_2B + &(&r * n)).ceil_quotient(&si)), cmp::min(b.clone(), (&(&_3B - &_1) + &(&r * n)).floor_quotient(&si)), )); r = &r + &_1; } } Mi.sort(); Mi.dedup(); if Mi.len() == 1 && Mi[0].0 == Mi[0].1 { // Verify that our cleartext encrypts to the ciphertext return compare_eq(&c, &server.encrypt(&Mi[0].0)); } i += 1; s_prev = si; M_prev = Mi; } }
{ let _0 = BigNum::zero(); let _1 = BigNum::one(); let _2 = BigNum::from_u32(2); let _3 = BigNum::from_u32(3); let server = Server::new(rsa_bits); let n = server.n(); let k = n.bytes() as usize; let B = _1.lsh(8 * (k - 2)); let _2B = &_2 * &B; let _3B = &_3 * &B; let c = server.get_ciphertext(); // We are only ever going to use `oracle` in the following way let wrapped_oracle = |s: &BigNum| -> bool { server.oracle(&(&c * &server.encrypt(s))) }; let mut M_prev = vec![(_2B.clone(), &_3B - &_1)]; let mut s_prev = _1.clone();
identifier_body
challenge47_48.rs
use crate::errors::*; use rsa::Rsa; use bignum::OpensslBigNum as BigNum; use bignum::{BigNumExt, BigNumTrait};
use std::cmp; struct Server { rsa: Rsa<BigNum>, } // We do not need an oracle which checks for full PKCS#1v1.5 conformance. // It suffices that the oracle tells us whether the cleartext is of the form // 00 || 02 || another k - 2 bytes, // where k is the number of bytes in the RSA modulus. impl Server { fn new(rsa_bits: usize) -> Self { let rsa = Rsa::generate(rsa_bits); Server { rsa } } fn n(&self) -> &BigNum { self.rsa.n() } fn oracle(&self, ciphertext: &BigNum) -> bool { let cleartext = self.rsa.decrypt(ciphertext); cleartext.rsh(8 * (self.rsa.n().bytes() - 2)) == BigNum::from_u32(2) } fn get_ciphertext(&self) -> BigNum { let k = self.rsa.n().bytes() as usize; let cleartext = b"kick it, CC"; let cleartext_len = cleartext.len(); assert!(cleartext_len <= k - 11); let mut padded_cleartext = vec![2u8]; let mut rng = rand::thread_rng(); padded_cleartext.extend((0..(k - 3 - cleartext_len)).map(|_| rng.gen_range(1, 256) as u8)); padded_cleartext.push(0); padded_cleartext.extend_from_slice(cleartext); let m: BigNum = BigNumTrait::from_bytes_be(&padded_cleartext); self.rsa.encrypt(&m) } fn encrypt(&self, cleartext: &BigNum) -> BigNum { self.rsa.encrypt(cleartext) } } // We use the variable names from the paper #[allow(non_snake_case)] #[allow(clippy::just_underscores_and_digits)] #[allow(clippy::many_single_char_names)] pub fn run(rsa_bits: usize) -> Result<()> { let _0 = BigNum::zero(); let _1 = BigNum::one(); let _2 = BigNum::from_u32(2); let _3 = BigNum::from_u32(3); let server = Server::new(rsa_bits); let n = server.n(); let k = n.bytes() as usize; let B = _1.lsh(8 * (k - 2)); let _2B = &_2 * &B; let _3B = &_3 * &B; let c = server.get_ciphertext(); // We are only ever going to use `oracle` in the following way let wrapped_oracle = |s: &BigNum| -> bool { server.oracle(&(&c * &server.encrypt(s))) }; let mut M_prev = vec![(_2B.clone(), &_3B - &_1)]; let mut s_prev = _1.clone(); let mut i = 1; // We know that the cleartext corresponding to our ciphertext is PKCS conforming, so we can skip // Step 1 of the paper. loop { // Step 2 let mut si; if i == 1 { // Step 2.a si = n.ceil_quotient(&_3B); while!wrapped_oracle(&si) { si = &si + &_1; } } else if M_prev.len() >= 2 { // Step 2.b si = &s_prev + &_1; while!wrapped_oracle(&si) { si = &si + &_1; } } else { // Step 2.c let (ref a, ref b) = M_prev[0]; let mut ri = (&_2 * &(&(b * &s_prev) - &_2B)).ceil_quotient(n); 'outer: loop { si = (&_2B + &(&ri * n)).ceil_quotient(b); let U = (&_3B + &(&ri * n)).ceil_quotient(a); while si < U { if wrapped_oracle(&si) { break 'outer; } si = &si + &_1; } ri = &ri + &_1; } } let mut Mi = Vec::new(); for &(ref a, ref b) in &M_prev { let mut r = (&(&(a * &si) - &_3B) + &_1).ceil_quotient(n); let U = (&(b * &si) - &_2B).floor_quotient(n); while r <= U { Mi.push(( cmp::max(a.clone(), (&_2B + &(&r * n)).ceil_quotient(&si)), cmp::min(b.clone(), (&(&_3B - &_1) + &(&r * n)).floor_quotient(&si)), )); r = &r + &_1; } } Mi.sort(); Mi.dedup(); if Mi.len() == 1 && Mi[0].0 == Mi[0].1 { // Verify that our cleartext encrypts to the ciphertext return compare_eq(&c, &server.encrypt(&Mi[0].0)); } i += 1; s_prev = si; M_prev = Mi; } }
use rand::Rng;
random_line_split
unwind-resource.rs
// Copyright 2012-2014 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. // ignore-fast use std::task; struct complainer { tx: Sender<bool>,
impl Drop for complainer { fn drop(&mut self) { println!("About to send!"); self.tx.send(true); println!("Sent!"); } } fn complainer(tx: Sender<bool>) -> complainer { println!("Hello!"); complainer { tx: tx } } fn f(tx: Sender<bool>) { let _tx = complainer(tx); fail!(); } pub fn main() { let (tx, rx) = channel(); task::spawn(proc() f(tx.clone())); println!("hiiiiiiiii"); assert!(rx.recv()); }
}
random_line_split
unwind-resource.rs
// Copyright 2012-2014 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. // ignore-fast use std::task; struct complainer { tx: Sender<bool>, } impl Drop for complainer { fn drop(&mut self) { println!("About to send!"); self.tx.send(true); println!("Sent!"); } } fn complainer(tx: Sender<bool>) -> complainer { println!("Hello!"); complainer { tx: tx } } fn f(tx: Sender<bool>)
pub fn main() { let (tx, rx) = channel(); task::spawn(proc() f(tx.clone())); println!("hiiiiiiiii"); assert!(rx.recv()); }
{ let _tx = complainer(tx); fail!(); }
identifier_body
unwind-resource.rs
// Copyright 2012-2014 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. // ignore-fast use std::task; struct complainer { tx: Sender<bool>, } impl Drop for complainer { fn
(&mut self) { println!("About to send!"); self.tx.send(true); println!("Sent!"); } } fn complainer(tx: Sender<bool>) -> complainer { println!("Hello!"); complainer { tx: tx } } fn f(tx: Sender<bool>) { let _tx = complainer(tx); fail!(); } pub fn main() { let (tx, rx) = channel(); task::spawn(proc() f(tx.clone())); println!("hiiiiiiiii"); assert!(rx.recv()); }
drop
identifier_name
unsafe_removed_from_name.rs
use clippy_utils::diagnostics::span_lint; use rustc_ast::ast::{Item, ItemKind, UseTree, UseTreeKind}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Span; use rustc_span::symbol::Ident; declare_clippy_lint! { /// ### What it does /// Checks for imports that remove "unsafe" from an item's /// name. /// /// ### Why is this bad? /// Renaming makes it less clear which traits and /// structures are unsafe. /// /// ### Example /// ```rust,ignore /// use std::cell::{UnsafeCell as TotallySafeCell}; /// /// extern crate crossbeam; /// use crossbeam::{spawn_unsafe as spawn}; /// ``` pub UNSAFE_REMOVED_FROM_NAME, style, "`unsafe` removed from API names on import" } declare_lint_pass!(UnsafeNameRemoval => [UNSAFE_REMOVED_FROM_NAME]); impl EarlyLintPass for UnsafeNameRemoval { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) { if let ItemKind::Use(ref use_tree) = item.kind { check_use_tree(use_tree, cx, item.span); } } } fn check_use_tree(use_tree: &UseTree, cx: &EarlyContext<'_>, span: Span) { match use_tree.kind { UseTreeKind::Simple(Some(new_name),..) => { let old_name = use_tree .prefix .segments .last() .expect("use paths cannot be empty") .ident; unsafe_to_safe_check(old_name, new_name, cx, span); }, UseTreeKind::Simple(None,..) | UseTreeKind::Glob => {}, UseTreeKind::Nested(ref nested_use_tree) => { for &(ref use_tree, _) in nested_use_tree { check_use_tree(use_tree, cx, span); } }, } } fn unsafe_to_safe_check(old_name: Ident, new_name: Ident, cx: &EarlyContext<'_>, span: Span) { let old_str = old_name.name.as_str(); let new_str = new_name.name.as_str(); if contains_unsafe(&old_str) &&!contains_unsafe(&new_str) { span_lint( cx, UNSAFE_REMOVED_FROM_NAME, span, &format!( "removed `unsafe` from the name of `{}` in use as `{}`", old_str, new_str ), ); } } #[must_use] fn
(name: &str) -> bool { name.contains("Unsafe") || name.contains("unsafe") }
contains_unsafe
identifier_name
unsafe_removed_from_name.rs
use clippy_utils::diagnostics::span_lint; use rustc_ast::ast::{Item, ItemKind, UseTree, UseTreeKind}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Span; use rustc_span::symbol::Ident; declare_clippy_lint! { /// ### What it does /// Checks for imports that remove "unsafe" from an item's /// name. /// /// ### Why is this bad? /// Renaming makes it less clear which traits and /// structures are unsafe. /// /// ### Example /// ```rust,ignore /// use std::cell::{UnsafeCell as TotallySafeCell}; /// /// extern crate crossbeam; /// use crossbeam::{spawn_unsafe as spawn}; /// ``` pub UNSAFE_REMOVED_FROM_NAME, style, "`unsafe` removed from API names on import" } declare_lint_pass!(UnsafeNameRemoval => [UNSAFE_REMOVED_FROM_NAME]); impl EarlyLintPass for UnsafeNameRemoval { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) { if let ItemKind::Use(ref use_tree) = item.kind { check_use_tree(use_tree, cx, item.span); } } } fn check_use_tree(use_tree: &UseTree, cx: &EarlyContext<'_>, span: Span)
fn unsafe_to_safe_check(old_name: Ident, new_name: Ident, cx: &EarlyContext<'_>, span: Span) { let old_str = old_name.name.as_str(); let new_str = new_name.name.as_str(); if contains_unsafe(&old_str) &&!contains_unsafe(&new_str) { span_lint( cx, UNSAFE_REMOVED_FROM_NAME, span, &format!( "removed `unsafe` from the name of `{}` in use as `{}`", old_str, new_str ), ); } } #[must_use] fn contains_unsafe(name: &str) -> bool { name.contains("Unsafe") || name.contains("unsafe") }
{ match use_tree.kind { UseTreeKind::Simple(Some(new_name), ..) => { let old_name = use_tree .prefix .segments .last() .expect("use paths cannot be empty") .ident; unsafe_to_safe_check(old_name, new_name, cx, span); }, UseTreeKind::Simple(None, ..) | UseTreeKind::Glob => {}, UseTreeKind::Nested(ref nested_use_tree) => { for &(ref use_tree, _) in nested_use_tree { check_use_tree(use_tree, cx, span); } }, } }
identifier_body
unsafe_removed_from_name.rs
use clippy_utils::diagnostics::span_lint; use rustc_ast::ast::{Item, ItemKind, UseTree, UseTreeKind}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::source_map::Span; use rustc_span::symbol::Ident; declare_clippy_lint! { /// ### What it does /// Checks for imports that remove "unsafe" from an item's /// name. /// /// ### Why is this bad? /// Renaming makes it less clear which traits and /// structures are unsafe. /// /// ### Example /// ```rust,ignore /// use std::cell::{UnsafeCell as TotallySafeCell}; /// /// extern crate crossbeam; /// use crossbeam::{spawn_unsafe as spawn}; /// ``` pub UNSAFE_REMOVED_FROM_NAME, style, "`unsafe` removed from API names on import" } declare_lint_pass!(UnsafeNameRemoval => [UNSAFE_REMOVED_FROM_NAME]); impl EarlyLintPass for UnsafeNameRemoval { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) { if let ItemKind::Use(ref use_tree) = item.kind { check_use_tree(use_tree, cx, item.span); } } } fn check_use_tree(use_tree: &UseTree, cx: &EarlyContext<'_>, span: Span) { match use_tree.kind { UseTreeKind::Simple(Some(new_name),..) => { let old_name = use_tree .prefix .segments .last() .expect("use paths cannot be empty") .ident; unsafe_to_safe_check(old_name, new_name, cx, span); }, UseTreeKind::Simple(None,..) | UseTreeKind::Glob => {}, UseTreeKind::Nested(ref nested_use_tree) => {
}, } } fn unsafe_to_safe_check(old_name: Ident, new_name: Ident, cx: &EarlyContext<'_>, span: Span) { let old_str = old_name.name.as_str(); let new_str = new_name.name.as_str(); if contains_unsafe(&old_str) &&!contains_unsafe(&new_str) { span_lint( cx, UNSAFE_REMOVED_FROM_NAME, span, &format!( "removed `unsafe` from the name of `{}` in use as `{}`", old_str, new_str ), ); } } #[must_use] fn contains_unsafe(name: &str) -> bool { name.contains("Unsafe") || name.contains("unsafe") }
for &(ref use_tree, _) in nested_use_tree { check_use_tree(use_tree, cx, span); }
random_line_split
bots.rs
//============================================================================= // // WARNING: This file is AUTO-GENERATED // // Do not make changes directly to this file. // // If you would like to make a change to the library, please update the schema // definitions at https://github.com/slack-rs/slack-api-schemas // // If you would like to make a change how the library was generated, // please edit https://github.com/slack-rs/slack-rs-api/tree/master/codegen // //============================================================================= pub use crate::mod_types::bots_types::*; use crate::requests::SlackWebRequestSender; /// Gets information about a bot user. /// /// Wraps https://api.slack.com/methods/bots.info pub async fn info<R>( client: &R, token: &str, request: &InfoRequest<'_>, ) -> Result<InfoResponse, InfoError<R::Error>> where R: SlackWebRequestSender,
{ let params = vec![Some(("token", token)), request.bot.map(|bot| ("bot", bot))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("bots.info"); client .send(&url, &params[..]) .await .map_err(InfoError::Client) .and_then(|result| { serde_json::from_str::<InfoResponse>(&result) .map_err(|e| InfoError::MalformedResponse(result, e)) }) .and_then(|o| o.into()) }
identifier_body
bots.rs
//============================================================================= // // WARNING: This file is AUTO-GENERATED // // Do not make changes directly to this file. // // If you would like to make a change to the library, please update the schema // definitions at https://github.com/slack-rs/slack-api-schemas // // If you would like to make a change how the library was generated, // please edit https://github.com/slack-rs/slack-rs-api/tree/master/codegen // //============================================================================= pub use crate::mod_types::bots_types::*; use crate::requests::SlackWebRequestSender; /// Gets information about a bot user. /// /// Wraps https://api.slack.com/methods/bots.info pub async fn
<R>( client: &R, token: &str, request: &InfoRequest<'_>, ) -> Result<InfoResponse, InfoError<R::Error>> where R: SlackWebRequestSender, { let params = vec![Some(("token", token)), request.bot.map(|bot| ("bot", bot))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("bots.info"); client .send(&url, &params[..]) .await .map_err(InfoError::Client) .and_then(|result| { serde_json::from_str::<InfoResponse>(&result) .map_err(|e| InfoError::MalformedResponse(result, e)) }) .and_then(|o| o.into()) }
info
identifier_name
bots.rs
//============================================================================= // // WARNING: This file is AUTO-GENERATED // // Do not make changes directly to this file. // // If you would like to make a change to the library, please update the schema // definitions at https://github.com/slack-rs/slack-api-schemas // // If you would like to make a change how the library was generated, // please edit https://github.com/slack-rs/slack-rs-api/tree/master/codegen // //============================================================================= pub use crate::mod_types::bots_types::*; use crate::requests::SlackWebRequestSender; /// Gets information about a bot user. /// /// Wraps https://api.slack.com/methods/bots.info pub async fn info<R>( client: &R, token: &str, request: &InfoRequest<'_>, ) -> Result<InfoResponse, InfoError<R::Error>> where R: SlackWebRequestSender,
.send(&url, &params[..]) .await .map_err(InfoError::Client) .and_then(|result| { serde_json::from_str::<InfoResponse>(&result) .map_err(|e| InfoError::MalformedResponse(result, e)) }) .and_then(|o| o.into()) }
{ let params = vec![Some(("token", token)), request.bot.map(|bot| ("bot", bot))]; let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>(); let url = crate::get_slack_url_for_method("bots.info"); client
random_line_split
UBT.rs
use std::cell::RefCell; use std::rc::Rc; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } } pub fn is_unival_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool { is_UT_WithState(root.as_ref(), root.as_ref().unwrap().borrow().val.clone()) } pub fn is_UT_WithState(root: Option<&Rc<RefCell<TreeNode>>>, val: i32) -> bool { if root.is_none() { return true; } let this_root = root.as_ref().unwrap(); let this_val = this_root.borrow().val; if this_val!= val
is_UT_WithState(this_root.borrow().left.as_ref(), this_val) && is_UT_WithState(this_root.borrow().right.as_ref(), this_val) }
{ return false; }
conditional_block
UBT.rs
use std::cell::RefCell; use std::rc::Rc; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode {
left: None, right: None, } } } pub fn is_unival_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool { is_UT_WithState(root.as_ref(), root.as_ref().unwrap().borrow().val.clone()) } pub fn is_UT_WithState(root: Option<&Rc<RefCell<TreeNode>>>, val: i32) -> bool { if root.is_none() { return true; } let this_root = root.as_ref().unwrap(); let this_val = this_root.borrow().val; if this_val!= val { return false; } is_UT_WithState(this_root.borrow().left.as_ref(), this_val) && is_UT_WithState(this_root.borrow().right.as_ref(), this_val) }
#[inline] pub fn new(val: i32) -> Self { TreeNode { val,
random_line_split
UBT.rs
use std::cell::RefCell; use std::rc::Rc; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } } pub fn
(root: Option<Rc<RefCell<TreeNode>>>) -> bool { is_UT_WithState(root.as_ref(), root.as_ref().unwrap().borrow().val.clone()) } pub fn is_UT_WithState(root: Option<&Rc<RefCell<TreeNode>>>, val: i32) -> bool { if root.is_none() { return true; } let this_root = root.as_ref().unwrap(); let this_val = this_root.borrow().val; if this_val!= val { return false; } is_UT_WithState(this_root.borrow().left.as_ref(), this_val) && is_UT_WithState(this_root.borrow().right.as_ref(), this_val) }
is_unival_tree
identifier_name
structures.rs
//! Structures provided by D3D11 //! //! # References //! [D3D11 Structures, MSDN] //! (https://msdn.microsoft.com/en-us/library/windows/desktop/ff476155(v=vs.85).aspx) #![allow(non_snake_case, non_camel_case_types)] use winapi::minwindef::*; use winapi::basetsd::*; use winapi::{LPCSTR, RECT}; use dxgi::DXGI_FORMAT; use core::enumerations::*; pub type D3D11_RECT = RECT; #[repr(C)] pub struct D3D11_BLEND_DESC { pub AlphaToCoverageEnable: BOOL, pub IndependentBlendEnable: BOOL, pub RenderTarget: [D3D11_RENDER_TARGET_BLEND_DESC; 8], } #[repr(C)] pub struct D3D11_BLEND_DESC1 { pub AlphaToCoverageEnable: BOOL, pub IndependentBlendEnable: BOOL, pub RenderTarget: [D3D11_RENDER_TARGET_BLEND_DESC1; 8],
#[repr(C)] pub struct D3D11_BOX { pub left: UINT, pub top: UINT, pub front: UINT, pub right: UINT, pub bottom: UINT, pub back: UINT, } #[repr(C)] pub struct D3D11_COUNTER_DESC { pub Counter: D3D11_COUNTER, pub MiscFlags: UINT, } #[repr(C)] pub struct D3D11_COUNTER_INFO { pub LastDeviceDependentCounter: D3D11_COUNTER, pub NumSimultaneousCounters: UINT, pub NumDetectableParallelUnits: UINT8, } #[repr(C)] pub struct D3D11_DEPTH_STENCIL_DESC { pub DepthEnable: BOOL, pub DepthWriteMask: D3D11_DEPTH_WRITE_MASK, pub DepthFunc: D3D11_COMPARISON_FUNC, pub StencilEnable: BOOL, pub StencilReadMask: UINT8, pub StencilWriteMask: UINT8, pub FrontFace: D3D11_DEPTH_STENCILOP_DESC, pub BackFace: D3D11_DEPTH_STENCILOP_DESC, } #[repr(C)] pub struct D3D11_DEPTH_STENCILOP_DESC { pub StencilFailOp: D3D11_STENCIL_OP, pub StencilDepthFailOp: D3D11_STENCIL_OP, pub StencilPassOp: D3D11_STENCIL_OP, pub StencilFunc: D3D11_COMPARISON_FUNC, } #[repr(C)] pub struct D3D11_FEATURE_DATA_ARCHITECTURE_INFO { pub TileBasedDeferredRenderer: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D9_OPTIONS { pub FullNonPow2TextureSupport: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D9_SHADOW_SUPPORT { pub SupportsDepthAsTextureWithLessEqualComparisonFilter: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D9_SIMPLE_INSTANCING_SUPPORT { pub SimpleInstancingSupported: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS { pub ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D11_OPTIONS { pub OutputMergerLogicOp: BOOL, pub UAVOnlyRenderingForcedSampleCount: BOOL, pub DiscardAPIsSeenByDriver: BOOL, pub FlagsForUpdateAndCopySeenByDriver: BOOL, pub ClearView: BOOL, pub CopyWithOverlap: BOOL, pub ConstantBufferPartialUpdate: BOOL, pub ConstantBufferOffsetting: BOOL, pub MapNoOverwriteOnDynamicConstantBuffer: BOOL, pub MapNoOverwriteOnDynamicBufferSRV: BOOL, pub MultisampleRTVWithForcedSampleCountOne: BOOL, pub SAD4ShaderInstructions: BOOL, pub ExtendedDoublesShaderInstructions: BOOL, pub ExtendedResourceSharing: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D11_OPTIONS1 { pub TiledResourcesTier: D3D11_TILED_RESOURCES_TIER, pub MinMaxFiltering: BOOL, pub ClearViewAlsoSupportsDepthOnlyFormats: BOOL, pub MapOnDefaultBuffers: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_DOUBLES { pub DoublePrecisionFloatShaderOps: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_FORMAT_SUPPORT { pub InFormat: DXGI_FORMAT, pub OutFormatSupport: UINT, } pub struct D3D11_FEATURE_DATA_FORMAT_SUPPORT2 { pub InFormat: DXGI_FORMAT, pub OutFormatSupport2: UINT, } #[repr(C)] pub struct D3D11_FEATURE_DATA_MARKER_SUPPORT { pub Profile: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_THREADING { pub DriverConcurrentCreates: BOOL, pub DriverCommandLists: BOOL, } #[repr(C)] pub struct D3D11_INPUT_ELEMENT_DESC { pub SemanticName: LPCSTR, pub SemanticIndex: UINT, pub Format: DXGI_FORMAT, pub InputSlot: UINT, pub AlignedByteOffset: UINT, pub InputSlotClass: D3D11_INPUT_CLASSIFICATION, pub InstanceDataStepRate: UINT, } #[repr(C)] pub struct D3D11_QUERY_DATA_PIPELINE_STATISTICS { pub IAVertices: UINT64, pub IAPrimitives: UINT64, pub VSInvocations: UINT64, pub GSInvocations: UINT64, pub GSPrimitives: UINT64, pub CInvocations: UINT64, pub CPrimitives: UINT64, pub PSInvocations: UINT64, pub HSInvocations: UINT64, pub DSInvocations: UINT64, pub CSInvocations: UINT64, } #[repr(C)] pub struct D3D11_QUERY_DATA_SO_STATISTICS { pub NumPrimitivesWritten: UINT64, pub PrimitivesStorageNeeded: UINT64, } #[repr(C)] pub struct D3D11_QUERY_DATA_TIMESTAMP_DISJOINT { pub Frequency: UINT64, pub Disjoint: BOOL, } #[repr(C)] pub struct D3D11_QUERY_DESC { pub Query: D3D11_QUERY, pub MiscFlags: UINT, } #[repr(C)] pub struct D3D11_RASTERIZER_DESC { pub FillMode: D3D11_FILL_MODE, pub CullMode: D3D11_CULL_MODE, pub FrontCounterClockwise: BOOL, pub DepthBias: INT, pub DepthBiasClamp: FLOAT, pub SlopeScaledDepthBias: FLOAT, pub DepthClipEnable: BOOL, pub ScissorEnable: BOOL, pub MultisampleEnable: BOOL, pub AntialiasedLineEnable: BOOL, } #[repr(C)] pub struct D3D11_RASTERIZER_DESC1 { pub FillMode: D3D11_FILL_MODE, pub CullMode: D3D11_CULL_MODE, pub FrontCounterClockwise: BOOL, pub DepthBias: INT, pub DepthBiasClamp: FLOAT, pub SlopeScaledDepthBias: FLOAT, pub DepthClipEnable: BOOL, pub ScissorEnable: BOOL, pub MultisampleEnable: BOOL, pub AntialiasedLineEnable: BOOL, pub ForcedSampleCount: UINT, } #[repr(C)] pub struct D3D11_RENDER_TARGET_BLEND_DESC { pub BlendEnable: BOOL, pub SrcBlend: D3D11_BLEND, pub DestBlend: D3D11_BLEND, pub BlendOp: D3D11_BLEND_OP, pub SrcBlendAlpha: D3D11_BLEND, pub DestBlendAlpha: D3D11_BLEND, pub BlendOpAlpha: D3D11_BLEND_OP, pub RenderTargetWriteMask: UINT8, } #[repr(C)] pub struct D3D11_RENDER_TARGET_BLEND_DESC1 { pub BlendEnable: BOOL, pub LogicOpEnable: BOOL, pub SrcBlend: D3D11_BLEND, pub DestBlend: D3D11_BLEND, pub BlendOp: D3D11_BLEND_OP, pub SrcBlendAlpha: D3D11_BLEND, pub DestBlendAlpha: D3D11_BLEND, pub BlendOpAlpha: D3D11_BLEND_OP, pub LogicOp: D3D11_LOGIC_OP, pub RenderTargetWriteMask: UINT8, } #[repr(C)] pub struct D3D11_SAMPLER_DESC { pub Filter: D3D11_FILTER, pub AddressU: D3D11_TEXTURE_ADDRESS_MODE, pub AddressV: D3D11_TEXTURE_ADDRESS_MODE, pub AddressW: D3D11_TEXTURE_ADDRESS_MODE, pub MipLODBias: FLOAT, pub MaxAnisotropy: UINT, pub ComparisonFunc: D3D11_COMPARISON_FUNC, pub BorderColor: [FLOAT; 4], pub MinLOD: FLOAT, pub MaxLOD: FLOAT, } #[repr(C)] pub struct D3D11_SO_DECLARATION_ENTRY { pub Stream: UINT, pub SemanticName: LPCSTR, pub SemanticIndex: UINT, pub StartComponent: BYTE, pub ComponentCount: BYTE, pub OutputSlot: BYTE, } #[repr(C)] pub struct D3D11_VIEWPORT { pub TopLeftX: FLOAT, pub TopLeftY: FLOAT, pub Width: FLOAT, pub Height: FLOAT, pub MinDepth: FLOAT, pub MaxDepth: FLOAT, }
}
random_line_split
structures.rs
//! Structures provided by D3D11 //! //! # References //! [D3D11 Structures, MSDN] //! (https://msdn.microsoft.com/en-us/library/windows/desktop/ff476155(v=vs.85).aspx) #![allow(non_snake_case, non_camel_case_types)] use winapi::minwindef::*; use winapi::basetsd::*; use winapi::{LPCSTR, RECT}; use dxgi::DXGI_FORMAT; use core::enumerations::*; pub type D3D11_RECT = RECT; #[repr(C)] pub struct D3D11_BLEND_DESC { pub AlphaToCoverageEnable: BOOL, pub IndependentBlendEnable: BOOL, pub RenderTarget: [D3D11_RENDER_TARGET_BLEND_DESC; 8], } #[repr(C)] pub struct D3D11_BLEND_DESC1 { pub AlphaToCoverageEnable: BOOL, pub IndependentBlendEnable: BOOL, pub RenderTarget: [D3D11_RENDER_TARGET_BLEND_DESC1; 8], } #[repr(C)] pub struct D3D11_BOX { pub left: UINT, pub top: UINT, pub front: UINT, pub right: UINT, pub bottom: UINT, pub back: UINT, } #[repr(C)] pub struct D3D11_COUNTER_DESC { pub Counter: D3D11_COUNTER, pub MiscFlags: UINT, } #[repr(C)] pub struct D3D11_COUNTER_INFO { pub LastDeviceDependentCounter: D3D11_COUNTER, pub NumSimultaneousCounters: UINT, pub NumDetectableParallelUnits: UINT8, } #[repr(C)] pub struct D3D11_DEPTH_STENCIL_DESC { pub DepthEnable: BOOL, pub DepthWriteMask: D3D11_DEPTH_WRITE_MASK, pub DepthFunc: D3D11_COMPARISON_FUNC, pub StencilEnable: BOOL, pub StencilReadMask: UINT8, pub StencilWriteMask: UINT8, pub FrontFace: D3D11_DEPTH_STENCILOP_DESC, pub BackFace: D3D11_DEPTH_STENCILOP_DESC, } #[repr(C)] pub struct D3D11_DEPTH_STENCILOP_DESC { pub StencilFailOp: D3D11_STENCIL_OP, pub StencilDepthFailOp: D3D11_STENCIL_OP, pub StencilPassOp: D3D11_STENCIL_OP, pub StencilFunc: D3D11_COMPARISON_FUNC, } #[repr(C)] pub struct D3D11_FEATURE_DATA_ARCHITECTURE_INFO { pub TileBasedDeferredRenderer: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D9_OPTIONS { pub FullNonPow2TextureSupport: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D9_SHADOW_SUPPORT { pub SupportsDepthAsTextureWithLessEqualComparisonFilter: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D9_SIMPLE_INSTANCING_SUPPORT { pub SimpleInstancingSupported: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS { pub ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_D3D11_OPTIONS { pub OutputMergerLogicOp: BOOL, pub UAVOnlyRenderingForcedSampleCount: BOOL, pub DiscardAPIsSeenByDriver: BOOL, pub FlagsForUpdateAndCopySeenByDriver: BOOL, pub ClearView: BOOL, pub CopyWithOverlap: BOOL, pub ConstantBufferPartialUpdate: BOOL, pub ConstantBufferOffsetting: BOOL, pub MapNoOverwriteOnDynamicConstantBuffer: BOOL, pub MapNoOverwriteOnDynamicBufferSRV: BOOL, pub MultisampleRTVWithForcedSampleCountOne: BOOL, pub SAD4ShaderInstructions: BOOL, pub ExtendedDoublesShaderInstructions: BOOL, pub ExtendedResourceSharing: BOOL, } #[repr(C)] pub struct
{ pub TiledResourcesTier: D3D11_TILED_RESOURCES_TIER, pub MinMaxFiltering: BOOL, pub ClearViewAlsoSupportsDepthOnlyFormats: BOOL, pub MapOnDefaultBuffers: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_DOUBLES { pub DoublePrecisionFloatShaderOps: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_FORMAT_SUPPORT { pub InFormat: DXGI_FORMAT, pub OutFormatSupport: UINT, } pub struct D3D11_FEATURE_DATA_FORMAT_SUPPORT2 { pub InFormat: DXGI_FORMAT, pub OutFormatSupport2: UINT, } #[repr(C)] pub struct D3D11_FEATURE_DATA_MARKER_SUPPORT { pub Profile: BOOL, } #[repr(C)] pub struct D3D11_FEATURE_DATA_THREADING { pub DriverConcurrentCreates: BOOL, pub DriverCommandLists: BOOL, } #[repr(C)] pub struct D3D11_INPUT_ELEMENT_DESC { pub SemanticName: LPCSTR, pub SemanticIndex: UINT, pub Format: DXGI_FORMAT, pub InputSlot: UINT, pub AlignedByteOffset: UINT, pub InputSlotClass: D3D11_INPUT_CLASSIFICATION, pub InstanceDataStepRate: UINT, } #[repr(C)] pub struct D3D11_QUERY_DATA_PIPELINE_STATISTICS { pub IAVertices: UINT64, pub IAPrimitives: UINT64, pub VSInvocations: UINT64, pub GSInvocations: UINT64, pub GSPrimitives: UINT64, pub CInvocations: UINT64, pub CPrimitives: UINT64, pub PSInvocations: UINT64, pub HSInvocations: UINT64, pub DSInvocations: UINT64, pub CSInvocations: UINT64, } #[repr(C)] pub struct D3D11_QUERY_DATA_SO_STATISTICS { pub NumPrimitivesWritten: UINT64, pub PrimitivesStorageNeeded: UINT64, } #[repr(C)] pub struct D3D11_QUERY_DATA_TIMESTAMP_DISJOINT { pub Frequency: UINT64, pub Disjoint: BOOL, } #[repr(C)] pub struct D3D11_QUERY_DESC { pub Query: D3D11_QUERY, pub MiscFlags: UINT, } #[repr(C)] pub struct D3D11_RASTERIZER_DESC { pub FillMode: D3D11_FILL_MODE, pub CullMode: D3D11_CULL_MODE, pub FrontCounterClockwise: BOOL, pub DepthBias: INT, pub DepthBiasClamp: FLOAT, pub SlopeScaledDepthBias: FLOAT, pub DepthClipEnable: BOOL, pub ScissorEnable: BOOL, pub MultisampleEnable: BOOL, pub AntialiasedLineEnable: BOOL, } #[repr(C)] pub struct D3D11_RASTERIZER_DESC1 { pub FillMode: D3D11_FILL_MODE, pub CullMode: D3D11_CULL_MODE, pub FrontCounterClockwise: BOOL, pub DepthBias: INT, pub DepthBiasClamp: FLOAT, pub SlopeScaledDepthBias: FLOAT, pub DepthClipEnable: BOOL, pub ScissorEnable: BOOL, pub MultisampleEnable: BOOL, pub AntialiasedLineEnable: BOOL, pub ForcedSampleCount: UINT, } #[repr(C)] pub struct D3D11_RENDER_TARGET_BLEND_DESC { pub BlendEnable: BOOL, pub SrcBlend: D3D11_BLEND, pub DestBlend: D3D11_BLEND, pub BlendOp: D3D11_BLEND_OP, pub SrcBlendAlpha: D3D11_BLEND, pub DestBlendAlpha: D3D11_BLEND, pub BlendOpAlpha: D3D11_BLEND_OP, pub RenderTargetWriteMask: UINT8, } #[repr(C)] pub struct D3D11_RENDER_TARGET_BLEND_DESC1 { pub BlendEnable: BOOL, pub LogicOpEnable: BOOL, pub SrcBlend: D3D11_BLEND, pub DestBlend: D3D11_BLEND, pub BlendOp: D3D11_BLEND_OP, pub SrcBlendAlpha: D3D11_BLEND, pub DestBlendAlpha: D3D11_BLEND, pub BlendOpAlpha: D3D11_BLEND_OP, pub LogicOp: D3D11_LOGIC_OP, pub RenderTargetWriteMask: UINT8, } #[repr(C)] pub struct D3D11_SAMPLER_DESC { pub Filter: D3D11_FILTER, pub AddressU: D3D11_TEXTURE_ADDRESS_MODE, pub AddressV: D3D11_TEXTURE_ADDRESS_MODE, pub AddressW: D3D11_TEXTURE_ADDRESS_MODE, pub MipLODBias: FLOAT, pub MaxAnisotropy: UINT, pub ComparisonFunc: D3D11_COMPARISON_FUNC, pub BorderColor: [FLOAT; 4], pub MinLOD: FLOAT, pub MaxLOD: FLOAT, } #[repr(C)] pub struct D3D11_SO_DECLARATION_ENTRY { pub Stream: UINT, pub SemanticName: LPCSTR, pub SemanticIndex: UINT, pub StartComponent: BYTE, pub ComponentCount: BYTE, pub OutputSlot: BYTE, } #[repr(C)] pub struct D3D11_VIEWPORT { pub TopLeftX: FLOAT, pub TopLeftY: FLOAT, pub Width: FLOAT, pub Height: FLOAT, pub MinDepth: FLOAT, pub MaxDepth: FLOAT, }
D3D11_FEATURE_DATA_D3D11_OPTIONS1
identifier_name
price_fraction.rs
// http://rosettacode.org/wiki/Price_fraction fn fix_price(num: f64) -> f64 { match num { 0.96...1.00 => 1.00, 0.91...0.96 => 0.98, 0.86...0.91 => 0.94, 0.81...0.86 => 0.90, 0.76...0.81 => 0.86, 0.71...0.76 => 0.82, 0.66...0.71 => 0.78, 0.61...0.66 => 0.74, 0.56...0.61 => 0.70, 0.51...0.56 => 0.66, 0.46...0.51 => 0.62, 0.41...0.46 => 0.58, 0.36...0.41 => 0.54, 0.31...0.36 => 0.50, 0.26...0.31 => 0.44, 0.21...0.26 => 0.38, 0.16...0.21 => 0.32, 0.11...0.16 => 0.26, 0.06...0.11 => 0.18, 0.00...0.06 => 0.10, // panics on invalid value _ => unreachable!(), } } fn main()
// typically this could be included in the match as those check for exhaustiveness already // by explicitly listing all remaining ranges / values instead of a catch-all underscore (_) // but f64::NaN, f64::INFINITY and f64::NEG_INFINITY can't be matched like this #[test] fn exhaustiveness_check() { let mut input_price = 0.; while input_price <= 1. { fix_price(input_price); input_price += 0.01; } }
{ let mut n: f64 = 0.04; while n <= 1.00 { println!("{:.2} => {}", n, fix_price(n)); n += 0.04; } }
identifier_body
price_fraction.rs
// http://rosettacode.org/wiki/Price_fraction fn fix_price(num: f64) -> f64 { match num { 0.96...1.00 => 1.00, 0.91...0.96 => 0.98, 0.86...0.91 => 0.94, 0.81...0.86 => 0.90, 0.76...0.81 => 0.86, 0.71...0.76 => 0.82, 0.66...0.71 => 0.78, 0.61...0.66 => 0.74, 0.56...0.61 => 0.70, 0.51...0.56 => 0.66, 0.46...0.51 => 0.62, 0.41...0.46 => 0.58, 0.36...0.41 => 0.54, 0.31...0.36 => 0.50, 0.26...0.31 => 0.44, 0.21...0.26 => 0.38, 0.16...0.21 => 0.32, 0.11...0.16 => 0.26, 0.06...0.11 => 0.18, 0.00...0.06 => 0.10,
_ => unreachable!(), } } fn main() { let mut n: f64 = 0.04; while n <= 1.00 { println!("{:.2} => {}", n, fix_price(n)); n += 0.04; } } // typically this could be included in the match as those check for exhaustiveness already // by explicitly listing all remaining ranges / values instead of a catch-all underscore (_) // but f64::NaN, f64::INFINITY and f64::NEG_INFINITY can't be matched like this #[test] fn exhaustiveness_check() { let mut input_price = 0.; while input_price <= 1. { fix_price(input_price); input_price += 0.01; } }
// panics on invalid value
random_line_split
price_fraction.rs
// http://rosettacode.org/wiki/Price_fraction fn
(num: f64) -> f64 { match num { 0.96...1.00 => 1.00, 0.91...0.96 => 0.98, 0.86...0.91 => 0.94, 0.81...0.86 => 0.90, 0.76...0.81 => 0.86, 0.71...0.76 => 0.82, 0.66...0.71 => 0.78, 0.61...0.66 => 0.74, 0.56...0.61 => 0.70, 0.51...0.56 => 0.66, 0.46...0.51 => 0.62, 0.41...0.46 => 0.58, 0.36...0.41 => 0.54, 0.31...0.36 => 0.50, 0.26...0.31 => 0.44, 0.21...0.26 => 0.38, 0.16...0.21 => 0.32, 0.11...0.16 => 0.26, 0.06...0.11 => 0.18, 0.00...0.06 => 0.10, // panics on invalid value _ => unreachable!(), } } fn main() { let mut n: f64 = 0.04; while n <= 1.00 { println!("{:.2} => {}", n, fix_price(n)); n += 0.04; } } // typically this could be included in the match as those check for exhaustiveness already // by explicitly listing all remaining ranges / values instead of a catch-all underscore (_) // but f64::NaN, f64::INFINITY and f64::NEG_INFINITY can't be matched like this #[test] fn exhaustiveness_check() { let mut input_price = 0.; while input_price <= 1. { fix_price(input_price); input_price += 0.01; } }
fix_price
identifier_name
main.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![deny(unused_imports)] #![deny(unused_variables)] #![feature(box_syntax)] #![feature(convert)] // For FFI #![allow(non_snake_case, dead_code)] //! The `servo` test application. //! //! Creates a `Browser` instance with a simple implementation of //! the compositor's `WindowMethods` to create a working web browser. //! //! This browser's implementation of `WindowMethods` is built on top //! of [glutin], the cross-platform OpenGL utility and windowing //! library. //! //! For the engine itself look next door in lib.rs. //! //! [glutin]: https://github.com/tomaka/glutin extern crate compositing; extern crate egl; extern crate env_logger; extern crate errno; extern crate euclid; extern crate gleam; extern crate layers; extern crate libc; extern crate msg; extern crate net_traits; extern crate servo; extern crate time; extern crate url; extern crate util; #[link(name = "stlport")] extern {} use compositing::windowing::WindowEvent; use net_traits::hosts; use servo::Browser; use std::env; use util::opts; mod input; mod window; struct
{ browser: Browser, } fn main() { env_logger::init().unwrap(); // Parse the command line options and store them globally opts::from_cmdline_args(env::args().collect::<Vec<_>>().as_slice()); hosts::global_init(); let window = if opts::get().headless { None } else { Some(window::Window::new()) }; // Our wrapper around `Browser` that also implements some // callbacks required by the glutin window implementation. let mut browser = BrowserWrapper { browser: Browser::new(window.clone()), }; match window { None => (), Some(ref window) => input::run_input_loop(&window.event_send) } browser.browser.handle_events(vec![WindowEvent::InitializeCompositing]); // Feed events from the window to the browser until the browser // says to stop. loop { let should_continue = match window { None => browser.browser.handle_events(vec![WindowEvent::Idle]), Some(ref window) => { let events = window.wait_events(); browser.browser.handle_events(events) } }; if!should_continue { break } } }
BrowserWrapper
identifier_name
main.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![deny(unused_imports)] #![deny(unused_variables)] #![feature(box_syntax)] #![feature(convert)] // For FFI #![allow(non_snake_case, dead_code)] //! The `servo` test application. //! //! Creates a `Browser` instance with a simple implementation of //! the compositor's `WindowMethods` to create a working web browser. //! //! This browser's implementation of `WindowMethods` is built on top //! of [glutin], the cross-platform OpenGL utility and windowing //! library. //! //! For the engine itself look next door in lib.rs. //! //! [glutin]: https://github.com/tomaka/glutin extern crate compositing; extern crate egl; extern crate env_logger; extern crate errno; extern crate euclid; extern crate gleam; extern crate layers; extern crate libc; extern crate msg; extern crate net_traits; extern crate servo; extern crate time; extern crate url; extern crate util; #[link(name = "stlport")] extern {} use compositing::windowing::WindowEvent; use net_traits::hosts; use servo::Browser; use std::env; use util::opts; mod input; mod window; struct BrowserWrapper { browser: Browser, } fn main() { env_logger::init().unwrap(); // Parse the command line options and store them globally opts::from_cmdline_args(env::args().collect::<Vec<_>>().as_slice()); hosts::global_init(); let window = if opts::get().headless { None } else { Some(window::Window::new()) }; // Our wrapper around `Browser` that also implements some // callbacks required by the glutin window implementation. let mut browser = BrowserWrapper { browser: Browser::new(window.clone()), }; match window { None => (), Some(ref window) => input::run_input_loop(&window.event_send) } browser.browser.handle_events(vec![WindowEvent::InitializeCompositing]); // Feed events from the window to the browser until the browser // says to stop. loop { let should_continue = match window { None => browser.browser.handle_events(vec![WindowEvent::Idle]), Some(ref window) => { let events = window.wait_events(); browser.browser.handle_events(events) } }; if!should_continue
} }
{ break }
conditional_block
main.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![deny(unused_imports)]
#![feature(convert)] // For FFI #![allow(non_snake_case, dead_code)] //! The `servo` test application. //! //! Creates a `Browser` instance with a simple implementation of //! the compositor's `WindowMethods` to create a working web browser. //! //! This browser's implementation of `WindowMethods` is built on top //! of [glutin], the cross-platform OpenGL utility and windowing //! library. //! //! For the engine itself look next door in lib.rs. //! //! [glutin]: https://github.com/tomaka/glutin extern crate compositing; extern crate egl; extern crate env_logger; extern crate errno; extern crate euclid; extern crate gleam; extern crate layers; extern crate libc; extern crate msg; extern crate net_traits; extern crate servo; extern crate time; extern crate url; extern crate util; #[link(name = "stlport")] extern {} use compositing::windowing::WindowEvent; use net_traits::hosts; use servo::Browser; use std::env; use util::opts; mod input; mod window; struct BrowserWrapper { browser: Browser, } fn main() { env_logger::init().unwrap(); // Parse the command line options and store them globally opts::from_cmdline_args(env::args().collect::<Vec<_>>().as_slice()); hosts::global_init(); let window = if opts::get().headless { None } else { Some(window::Window::new()) }; // Our wrapper around `Browser` that also implements some // callbacks required by the glutin window implementation. let mut browser = BrowserWrapper { browser: Browser::new(window.clone()), }; match window { None => (), Some(ref window) => input::run_input_loop(&window.event_send) } browser.browser.handle_events(vec![WindowEvent::InitializeCompositing]); // Feed events from the window to the browser until the browser // says to stop. loop { let should_continue = match window { None => browser.browser.handle_events(vec![WindowEvent::Idle]), Some(ref window) => { let events = window.wait_events(); browser.browser.handle_events(events) } }; if!should_continue { break } } }
#![deny(unused_variables)] #![feature(box_syntax)]
random_line_split
addrinfo.rs
// Copyright 2014 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. use ai = std::io::net::addrinfo; use std::c_str::CString; use std::cast; use std::io::IoError; use std::libc; use std::libc::{c_char, c_int}; use std::ptr::{null, mut_null}; use super::net::sockaddr_to_addr; pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn
(host: Option<&str>, servname: Option<&str>, hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError> { assert!(host.is_some() || servname.is_some()); let c_host = host.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str()); let c_serv = servname.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str()); let hint = hint.map(|hint| { libc::addrinfo { ai_flags: hint.flags as c_int, ai_family: hint.family as c_int, ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, ai_canonname: null(), ai_addr: null(), ai_next: null() } }); let hint_ptr = hint.as_ref().map_or(null(), |x| x as *libc::addrinfo); let mut res = mut_null(); // Make the call let s = unsafe { let ch = if c_host.is_null() { null() } else { c_host.with_ref(|x| x) }; let cs = if c_serv.is_null() { null() } else { c_serv.with_ref(|x| x) }; getaddrinfo(ch, cs, hint_ptr, &mut res) }; // Error? if s!= 0 { return Err(get_error(s)); } // Collect all the results we found let mut addrs = ~[]; let mut rp = res; while rp.is_not_null() { unsafe { let addr = match sockaddr_to_addr(cast::transmute((*rp).ai_addr), (*rp).ai_addrlen as uint) { Ok(a) => a, Err(e) => return Err(e) }; addrs.push(ai::Info { address: addr, family: (*rp).ai_family as uint, socktype: None, protocol: None, flags: (*rp).ai_flags as uint }); rp = (*rp).ai_next as *mut libc::addrinfo; } } unsafe { freeaddrinfo(res); } Ok(addrs) } } extern "system" { fn getaddrinfo(node: *c_char, service: *c_char, hints: *libc::addrinfo, res: *mut *mut libc::addrinfo) -> c_int; fn freeaddrinfo(res: *mut libc::addrinfo); #[cfg(not(windows))] fn gai_strerror(errcode: c_int) -> *c_char; #[cfg(windows)] fn WSAGetLastError() -> c_int; } #[cfg(windows)] fn get_error(_: c_int) -> IoError { use super::translate_error; unsafe { translate_error(WSAGetLastError() as i32, true) } } #[cfg(not(windows))] fn get_error(s: c_int) -> IoError { use std::io; use std::str::raw::from_c_str; let err_str = unsafe { from_c_str(gai_strerror(s)) }; IoError { kind: io::OtherIoError, desc: "unable to resolve host", detail: Some(err_str), } }
run
identifier_name
addrinfo.rs
// Copyright 2014 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. use ai = std::io::net::addrinfo; use std::c_str::CString; use std::cast; use std::io::IoError; use std::libc; use std::libc::{c_char, c_int}; use std::ptr::{null, mut_null}; use super::net::sockaddr_to_addr; pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn run(host: Option<&str>, servname: Option<&str>, hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError> { assert!(host.is_some() || servname.is_some()); let c_host = host.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str()); let c_serv = servname.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str()); let hint = hint.map(|hint| { libc::addrinfo { ai_flags: hint.flags as c_int, ai_family: hint.family as c_int, ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, ai_canonname: null(), ai_addr: null(), ai_next: null() } }); let hint_ptr = hint.as_ref().map_or(null(), |x| x as *libc::addrinfo); let mut res = mut_null(); // Make the call let s = unsafe { let ch = if c_host.is_null()
else { c_host.with_ref(|x| x) }; let cs = if c_serv.is_null() { null() } else { c_serv.with_ref(|x| x) }; getaddrinfo(ch, cs, hint_ptr, &mut res) }; // Error? if s!= 0 { return Err(get_error(s)); } // Collect all the results we found let mut addrs = ~[]; let mut rp = res; while rp.is_not_null() { unsafe { let addr = match sockaddr_to_addr(cast::transmute((*rp).ai_addr), (*rp).ai_addrlen as uint) { Ok(a) => a, Err(e) => return Err(e) }; addrs.push(ai::Info { address: addr, family: (*rp).ai_family as uint, socktype: None, protocol: None, flags: (*rp).ai_flags as uint }); rp = (*rp).ai_next as *mut libc::addrinfo; } } unsafe { freeaddrinfo(res); } Ok(addrs) } } extern "system" { fn getaddrinfo(node: *c_char, service: *c_char, hints: *libc::addrinfo, res: *mut *mut libc::addrinfo) -> c_int; fn freeaddrinfo(res: *mut libc::addrinfo); #[cfg(not(windows))] fn gai_strerror(errcode: c_int) -> *c_char; #[cfg(windows)] fn WSAGetLastError() -> c_int; } #[cfg(windows)] fn get_error(_: c_int) -> IoError { use super::translate_error; unsafe { translate_error(WSAGetLastError() as i32, true) } } #[cfg(not(windows))] fn get_error(s: c_int) -> IoError { use std::io; use std::str::raw::from_c_str; let err_str = unsafe { from_c_str(gai_strerror(s)) }; IoError { kind: io::OtherIoError, desc: "unable to resolve host", detail: Some(err_str), } }
{ null() }
conditional_block
addrinfo.rs
// Copyright 2014 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. use ai = std::io::net::addrinfo; use std::c_str::CString; use std::cast; use std::io::IoError; use std::libc; use std::libc::{c_char, c_int}; use std::ptr::{null, mut_null}; use super::net::sockaddr_to_addr; pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn run(host: Option<&str>, servname: Option<&str>, hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError> { assert!(host.is_some() || servname.is_some()); let c_host = host.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str()); let c_serv = servname.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str()); let hint = hint.map(|hint| { libc::addrinfo { ai_flags: hint.flags as c_int, ai_family: hint.family as c_int, ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, ai_canonname: null(), ai_addr: null(), ai_next: null() } }); let hint_ptr = hint.as_ref().map_or(null(), |x| x as *libc::addrinfo); let mut res = mut_null(); // Make the call let s = unsafe { let ch = if c_host.is_null() { null() } else { c_host.with_ref(|x| x) }; let cs = if c_serv.is_null() { null() } else { c_serv.with_ref(|x| x) }; getaddrinfo(ch, cs, hint_ptr, &mut res) }; // Error? if s!= 0 { return Err(get_error(s)); } // Collect all the results we found let mut addrs = ~[]; let mut rp = res; while rp.is_not_null() { unsafe { let addr = match sockaddr_to_addr(cast::transmute((*rp).ai_addr), (*rp).ai_addrlen as uint) { Ok(a) => a, Err(e) => return Err(e) }; addrs.push(ai::Info { address: addr, family: (*rp).ai_family as uint, socktype: None, protocol: None, flags: (*rp).ai_flags as uint }); rp = (*rp).ai_next as *mut libc::addrinfo; } } unsafe { freeaddrinfo(res); } Ok(addrs) } } extern "system" { fn getaddrinfo(node: *c_char, service: *c_char, hints: *libc::addrinfo, res: *mut *mut libc::addrinfo) -> c_int; fn freeaddrinfo(res: *mut libc::addrinfo); #[cfg(not(windows))] fn gai_strerror(errcode: c_int) -> *c_char; #[cfg(windows)] fn WSAGetLastError() -> c_int; } #[cfg(windows)] fn get_error(_: c_int) -> IoError { use super::translate_error; unsafe { translate_error(WSAGetLastError() as i32, true) } } #[cfg(not(windows))] fn get_error(s: c_int) -> IoError
{ use std::io; use std::str::raw::from_c_str; let err_str = unsafe { from_c_str(gai_strerror(s)) }; IoError { kind: io::OtherIoError, desc: "unable to resolve host", detail: Some(err_str), } }
identifier_body
addrinfo.rs
// Copyright 2014 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. use ai = std::io::net::addrinfo; use std::c_str::CString; use std::cast; use std::io::IoError; use std::libc; use std::libc::{c_char, c_int}; use std::ptr::{null, mut_null}; use super::net::sockaddr_to_addr; pub struct GetAddrInfoRequest; impl GetAddrInfoRequest { pub fn run(host: Option<&str>, servname: Option<&str>, hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError> { assert!(host.is_some() || servname.is_some()); let c_host = host.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str()); let c_serv = servname.map_or(unsafe { CString::new(null(), true) }, |x| x.to_c_str()); let hint = hint.map(|hint| { libc::addrinfo { ai_flags: hint.flags as c_int, ai_family: hint.family as c_int, ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, ai_canonname: null(), ai_addr: null(), ai_next: null() }
let mut res = mut_null(); // Make the call let s = unsafe { let ch = if c_host.is_null() { null() } else { c_host.with_ref(|x| x) }; let cs = if c_serv.is_null() { null() } else { c_serv.with_ref(|x| x) }; getaddrinfo(ch, cs, hint_ptr, &mut res) }; // Error? if s!= 0 { return Err(get_error(s)); } // Collect all the results we found let mut addrs = ~[]; let mut rp = res; while rp.is_not_null() { unsafe { let addr = match sockaddr_to_addr(cast::transmute((*rp).ai_addr), (*rp).ai_addrlen as uint) { Ok(a) => a, Err(e) => return Err(e) }; addrs.push(ai::Info { address: addr, family: (*rp).ai_family as uint, socktype: None, protocol: None, flags: (*rp).ai_flags as uint }); rp = (*rp).ai_next as *mut libc::addrinfo; } } unsafe { freeaddrinfo(res); } Ok(addrs) } } extern "system" { fn getaddrinfo(node: *c_char, service: *c_char, hints: *libc::addrinfo, res: *mut *mut libc::addrinfo) -> c_int; fn freeaddrinfo(res: *mut libc::addrinfo); #[cfg(not(windows))] fn gai_strerror(errcode: c_int) -> *c_char; #[cfg(windows)] fn WSAGetLastError() -> c_int; } #[cfg(windows)] fn get_error(_: c_int) -> IoError { use super::translate_error; unsafe { translate_error(WSAGetLastError() as i32, true) } } #[cfg(not(windows))] fn get_error(s: c_int) -> IoError { use std::io; use std::str::raw::from_c_str; let err_str = unsafe { from_c_str(gai_strerror(s)) }; IoError { kind: io::OtherIoError, desc: "unable to resolve host", detail: Some(err_str), } }
}); let hint_ptr = hint.as_ref().map_or(null(), |x| x as *libc::addrinfo);
random_line_split
after.rs
use wtest_basic::dependencies::*; #[cfg( feature = "in_wtools" )] use wtools::former::Former; #[cfg( not( feature = "in_wtools" ) )] use former::Former; #[ derive( Debug, PartialEq, Former ) ] #[ form_after( fn after1< 'a >() -> Option< &'a str > ) ] pub struct Struct1 { #[ default( 31 ) ] pub int_1 : i32, } // impl Struct1 { fn after1< 'a >( &self ) -> Option< &'a str > { Some( "abc" ) } } // fn
() -> anyhow::Result< () > { let got = Struct1::former().form(); let expected = Some( "abc" ); assert_eq!( got, expected ); let got = Struct1::former()._form(); let expected = Struct1 { int_1 : 31 }; assert_eq!( got, expected ); Ok( () ) } // #[ test ] fn main_test() -> anyhow::Result< () > { basic()?; Ok( () ) }
basic
identifier_name
after.rs
use wtest_basic::dependencies::*; #[cfg( feature = "in_wtools" )] use wtools::former::Former; #[cfg( not( feature = "in_wtools" ) )] use former::Former; #[ derive( Debug, PartialEq, Former ) ] #[ form_after( fn after1< 'a >() -> Option< &'a str > ) ] pub struct Struct1 { #[ default( 31 ) ] pub int_1 : i32, } // impl Struct1
} // fn basic() -> anyhow::Result< () > { let got = Struct1::former().form(); let expected = Some( "abc" ); assert_eq!( got, expected ); let got = Struct1::former()._form(); let expected = Struct1 { int_1 : 31 }; assert_eq!( got, expected ); Ok( () ) } // #[ test ] fn main_test() -> anyhow::Result< () > { basic()?; Ok( () ) }
{ fn after1< 'a >( &self ) -> Option< &'a str > { Some( "abc" ) }
random_line_split
allocator.rs
use gccjit::{FunctionType, ToRValue}; use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::sym; use crate::GccContext; pub(crate) unsafe fn codegen(tcx: TyCtxt<'_>, mods: &mut GccContext, _module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool) { let context = &mods.context; let usize = match tcx.sess.target.pointer_width { 16 => context.new_type::<u16>(), 32 => context.new_type::<u32>(),
}; let i8 = context.new_type::<i8>(); let i8p = i8.make_pointer(); let void = context.new_type::<()>(); for method in ALLOCATOR_METHODS { let mut types = Vec::with_capacity(method.inputs.len()); for ty in method.inputs.iter() { match *ty { AllocatorTy::Layout => { types.push(usize); types.push(usize); } AllocatorTy::Ptr => types.push(i8p), AllocatorTy::Usize => types.push(usize), AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"), } } let output = match method.output { AllocatorTy::ResultPtr => Some(i8p), AllocatorTy::Unit => None, AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => { panic!("invalid allocator output") } }; let name = format!("__rust_{}", method.name); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let func = context.new_function(None, FunctionType::Exported, output.unwrap_or(void), &args, name, false); if tcx.sess.target.options.default_hidden_visibility { // TODO(antoyo): set visibility. } if tcx.sess.must_emit_unwind_tables() { // TODO(antoyo): emit unwind tables. } let callee = kind.fn_name(method.name); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let callee = context.new_function(None, FunctionType::Extern, output.unwrap_or(void), &args, callee, false); // TODO(antoyo): set visibility. let block = func.new_block("entry"); let args = args .iter() .enumerate() .map(|(i, _)| func.get_param(i as i32).to_rvalue()) .collect::<Vec<_>>(); let ret = context.new_call(None, callee, &args); //llvm::LLVMSetTailCall(ret, True); if output.is_some() { block.end_with_return(None, ret); } else { block.end_with_void_return(None); } // TODO(@Commeownist): Check if we need to emit some extra debugging info in certain circumstances // as described in https://github.com/rust-lang/rust/commit/77a96ed5646f7c3ee8897693decc4626fe380643 } let types = [usize, usize]; let name = "__rust_alloc_error_handler".to_string(); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let func = context.new_function(None, FunctionType::Exported, void, &args, name, false); let kind = if has_alloc_error_handler { AllocatorKind::Global } else { AllocatorKind::Default }; let callee = kind.fn_name(sym::oom); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let callee = context.new_function(None, FunctionType::Extern, void, &args, callee, false); //llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let block = func.new_block("entry"); let args = args .iter() .enumerate() .map(|(i, _)| func.get_param(i as i32).to_rvalue()) .collect::<Vec<_>>(); let _ret = context.new_call(None, callee, &args); //llvm::LLVMSetTailCall(ret, True); block.end_with_void_return(None); }
64 => context.new_type::<u64>(), tws => bug!("Unsupported target word size for int: {}", tws),
random_line_split
allocator.rs
use gccjit::{FunctionType, ToRValue}; use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::sym; use crate::GccContext; pub(crate) unsafe fn
(tcx: TyCtxt<'_>, mods: &mut GccContext, _module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool) { let context = &mods.context; let usize = match tcx.sess.target.pointer_width { 16 => context.new_type::<u16>(), 32 => context.new_type::<u32>(), 64 => context.new_type::<u64>(), tws => bug!("Unsupported target word size for int: {}", tws), }; let i8 = context.new_type::<i8>(); let i8p = i8.make_pointer(); let void = context.new_type::<()>(); for method in ALLOCATOR_METHODS { let mut types = Vec::with_capacity(method.inputs.len()); for ty in method.inputs.iter() { match *ty { AllocatorTy::Layout => { types.push(usize); types.push(usize); } AllocatorTy::Ptr => types.push(i8p), AllocatorTy::Usize => types.push(usize), AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"), } } let output = match method.output { AllocatorTy::ResultPtr => Some(i8p), AllocatorTy::Unit => None, AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => { panic!("invalid allocator output") } }; let name = format!("__rust_{}", method.name); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let func = context.new_function(None, FunctionType::Exported, output.unwrap_or(void), &args, name, false); if tcx.sess.target.options.default_hidden_visibility { // TODO(antoyo): set visibility. } if tcx.sess.must_emit_unwind_tables() { // TODO(antoyo): emit unwind tables. } let callee = kind.fn_name(method.name); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let callee = context.new_function(None, FunctionType::Extern, output.unwrap_or(void), &args, callee, false); // TODO(antoyo): set visibility. let block = func.new_block("entry"); let args = args .iter() .enumerate() .map(|(i, _)| func.get_param(i as i32).to_rvalue()) .collect::<Vec<_>>(); let ret = context.new_call(None, callee, &args); //llvm::LLVMSetTailCall(ret, True); if output.is_some() { block.end_with_return(None, ret); } else { block.end_with_void_return(None); } // TODO(@Commeownist): Check if we need to emit some extra debugging info in certain circumstances // as described in https://github.com/rust-lang/rust/commit/77a96ed5646f7c3ee8897693decc4626fe380643 } let types = [usize, usize]; let name = "__rust_alloc_error_handler".to_string(); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let func = context.new_function(None, FunctionType::Exported, void, &args, name, false); let kind = if has_alloc_error_handler { AllocatorKind::Global } else { AllocatorKind::Default }; let callee = kind.fn_name(sym::oom); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let callee = context.new_function(None, FunctionType::Extern, void, &args, callee, false); //llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let block = func.new_block("entry"); let args = args .iter() .enumerate() .map(|(i, _)| func.get_param(i as i32).to_rvalue()) .collect::<Vec<_>>(); let _ret = context.new_call(None, callee, &args); //llvm::LLVMSetTailCall(ret, True); block.end_with_void_return(None); }
codegen
identifier_name
allocator.rs
use gccjit::{FunctionType, ToRValue}; use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::sym; use crate::GccContext; pub(crate) unsafe fn codegen(tcx: TyCtxt<'_>, mods: &mut GccContext, _module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool)
} AllocatorTy::Ptr => types.push(i8p), AllocatorTy::Usize => types.push(usize), AllocatorTy::ResultPtr | AllocatorTy::Unit => panic!("invalid allocator arg"), } } let output = match method.output { AllocatorTy::ResultPtr => Some(i8p), AllocatorTy::Unit => None, AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => { panic!("invalid allocator output") } }; let name = format!("__rust_{}", method.name); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let func = context.new_function(None, FunctionType::Exported, output.unwrap_or(void), &args, name, false); if tcx.sess.target.options.default_hidden_visibility { // TODO(antoyo): set visibility. } if tcx.sess.must_emit_unwind_tables() { // TODO(antoyo): emit unwind tables. } let callee = kind.fn_name(method.name); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let callee = context.new_function(None, FunctionType::Extern, output.unwrap_or(void), &args, callee, false); // TODO(antoyo): set visibility. let block = func.new_block("entry"); let args = args .iter() .enumerate() .map(|(i, _)| func.get_param(i as i32).to_rvalue()) .collect::<Vec<_>>(); let ret = context.new_call(None, callee, &args); //llvm::LLVMSetTailCall(ret, True); if output.is_some() { block.end_with_return(None, ret); } else { block.end_with_void_return(None); } // TODO(@Commeownist): Check if we need to emit some extra debugging info in certain circumstances // as described in https://github.com/rust-lang/rust/commit/77a96ed5646f7c3ee8897693decc4626fe380643 } let types = [usize, usize]; let name = "__rust_alloc_error_handler".to_string(); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let func = context.new_function(None, FunctionType::Exported, void, &args, name, false); let kind = if has_alloc_error_handler { AllocatorKind::Global } else { AllocatorKind::Default }; let callee = kind.fn_name(sym::oom); let args: Vec<_> = types.iter().enumerate() .map(|(index, typ)| context.new_parameter(None, *typ, &format!("param{}", index))) .collect(); let callee = context.new_function(None, FunctionType::Extern, void, &args, callee, false); //llvm::LLVMRustSetVisibility(callee, llvm::Visibility::Hidden); let block = func.new_block("entry"); let args = args .iter() .enumerate() .map(|(i, _)| func.get_param(i as i32).to_rvalue()) .collect::<Vec<_>>(); let _ret = context.new_call(None, callee, &args); //llvm::LLVMSetTailCall(ret, True); block.end_with_void_return(None); }
{ let context = &mods.context; let usize = match tcx.sess.target.pointer_width { 16 => context.new_type::<u16>(), 32 => context.new_type::<u32>(), 64 => context.new_type::<u64>(), tws => bug!("Unsupported target word size for int: {}", tws), }; let i8 = context.new_type::<i8>(); let i8p = i8.make_pointer(); let void = context.new_type::<()>(); for method in ALLOCATOR_METHODS { let mut types = Vec::with_capacity(method.inputs.len()); for ty in method.inputs.iter() { match *ty { AllocatorTy::Layout => { types.push(usize); types.push(usize);
identifier_body
terminal.rs
#![macro_use] use io::display; use io::pio::*; use core::fmt; use spin::Mutex; pub struct Terminal { writer: display::Writer, color: u8, x: usize, y: usize, } pub static TERM: Mutex<Terminal> = Mutex::new(Terminal { writer: display::Writer { ptr: 0xb8000 }, color: display::Color::new(display::Color::White, display::Color::Black), x: 0, y: 0, }); impl Terminal { pub fn new() -> Terminal { Terminal { writer: display::Writer::new(0xb8000), color: display::Color::new(display::Color::White, display::Color::Black), x: 0, y: 0, } } pub fn set_color(&mut self, color: u8) { self.color = color; } pub fn advance(&mut self) { if self.x <= display::VIDEO_WIDTH { self.x += 1; } else { self.newline(); } } pub fn newline(&mut self) { self.x = 0; self.y += 1; if self.y > display::VIDEO_HEIGHT { self.scroll(); } } pub fn clear(&mut self) { for i in 0..(display::VIDEO_WIDTH * display::VIDEO_HEIGHT) { self.writer.write_index(display::Entry::new(b' ', self.color), i); } } pub fn scroll(&mut self)
pub fn backspace(&mut self) { self.writer.write_index(display::Entry::new(b' ', self.color), self.y * display::VIDEO_WIDTH + self.x - 1); if self.x == 0 { self.y -= 1; self.x = display::VIDEO_WIDTH; } else { self.x -= 1; } } pub fn update_cursor(&self) { let pos: u16 = self.y as u16 * display::VIDEO_WIDTH as u16 + self.x as u16; outb(0x3d4, 0x0f); outb(0x3d5, pos as u8 & 0xff); outb(0x3d4, 0x0e); outb(0x3d5, (pos >> 8) as u8 & 0xff); } } impl fmt::Write for Terminal { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for byte in s.bytes() { match byte { b'\n' => self.newline(), b'\x08' => self.backspace(), byte => { self.writer.write_index(display::Entry::new(byte, self.color), self.y * display::VIDEO_WIDTH + self.x); self.advance(); } } } self.update_cursor(); Ok(()) } }
{ self.x = 0; self.y = 0; // for i in 0..(display::VIDEO_WIDTH * (display::VIDEO_HEIGHT - 1)) { // self.writer.write_index(self.writer.at(i + display::VIDEO_WIDTH), i); // } }
identifier_body
terminal.rs
#![macro_use] use io::display; use io::pio::*; use core::fmt; use spin::Mutex; pub struct Terminal { writer: display::Writer, color: u8, x: usize, y: usize, } pub static TERM: Mutex<Terminal> = Mutex::new(Terminal { writer: display::Writer { ptr: 0xb8000 }, color: display::Color::new(display::Color::White, display::Color::Black), x: 0, y: 0, }); impl Terminal { pub fn
() -> Terminal { Terminal { writer: display::Writer::new(0xb8000), color: display::Color::new(display::Color::White, display::Color::Black), x: 0, y: 0, } } pub fn set_color(&mut self, color: u8) { self.color = color; } pub fn advance(&mut self) { if self.x <= display::VIDEO_WIDTH { self.x += 1; } else { self.newline(); } } pub fn newline(&mut self) { self.x = 0; self.y += 1; if self.y > display::VIDEO_HEIGHT { self.scroll(); } } pub fn clear(&mut self) { for i in 0..(display::VIDEO_WIDTH * display::VIDEO_HEIGHT) { self.writer.write_index(display::Entry::new(b' ', self.color), i); } } pub fn scroll(&mut self) { self.x = 0; self.y = 0; // for i in 0..(display::VIDEO_WIDTH * (display::VIDEO_HEIGHT - 1)) { // self.writer.write_index(self.writer.at(i + display::VIDEO_WIDTH), i); // } } pub fn backspace(&mut self) { self.writer.write_index(display::Entry::new(b' ', self.color), self.y * display::VIDEO_WIDTH + self.x - 1); if self.x == 0 { self.y -= 1; self.x = display::VIDEO_WIDTH; } else { self.x -= 1; } } pub fn update_cursor(&self) { let pos: u16 = self.y as u16 * display::VIDEO_WIDTH as u16 + self.x as u16; outb(0x3d4, 0x0f); outb(0x3d5, pos as u8 & 0xff); outb(0x3d4, 0x0e); outb(0x3d5, (pos >> 8) as u8 & 0xff); } } impl fmt::Write for Terminal { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for byte in s.bytes() { match byte { b'\n' => self.newline(), b'\x08' => self.backspace(), byte => { self.writer.write_index(display::Entry::new(byte, self.color), self.y * display::VIDEO_WIDTH + self.x); self.advance(); } } } self.update_cursor(); Ok(()) } }
new
identifier_name
terminal.rs
#![macro_use] use io::display; use io::pio::*; use core::fmt; use spin::Mutex; pub struct Terminal { writer: display::Writer, color: u8, x: usize, y: usize, } pub static TERM: Mutex<Terminal> = Mutex::new(Terminal { writer: display::Writer { ptr: 0xb8000 }, color: display::Color::new(display::Color::White, display::Color::Black), x: 0, y: 0, }); impl Terminal { pub fn new() -> Terminal { Terminal { writer: display::Writer::new(0xb8000), color: display::Color::new(display::Color::White, display::Color::Black), x: 0, y: 0, } } pub fn set_color(&mut self, color: u8) { self.color = color; }
pub fn advance(&mut self) { if self.x <= display::VIDEO_WIDTH { self.x += 1; } else { self.newline(); } } pub fn newline(&mut self) { self.x = 0; self.y += 1; if self.y > display::VIDEO_HEIGHT { self.scroll(); } } pub fn clear(&mut self) { for i in 0..(display::VIDEO_WIDTH * display::VIDEO_HEIGHT) { self.writer.write_index(display::Entry::new(b' ', self.color), i); } } pub fn scroll(&mut self) { self.x = 0; self.y = 0; // for i in 0..(display::VIDEO_WIDTH * (display::VIDEO_HEIGHT - 1)) { // self.writer.write_index(self.writer.at(i + display::VIDEO_WIDTH), i); // } } pub fn backspace(&mut self) { self.writer.write_index(display::Entry::new(b' ', self.color), self.y * display::VIDEO_WIDTH + self.x - 1); if self.x == 0 { self.y -= 1; self.x = display::VIDEO_WIDTH; } else { self.x -= 1; } } pub fn update_cursor(&self) { let pos: u16 = self.y as u16 * display::VIDEO_WIDTH as u16 + self.x as u16; outb(0x3d4, 0x0f); outb(0x3d5, pos as u8 & 0xff); outb(0x3d4, 0x0e); outb(0x3d5, (pos >> 8) as u8 & 0xff); } } impl fmt::Write for Terminal { fn write_str(&mut self, s: &str) -> ::core::fmt::Result { for byte in s.bytes() { match byte { b'\n' => self.newline(), b'\x08' => self.backspace(), byte => { self.writer.write_index(display::Entry::new(byte, self.color), self.y * display::VIDEO_WIDTH + self.x); self.advance(); } } } self.update_cursor(); Ok(()) } }
random_line_split
num.rs
// Adapted from https://github.com/Alexhuszagh/rust-lexical. //! Utilities for Rust numbers. use core::ops; /// Precalculated values of radix**i for i in range [0, arr.len()-1]. /// Each value can be **exactly** represented as that type. const F32_POW10: [f32; 11] = [ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, ]; /// Precalculated values of radix**i for i in range [0, arr.len()-1]. /// Each value can be **exactly** represented as that type. const F64_POW10: [f64; 23] = [ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 1000000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 10000000000000000.0, 100000000000000000.0, 1000000000000000000.0, 10000000000000000000.0, 100000000000000000000.0, 1000000000000000000000.0, 10000000000000000000000.0, ]; /// Type that can be converted to primitive with `as`. pub trait AsPrimitive: Sized + Copy + PartialOrd { fn as_u32(self) -> u32; fn as_u64(self) -> u64; fn as_u128(self) -> u128; fn as_usize(self) -> usize; fn as_f32(self) -> f32; fn as_f64(self) -> f64; } macro_rules! as_primitive_impl { ($($ty:ident)*) => { $( impl AsPrimitive for $ty { #[inline] fn as_u32(self) -> u32 { self as u32 } #[inline] fn as_u64(self) -> u64 { self as u64 } #[inline] fn as_u128(self) -> u128 { self as u128 } #[inline] fn as_usize(self) -> usize { self as usize } #[inline] fn as_f32(self) -> f32 { self as f32 } #[inline] fn as_f64(self) -> f64 { self as f64 } } )* }; } as_primitive_impl! { u32 u64 u128 usize f32 f64 } /// An interface for casting between machine scalars. pub trait AsCast: AsPrimitive { /// Creates a number from another value that can be converted into /// a primitive via the `AsPrimitive` trait. fn as_cast<N: AsPrimitive>(n: N) -> Self; } macro_rules! as_cast_impl { ($ty:ident, $method:ident) => { impl AsCast for $ty { #[inline] fn as_cast<N: AsPrimitive>(n: N) -> Self { n.$method() } } }; } as_cast_impl!(u32, as_u32); as_cast_impl!(u64, as_u64); as_cast_impl!(u128, as_u128); as_cast_impl!(usize, as_usize); as_cast_impl!(f32, as_f32); as_cast_impl!(f64, as_f64); /// Numerical type trait. pub trait Number: AsCast + ops::Add<Output = Self> {} macro_rules! number_impl { ($($ty:ident)*) => { $( impl Number for $ty {} )* }; } number_impl! { u32 u64 u128 usize f32 f64 } /// Defines a trait that supports integral operations. pub trait Integer: Number + ops::BitAnd<Output = Self> + ops::Shr<i32, Output = Self> { const ZERO: Self; } macro_rules! integer_impl { ($($ty:tt)*) => { $( impl Integer for $ty { const ZERO: Self = 0; } )* }; } integer_impl! { u32 u64 u128 usize } /// Type trait for the mantissa type. pub trait Mantissa: Integer { /// Mask to extract the high bits from the integer. const HIMASK: Self; /// Mask to extract the low bits from the integer. const LOMASK: Self; /// Full size of the integer, in bits. const FULL: i32; /// Half size of the integer, in bits. const HALF: i32 = Self::FULL / 2; } impl Mantissa for u64 { const HIMASK: u64 = 0xFFFFFFFF00000000; const LOMASK: u64 = 0x00000000FFFFFFFF; const FULL: i32 = 64; } /// Get exact exponent limit for radix. pub trait Float: Number { /// Unsigned type of the same size. type Unsigned: Integer; /// Literal zero. const ZERO: Self; /// Maximum number of digits that can contribute in the mantissa. /// /// We can exactly represent a float in radix `b` from radix 2 if /// `b` is divisible by 2. This function calculates the exact number of /// digits required to exactly represent that float. /// /// According to the "Handbook of Floating Point Arithmetic", /// for IEEE754, with emin being the min exponent, p2 being the /// precision, and b being the radix, the number of digits follows as: /// /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋` /// /// For f32, this follows as: /// emin = -126 /// p2 = 24 /// /// For f64, this follows as: /// emin = -1022 /// p2 = 53 /// /// In Python: /// `-emin + p2 + math.floor((emin+1)*math.log(2, b) - math.log(1-2**(-p2), b))` /// /// This was used to calculate the maximum number of digits for [2, 36]. const MAX_DIGITS: usize; // MASKS /// Bitmask for the sign bit. const SIGN_MASK: Self::Unsigned; /// Bitmask for the exponent, including the hidden bit. const EXPONENT_MASK: Self::Unsigned; /// Bitmask for the hidden bit in exponent, which is an implicit 1 in the fraction. const HIDDEN_BIT_MASK: Self::Unsigned; /// Bitmask for the mantissa (fraction), excluding the hidden bit. const MANTISSA_MASK: Self::Unsigned; // PROPERTIES /// Positive infinity as bits. const INFINITY_BITS: Self::Unsigned; /// Positive infinity as bits. const NEGATIVE_INFINITY_BITS: Self::Unsigned; /// Size of the significand (mantissa) without hidden bit. const MANTISSA_SIZE: i32; /// Bias of the exponet const EXPONENT_BIAS: i32; /// Exponent portion of a denormal float. const DENORMAL_EXPONENT: i32; /// Maximum exponent value in float. const MAX_EXPONENT: i32; // ROUNDING /// Default number of bits to shift (or 64 - mantissa size - 1). const DEFAULT_SHIFT: i32; /// Mask to determine if a full-carry occurred (1 in bit above hidden bit). const CARRY_MASK: u64; /// Get min and max exponent limits (exact) from radix. fn exponent_limit() -> (i32, i32); /// Get the number of digits that can be shifted from exponent to mantissa. fn mantissa_limit() -> i32; // Re-exported methods from std. fn pow10(self, n: i32) -> Self; fn from_bits(u: Self::Unsigned) -> Self; fn to_bits(self) -> Self::Unsigned; fn is_sign_positive(self) -> bool; fn is_sign_negative(self) -> bool; /// Returns true if the float is a denormal. #[inline] fn is_denormal(self) -> bool { self.to_bits() & Self::EXPONENT_MASK == Self::Unsigned::ZERO } /// Returns true if the float is a NaN or Infinite. #[inline] fn is_special(self) -> bool { self.to_bits() & Self::EXPONENT_MASK == Self::EXPONENT_MASK } /// Returns true if the float is infinite. #[inline] fn is_inf(self) -> bool { self.is_special() && (self.to_bits() & Self::MANTISSA_MASK) == Self::Unsigned::ZERO } /// Get exponent component from the float. #[inline] fn exponent(self) -> i32 { if self.is_denormal() { return Self::DENORMAL_EXPONENT; } let bits = self.to_bits(); let biased_e = ((bits & Self::EXPONENT_MASK) >> Self::MANTISSA_SIZE).as_u32(); biased_e as i32 - Self::EXPONENT_BIAS } /// Get mantissa (significand) component from float. #[inline] fn mantissa(self) -> Self::Unsigned { let bits = self.to_bits(); let s = bits & Self::MANTISSA_MASK; if!self.is_denormal() { s + Self::HIDDEN_BIT_MASK } else { s } } /// Get next greater float for a positive float. /// Value must be >= 0.0 and < INFINITY. #[inline] fn next_positive(self) -> Self { debug_assert!(self.is_sign_positive() &&!self.is_inf()); Self::from_bits(self.to_bits() + Self::Unsigned::as_cast(1u32)) } /// Round a positive number to even. #[inline] fn round_positive_even(self) -> Self { if self.mantissa() & Self::Unsigned::as_cast(1u32) == Self::Unsigned::as_cast(1u32) { self.next_positive() } else { self } } } impl Float for f32 { type Unsigned = u32; const ZERO: f32 = 0.0; const MAX_DIGITS: usize = 114; const SIGN_MASK: u32 = 0x80000000; const EXPONENT_MASK: u32 = 0x7F800000; const HIDDEN_BIT_MASK: u32 = 0x00800000; const MANTISSA_MASK: u32 = 0x007FFFFF; const INFINITY_BITS: u32 = 0x7F800000; const NEGATIVE_INFINITY_BITS: u32 = Self::INFINITY_BITS | Self::SIGN_MASK; const MANTISSA_SIZE: i32 = 23; const EXPONENT_BIAS: i32 = 127 + Self::MANTISSA_SIZE; const DENORMAL_EXPONENT: i32 = 1 - Self::EXPONENT_BIAS; const MAX_EXPONENT: i32 = 0xFF - Self::EXPONENT_BIAS; const DEFAULT_SHIFT: i32 = u64::FULL - f32::MANTISSA_SIZE - 1; const CARRY_MASK: u64 = 0x1000000; #[inline] fn exponent_limit() -> (i32, i32) { (-10, 10) } #[inline] fn mantissa_limit() -> i32 { 7 } #[inline] fn pow10(self, n: i32) -> f32 { // Check the exponent is within bounds in debug builds. debug_assert!({ let (min, max) = Self::exponent_limit(); n >= min && n <= max }); if n > 0 { self * F32_POW10[n as usize] } else { self / F32_POW10[-n as usize] } } #[inline] fn from_bits(u: u32) -> f32 { f32::from_bits(u) } #[inline] fn to_bits(self) -> u32 { f32::to_bits(self) } #[inline] fn is_sign_positive(self) -> bool { f32::is_sign_positive(self) } #[inline] fn is_sign_negative(self) -> bool { f32::is_sign_negative(self) } } impl Float for f64 { type Unsigned = u64; const ZERO: f64 = 0.0; const MAX_DIGITS: usize = 769; const SIGN_MASK: u64 = 0x8000000000000000; const EXPONENT_MASK: u64 = 0x7FF0000000000000; const HIDDEN_BIT_MASK: u64 = 0x0010000000000000; const MANTISSA_MASK: u64 = 0x000FFFFFFFFFFFFF; const INFINITY_BITS: u64 = 0x7FF0000000000000; const NEGATIVE_INFINITY_BITS: u64 = Self::INFINITY_BITS | Self::SIGN_MASK; const MANTISSA_SIZE: i32 = 52; const EXPONENT_BIAS: i32 = 1023 + Self::MANTISSA_SIZE; const DENORMAL_EXPONENT: i32 = 1 - Self::EXPONENT_BIAS; const MAX_EXPONENT: i32 = 0x7FF - Self::EXPONENT_BIAS; const DEFAULT_SHIFT: i32 = u64::FULL - f64::MANTISSA_SIZE - 1; const CARRY_MASK: u64 = 0x20000000000000; #[inline] fn exponent_limit() -> (i32, i32) { (-22, 22) } #[inline] fn mantissa_limit() -> i32 { 15 } #[inline] fn pow10(self, n: i32) -> f64 { // Check the exponent is within bounds in debug builds. debug_assert!({ let (min, max) = Self::exponent_limit(); n >= min && n <= max }); if n > 0 {
self / F64_POW10[-n as usize] } } #[inline] fn from_bits(u: u64) -> f64 { f64::from_bits(u) } #[inline] fn to_bits(self) -> u64 { f64::to_bits(self) } #[inline] fn is_sign_positive(self) -> bool { f64::is_sign_positive(self) } #[inline] fn is_sign_negative(self) -> bool { f64::is_sign_negative(self) } }
self * F64_POW10[n as usize] } else {
conditional_block
num.rs
// Adapted from https://github.com/Alexhuszagh/rust-lexical. //! Utilities for Rust numbers. use core::ops; /// Precalculated values of radix**i for i in range [0, arr.len()-1]. /// Each value can be **exactly** represented as that type. const F32_POW10: [f32; 11] = [ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, ]; /// Precalculated values of radix**i for i in range [0, arr.len()-1]. /// Each value can be **exactly** represented as that type. const F64_POW10: [f64; 23] = [ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 1000000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 10000000000000000.0, 100000000000000000.0, 1000000000000000000.0, 10000000000000000000.0, 100000000000000000000.0, 1000000000000000000000.0, 10000000000000000000000.0, ]; /// Type that can be converted to primitive with `as`. pub trait AsPrimitive: Sized + Copy + PartialOrd { fn as_u32(self) -> u32; fn as_u64(self) -> u64; fn as_u128(self) -> u128; fn as_usize(self) -> usize; fn as_f32(self) -> f32; fn as_f64(self) -> f64; } macro_rules! as_primitive_impl { ($($ty:ident)*) => { $( impl AsPrimitive for $ty { #[inline] fn as_u32(self) -> u32 { self as u32 } #[inline] fn as_u64(self) -> u64 { self as u64 } #[inline] fn as_u128(self) -> u128 { self as u128 } #[inline] fn as_usize(self) -> usize { self as usize } #[inline] fn as_f32(self) -> f32 { self as f32 } #[inline] fn as_f64(self) -> f64 { self as f64 } } )* }; } as_primitive_impl! { u32 u64 u128 usize f32 f64 } /// An interface for casting between machine scalars. pub trait AsCast: AsPrimitive { /// Creates a number from another value that can be converted into /// a primitive via the `AsPrimitive` trait. fn as_cast<N: AsPrimitive>(n: N) -> Self; } macro_rules! as_cast_impl { ($ty:ident, $method:ident) => { impl AsCast for $ty { #[inline] fn as_cast<N: AsPrimitive>(n: N) -> Self { n.$method() } } }; } as_cast_impl!(u32, as_u32); as_cast_impl!(u64, as_u64); as_cast_impl!(u128, as_u128); as_cast_impl!(usize, as_usize); as_cast_impl!(f32, as_f32); as_cast_impl!(f64, as_f64); /// Numerical type trait. pub trait Number: AsCast + ops::Add<Output = Self> {} macro_rules! number_impl { ($($ty:ident)*) => { $( impl Number for $ty {} )* }; } number_impl! { u32 u64 u128 usize f32 f64 } /// Defines a trait that supports integral operations. pub trait Integer: Number + ops::BitAnd<Output = Self> + ops::Shr<i32, Output = Self> { const ZERO: Self; } macro_rules! integer_impl { ($($ty:tt)*) => { $( impl Integer for $ty { const ZERO: Self = 0; } )* }; } integer_impl! { u32 u64 u128 usize } /// Type trait for the mantissa type. pub trait Mantissa: Integer { /// Mask to extract the high bits from the integer. const HIMASK: Self; /// Mask to extract the low bits from the integer. const LOMASK: Self; /// Full size of the integer, in bits. const FULL: i32; /// Half size of the integer, in bits. const HALF: i32 = Self::FULL / 2; } impl Mantissa for u64 { const HIMASK: u64 = 0xFFFFFFFF00000000; const LOMASK: u64 = 0x00000000FFFFFFFF; const FULL: i32 = 64; } /// Get exact exponent limit for radix. pub trait Float: Number { /// Unsigned type of the same size. type Unsigned: Integer; /// Literal zero. const ZERO: Self; /// Maximum number of digits that can contribute in the mantissa. /// /// We can exactly represent a float in radix `b` from radix 2 if /// `b` is divisible by 2. This function calculates the exact number of /// digits required to exactly represent that float. /// /// According to the "Handbook of Floating Point Arithmetic", /// for IEEE754, with emin being the min exponent, p2 being the /// precision, and b being the radix, the number of digits follows as: /// /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋` /// /// For f32, this follows as: /// emin = -126 /// p2 = 24 /// /// For f64, this follows as: /// emin = -1022 /// p2 = 53 /// /// In Python: /// `-emin + p2 + math.floor((emin+1)*math.log(2, b) - math.log(1-2**(-p2), b))` /// /// This was used to calculate the maximum number of digits for [2, 36]. const MAX_DIGITS: usize; // MASKS /// Bitmask for the sign bit. const SIGN_MASK: Self::Unsigned; /// Bitmask for the exponent, including the hidden bit. const EXPONENT_MASK: Self::Unsigned; /// Bitmask for the hidden bit in exponent, which is an implicit 1 in the fraction. const HIDDEN_BIT_MASK: Self::Unsigned; /// Bitmask for the mantissa (fraction), excluding the hidden bit. const MANTISSA_MASK: Self::Unsigned; // PROPERTIES /// Positive infinity as bits. const INFINITY_BITS: Self::Unsigned; /// Positive infinity as bits. const NEGATIVE_INFINITY_BITS: Self::Unsigned; /// Size of the significand (mantissa) without hidden bit. const MANTISSA_SIZE: i32; /// Bias of the exponet const EXPONENT_BIAS: i32; /// Exponent portion of a denormal float. const DENORMAL_EXPONENT: i32; /// Maximum exponent value in float. const MAX_EXPONENT: i32; // ROUNDING /// Default number of bits to shift (or 64 - mantissa size - 1). const DEFAULT_SHIFT: i32; /// Mask to determine if a full-carry occurred (1 in bit above hidden bit). const CARRY_MASK: u64; /// Get min and max exponent limits (exact) from radix. fn exponent_limit() -> (i32, i32); /// Get the number of digits that can be shifted from exponent to mantissa. fn mantissa_limit() -> i32; // Re-exported methods from std. fn pow10(self, n: i32) -> Self; fn from_bits(u: Self::Unsigned) -> Self; fn to_bits(self) -> Self::Unsigned; fn is_sign_positive(self) -> bool; fn is_sign_negative(self) -> bool; /// Returns true if the float is a denormal. #[inline] fn is_denormal(self) -> bool { self.to_bits() & Self::EXPONENT_MASK == Self::Unsigned::ZERO } /// Returns true if the float is a NaN or Infinite. #[inline] fn is_special(self) -> bool { self.to_bits() & Self::EXPONENT_MASK == Self::EXPONENT_MASK } /// Returns true if the float is infinite. #[inline] fn is_inf(self) -> bool { self.is_special() && (self.to_bits() & Self::MANTISSA_MASK) == Self::Unsigned::ZERO } /// Get exponent component from the float. #[inline] fn exponent(self) -> i32 { if self.is_denormal() { return Self::DENORMAL_EXPONENT; } let bits = self.to_bits(); let biased_e = ((bits & Self::EXPONENT_MASK) >> Self::MANTISSA_SIZE).as_u32(); biased_e as i32 - Self::EXPONENT_BIAS } /// Get mantissa (significand) component from float. #[inline] fn mantissa(self) -> Self::Unsigned { let bits = self.to_bits(); let s = bits & Self::MANTISSA_MASK; if!self.is_denormal() { s + Self::HIDDEN_BIT_MASK } else { s } } /// Get next greater float for a positive float. /// Value must be >= 0.0 and < INFINITY. #[inline] fn next_positive(self) -> Self { debug_assert!(self.is_sign_positive() &&!self.is_inf()); Self::from_bits(self.to_bits() + Self::Unsigned::as_cast(1u32)) } /// Round a positive number to even. #[inline] fn round_positive_even(self) -> Self { if self.mantissa() & Self::Unsigned::as_cast(1u32) == Self::Unsigned::as_cast(1u32) { self.next_positive() } else { self } } } impl Float for f32 { type Unsigned = u32; const ZERO: f32 = 0.0; const MAX_DIGITS: usize = 114; const SIGN_MASK: u32 = 0x80000000; const EXPONENT_MASK: u32 = 0x7F800000; const HIDDEN_BIT_MASK: u32 = 0x00800000; const MANTISSA_MASK: u32 = 0x007FFFFF; const INFINITY_BITS: u32 = 0x7F800000; const NEGATIVE_INFINITY_BITS: u32 = Self::INFINITY_BITS | Self::SIGN_MASK; const MANTISSA_SIZE: i32 = 23; const EXPONENT_BIAS: i32 = 127 + Self::MANTISSA_SIZE; const DENORMAL_EXPONENT: i32 = 1 - Self::EXPONENT_BIAS; const MAX_EXPONENT: i32 = 0xFF - Self::EXPONENT_BIAS; const DEFAULT_SHIFT: i32 = u64::FULL - f32::MANTISSA_SIZE - 1; const CARRY_MASK: u64 = 0x1000000; #[inline] fn exponent_limit() -> (i32, i32) { (-10, 10) } #[inline] fn mantissa_limit() -> i32 { 7 } #[inline] fn pow10(self, n: i32) -> f32 { // Check the exponent is within bounds in debug builds. debug_assert!({ let (min, max) = Self::exponent_limit(); n >= min && n <= max }); if n > 0 { self * F32_POW10[n as usize] } else { self / F32_POW10[-n as usize] } } #[inline] fn from_bits(u: u32) -> f32 { f32::from_bits(u) } #[inline] fn to_bits(self) -> u32 { f32::to_bits(self) } #[inline] fn is_sign_positive(self) -> bool { f32::is_sign_positive(self) } #[inline] fn is_sign_negative(self) -> bool { f32::is_sign_negative(self) } } impl Float for f64 { type Unsigned = u64; const ZERO: f64 = 0.0; const MAX_DIGITS: usize = 769; const SIGN_MASK: u64 = 0x8000000000000000; const EXPONENT_MASK: u64 = 0x7FF0000000000000; const HIDDEN_BIT_MASK: u64 = 0x0010000000000000; const MANTISSA_MASK: u64 = 0x000FFFFFFFFFFFFF; const INFINITY_BITS: u64 = 0x7FF0000000000000; const NEGATIVE_INFINITY_BITS: u64 = Self::INFINITY_BITS | Self::SIGN_MASK; const MANTISSA_SIZE: i32 = 52; const EXPONENT_BIAS: i32 = 1023 + Self::MANTISSA_SIZE; const DENORMAL_EXPONENT: i32 = 1 - Self::EXPONENT_BIAS; const MAX_EXPONENT: i32 = 0x7FF - Self::EXPONENT_BIAS; const DEFAULT_SHIFT: i32 = u64::FULL - f64::MANTISSA_SIZE - 1; const CARRY_MASK: u64 = 0x20000000000000; #[inline] fn exponent_limit() -> (i32, i32) { (-22, 22) } #[inline] fn mantissa_lim
15 } #[inline] fn pow10(self, n: i32) -> f64 { // Check the exponent is within bounds in debug builds. debug_assert!({ let (min, max) = Self::exponent_limit(); n >= min && n <= max }); if n > 0 { self * F64_POW10[n as usize] } else { self / F64_POW10[-n as usize] } } #[inline] fn from_bits(u: u64) -> f64 { f64::from_bits(u) } #[inline] fn to_bits(self) -> u64 { f64::to_bits(self) } #[inline] fn is_sign_positive(self) -> bool { f64::is_sign_positive(self) } #[inline] fn is_sign_negative(self) -> bool { f64::is_sign_negative(self) } }
it() -> i32 {
identifier_name
num.rs
// Adapted from https://github.com/Alexhuszagh/rust-lexical. //! Utilities for Rust numbers. use core::ops; /// Precalculated values of radix**i for i in range [0, arr.len()-1]. /// Each value can be **exactly** represented as that type. const F32_POW10: [f32; 11] = [ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, ]; /// Precalculated values of radix**i for i in range [0, arr.len()-1]. /// Each value can be **exactly** represented as that type. const F64_POW10: [f64; 23] = [ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 1000000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 10000000000000000.0, 100000000000000000.0, 1000000000000000000.0, 10000000000000000000.0, 100000000000000000000.0, 1000000000000000000000.0, 10000000000000000000000.0, ]; /// Type that can be converted to primitive with `as`. pub trait AsPrimitive: Sized + Copy + PartialOrd { fn as_u32(self) -> u32; fn as_u64(self) -> u64; fn as_u128(self) -> u128; fn as_usize(self) -> usize; fn as_f32(self) -> f32; fn as_f64(self) -> f64; } macro_rules! as_primitive_impl { ($($ty:ident)*) => { $( impl AsPrimitive for $ty { #[inline] fn as_u32(self) -> u32 { self as u32 } #[inline] fn as_u64(self) -> u64 { self as u64 } #[inline] fn as_u128(self) -> u128 { self as u128 } #[inline] fn as_usize(self) -> usize { self as usize } #[inline] fn as_f32(self) -> f32 { self as f32 } #[inline] fn as_f64(self) -> f64 { self as f64 } } )* }; } as_primitive_impl! { u32 u64 u128 usize f32 f64 } /// An interface for casting between machine scalars. pub trait AsCast: AsPrimitive { /// Creates a number from another value that can be converted into /// a primitive via the `AsPrimitive` trait. fn as_cast<N: AsPrimitive>(n: N) -> Self; } macro_rules! as_cast_impl { ($ty:ident, $method:ident) => { impl AsCast for $ty { #[inline] fn as_cast<N: AsPrimitive>(n: N) -> Self { n.$method() } } }; } as_cast_impl!(u32, as_u32); as_cast_impl!(u64, as_u64); as_cast_impl!(u128, as_u128); as_cast_impl!(usize, as_usize); as_cast_impl!(f32, as_f32); as_cast_impl!(f64, as_f64); /// Numerical type trait. pub trait Number: AsCast + ops::Add<Output = Self> {} macro_rules! number_impl { ($($ty:ident)*) => { $( impl Number for $ty {} )* }; } number_impl! { u32 u64 u128 usize f32 f64 } /// Defines a trait that supports integral operations. pub trait Integer: Number + ops::BitAnd<Output = Self> + ops::Shr<i32, Output = Self> { const ZERO: Self; } macro_rules! integer_impl { ($($ty:tt)*) => { $( impl Integer for $ty { const ZERO: Self = 0; } )* }; } integer_impl! { u32 u64 u128 usize } /// Type trait for the mantissa type.
/// Mask to extract the high bits from the integer. const HIMASK: Self; /// Mask to extract the low bits from the integer. const LOMASK: Self; /// Full size of the integer, in bits. const FULL: i32; /// Half size of the integer, in bits. const HALF: i32 = Self::FULL / 2; } impl Mantissa for u64 { const HIMASK: u64 = 0xFFFFFFFF00000000; const LOMASK: u64 = 0x00000000FFFFFFFF; const FULL: i32 = 64; } /// Get exact exponent limit for radix. pub trait Float: Number { /// Unsigned type of the same size. type Unsigned: Integer; /// Literal zero. const ZERO: Self; /// Maximum number of digits that can contribute in the mantissa. /// /// We can exactly represent a float in radix `b` from radix 2 if /// `b` is divisible by 2. This function calculates the exact number of /// digits required to exactly represent that float. /// /// According to the "Handbook of Floating Point Arithmetic", /// for IEEE754, with emin being the min exponent, p2 being the /// precision, and b being the radix, the number of digits follows as: /// /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋` /// /// For f32, this follows as: /// emin = -126 /// p2 = 24 /// /// For f64, this follows as: /// emin = -1022 /// p2 = 53 /// /// In Python: /// `-emin + p2 + math.floor((emin+1)*math.log(2, b) - math.log(1-2**(-p2), b))` /// /// This was used to calculate the maximum number of digits for [2, 36]. const MAX_DIGITS: usize; // MASKS /// Bitmask for the sign bit. const SIGN_MASK: Self::Unsigned; /// Bitmask for the exponent, including the hidden bit. const EXPONENT_MASK: Self::Unsigned; /// Bitmask for the hidden bit in exponent, which is an implicit 1 in the fraction. const HIDDEN_BIT_MASK: Self::Unsigned; /// Bitmask for the mantissa (fraction), excluding the hidden bit. const MANTISSA_MASK: Self::Unsigned; // PROPERTIES /// Positive infinity as bits. const INFINITY_BITS: Self::Unsigned; /// Positive infinity as bits. const NEGATIVE_INFINITY_BITS: Self::Unsigned; /// Size of the significand (mantissa) without hidden bit. const MANTISSA_SIZE: i32; /// Bias of the exponet const EXPONENT_BIAS: i32; /// Exponent portion of a denormal float. const DENORMAL_EXPONENT: i32; /// Maximum exponent value in float. const MAX_EXPONENT: i32; // ROUNDING /// Default number of bits to shift (or 64 - mantissa size - 1). const DEFAULT_SHIFT: i32; /// Mask to determine if a full-carry occurred (1 in bit above hidden bit). const CARRY_MASK: u64; /// Get min and max exponent limits (exact) from radix. fn exponent_limit() -> (i32, i32); /// Get the number of digits that can be shifted from exponent to mantissa. fn mantissa_limit() -> i32; // Re-exported methods from std. fn pow10(self, n: i32) -> Self; fn from_bits(u: Self::Unsigned) -> Self; fn to_bits(self) -> Self::Unsigned; fn is_sign_positive(self) -> bool; fn is_sign_negative(self) -> bool; /// Returns true if the float is a denormal. #[inline] fn is_denormal(self) -> bool { self.to_bits() & Self::EXPONENT_MASK == Self::Unsigned::ZERO } /// Returns true if the float is a NaN or Infinite. #[inline] fn is_special(self) -> bool { self.to_bits() & Self::EXPONENT_MASK == Self::EXPONENT_MASK } /// Returns true if the float is infinite. #[inline] fn is_inf(self) -> bool { self.is_special() && (self.to_bits() & Self::MANTISSA_MASK) == Self::Unsigned::ZERO } /// Get exponent component from the float. #[inline] fn exponent(self) -> i32 { if self.is_denormal() { return Self::DENORMAL_EXPONENT; } let bits = self.to_bits(); let biased_e = ((bits & Self::EXPONENT_MASK) >> Self::MANTISSA_SIZE).as_u32(); biased_e as i32 - Self::EXPONENT_BIAS } /// Get mantissa (significand) component from float. #[inline] fn mantissa(self) -> Self::Unsigned { let bits = self.to_bits(); let s = bits & Self::MANTISSA_MASK; if!self.is_denormal() { s + Self::HIDDEN_BIT_MASK } else { s } } /// Get next greater float for a positive float. /// Value must be >= 0.0 and < INFINITY. #[inline] fn next_positive(self) -> Self { debug_assert!(self.is_sign_positive() &&!self.is_inf()); Self::from_bits(self.to_bits() + Self::Unsigned::as_cast(1u32)) } /// Round a positive number to even. #[inline] fn round_positive_even(self) -> Self { if self.mantissa() & Self::Unsigned::as_cast(1u32) == Self::Unsigned::as_cast(1u32) { self.next_positive() } else { self } } } impl Float for f32 { type Unsigned = u32; const ZERO: f32 = 0.0; const MAX_DIGITS: usize = 114; const SIGN_MASK: u32 = 0x80000000; const EXPONENT_MASK: u32 = 0x7F800000; const HIDDEN_BIT_MASK: u32 = 0x00800000; const MANTISSA_MASK: u32 = 0x007FFFFF; const INFINITY_BITS: u32 = 0x7F800000; const NEGATIVE_INFINITY_BITS: u32 = Self::INFINITY_BITS | Self::SIGN_MASK; const MANTISSA_SIZE: i32 = 23; const EXPONENT_BIAS: i32 = 127 + Self::MANTISSA_SIZE; const DENORMAL_EXPONENT: i32 = 1 - Self::EXPONENT_BIAS; const MAX_EXPONENT: i32 = 0xFF - Self::EXPONENT_BIAS; const DEFAULT_SHIFT: i32 = u64::FULL - f32::MANTISSA_SIZE - 1; const CARRY_MASK: u64 = 0x1000000; #[inline] fn exponent_limit() -> (i32, i32) { (-10, 10) } #[inline] fn mantissa_limit() -> i32 { 7 } #[inline] fn pow10(self, n: i32) -> f32 { // Check the exponent is within bounds in debug builds. debug_assert!({ let (min, max) = Self::exponent_limit(); n >= min && n <= max }); if n > 0 { self * F32_POW10[n as usize] } else { self / F32_POW10[-n as usize] } } #[inline] fn from_bits(u: u32) -> f32 { f32::from_bits(u) } #[inline] fn to_bits(self) -> u32 { f32::to_bits(self) } #[inline] fn is_sign_positive(self) -> bool { f32::is_sign_positive(self) } #[inline] fn is_sign_negative(self) -> bool { f32::is_sign_negative(self) } } impl Float for f64 { type Unsigned = u64; const ZERO: f64 = 0.0; const MAX_DIGITS: usize = 769; const SIGN_MASK: u64 = 0x8000000000000000; const EXPONENT_MASK: u64 = 0x7FF0000000000000; const HIDDEN_BIT_MASK: u64 = 0x0010000000000000; const MANTISSA_MASK: u64 = 0x000FFFFFFFFFFFFF; const INFINITY_BITS: u64 = 0x7FF0000000000000; const NEGATIVE_INFINITY_BITS: u64 = Self::INFINITY_BITS | Self::SIGN_MASK; const MANTISSA_SIZE: i32 = 52; const EXPONENT_BIAS: i32 = 1023 + Self::MANTISSA_SIZE; const DENORMAL_EXPONENT: i32 = 1 - Self::EXPONENT_BIAS; const MAX_EXPONENT: i32 = 0x7FF - Self::EXPONENT_BIAS; const DEFAULT_SHIFT: i32 = u64::FULL - f64::MANTISSA_SIZE - 1; const CARRY_MASK: u64 = 0x20000000000000; #[inline] fn exponent_limit() -> (i32, i32) { (-22, 22) } #[inline] fn mantissa_limit() -> i32 { 15 } #[inline] fn pow10(self, n: i32) -> f64 { // Check the exponent is within bounds in debug builds. debug_assert!({ let (min, max) = Self::exponent_limit(); n >= min && n <= max }); if n > 0 { self * F64_POW10[n as usize] } else { self / F64_POW10[-n as usize] } } #[inline] fn from_bits(u: u64) -> f64 { f64::from_bits(u) } #[inline] fn to_bits(self) -> u64 { f64::to_bits(self) } #[inline] fn is_sign_positive(self) -> bool { f64::is_sign_positive(self) } #[inline] fn is_sign_negative(self) -> bool { f64::is_sign_negative(self) } }
pub trait Mantissa: Integer {
random_line_split
num.rs
// Adapted from https://github.com/Alexhuszagh/rust-lexical. //! Utilities for Rust numbers. use core::ops; /// Precalculated values of radix**i for i in range [0, arr.len()-1]. /// Each value can be **exactly** represented as that type. const F32_POW10: [f32; 11] = [ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, ]; /// Precalculated values of radix**i for i in range [0, arr.len()-1]. /// Each value can be **exactly** represented as that type. const F64_POW10: [f64; 23] = [ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 1000000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 10000000000000000.0, 100000000000000000.0, 1000000000000000000.0, 10000000000000000000.0, 100000000000000000000.0, 1000000000000000000000.0, 10000000000000000000000.0, ]; /// Type that can be converted to primitive with `as`. pub trait AsPrimitive: Sized + Copy + PartialOrd { fn as_u32(self) -> u32; fn as_u64(self) -> u64; fn as_u128(self) -> u128; fn as_usize(self) -> usize; fn as_f32(self) -> f32; fn as_f64(self) -> f64; } macro_rules! as_primitive_impl { ($($ty:ident)*) => { $( impl AsPrimitive for $ty { #[inline] fn as_u32(self) -> u32 { self as u32 } #[inline] fn as_u64(self) -> u64 { self as u64 } #[inline] fn as_u128(self) -> u128 { self as u128 } #[inline] fn as_usize(self) -> usize { self as usize } #[inline] fn as_f32(self) -> f32 { self as f32 } #[inline] fn as_f64(self) -> f64 { self as f64 } } )* }; } as_primitive_impl! { u32 u64 u128 usize f32 f64 } /// An interface for casting between machine scalars. pub trait AsCast: AsPrimitive { /// Creates a number from another value that can be converted into /// a primitive via the `AsPrimitive` trait. fn as_cast<N: AsPrimitive>(n: N) -> Self; } macro_rules! as_cast_impl { ($ty:ident, $method:ident) => { impl AsCast for $ty { #[inline] fn as_cast<N: AsPrimitive>(n: N) -> Self { n.$method() } } }; } as_cast_impl!(u32, as_u32); as_cast_impl!(u64, as_u64); as_cast_impl!(u128, as_u128); as_cast_impl!(usize, as_usize); as_cast_impl!(f32, as_f32); as_cast_impl!(f64, as_f64); /// Numerical type trait. pub trait Number: AsCast + ops::Add<Output = Self> {} macro_rules! number_impl { ($($ty:ident)*) => { $( impl Number for $ty {} )* }; } number_impl! { u32 u64 u128 usize f32 f64 } /// Defines a trait that supports integral operations. pub trait Integer: Number + ops::BitAnd<Output = Self> + ops::Shr<i32, Output = Self> { const ZERO: Self; } macro_rules! integer_impl { ($($ty:tt)*) => { $( impl Integer for $ty { const ZERO: Self = 0; } )* }; } integer_impl! { u32 u64 u128 usize } /// Type trait for the mantissa type. pub trait Mantissa: Integer { /// Mask to extract the high bits from the integer. const HIMASK: Self; /// Mask to extract the low bits from the integer. const LOMASK: Self; /// Full size of the integer, in bits. const FULL: i32; /// Half size of the integer, in bits. const HALF: i32 = Self::FULL / 2; } impl Mantissa for u64 { const HIMASK: u64 = 0xFFFFFFFF00000000; const LOMASK: u64 = 0x00000000FFFFFFFF; const FULL: i32 = 64; } /// Get exact exponent limit for radix. pub trait Float: Number { /// Unsigned type of the same size. type Unsigned: Integer; /// Literal zero. const ZERO: Self; /// Maximum number of digits that can contribute in the mantissa. /// /// We can exactly represent a float in radix `b` from radix 2 if /// `b` is divisible by 2. This function calculates the exact number of /// digits required to exactly represent that float. /// /// According to the "Handbook of Floating Point Arithmetic", /// for IEEE754, with emin being the min exponent, p2 being the /// precision, and b being the radix, the number of digits follows as: /// /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋` /// /// For f32, this follows as: /// emin = -126 /// p2 = 24 /// /// For f64, this follows as: /// emin = -1022 /// p2 = 53 /// /// In Python: /// `-emin + p2 + math.floor((emin+1)*math.log(2, b) - math.log(1-2**(-p2), b))` /// /// This was used to calculate the maximum number of digits for [2, 36]. const MAX_DIGITS: usize; // MASKS /// Bitmask for the sign bit. const SIGN_MASK: Self::Unsigned; /// Bitmask for the exponent, including the hidden bit. const EXPONENT_MASK: Self::Unsigned; /// Bitmask for the hidden bit in exponent, which is an implicit 1 in the fraction. const HIDDEN_BIT_MASK: Self::Unsigned; /// Bitmask for the mantissa (fraction), excluding the hidden bit. const MANTISSA_MASK: Self::Unsigned; // PROPERTIES /// Positive infinity as bits. const INFINITY_BITS: Self::Unsigned; /// Positive infinity as bits. const NEGATIVE_INFINITY_BITS: Self::Unsigned; /// Size of the significand (mantissa) without hidden bit. const MANTISSA_SIZE: i32; /// Bias of the exponet const EXPONENT_BIAS: i32; /// Exponent portion of a denormal float. const DENORMAL_EXPONENT: i32; /// Maximum exponent value in float. const MAX_EXPONENT: i32; // ROUNDING /// Default number of bits to shift (or 64 - mantissa size - 1). const DEFAULT_SHIFT: i32; /// Mask to determine if a full-carry occurred (1 in bit above hidden bit). const CARRY_MASK: u64; /// Get min and max exponent limits (exact) from radix. fn exponent_limit() -> (i32, i32); /// Get the number of digits that can be shifted from exponent to mantissa. fn mantissa_limit() -> i32; // Re-exported methods from std. fn pow10(self, n: i32) -> Self; fn from_bits(u: Self::Unsigned) -> Self; fn to_bits(self) -> Self::Unsigned; fn is_sign_positive(self) -> bool; fn is_sign_negative(self) -> bool; /// Returns true if the float is a denormal. #[inline] fn is_denormal(self) -> bool { self.to_bits() & Self::EXPONENT_MASK == Self::Unsigned::ZERO } /// Returns true if the float is a NaN or Infinite. #[inline] fn is_special(self) -> bool { self.to_bits() & Self::EXPONENT_MASK == Self::EXPONENT_MASK } /// Returns true if the float is infinite. #[inline] fn is_inf(self) -> bool { self.is_special() && (self.to_bits() & Self::MANTISSA_MASK) == Self::Unsigned::ZERO } /// Get exponent component from the float. #[inline] fn exponent(self) -> i32 { if self.is_denormal() { return Self::DENORMAL_EXPONENT; } let bits = self.to_bits(); let biased_e = ((bits & Self::EXPONENT_MASK) >> Self::MANTISSA_SIZE).as_u32(); biased_e as i32 - Self::EXPONENT_BIAS } /// Get mantissa (significand) component from float. #[inline] fn mantissa(self) -> Self::Unsigned { let bits = self.to_bits(); let s = bits & Self::MANTISSA_MASK; if!self.is_denormal() { s + Self::HIDDEN_BIT_MASK } else { s } } /// Get next greater float for a positive float. /// Value must be >= 0.0 and < INFINITY. #[inline] fn next_positive(self) -> Self { debug_assert!(self.is_sign_positive() &&!self.is_inf()); Self::from_bits(self.to_bits() + Self::Unsigned::as_cast(1u32)) } /// Round a positive number to even. #[inline] fn round_positive_even(self) -> Self { if self.mantissa() & Self::Unsigned::as_cast(1u32) == Self::Unsigned::as_cast(1u32) { self.next_positive() } else { self } } } impl Float for f32 { type Unsigned = u32; const ZERO: f32 = 0.0; const MAX_DIGITS: usize = 114; const SIGN_MASK: u32 = 0x80000000; const EXPONENT_MASK: u32 = 0x7F800000; const HIDDEN_BIT_MASK: u32 = 0x00800000; const MANTISSA_MASK: u32 = 0x007FFFFF; const INFINITY_BITS: u32 = 0x7F800000; const NEGATIVE_INFINITY_BITS: u32 = Self::INFINITY_BITS | Self::SIGN_MASK; const MANTISSA_SIZE: i32 = 23; const EXPONENT_BIAS: i32 = 127 + Self::MANTISSA_SIZE; const DENORMAL_EXPONENT: i32 = 1 - Self::EXPONENT_BIAS; const MAX_EXPONENT: i32 = 0xFF - Self::EXPONENT_BIAS; const DEFAULT_SHIFT: i32 = u64::FULL - f32::MANTISSA_SIZE - 1; const CARRY_MASK: u64 = 0x1000000; #[inline] fn exponent_limit() -> (i32, i32) { (-10, 10) } #[inline] fn mantissa_limit() -> i32 { 7 } #[inline] fn pow10(self, n: i32) -> f32 { // Check the exponent is within bounds in debug builds. debug_assert!({ let (min, max) = Self::exponent_limit(); n >= min && n <= max }); if n > 0 { self * F32_POW10[n as usize] } else { self / F32_POW10[-n as usize] } } #[inline] fn from_bits(u: u32) -> f32 { f32::from_bits(u) } #[inline] fn to_bits(self) -> u32 { f32::to_bits(self) } #[inline] fn is_sign_positive(self) -> bool { f32::is_sign_positive(self) } #[inline] fn is_sign_negative(self) -> bool { f32::is_sign_negative(self) } } impl Float for f64 { type Unsigned = u64; const ZERO: f64 = 0.0; const MAX_DIGITS: usize = 769; const SIGN_MASK: u64 = 0x8000000000000000; const EXPONENT_MASK: u64 = 0x7FF0000000000000; const HIDDEN_BIT_MASK: u64 = 0x0010000000000000; const MANTISSA_MASK: u64 = 0x000FFFFFFFFFFFFF; const INFINITY_BITS: u64 = 0x7FF0000000000000; const NEGATIVE_INFINITY_BITS: u64 = Self::INFINITY_BITS | Self::SIGN_MASK; const MANTISSA_SIZE: i32 = 52; const EXPONENT_BIAS: i32 = 1023 + Self::MANTISSA_SIZE; const DENORMAL_EXPONENT: i32 = 1 - Self::EXPONENT_BIAS; const MAX_EXPONENT: i32 = 0x7FF - Self::EXPONENT_BIAS; const DEFAULT_SHIFT: i32 = u64::FULL - f64::MANTISSA_SIZE - 1; const CARRY_MASK: u64 = 0x20000000000000; #[inline] fn exponent_limit() -> (i32, i32) { (-22, 22) } #[inline] fn mantissa_limit() -> i32 { 15 } #[inline] fn pow10(self, n: i32) -> f64 { // Check the exponent is within bounds in debug builds. debug_assert!({ let (min, max) = Self::exponent_limit(); n >= min && n <= max }); if n > 0 { self * F64_POW10[n as usize] } else { self / F64_POW10[-n as usize] } } #[inline] fn from_bits(u: u64) -> f64 { f64::from_bits(u) } #[inline] fn to_bits(self) -> u64 { f64::to_bits(self) } #[inline] fn is_sign_positive(self) -> bool { f6
ne] fn is_sign_negative(self) -> bool { f64::is_sign_negative(self) } }
4::is_sign_positive(self) } #[inli
identifier_body
issue-52126-assign-op-invariance.rs
// Issue 52126: With respect to variance, the assign-op's like += were // accidentally lumped together with other binary op's. In both cases // we were coercing the LHS of the op to the expected supertype. // // The problem is that since the LHS of += is modified, we need the // parameter to be invariant with respect to the overall type, not // covariant. use std::collections::HashMap; use std::ops::AddAssign; pub fn main() { panics(); } pub struct
<'l> { map: HashMap<&'l str, usize>, } impl<'l> AddAssign for Counter<'l> { fn add_assign(&mut self, rhs: Counter<'l>) { rhs.map.into_iter().for_each(|(key, val)| { let count = self.map.entry(key).or_insert(0); *count += val; }); } } /// Often crashes, if not prints invalid strings. pub fn panics() { let mut acc = Counter{map: HashMap::new()}; for line in vec!["123456789".to_string(), "12345678".to_string()] { let v: Vec<&str> = line.split_whitespace().collect(); //~^ ERROR `line` does not live long enough // println!("accumulator before add_assign {:?}", acc.map); let mut map = HashMap::new(); for str_ref in v { let e = map.entry(str_ref); println!("entry: {:?}", e); let count = e.or_insert(0); *count += 1; } let cnt2 = Counter{map}; acc += cnt2; // println!("accumulator after add_assign {:?}", acc.map); // line gets dropped here but references are kept in acc.map } }
Counter
identifier_name
issue-52126-assign-op-invariance.rs
// Issue 52126: With respect to variance, the assign-op's like += were // accidentally lumped together with other binary op's. In both cases // we were coercing the LHS of the op to the expected supertype. // // The problem is that since the LHS of += is modified, we need the // parameter to be invariant with respect to the overall type, not // covariant. use std::collections::HashMap; use std::ops::AddAssign; pub fn main() { panics(); } pub struct Counter<'l> { map: HashMap<&'l str, usize>, } impl<'l> AddAssign for Counter<'l> { fn add_assign(&mut self, rhs: Counter<'l>)
} /// Often crashes, if not prints invalid strings. pub fn panics() { let mut acc = Counter{map: HashMap::new()}; for line in vec!["123456789".to_string(), "12345678".to_string()] { let v: Vec<&str> = line.split_whitespace().collect(); //~^ ERROR `line` does not live long enough // println!("accumulator before add_assign {:?}", acc.map); let mut map = HashMap::new(); for str_ref in v { let e = map.entry(str_ref); println!("entry: {:?}", e); let count = e.or_insert(0); *count += 1; } let cnt2 = Counter{map}; acc += cnt2; // println!("accumulator after add_assign {:?}", acc.map); // line gets dropped here but references are kept in acc.map } }
{ rhs.map.into_iter().for_each(|(key, val)| { let count = self.map.entry(key).or_insert(0); *count += val; }); }
identifier_body
issue-52126-assign-op-invariance.rs
// Issue 52126: With respect to variance, the assign-op's like += were
// we were coercing the LHS of the op to the expected supertype. // // The problem is that since the LHS of += is modified, we need the // parameter to be invariant with respect to the overall type, not // covariant. use std::collections::HashMap; use std::ops::AddAssign; pub fn main() { panics(); } pub struct Counter<'l> { map: HashMap<&'l str, usize>, } impl<'l> AddAssign for Counter<'l> { fn add_assign(&mut self, rhs: Counter<'l>) { rhs.map.into_iter().for_each(|(key, val)| { let count = self.map.entry(key).or_insert(0); *count += val; }); } } /// Often crashes, if not prints invalid strings. pub fn panics() { let mut acc = Counter{map: HashMap::new()}; for line in vec!["123456789".to_string(), "12345678".to_string()] { let v: Vec<&str> = line.split_whitespace().collect(); //~^ ERROR `line` does not live long enough // println!("accumulator before add_assign {:?}", acc.map); let mut map = HashMap::new(); for str_ref in v { let e = map.entry(str_ref); println!("entry: {:?}", e); let count = e.or_insert(0); *count += 1; } let cnt2 = Counter{map}; acc += cnt2; // println!("accumulator after add_assign {:?}", acc.map); // line gets dropped here but references are kept in acc.map } }
// accidentally lumped together with other binary op's. In both cases
random_line_split
drawing_area.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::object::Downcast; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::mem; use std::ptr; glib_wrapper! { pub struct DrawingArea(Object<ffi::GtkDrawingArea, ffi::GtkDrawingAreaClass>): Widget, Buildable; match fn { get_type => || ffi::gtk_drawing_area_get_type(), } } impl DrawingArea { pub fn new() -> DrawingArea {
} impl Default for DrawingArea { fn default() -> Self { Self::new() } }
assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_drawing_area_new()).downcast_unchecked() } }
random_line_split
drawing_area.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::object::Downcast; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::mem; use std::ptr; glib_wrapper! { pub struct DrawingArea(Object<ffi::GtkDrawingArea, ffi::GtkDrawingAreaClass>): Widget, Buildable; match fn { get_type => || ffi::gtk_drawing_area_get_type(), } } impl DrawingArea { pub fn
() -> DrawingArea { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_drawing_area_new()).downcast_unchecked() } } } impl Default for DrawingArea { fn default() -> Self { Self::new() } }
new
identifier_name
drawing_area.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::object::Downcast; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::mem; use std::ptr; glib_wrapper! { pub struct DrawingArea(Object<ffi::GtkDrawingArea, ffi::GtkDrawingAreaClass>): Widget, Buildable; match fn { get_type => || ffi::gtk_drawing_area_get_type(), } } impl DrawingArea { pub fn new() -> DrawingArea { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_drawing_area_new()).downcast_unchecked() } } } impl Default for DrawingArea { fn default() -> Self
}
{ Self::new() }
identifier_body
ecp.rs
E; } #[allow(non_snake_case)] /* set from x - calculate y from curve equation */ pub fn new_big(ix: &BIG) -> ECP { let mut E=ECP::new(); E.x.bcopy(ix); E.z.one(); let mut rhs=ECP::rhs(&mut E.x); if rhs.jacobi()==1 { if rom::CURVETYPE!=rom::MONTGOMERY {E.y.copy(&rhs.sqrt())} E.inf=false; } else {E.inf=true} return E; } /* set this=O */ pub fn inf(&mut self) { self.inf=true; self.x.zero(); self.y.one(); self.z.one(); } /* Calculate RHS of curve equation */ fn rhs(x: &mut FP) -> FP { x.norm(); let mut r=FP::new_copy(x); r.sqr(); if rom::CURVETYPE==rom::WEIERSTRASS { // x^3+Ax+B let b=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); r.mul(x); if rom::CURVE_A==-3 { let mut cx=FP::new_copy(x); cx.imul(3); cx.neg(); cx.norm(); r.add(&cx); } r.add(&b); } if rom::CURVETYPE==rom::EDWARDS { // (Ax^2-1)/(Bx^2-1) let mut b=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); let one=FP::new_int(1); b.mul(&mut r); b.sub(&one); if rom::CURVE_A==-1 {r.neg()} r.sub(&one); b.inverse(); r.mul(&mut b); } if rom::CURVETYPE==rom::MONTGOMERY { // x^3+Ax^2+x let mut x3=FP::new(); x3.copy(&r); x3.mul(x); r.imul(rom::CURVE_A); r.add(&x3); r.add(&x); } r.reduce(); return r; } /* test for O point-at-infinity */ pub fn is_infinity(&mut self) -> bool { if rom::CURVETYPE==rom::EDWARDS { self.x.reduce(); self.y.reduce(); self.z.reduce(); return self.x.iszilch() && self.y.equals(&mut self.z); } else {return self.inf} } /* Conditional swap of P and Q dependant on d */ pub fn cswap(&mut self,Q: &mut ECP,d: isize) { self.x.cswap(&mut Q.x,d); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.cswap(&mut Q.y,d)} self.z.cswap(&mut Q.z,d); if rom::CURVETYPE!=rom::EDWARDS { let mut bd=true; if d==0 {bd=false} bd=bd&&(self.inf!=Q.inf); self.inf=bd!=self.inf; Q.inf=bd!=Q.inf; } } /* Conditional move of Q to P dependant on d */ pub fn cmove(&mut self,Q: &ECP,d: isize) { self.x.cmove(&Q.x,d); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.cmove(&Q.y,d)} self.z.cmove(&Q.z,d); if rom::CURVETYPE!=rom::EDWARDS { let mut bd=true; if d==0 {bd=false} self.inf=self.inf!=((self.inf!=Q.inf)&&bd); } } /* return 1 if b==c, no branching */ fn teq(b: i32,c: i32) -> isize { let mut x=b^c; x-=1; // if x=0, x now -1 return ((x>>31)&1) as isize; } /* this=P */ pub fn copy(&mut self,P: & ECP) { self.x.copy(&P.x); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.copy(&P.y)} self.z.copy(&P.z); self.inf=P.inf; } /* this=-this */ pub fn neg(&mut self) { if self.is_infinity() {return} if rom::CURVETYPE==rom::WEIERSTRASS { self.y.neg(); self.y.norm(); } if rom::CURVETYPE==rom::EDWARDS { self.x.neg(); self.x.norm(); } return; } /* multiply x coordinate */ pub fn mulx(&mut self,c: &mut FP) { self.x.mul(c); } /* Constant time select from pre-computed table */ fn selector(&mut self, W: &[ECP],b: i32) { // unsure about &[& syntax. An array of pointers I hope.. let mut MP=ECP::new(); let m=b>>31; let mut babs=(b^m)-m; babs=(babs-1)/2; self.cmove(&W[0],ECP::teq(babs,0)); // conditional move self.cmove(&W[1],ECP::teq(babs,1)); self.cmove(&W[2],ECP::teq(babs,2)); self.cmove(&W[3],ECP::teq(babs,3)); self.cmove(&W[4],ECP::teq(babs,4)); self.cmove(&W[5],ECP::teq(babs,5)); self.cmove(&W[6],ECP::teq(babs,6)); self.cmove(&W[7],ECP::teq(babs,7)); MP.copy(self); MP.neg(); self.cmove(&MP,(m&1) as isize); } /* Test P == Q */ pub fn equals(&mut self,Q: &mut ECP) -> bool { if self.is_infinity() && Q.is_infinity() {return true} if self.is_infinity() || Q.is_infinity() {return false} if rom::CURVETYPE==rom::WEIERSTRASS { let mut zs2=FP::new_copy(&self.z); zs2.sqr(); let mut zo2=FP::new_copy(&Q.z); zo2.sqr(); let mut zs3=FP::new_copy(&zs2); zs3.mul(&mut self.z); let mut zo3=FP::new_copy(&zo2); zo3.mul(&mut Q.z); zs2.mul(&mut Q.x); zo2.mul(&mut self.x); if!zs2.equals(&mut zo2) {return false} zs3.mul(&mut Q.y); zo3.mul(&mut self.y); if!zs3.equals(&mut zo3) {return false} } else { let mut a=FP::new(); let mut b=FP::new(); a.copy(&self.x); a.mul(&mut Q.z); a.reduce(); b.copy(&Q.x); b.mul(&mut self.z); b.reduce(); if!a.equals(&mut b) {return false} if rom::CURVETYPE==rom::EDWARDS { a.copy(&self.y); a.mul(&mut Q.z); a.reduce(); b.copy(&Q.y); b.mul(&mut self.z); b.reduce(); if!a.equals(&mut b) {return false} } } return true; } /* set to affine - from (x,y,z) to (x,y) */ pub fn affine(&mut self) { if self.is_infinity() {return} let mut one=FP::new_int(1); if self.z.equals(&mut one) {return} self.z.inverse(); if rom::CURVETYPE==rom::WEIERSTRASS { let mut z2=FP::new_copy(&self.z); z2.sqr(); self.x.mul(&mut z2); self.x.reduce(); self.y.mul(&mut z2); self.y.mul(&mut self.z); self.y.reduce(); } if rom::CURVETYPE==rom::EDWARDS { self.x.mul(&mut self.z); self.x.reduce(); self.y.mul(&mut self.z); self.y.reduce(); } if rom::CURVETYPE==rom::MONTGOMERY { self.x.mul(&mut self.z); self.x.reduce(); } self.z.one(); } /* extract x as a BIG */ pub fn getx(&mut self) -> BIG { self.affine(); return self.x.redc(); } /* extract y as a BIG */ pub fn gety(&mut self) -> BIG { self.affine(); return self.y.redc(); } /* get sign of Y */ pub fn gets(&mut self) -> isize { self.affine(); let y=self.gety(); return y.parity(); } /* extract x as an FP */ pub fn getpx(&self) -> FP { let w=FP::new_copy(&self.x); return w; } /* extract y as an FP */ pub fn getpy(&self) -> FP { let w=FP::new_copy(&self.y); return w; } /* extract z as an FP */ pub fn getpz(&self) -> FP { let w=FP::new_copy(&self.z); return w; } /* convert to byte array */ pub fn tobytes(&mut self,b: &mut [u8]) { let mb=rom::MODBYTES as usize; let mut t:[u8;rom::MODBYTES as usize]=[0;rom::MODBYTES as usize]; if rom::CURVETYPE!=rom::MONTGOMERY { b[0]=0x04; } else {b[0]=0x02} self.affine(); self.x.redc().tobytes(&mut t); for i in 0..mb {b[i+1]=t[i]} if rom::CURVETYPE!=rom::MONTGOMERY { self.y.redc().tobytes(&mut t); for i in 0..mb {b[i+mb+1]=t[i]} } } /* convert from byte array to point */ pub fn frombytes(b: &[u8]) -> ECP { let mut t:[u8;rom::MODBYTES as usize]=[0;rom::MODBYTES as usize]; let mb=rom::MODBYTES as usize; let p=BIG::new_ints(&rom::MODULUS); for i in 0..mb {t[i]=b[i+1]} let px=BIG::frombytes(&t); if BIG::comp(&px,&p)>=0 {return ECP::new()} if b[0]==0x04 { for i in 0..mb {t[i]=b[i+mb+1]} let py=BIG::frombytes(&t); if BIG::comp(&py,&p)>=0 {return ECP::new()} return ECP::new_bigs(&px,&py); } else {return ECP::new_big(&px)} } pub fn to_hex(&self) -> String { let mut ret: String = String::with_capacity(4 * BIG_HEX_STRING_LEN); ret.push_str(&format!("{} {} {} {}", self.inf, self.x.to_hex(), self.y.to_hex(), self.z.to_hex())); return ret; } pub fn from_hex_iter(iter: &mut SplitWhitespace) -> ECP { let mut ret:ECP = ECP::new(); if let Some(x) = iter.next() { ret.inf = x == "true"; ret.x = FP::from_hex(iter.next().unwrap_or("").to_string()); ret.y = FP::from_hex(iter.next().unwrap_or("").to_string()); ret.z = FP::from_hex(iter.next().unwrap_or("").to_string()); } return ret; } pub fn from_hex(val: String) -> ECP { let mut iter = val.split_whitespace(); return ECP::from_hex_iter(&mut iter); } /* convert to hex string */ pub fn tostring(&mut self) -> String { if self.is_infinity() {return String::from("infinity")} self.affine(); if rom::CURVETYPE==rom::MONTGOMERY { return format!("({})",self.x.redc().tostring()); } else {return format!("({},{})",self.x.redc().tostring(),self.y.redc().tostring())} ; } /* this*=2 */ pub fn dbl(&mut self) { if rom::CURVETYPE==rom::WEIERSTRASS { if self.inf {return} if self.y.iszilch() { self.inf(); return; } let mut w1=FP::new_copy(&self.x); let mut w6=FP::new_copy(&self.z); let mut w2=FP::new(); let mut w3=FP::new_copy(&self.x); let mut w8=FP::new_copy(&self.x); if rom::CURVE_A==-3 { w6.sqr(); w1.copy(&w6); w1.neg(); w3.add(&w1); w8.add(&w6); w3.mul(&mut w8); w8.copy(&w3); w8.imul(3); } else { w1.sqr(); w8.copy(&w1); w8.imul(3); } w2.copy(&self.y); w2.sqr(); w3.copy(&self.x); w3.mul(&mut w2); w3.imul(4); w1.copy(&w3); w1.neg(); w1.norm(); self.x.copy(&w8); self.x.sqr(); self.x.add(&w1); self.x.add(&w1); self.x.norm(); self.z.mul(&mut self.y); self.z.dbl(); w2.dbl(); w2.sqr(); w2.dbl(); w3.sub(&self.x); self.y.copy(&w8); self.y.mul(&mut w3); //w2.norm(); self.y.sub(&w2); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::EDWARDS { let mut c=FP::new_copy(&self.x); let mut d=FP::new_copy(&self.y); let mut h=FP::new_copy(&self.z); let mut j=FP::new(); self.x.mul(&mut self.y); self.x.dbl(); c.sqr(); d.sqr(); if rom::CURVE_A == -1 {c.neg()} self.y.copy(&c); self.y.add(&d); self.y.norm(); h.sqr(); h.dbl(); self.z.copy(&self.y); j.copy(&self.y); j.sub(&h); self.x.mul(&mut j); c.sub(&d); self.y.mul(&mut c); self.z.mul(&mut j); self.x.norm(); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::MONTGOMERY { let mut a=FP::new_copy(&self.x); let mut b=FP::new_copy(&self.x); let mut aa=FP::new(); let mut bb=FP::new(); let mut c=FP::new(); if self.inf {return} a.add(&self.z); aa.copy(&a); aa.sqr(); b.sub(&self.z); bb.copy(&b); bb.sqr(); c.copy(&aa); c.sub(&bb); self.x.copy(&aa); self.x.mul(&mut bb); a.copy(&c); a.imul((rom::CURVE_A+2)/4); bb.add(&a); self.z.copy(&bb); self.z.mul(&mut c); self.x.norm(); self.z.norm(); } return; } /* self+=Q */ pub fn add(&mut self,Q:&mut ECP) { if rom::CURVETYPE==rom::WEIERSTRASS { if self.inf { self.copy(&Q); return; } if Q.inf {return} let mut aff=false; let mut one=FP::new_int(1); if Q.z.equals(&mut one) {aff=true} let mut a=FP::new(); let mut c=FP::new(); let mut b=FP::new_copy(&self.z); let mut d=FP::new_copy(&self.z); if!aff { a.copy(&Q.z); c.copy(&Q.z); a.sqr(); b.sqr(); c.mul(&mut a); d.mul(&mut b); a.mul(&mut self.x); c.mul(&mut self.y); } else { a.copy(&self.x); c.copy(&self.y); b.sqr(); d.mul(&mut b); } b.mul(&mut Q.x); b.sub(&a); d.mul(&mut Q.y); d.sub(&c); if b.iszilch() { if d.iszilch() { self.dbl(); return; } else { self.inf=true; return; } } if!aff {self.z.mul(&mut Q.z)} self.z.mul(&mut b); let mut e=FP::new_copy(&b); e.sqr(); b.mul(&mut e); a.mul(&mut e); e.copy(&a); e.add(&a); e.add(&b); self.x.copy(&d); self.x.sqr(); self.x.sub(&e); a.sub(&self.x); self.y.copy(&a); self.y.mul(&mut d); c.mul(&mut b); self.y.sub(&c); self.x.norm(); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::EDWARDS { let mut bb=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); let mut a=FP::new_copy(&self.z); let mut b=FP::new(); let mut c=FP::new_copy(&self.x); let mut d=FP::new_copy(&self.y); let mut e=FP::new(); let mut f=FP::new(); let mut g=FP::new(); a.mul(&mut Q.z); b.copy(&a); b.sqr(); c.mul(&mut Q.x); d.mul(&mut Q.y); e.copy(&c); e.mul(&mut d); e.mul(&mut bb); f.copy(&b); f.sub(&e); g.copy(&b); g.add(&e); if rom::CURVE_A==1 { e.copy(&d); e.sub(&c); } c.add(&d); b.copy(&self.x); b.add(&self.y); d.copy(&Q.x); d.add(&Q.y); b.mul(&mut d); b.sub(&c); b.mul(&mut f); self.x.copy(&a); self.x.mul(&mut b); if rom::CURVE_A==1 { c.copy(&e); c.mul(&mut g); } if rom::CURVE_A == -1 { c.mul(&mut g); } self.y.copy(&a); self.y.mul(&mut c); self.z.copy(&f); self.z.mul(&mut g); self.x.norm(); self.y.norm(); self.z.norm(); } return; } /* Differential Add for Montgomery curves. this+=Q where W is this-Q and is affine. */ pub fn dadd(&mut self,Q: &ECP,W: &ECP) { let mut a=FP::new_copy(&self.x); let mut b=FP::new_copy(&self.x); let mut c=FP::new_copy(&Q.x); let mut d=FP::new_copy(&Q.x); let mut da=FP::new(); let mut cb=FP::new(); a.add(&self.z); b.sub(&self.z); c.add(&Q.z); d.sub(&Q.z); da.copy(&d); da.mul(&mut a); cb.copy(&c); cb.mul(&mut b); a.copy(&da); a.add(&cb); a.sqr(); b.copy(&da); b.sub(&cb); b.sqr(); self.x.copy(&a); self.z.copy(&W.x); self.z.mul(&mut b); if self.z.iszilch() { self.inf(); } else {self.inf=false;} self.x.norm(); } /* self-=Q */ pub fn sub(&mut self,Q:&mut ECP) { Q.neg(); self.add(Q); Q.neg(); } fn multiaffine(P: &mut [ECP]) { let mut t1=FP::new(); let mut t2=FP::new(); let mut work:[FP;8]=[FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new()]; let m=8; work[0].one(); work[1].copy(&P[0].z);
work[i].mul(&mut P[i-1].z); } t1.copy(&work[m-1]); t1.mul(&mut P[m-1].z); t1.inverse(); t2.copy(&P[m-1].z); work[m-1].mul(&mut t1); let mut i=m-2; loop { if i==0 { work[0].copy(&t1); work[0].mul(&mut t2); break; } work[i].mul(&mut t2); work[i].mul(&mut t1); t2.mul(&mut P[i].z); i-=1; } /* now work[] contains inverses of all Z coordinates */ for i in 0..m { P[i].z.one(); t1.copy(&work[i]); t1.sqr(); P[i].x.mul(&mut t1); t1.mul(&mut work[i]); P[i].y.mul(&mut t1); } } /* constant time multiply by small integer of length bts - use ladder */ pub fn pinmul(&mut self,e: i32,bts: i32) -> ECP { if rom::CURVETYPE==rom::MONTGOMERY { return self.mul(&mut BIG::new_int(e as isize)); } else { let mut P=ECP::new(); let mut R0=ECP::new(); let mut R1=ECP::new(); R1.copy(&self); for i in (0..bts).rev() { let b=((e>>i)&1) as isize; P.copy(&R1); P.add(&mut R0); R0.cswap(&mut R1,b); R1.copy(&P); R0.dbl(); R0.cswap(&mut R1,b); } P.copy(&R0); P.affine();
for i in 2..m { t1.copy(&work[i-1]); work[i].copy(&t1);
random_line_split
ecp.rs
} impl fmt::Debug for ECP { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ECP: [ {}, {}, {}, {} ]", self.inf, self.x, self.y, self.z) } } impl PartialEq for ECP { fn eq(&self, other: &ECP) -> bool { return (self.inf == other.inf) && (self.x == other.x) && (self.y == other.y) && (self.z == other.z); } } #[allow(non_snake_case)] impl ECP { pub fn new() -> ECP { ECP { x: FP::new(), y: FP::new(), z: FP::new(), inf: true } } /* set (x,y) from two BIGs */ pub fn new_bigs(ix: &BIG,iy: &BIG) -> ECP { let mut E=ECP::new(); E.x.bcopy(ix); E.y.bcopy(iy); E.z.one(); let mut rhs=ECP::rhs(&mut E.x); if rom::CURVETYPE==rom::MONTGOMERY { if rhs.jacobi()==1 { E.inf=false; } else {E.inf()} } else { let mut y2=FP::new_copy(&E.y); y2.sqr(); if y2.equals(&mut rhs) { E.inf=false } else {E.inf()} } return E; } /* set (x,y) from BIG and a bit */ pub fn new_bigint(ix: &BIG,s: isize) -> ECP { let mut E=ECP::new(); E.x.bcopy(ix); E.z.one(); let mut rhs=ECP::rhs(&mut E.x); if rhs.jacobi()==1 { let mut ny=rhs.sqrt(); if ny.redc().parity()!=s {ny.neg()} E.y.copy(&ny); E.inf=false; } else {E.inf()} return E; } #[allow(non_snake_case)] /* set from x - calculate y from curve equation */ pub fn new_big(ix: &BIG) -> ECP { let mut E=ECP::new(); E.x.bcopy(ix); E.z.one(); let mut rhs=ECP::rhs(&mut E.x); if rhs.jacobi()==1 { if rom::CURVETYPE!=rom::MONTGOMERY {E.y.copy(&rhs.sqrt())} E.inf=false; } else {E.inf=true} return E; } /* set this=O */ pub fn inf(&mut self) { self.inf=true; self.x.zero(); self.y.one(); self.z.one(); } /* Calculate RHS of curve equation */ fn rhs(x: &mut FP) -> FP { x.norm(); let mut r=FP::new_copy(x); r.sqr(); if rom::CURVETYPE==rom::WEIERSTRASS { // x^3+Ax+B let b=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); r.mul(x); if rom::CURVE_A==-3 { let mut cx=FP::new_copy(x); cx.imul(3); cx.neg(); cx.norm(); r.add(&cx); } r.add(&b); } if rom::CURVETYPE==rom::EDWARDS { // (Ax^2-1)/(Bx^2-1) let mut b=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); let one=FP::new_int(1); b.mul(&mut r); b.sub(&one); if rom::CURVE_A==-1 {r.neg()} r.sub(&one); b.inverse(); r.mul(&mut b); } if rom::CURVETYPE==rom::MONTGOMERY { // x^3+Ax^2+x let mut x3=FP::new(); x3.copy(&r); x3.mul(x); r.imul(rom::CURVE_A); r.add(&x3); r.add(&x); } r.reduce(); return r; } /* test for O point-at-infinity */ pub fn is_infinity(&mut self) -> bool { if rom::CURVETYPE==rom::EDWARDS { self.x.reduce(); self.y.reduce(); self.z.reduce(); return self.x.iszilch() && self.y.equals(&mut self.z); } else {return self.inf} } /* Conditional swap of P and Q dependant on d */ pub fn cswap(&mut self,Q: &mut ECP,d: isize) { self.x.cswap(&mut Q.x,d); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.cswap(&mut Q.y,d)} self.z.cswap(&mut Q.z,d); if rom::CURVETYPE!=rom::EDWARDS { let mut bd=true; if d==0 {bd=false} bd=bd&&(self.inf!=Q.inf); self.inf=bd!=self.inf; Q.inf=bd!=Q.inf; } } /* Conditional move of Q to P dependant on d */ pub fn cmove(&mut self,Q: &ECP,d: isize) { self.x.cmove(&Q.x,d); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.cmove(&Q.y,d)} self.z.cmove(&Q.z,d); if rom::CURVETYPE!=rom::EDWARDS { let mut bd=true; if d==0 {bd=false} self.inf=self.inf!=((self.inf!=Q.inf)&&bd); } } /* return 1 if b==c, no branching */ fn teq(b: i32,c: i32) -> isize { let mut x=b^c; x-=1; // if x=0, x now -1 return ((x>>31)&1) as isize; } /* this=P */ pub fn copy(&mut self,P: & ECP) { self.x.copy(&P.x); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.copy(&P.y)} self.z.copy(&P.z); self.inf=P.inf; } /* this=-this */ pub fn neg(&mut self) { if self.is_infinity() {return} if rom::CURVETYPE==rom::WEIERSTRASS { self.y.neg(); self.y.norm(); } if rom::CURVETYPE==rom::EDWARDS { self.x.neg(); self.x.norm(); } return; } /* multiply x coordinate */ pub fn mulx(&mut self,c: &mut FP) { self.x.mul(c); } /* Constant time select from pre-computed table */ fn selector(&mut self, W: &[ECP],b: i32) { // unsure about &[& syntax. An array of pointers I hope.. let mut MP=ECP::new(); let m=b>>31; let mut babs=(b^m)-m; babs=(babs-1)/2; self.cmove(&W[0],ECP::teq(babs,0)); // conditional move self.cmove(&W[1],ECP::teq(babs,1)); self.cmove(&W[2],ECP::teq(babs,2)); self.cmove(&W[3],ECP::teq(babs,3)); self.cmove(&W[4],ECP::teq(babs,4)); self.cmove(&W[5],ECP::teq(babs,5)); self.cmove(&W[6],ECP::teq(babs,6)); self.cmove(&W[7],ECP::teq(babs,7)); MP.copy(self); MP.neg(); self.cmove(&MP,(m&1) as isize); } /* Test P == Q */ pub fn equals(&mut self,Q: &mut ECP) -> bool { if self.is_infinity() && Q.is_infinity() {return true} if self.is_infinity() || Q.is_infinity() {return false} if rom::CURVETYPE==rom::WEIERSTRASS { let mut zs2=FP::new_copy(&self.z); zs2.sqr(); let mut zo2=FP::new_copy(&Q.z); zo2.sqr(); let mut zs3=FP::new_copy(&zs2); zs3.mul(&mut self.z); let mut zo3=FP::new_copy(&zo2); zo3.mul(&mut Q.z); zs2.mul(&mut Q.x); zo2.mul(&mut self.x); if!zs2.equals(&mut zo2) {return false} zs3.mul(&mut Q.y); zo3.mul(&mut self.y); if!zs3.equals(&mut zo3) {return false} } else { let mut a=FP::new(); let mut b=FP::new(); a.copy(&self.x); a.mul(&mut Q.z); a.reduce(); b.copy(&Q.x); b.mul(&mut self.z); b.reduce(); if!a.equals(&mut b) {return false} if rom::CURVETYPE==rom::EDWARDS { a.copy(&self.y); a.mul(&mut Q.z); a.reduce(); b.copy(&Q.y); b.mul(&mut self.z); b.reduce(); if!a.equals(&mut b) {return false} } } return true; } /* set to affine - from (x,y,z) to (x,y) */ pub fn affine(&mut self) { if self.is_infinity() {return} let mut one=FP::new_int(1); if self.z.equals(&mut one) {return} self.z.inverse(); if rom::CURVETYPE==rom::WEIERSTRASS { let mut z2=FP::new_copy(&self.z); z2.sqr(); self.x.mul(&mut z2); self.x.reduce(); self.y.mul(&mut z2); self.y.mul(&mut self.z); self.y.reduce(); } if rom::CURVETYPE==rom::EDWARDS { self.x.mul(&mut self.z); self.x.reduce(); self.y.mul(&mut self.z); self.y.reduce(); } if rom::CURVETYPE==rom::MONTGOMERY { self.x.mul(&mut self.z); self.x.reduce(); } self.z.one(); } /* extract x as a BIG */ pub fn getx(&mut self) -> BIG { self.affine(); return self.x.redc(); } /* extract y as a BIG */ pub fn gety(&mut self) -> BIG { self.affine(); return self.y.redc(); } /* get sign of Y */ pub fn gets(&mut self) -> isize { self.affine(); let y=self.gety(); return y.parity(); } /* extract x as an FP */ pub fn getpx(&self) -> FP { let w=FP::new_copy(&self.x); return w; } /* extract y as an FP */ pub fn getpy(&self) -> FP { let w=FP::new_copy(&self.y); return w; } /* extract z as an FP */ pub fn getpz(&self) -> FP { let w=FP::new_copy(&self.z); return w; } /* convert to byte array */ pub fn tobytes(&mut self,b: &mut [u8]) { let mb=rom::MODBYTES as usize; let mut t:[u8;rom::MODBYTES as usize]=[0;rom::MODBYTES as usize]; if rom::CURVETYPE!=rom::MONTGOMERY { b[0]=0x04; } else {b[0]=0x02} self.affine(); self.x.redc().tobytes(&mut t); for i in 0..mb {b[i+1]=t[i]} if rom::CURVETYPE!=rom::MONTGOMERY { self.y.redc().tobytes(&mut t); for i in 0..mb {b[i+mb+1]=t[i]} } } /* convert from byte array to point */ pub fn frombytes(b: &[u8]) -> ECP { let mut t:[u8;rom::MODBYTES as usize]=[0;rom::MODBYTES as usize]; let mb=rom::MODBYTES as usize; let p=BIG::new_ints(&rom::MODULUS); for i in 0..mb {t[i]=b[i+1]} let px=BIG::frombytes(&t); if BIG::comp(&px,&p)>=0 {return ECP::new()} if b[0]==0x04 { for i in 0..mb {t[i]=b[i+mb+1]} let py=BIG::frombytes(&t); if BIG::comp(&py,&p)>=0 {return ECP::new()} return ECP::new_bigs(&px,&py); } else {return ECP::new_big(&px)} } pub fn to_hex(&self) -> String { let mut ret: String = String::with_capacity(4 * BIG_HEX_STRING_LEN); ret.push_str(&format!("{} {} {} {}", self.inf, self.x.to_hex(), self.y.to_hex(), self.z.to_hex())); return ret; } pub fn from_hex_iter(iter: &mut SplitWhitespace) -> ECP { let mut ret:ECP = ECP::new(); if let Some(x) = iter.next() { ret.inf = x == "true"; ret.x = FP::from_hex(iter.next().unwrap_or("").to_string()); ret.y = FP::from_hex(iter.next().unwrap_or("").to_string()); ret.z = FP::from_hex(iter.next().unwrap_or("").to_string()); } return ret; } pub fn from_hex(val: String) -> ECP { let mut iter = val.split_whitespace(); return ECP::from_hex_iter(&mut iter); } /* convert to hex string */ pub fn tostring(&mut self) -> String { if self.is_infinity() {return String::from("infinity")} self.affine(); if rom::CURVETYPE==rom::MONTGOMERY { return format!("({})",self.x.redc().tostring()); } else {return format!("({},{})",self.x.redc().tostring(),self.y.redc().tostring())} ; } /* this*=2 */ pub fn dbl(&mut self) { if rom::CURVETYPE==rom::WEIERSTRASS { if self.inf {return} if self.y.iszilch() { self.inf(); return; } let mut w1=FP::new_copy(&self.x); let mut w6=FP::new_copy(&self.z); let mut w2=FP::new(); let mut w3=FP::new_copy(&self.x); let mut w8=FP::new_copy(&self.x); if rom::CURVE_A==-3 { w6.sqr(); w1.copy(&w6); w1.neg(); w3.add(&w1); w8.add(&w6); w3.mul(&mut w8); w8.copy(&w3); w8.imul(3); } else { w1.sqr(); w8.copy(&w1); w8.imul(3); } w2.copy(&self.y); w2.sqr(); w3.copy(&self.x); w3.mul(&mut w2); w3.imul(4); w1.copy(&w3); w1.neg(); w1.norm(); self.x.copy(&w8); self.x.sqr(); self.x.add(&w1); self.x.add(&w1); self.x.norm(); self.z.mul(&mut self.y); self.z.dbl(); w2.dbl(); w2.sqr(); w2.dbl(); w3.sub(&self.x); self.y.copy(&w8); self.y.mul(&mut w3); //w2.norm(); self.y.sub(&w2); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::EDWARDS { let mut c=FP::new_copy(&self.x); let mut d=FP::new_copy(&self.y); let mut h=FP::new_copy(&self.z); let mut j=FP::new(); self.x.mul(&mut self.y); self.x.dbl(); c.sqr(); d.sqr(); if rom::CURVE_A == -1 {c.neg()} self.y.copy(&c); self.y.add(&d); self.y.norm(); h.sqr(); h.dbl(); self.z.copy(&self.y); j.copy(&self.y); j.sub(&h); self.x.mul(&mut j); c.sub(&d); self.y.mul(&mut c); self.z.mul(&mut j); self.x.norm(); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::MONTGOMERY { let mut a=FP::new_copy(&self.x); let mut b=FP::new_copy(&self.x); let mut aa=FP::new(); let mut bb=FP::new(); let mut c=FP::new(); if self.inf {return} a.add(&self.z); aa.copy(&a); aa.sqr(); b.sub(&self.z); bb.copy(&b); bb.sqr(); c.copy(&aa); c.sub(&bb); self.x.copy(&aa); self.x.mul(&mut bb); a.copy(&c); a.imul((rom::CURVE_A+2)/4); bb.add(&a); self.z.copy(&bb); self.z.mul(&mut c); self.x.norm(); self.z.norm(); } return; } /* self+=Q */ pub fn add(&mut self,Q:&mut ECP) { if rom::CURVETYPE==rom::WEIERSTRASS { if self.inf { self.copy(&Q); return; } if Q.inf {return} let mut aff=false; let mut one=FP::new_int(1); if Q.z.equals(&mut one) {aff=true} let mut a=FP::new(); let mut c=FP::new(); let mut b=FP::new_copy(&self.z); let mut d=FP::new_copy(&self.z); if!aff { a.copy(&Q.z); c.copy(&Q.z); a.sqr(); b.sqr(); c.mul(&mut a); d.mul(&mut b); a.mul(&mut self.x); c.mul(&mut self.y); } else { a.copy(&self.x); c.copy(&self.y); b.sqr(); d.mul(&mut b); } b.mul(&mut Q.x); b.sub(&a); d.mul(&mut Q.y); d.sub(&c); if b.iszilch() { if d.iszilch() { self.dbl(); return; } else { self.inf=true; return; } } if!aff {self.z.mul(&mut Q.z)} self.z.mul(&mut b); let mut e=FP::new_copy(&b); e.sqr(); b.mul(&mut e); a.mul(&mut e); e.copy(&a); e.add(&a); e.add(&b); self.x.copy(&d); self.x.sqr(); self.x.sub(&e); a.sub(&self.x); self.y.copy(&a); self.y.mul(&mut d); c.mul(&mut b); self.y.sub(&c); self.x.norm(); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::EDWARDS { let mut bb=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); let mut a=FP::new_copy(&self.z); let mut b=FP::new(); let mut c=FP::new_copy(&self.x); let mut d=FP::new_copy(&self.y); let mut e=FP::new(); let mut f=FP::new(); let mut g=FP::new(); a.mul(&mut Q.z); b.copy(&a); b.sqr(); c.mul(&mut Q.x); d.mul(&mut Q.y); e.copy(&c); e.mul(&mut d); e.mul(&mut bb); f.copy(&b); f.sub(&e); g.copy(&b); g.add(&e); if rom::CURVE_A==1 { e.copy(&d); e.sub(&c); } c.add(&d); b.copy(&self.x); b.add(&self.y); d.copy(&Q.x); d.add(&Q.y); b.mul(&mut d); b.sub(&c); b.mul(&mut f); self.x.copy(&a); self.x.mul(&mut b); if rom::CURVE_A==1 { c.copy(&e); c.mul(&mut g); } if rom::CURVE_A == -1 { c.mul(&mut g); } self.y.copy(&a); self.y.mul(&mut c); self.z.copy(&f); self.z.mul(&mut g); self.x.norm(); self.y.norm(); self.z.norm(); } return; } /* Differential Add for Montgomery curves. this+=Q where W is this-Q and is affine. */ pub fn dadd(&mut self,Q: &ECP,W: &ECP) { let mut a=FP::new_copy(&self.x); let mut b=FP::new_copy(&self.x); let mut c=FP::new_copy(&Q.x); let mut d=FP::new_copy(&Q.x); let mut da=FP::new(); let mut cb=FP::new(); a.add(&self.z); b.sub(&self.z); c.add(&Q.z); d.sub(&Q.z); da.copy(&d); da.mul(&mut a); cb.copy(&c); cb.mul(&mut b); a.copy(&da); a.add(&cb); a.sqr(); b.copy(&da); b.sub(&cb); b.sqr(); self.x.copy(&a); self.z.copy(&W.x); self.z.mul(&mut b); if self.z.iszilch() { self.inf(); } else {self.inf=false;} self.x.norm(); } /* self-=Q */ pub fn sub(&mut self,Q:&mut ECP) { Q.neg(); self.add(Q); Q.neg(); } fn multiaffine(P: &mut [ECP]) { let mut t1=FP::new(); let mut t2=FP::new(); let mut work:[FP;8]=[FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new
{ write!(f, "ECP: [ {}, {}, {}, {} ]", self.inf, self.x, self.y, self.z) }
identifier_body
ecp.rs
} #[allow(non_snake_case)] /* set from x - calculate y from curve equation */ pub fn new_big(ix: &BIG) -> ECP { let mut E=ECP::new(); E.x.bcopy(ix); E.z.one(); let mut rhs=ECP::rhs(&mut E.x); if rhs.jacobi()==1 { if rom::CURVETYPE!=rom::MONTGOMERY {E.y.copy(&rhs.sqrt())} E.inf=false; } else {E.inf=true} return E; } /* set this=O */ pub fn inf(&mut self) { self.inf=true; self.x.zero(); self.y.one(); self.z.one(); } /* Calculate RHS of curve equation */ fn rhs(x: &mut FP) -> FP { x.norm(); let mut r=FP::new_copy(x); r.sqr(); if rom::CURVETYPE==rom::WEIERSTRASS { // x^3+Ax+B let b=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); r.mul(x); if rom::CURVE_A==-3 { let mut cx=FP::new_copy(x); cx.imul(3); cx.neg(); cx.norm(); r.add(&cx); } r.add(&b); } if rom::CURVETYPE==rom::EDWARDS { // (Ax^2-1)/(Bx^2-1) let mut b=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); let one=FP::new_int(1); b.mul(&mut r); b.sub(&one); if rom::CURVE_A==-1 {r.neg()} r.sub(&one); b.inverse(); r.mul(&mut b); } if rom::CURVETYPE==rom::MONTGOMERY { // x^3+Ax^2+x let mut x3=FP::new(); x3.copy(&r); x3.mul(x); r.imul(rom::CURVE_A); r.add(&x3); r.add(&x); } r.reduce(); return r; } /* test for O point-at-infinity */ pub fn is_infinity(&mut self) -> bool { if rom::CURVETYPE==rom::EDWARDS { self.x.reduce(); self.y.reduce(); self.z.reduce(); return self.x.iszilch() && self.y.equals(&mut self.z); } else {return self.inf} } /* Conditional swap of P and Q dependant on d */ pub fn cswap(&mut self,Q: &mut ECP,d: isize) { self.x.cswap(&mut Q.x,d); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.cswap(&mut Q.y,d)} self.z.cswap(&mut Q.z,d); if rom::CURVETYPE!=rom::EDWARDS { let mut bd=true; if d==0 {bd=false} bd=bd&&(self.inf!=Q.inf); self.inf=bd!=self.inf; Q.inf=bd!=Q.inf; } } /* Conditional move of Q to P dependant on d */ pub fn cmove(&mut self,Q: &ECP,d: isize) { self.x.cmove(&Q.x,d); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.cmove(&Q.y,d)} self.z.cmove(&Q.z,d); if rom::CURVETYPE!=rom::EDWARDS { let mut bd=true; if d==0 {bd=false} self.inf=self.inf!=((self.inf!=Q.inf)&&bd); } } /* return 1 if b==c, no branching */ fn teq(b: i32,c: i32) -> isize { let mut x=b^c; x-=1; // if x=0, x now -1 return ((x>>31)&1) as isize; } /* this=P */ pub fn copy(&mut self,P: & ECP) { self.x.copy(&P.x); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.copy(&P.y)} self.z.copy(&P.z); self.inf=P.inf; } /* this=-this */ pub fn neg(&mut self) { if self.is_infinity() {return} if rom::CURVETYPE==rom::WEIERSTRASS { self.y.neg(); self.y.norm(); } if rom::CURVETYPE==rom::EDWARDS { self.x.neg(); self.x.norm(); } return; } /* multiply x coordinate */ pub fn mulx(&mut self,c: &mut FP) { self.x.mul(c); } /* Constant time select from pre-computed table */ fn selector(&mut self, W: &[ECP],b: i32) { // unsure about &[& syntax. An array of pointers I hope.. let mut MP=ECP::new(); let m=b>>31; let mut babs=(b^m)-m; babs=(babs-1)/2; self.cmove(&W[0],ECP::teq(babs,0)); // conditional move self.cmove(&W[1],ECP::teq(babs,1)); self.cmove(&W[2],ECP::teq(babs,2)); self.cmove(&W[3],ECP::teq(babs,3)); self.cmove(&W[4],ECP::teq(babs,4)); self.cmove(&W[5],ECP::teq(babs,5)); self.cmove(&W[6],ECP::teq(babs,6)); self.cmove(&W[7],ECP::teq(babs,7)); MP.copy(self); MP.neg(); self.cmove(&MP,(m&1) as isize); } /* Test P == Q */ pub fn equals(&mut self,Q: &mut ECP) -> bool { if self.is_infinity() && Q.is_infinity() {return true} if self.is_infinity() || Q.is_infinity() {return false} if rom::CURVETYPE==rom::WEIERSTRASS { let mut zs2=FP::new_copy(&self.z); zs2.sqr(); let mut zo2=FP::new_copy(&Q.z); zo2.sqr(); let mut zs3=FP::new_copy(&zs2); zs3.mul(&mut self.z); let mut zo3=FP::new_copy(&zo2); zo3.mul(&mut Q.z); zs2.mul(&mut Q.x); zo2.mul(&mut self.x); if!zs2.equals(&mut zo2) {return false} zs3.mul(&mut Q.y); zo3.mul(&mut self.y); if!zs3.equals(&mut zo3) {return false} } else { let mut a=FP::new(); let mut b=FP::new(); a.copy(&self.x); a.mul(&mut Q.z); a.reduce(); b.copy(&Q.x); b.mul(&mut self.z); b.reduce(); if!a.equals(&mut b) {return false} if rom::CURVETYPE==rom::EDWARDS { a.copy(&self.y); a.mul(&mut Q.z); a.reduce(); b.copy(&Q.y); b.mul(&mut self.z); b.reduce(); if!a.equals(&mut b) {return false} } } return true; } /* set to affine - from (x,y,z) to (x,y) */ pub fn affine(&mut self) { if self.is_infinity() {return} let mut one=FP::new_int(1); if self.z.equals(&mut one) {return} self.z.inverse(); if rom::CURVETYPE==rom::WEIERSTRASS { let mut z2=FP::new_copy(&self.z); z2.sqr(); self.x.mul(&mut z2); self.x.reduce(); self.y.mul(&mut z2); self.y.mul(&mut self.z); self.y.reduce(); } if rom::CURVETYPE==rom::EDWARDS { self.x.mul(&mut self.z); self.x.reduce(); self.y.mul(&mut self.z); self.y.reduce(); } if rom::CURVETYPE==rom::MONTGOMERY { self.x.mul(&mut self.z); self.x.reduce(); } self.z.one(); } /* extract x as a BIG */ pub fn getx(&mut self) -> BIG { self.affine(); return self.x.redc(); } /* extract y as a BIG */ pub fn gety(&mut self) -> BIG { self.affine(); return self.y.redc(); } /* get sign of Y */ pub fn gets(&mut self) -> isize { self.affine(); let y=self.gety(); return y.parity(); } /* extract x as an FP */ pub fn getpx(&self) -> FP { let w=FP::new_copy(&self.x); return w; } /* extract y as an FP */ pub fn getpy(&self) -> FP { let w=FP::new_copy(&self.y); return w; } /* extract z as an FP */ pub fn getpz(&self) -> FP { let w=FP::new_copy(&self.z); return w; } /* convert to byte array */ pub fn tobytes(&mut self,b: &mut [u8]) { let mb=rom::MODBYTES as usize; let mut t:[u8;rom::MODBYTES as usize]=[0;rom::MODBYTES as usize]; if rom::CURVETYPE!=rom::MONTGOMERY { b[0]=0x04; } else {b[0]=0x02} self.affine(); self.x.redc().tobytes(&mut t); for i in 0..mb {b[i+1]=t[i]} if rom::CURVETYPE!=rom::MONTGOMERY { self.y.redc().tobytes(&mut t); for i in 0..mb {b[i+mb+1]=t[i]} } } /* convert from byte array to point */ pub fn frombytes(b: &[u8]) -> ECP { let mut t:[u8;rom::MODBYTES as usize]=[0;rom::MODBYTES as usize]; let mb=rom::MODBYTES as usize; let p=BIG::new_ints(&rom::MODULUS); for i in 0..mb {t[i]=b[i+1]} let px=BIG::frombytes(&t); if BIG::comp(&px,&p)>=0 {return ECP::new()} if b[0]==0x04 { for i in 0..mb {t[i]=b[i+mb+1]} let py=BIG::frombytes(&t); if BIG::comp(&py,&p)>=0 {return ECP::new()} return ECP::new_bigs(&px,&py); } else {return ECP::new_big(&px)} } pub fn to_hex(&self) -> String { let mut ret: String = String::with_capacity(4 * BIG_HEX_STRING_LEN); ret.push_str(&format!("{} {} {} {}", self.inf, self.x.to_hex(), self.y.to_hex(), self.z.to_hex())); return ret; } pub fn from_hex_iter(iter: &mut SplitWhitespace) -> ECP { let mut ret:ECP = ECP::new(); if let Some(x) = iter.next() { ret.inf = x == "true"; ret.x = FP::from_hex(iter.next().unwrap_or("").to_string()); ret.y = FP::from_hex(iter.next().unwrap_or("").to_string()); ret.z = FP::from_hex(iter.next().unwrap_or("").to_string()); } return ret; } pub fn from_hex(val: String) -> ECP { let mut iter = val.split_whitespace(); return ECP::from_hex_iter(&mut iter); } /* convert to hex string */ pub fn tostring(&mut self) -> String { if self.is_infinity() {return String::from("infinity")} self.affine(); if rom::CURVETYPE==rom::MONTGOMERY { return format!("({})",self.x.redc().tostring()); } else {return format!("({},{})",self.x.redc().tostring(),self.y.redc().tostring())} ; } /* this*=2 */ pub fn dbl(&mut self) { if rom::CURVETYPE==rom::WEIERSTRASS { if self.inf {return} if self.y.iszilch() { self.inf(); return; } let mut w1=FP::new_copy(&self.x); let mut w6=FP::new_copy(&self.z); let mut w2=FP::new(); let mut w3=FP::new_copy(&self.x); let mut w8=FP::new_copy(&self.x); if rom::CURVE_A==-3 { w6.sqr(); w1.copy(&w6); w1.neg(); w3.add(&w1); w8.add(&w6); w3.mul(&mut w8); w8.copy(&w3); w8.imul(3); } else { w1.sqr(); w8.copy(&w1); w8.imul(3); } w2.copy(&self.y); w2.sqr(); w3.copy(&self.x); w3.mul(&mut w2); w3.imul(4); w1.copy(&w3); w1.neg(); w1.norm(); self.x.copy(&w8); self.x.sqr(); self.x.add(&w1); self.x.add(&w1); self.x.norm(); self.z.mul(&mut self.y); self.z.dbl(); w2.dbl(); w2.sqr(); w2.dbl(); w3.sub(&self.x); self.y.copy(&w8); self.y.mul(&mut w3); //w2.norm(); self.y.sub(&w2); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::EDWARDS { let mut c=FP::new_copy(&self.x); let mut d=FP::new_copy(&self.y); let mut h=FP::new_copy(&self.z); let mut j=FP::new(); self.x.mul(&mut self.y); self.x.dbl(); c.sqr(); d.sqr(); if rom::CURVE_A == -1 {c.neg()} self.y.copy(&c); self.y.add(&d); self.y.norm(); h.sqr(); h.dbl(); self.z.copy(&self.y); j.copy(&self.y); j.sub(&h); self.x.mul(&mut j); c.sub(&d); self.y.mul(&mut c); self.z.mul(&mut j); self.x.norm(); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::MONTGOMERY
self.z.copy(&bb); self.z.mul(&mut c); self.x.norm(); self.z.norm(); } return; } /* self+=Q */ pub fn add(&mut self,Q:&mut ECP) { if rom::CURVETYPE==rom::WEIERSTRASS { if self.inf { self.copy(&Q); return; } if Q.inf {return} let mut aff=false; let mut one=FP::new_int(1); if Q.z.equals(&mut one) {aff=true} let mut a=FP::new(); let mut c=FP::new(); let mut b=FP::new_copy(&self.z); let mut d=FP::new_copy(&self.z); if!aff { a.copy(&Q.z); c.copy(&Q.z); a.sqr(); b.sqr(); c.mul(&mut a); d.mul(&mut b); a.mul(&mut self.x); c.mul(&mut self.y); } else { a.copy(&self.x); c.copy(&self.y); b.sqr(); d.mul(&mut b); } b.mul(&mut Q.x); b.sub(&a); d.mul(&mut Q.y); d.sub(&c); if b.iszilch() { if d.iszilch() { self.dbl(); return; } else { self.inf=true; return; } } if!aff {self.z.mul(&mut Q.z)} self.z.mul(&mut b); let mut e=FP::new_copy(&b); e.sqr(); b.mul(&mut e); a.mul(&mut e); e.copy(&a); e.add(&a); e.add(&b); self.x.copy(&d); self.x.sqr(); self.x.sub(&e); a.sub(&self.x); self.y.copy(&a); self.y.mul(&mut d); c.mul(&mut b); self.y.sub(&c); self.x.norm(); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::EDWARDS { let mut bb=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); let mut a=FP::new_copy(&self.z); let mut b=FP::new(); let mut c=FP::new_copy(&self.x); let mut d=FP::new_copy(&self.y); let mut e=FP::new(); let mut f=FP::new(); let mut g=FP::new(); a.mul(&mut Q.z); b.copy(&a); b.sqr(); c.mul(&mut Q.x); d.mul(&mut Q.y); e.copy(&c); e.mul(&mut d); e.mul(&mut bb); f.copy(&b); f.sub(&e); g.copy(&b); g.add(&e); if rom::CURVE_A==1 { e.copy(&d); e.sub(&c); } c.add(&d); b.copy(&self.x); b.add(&self.y); d.copy(&Q.x); d.add(&Q.y); b.mul(&mut d); b.sub(&c); b.mul(&mut f); self.x.copy(&a); self.x.mul(&mut b); if rom::CURVE_A==1 { c.copy(&e); c.mul(&mut g); } if rom::CURVE_A == -1 { c.mul(&mut g); } self.y.copy(&a); self.y.mul(&mut c); self.z.copy(&f); self.z.mul(&mut g); self.x.norm(); self.y.norm(); self.z.norm(); } return; } /* Differential Add for Montgomery curves. this+=Q where W is this-Q and is affine. */ pub fn dadd(&mut self,Q: &ECP,W: &ECP) { let mut a=FP::new_copy(&self.x); let mut b=FP::new_copy(&self.x); let mut c=FP::new_copy(&Q.x); let mut d=FP::new_copy(&Q.x); let mut da=FP::new(); let mut cb=FP::new(); a.add(&self.z); b.sub(&self.z); c.add(&Q.z); d.sub(&Q.z); da.copy(&d); da.mul(&mut a); cb.copy(&c); cb.mul(&mut b); a.copy(&da); a.add(&cb); a.sqr(); b.copy(&da); b.sub(&cb); b.sqr(); self.x.copy(&a); self.z.copy(&W.x); self.z.mul(&mut b); if self.z.iszilch() { self.inf(); } else {self.inf=false;} self.x.norm(); } /* self-=Q */ pub fn sub(&mut self,Q:&mut ECP) { Q.neg(); self.add(Q); Q.neg(); } fn multiaffine(P: &mut [ECP]) { let mut t1=FP::new(); let mut t2=FP::new(); let mut work:[FP;8]=[FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new()]; let m=8; work[0].one(); work[1].copy(&P[0].z); for i in 2..m { t1.copy(&work[i-1]); work[i].copy(&t1); work[i].mul(&mut P[i-1].z); } t1.copy(&work[m-1]); t1.mul(&mut P[m-1].z); t1.inverse(); t2.copy(&P[m-1].z); work[m-1].mul(&mut t1); let mut i=m-2; loop { if i==0 { work[0].copy(&t1); work[0].mul(&mut t2); break; } work[i].mul(&mut t2); work[i].mul(&mut t1); t2.mul(&mut P[i].z); i-=1; } /* now work[] contains inverses of all Z coordinates */ for i in 0..m { P[i].z.one(); t1.copy(&work[i]); t1.sqr(); P[i].x.mul(&mut t1); t1.mul(&mut work[i]); P[i].y.mul(&mut t1); } } /* constant time multiply by small integer of length bts - use ladder */ pub fn pinmul(&mut self,e: i32,bts: i32) -> ECP { if rom::CURVETYPE==rom::MONTGOMERY { return self.mul(&mut BIG::new_int(e as isize)); } else { let mut P=ECP::new(); let mut R0=ECP::new(); let mut R1=ECP::new(); R1.copy(&self); for i in (0..bts).rev() { let b=((e>>i)&1) as isize; P.copy(&R1); P.add(&mut R0); R0.cswap(&mut R1,b); R1.copy(&P); R0.dbl(); R0.cswap(&mut R1,b); } P.copy(&R0); P.affine();
{ let mut a=FP::new_copy(&self.x); let mut b=FP::new_copy(&self.x); let mut aa=FP::new(); let mut bb=FP::new(); let mut c=FP::new(); if self.inf {return} a.add(&self.z); aa.copy(&a); aa.sqr(); b.sub(&self.z); bb.copy(&b); bb.sqr(); c.copy(&aa); c.sub(&bb); self.x.copy(&aa); self.x.mul(&mut bb); a.copy(&c); a.imul((rom::CURVE_A+2)/4); bb.add(&a);
conditional_block
ecp.rs
} #[allow(non_snake_case)] /* set from x - calculate y from curve equation */ pub fn new_big(ix: &BIG) -> ECP { let mut E=ECP::new(); E.x.bcopy(ix); E.z.one(); let mut rhs=ECP::rhs(&mut E.x); if rhs.jacobi()==1 { if rom::CURVETYPE!=rom::MONTGOMERY {E.y.copy(&rhs.sqrt())} E.inf=false; } else {E.inf=true} return E; } /* set this=O */ pub fn inf(&mut self) { self.inf=true; self.x.zero(); self.y.one(); self.z.one(); } /* Calculate RHS of curve equation */ fn rhs(x: &mut FP) -> FP { x.norm(); let mut r=FP::new_copy(x); r.sqr(); if rom::CURVETYPE==rom::WEIERSTRASS { // x^3+Ax+B let b=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); r.mul(x); if rom::CURVE_A==-3 { let mut cx=FP::new_copy(x); cx.imul(3); cx.neg(); cx.norm(); r.add(&cx); } r.add(&b); } if rom::CURVETYPE==rom::EDWARDS { // (Ax^2-1)/(Bx^2-1) let mut b=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); let one=FP::new_int(1); b.mul(&mut r); b.sub(&one); if rom::CURVE_A==-1 {r.neg()} r.sub(&one); b.inverse(); r.mul(&mut b); } if rom::CURVETYPE==rom::MONTGOMERY { // x^3+Ax^2+x let mut x3=FP::new(); x3.copy(&r); x3.mul(x); r.imul(rom::CURVE_A); r.add(&x3); r.add(&x); } r.reduce(); return r; } /* test for O point-at-infinity */ pub fn is_infinity(&mut self) -> bool { if rom::CURVETYPE==rom::EDWARDS { self.x.reduce(); self.y.reduce(); self.z.reduce(); return self.x.iszilch() && self.y.equals(&mut self.z); } else {return self.inf} } /* Conditional swap of P and Q dependant on d */ pub fn cswap(&mut self,Q: &mut ECP,d: isize) { self.x.cswap(&mut Q.x,d); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.cswap(&mut Q.y,d)} self.z.cswap(&mut Q.z,d); if rom::CURVETYPE!=rom::EDWARDS { let mut bd=true; if d==0 {bd=false} bd=bd&&(self.inf!=Q.inf); self.inf=bd!=self.inf; Q.inf=bd!=Q.inf; } } /* Conditional move of Q to P dependant on d */ pub fn cmove(&mut self,Q: &ECP,d: isize) { self.x.cmove(&Q.x,d); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.cmove(&Q.y,d)} self.z.cmove(&Q.z,d); if rom::CURVETYPE!=rom::EDWARDS { let mut bd=true; if d==0 {bd=false} self.inf=self.inf!=((self.inf!=Q.inf)&&bd); } } /* return 1 if b==c, no branching */ fn teq(b: i32,c: i32) -> isize { let mut x=b^c; x-=1; // if x=0, x now -1 return ((x>>31)&1) as isize; } /* this=P */ pub fn copy(&mut self,P: & ECP) { self.x.copy(&P.x); if rom::CURVETYPE!=rom::MONTGOMERY {self.y.copy(&P.y)} self.z.copy(&P.z); self.inf=P.inf; } /* this=-this */ pub fn neg(&mut self) { if self.is_infinity() {return} if rom::CURVETYPE==rom::WEIERSTRASS { self.y.neg(); self.y.norm(); } if rom::CURVETYPE==rom::EDWARDS { self.x.neg(); self.x.norm(); } return; } /* multiply x coordinate */ pub fn mulx(&mut self,c: &mut FP) { self.x.mul(c); } /* Constant time select from pre-computed table */ fn selector(&mut self, W: &[ECP],b: i32) { // unsure about &[& syntax. An array of pointers I hope.. let mut MP=ECP::new(); let m=b>>31; let mut babs=(b^m)-m; babs=(babs-1)/2; self.cmove(&W[0],ECP::teq(babs,0)); // conditional move self.cmove(&W[1],ECP::teq(babs,1)); self.cmove(&W[2],ECP::teq(babs,2)); self.cmove(&W[3],ECP::teq(babs,3)); self.cmove(&W[4],ECP::teq(babs,4)); self.cmove(&W[5],ECP::teq(babs,5)); self.cmove(&W[6],ECP::teq(babs,6)); self.cmove(&W[7],ECP::teq(babs,7)); MP.copy(self); MP.neg(); self.cmove(&MP,(m&1) as isize); } /* Test P == Q */ pub fn equals(&mut self,Q: &mut ECP) -> bool { if self.is_infinity() && Q.is_infinity() {return true} if self.is_infinity() || Q.is_infinity() {return false} if rom::CURVETYPE==rom::WEIERSTRASS { let mut zs2=FP::new_copy(&self.z); zs2.sqr(); let mut zo2=FP::new_copy(&Q.z); zo2.sqr(); let mut zs3=FP::new_copy(&zs2); zs3.mul(&mut self.z); let mut zo3=FP::new_copy(&zo2); zo3.mul(&mut Q.z); zs2.mul(&mut Q.x); zo2.mul(&mut self.x); if!zs2.equals(&mut zo2) {return false} zs3.mul(&mut Q.y); zo3.mul(&mut self.y); if!zs3.equals(&mut zo3) {return false} } else { let mut a=FP::new(); let mut b=FP::new(); a.copy(&self.x); a.mul(&mut Q.z); a.reduce(); b.copy(&Q.x); b.mul(&mut self.z); b.reduce(); if!a.equals(&mut b) {return false} if rom::CURVETYPE==rom::EDWARDS { a.copy(&self.y); a.mul(&mut Q.z); a.reduce(); b.copy(&Q.y); b.mul(&mut self.z); b.reduce(); if!a.equals(&mut b) {return false} } } return true; } /* set to affine - from (x,y,z) to (x,y) */ pub fn affine(&mut self) { if self.is_infinity() {return} let mut one=FP::new_int(1); if self.z.equals(&mut one) {return} self.z.inverse(); if rom::CURVETYPE==rom::WEIERSTRASS { let mut z2=FP::new_copy(&self.z); z2.sqr(); self.x.mul(&mut z2); self.x.reduce(); self.y.mul(&mut z2); self.y.mul(&mut self.z); self.y.reduce(); } if rom::CURVETYPE==rom::EDWARDS { self.x.mul(&mut self.z); self.x.reduce(); self.y.mul(&mut self.z); self.y.reduce(); } if rom::CURVETYPE==rom::MONTGOMERY { self.x.mul(&mut self.z); self.x.reduce(); } self.z.one(); } /* extract x as a BIG */ pub fn getx(&mut self) -> BIG { self.affine(); return self.x.redc(); } /* extract y as a BIG */ pub fn gety(&mut self) -> BIG { self.affine(); return self.y.redc(); } /* get sign of Y */ pub fn gets(&mut self) -> isize { self.affine(); let y=self.gety(); return y.parity(); } /* extract x as an FP */ pub fn getpx(&self) -> FP { let w=FP::new_copy(&self.x); return w; } /* extract y as an FP */ pub fn getpy(&self) -> FP { let w=FP::new_copy(&self.y); return w; } /* extract z as an FP */ pub fn getpz(&self) -> FP { let w=FP::new_copy(&self.z); return w; } /* convert to byte array */ pub fn tobytes(&mut self,b: &mut [u8]) { let mb=rom::MODBYTES as usize; let mut t:[u8;rom::MODBYTES as usize]=[0;rom::MODBYTES as usize]; if rom::CURVETYPE!=rom::MONTGOMERY { b[0]=0x04; } else {b[0]=0x02} self.affine(); self.x.redc().tobytes(&mut t); for i in 0..mb {b[i+1]=t[i]} if rom::CURVETYPE!=rom::MONTGOMERY { self.y.redc().tobytes(&mut t); for i in 0..mb {b[i+mb+1]=t[i]} } } /* convert from byte array to point */ pub fn frombytes(b: &[u8]) -> ECP { let mut t:[u8;rom::MODBYTES as usize]=[0;rom::MODBYTES as usize]; let mb=rom::MODBYTES as usize; let p=BIG::new_ints(&rom::MODULUS); for i in 0..mb {t[i]=b[i+1]} let px=BIG::frombytes(&t); if BIG::comp(&px,&p)>=0 {return ECP::new()} if b[0]==0x04 { for i in 0..mb {t[i]=b[i+mb+1]} let py=BIG::frombytes(&t); if BIG::comp(&py,&p)>=0 {return ECP::new()} return ECP::new_bigs(&px,&py); } else {return ECP::new_big(&px)} } pub fn to_hex(&self) -> String { let mut ret: String = String::with_capacity(4 * BIG_HEX_STRING_LEN); ret.push_str(&format!("{} {} {} {}", self.inf, self.x.to_hex(), self.y.to_hex(), self.z.to_hex())); return ret; } pub fn from_hex_iter(iter: &mut SplitWhitespace) -> ECP { let mut ret:ECP = ECP::new(); if let Some(x) = iter.next() { ret.inf = x == "true"; ret.x = FP::from_hex(iter.next().unwrap_or("").to_string()); ret.y = FP::from_hex(iter.next().unwrap_or("").to_string()); ret.z = FP::from_hex(iter.next().unwrap_or("").to_string()); } return ret; } pub fn from_hex(val: String) -> ECP { let mut iter = val.split_whitespace(); return ECP::from_hex_iter(&mut iter); } /* convert to hex string */ pub fn tostring(&mut self) -> String { if self.is_infinity() {return String::from("infinity")} self.affine(); if rom::CURVETYPE==rom::MONTGOMERY { return format!("({})",self.x.redc().tostring()); } else {return format!("({},{})",self.x.redc().tostring(),self.y.redc().tostring())} ; } /* this*=2 */ pub fn dbl(&mut self) { if rom::CURVETYPE==rom::WEIERSTRASS { if self.inf {return} if self.y.iszilch() { self.inf(); return; } let mut w1=FP::new_copy(&self.x); let mut w6=FP::new_copy(&self.z); let mut w2=FP::new(); let mut w3=FP::new_copy(&self.x); let mut w8=FP::new_copy(&self.x); if rom::CURVE_A==-3 { w6.sqr(); w1.copy(&w6); w1.neg(); w3.add(&w1); w8.add(&w6); w3.mul(&mut w8); w8.copy(&w3); w8.imul(3); } else { w1.sqr(); w8.copy(&w1); w8.imul(3); } w2.copy(&self.y); w2.sqr(); w3.copy(&self.x); w3.mul(&mut w2); w3.imul(4); w1.copy(&w3); w1.neg(); w1.norm(); self.x.copy(&w8); self.x.sqr(); self.x.add(&w1); self.x.add(&w1); self.x.norm(); self.z.mul(&mut self.y); self.z.dbl(); w2.dbl(); w2.sqr(); w2.dbl(); w3.sub(&self.x); self.y.copy(&w8); self.y.mul(&mut w3); //w2.norm(); self.y.sub(&w2); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::EDWARDS { let mut c=FP::new_copy(&self.x); let mut d=FP::new_copy(&self.y); let mut h=FP::new_copy(&self.z); let mut j=FP::new(); self.x.mul(&mut self.y); self.x.dbl(); c.sqr(); d.sqr(); if rom::CURVE_A == -1 {c.neg()} self.y.copy(&c); self.y.add(&d); self.y.norm(); h.sqr(); h.dbl(); self.z.copy(&self.y); j.copy(&self.y); j.sub(&h); self.x.mul(&mut j); c.sub(&d); self.y.mul(&mut c); self.z.mul(&mut j); self.x.norm(); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::MONTGOMERY { let mut a=FP::new_copy(&self.x); let mut b=FP::new_copy(&self.x); let mut aa=FP::new(); let mut bb=FP::new(); let mut c=FP::new(); if self.inf {return} a.add(&self.z); aa.copy(&a); aa.sqr(); b.sub(&self.z); bb.copy(&b); bb.sqr(); c.copy(&aa); c.sub(&bb); self.x.copy(&aa); self.x.mul(&mut bb); a.copy(&c); a.imul((rom::CURVE_A+2)/4); bb.add(&a); self.z.copy(&bb); self.z.mul(&mut c); self.x.norm(); self.z.norm(); } return; } /* self+=Q */ pub fn add(&mut self,Q:&mut ECP) { if rom::CURVETYPE==rom::WEIERSTRASS { if self.inf { self.copy(&Q); return; } if Q.inf {return} let mut aff=false; let mut one=FP::new_int(1); if Q.z.equals(&mut one) {aff=true} let mut a=FP::new(); let mut c=FP::new(); let mut b=FP::new_copy(&self.z); let mut d=FP::new_copy(&self.z); if!aff { a.copy(&Q.z); c.copy(&Q.z); a.sqr(); b.sqr(); c.mul(&mut a); d.mul(&mut b); a.mul(&mut self.x); c.mul(&mut self.y); } else { a.copy(&self.x); c.copy(&self.y); b.sqr(); d.mul(&mut b); } b.mul(&mut Q.x); b.sub(&a); d.mul(&mut Q.y); d.sub(&c); if b.iszilch() { if d.iszilch() { self.dbl(); return; } else { self.inf=true; return; } } if!aff {self.z.mul(&mut Q.z)} self.z.mul(&mut b); let mut e=FP::new_copy(&b); e.sqr(); b.mul(&mut e); a.mul(&mut e); e.copy(&a); e.add(&a); e.add(&b); self.x.copy(&d); self.x.sqr(); self.x.sub(&e); a.sub(&self.x); self.y.copy(&a); self.y.mul(&mut d); c.mul(&mut b); self.y.sub(&c); self.x.norm(); self.y.norm(); self.z.norm(); } if rom::CURVETYPE==rom::EDWARDS { let mut bb=FP::new_big(&BIG::new_ints(&rom::CURVE_B)); let mut a=FP::new_copy(&self.z); let mut b=FP::new(); let mut c=FP::new_copy(&self.x); let mut d=FP::new_copy(&self.y); let mut e=FP::new(); let mut f=FP::new(); let mut g=FP::new(); a.mul(&mut Q.z); b.copy(&a); b.sqr(); c.mul(&mut Q.x); d.mul(&mut Q.y); e.copy(&c); e.mul(&mut d); e.mul(&mut bb); f.copy(&b); f.sub(&e); g.copy(&b); g.add(&e); if rom::CURVE_A==1 { e.copy(&d); e.sub(&c); } c.add(&d); b.copy(&self.x); b.add(&self.y); d.copy(&Q.x); d.add(&Q.y); b.mul(&mut d); b.sub(&c); b.mul(&mut f); self.x.copy(&a); self.x.mul(&mut b); if rom::CURVE_A==1 { c.copy(&e); c.mul(&mut g); } if rom::CURVE_A == -1 { c.mul(&mut g); } self.y.copy(&a); self.y.mul(&mut c); self.z.copy(&f); self.z.mul(&mut g); self.x.norm(); self.y.norm(); self.z.norm(); } return; } /* Differential Add for Montgomery curves. this+=Q where W is this-Q and is affine. */ pub fn dadd(&mut self,Q: &ECP,W: &ECP) { let mut a=FP::new_copy(&self.x); let mut b=FP::new_copy(&self.x); let mut c=FP::new_copy(&Q.x); let mut d=FP::new_copy(&Q.x); let mut da=FP::new(); let mut cb=FP::new(); a.add(&self.z); b.sub(&self.z); c.add(&Q.z); d.sub(&Q.z); da.copy(&d); da.mul(&mut a); cb.copy(&c); cb.mul(&mut b); a.copy(&da); a.add(&cb); a.sqr(); b.copy(&da); b.sub(&cb); b.sqr(); self.x.copy(&a); self.z.copy(&W.x); self.z.mul(&mut b); if self.z.iszilch() { self.inf(); } else {self.inf=false;} self.x.norm(); } /* self-=Q */ pub fn sub(&mut self,Q:&mut ECP) { Q.neg(); self.add(Q); Q.neg(); } fn multiaffine(P: &mut [ECP]) { let mut t1=FP::new(); let mut t2=FP::new(); let mut work:[FP;8]=[FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new(),FP::new()]; let m=8; work[0].one(); work[1].copy(&P[0].z); for i in 2..m { t1.copy(&work[i-1]); work[i].copy(&t1); work[i].mul(&mut P[i-1].z); } t1.copy(&work[m-1]); t1.mul(&mut P[m-1].z); t1.inverse(); t2.copy(&P[m-1].z); work[m-1].mul(&mut t1); let mut i=m-2; loop { if i==0 { work[0].copy(&t1); work[0].mul(&mut t2); break; } work[i].mul(&mut t2); work[i].mul(&mut t1); t2.mul(&mut P[i].z); i-=1; } /* now work[] contains inverses of all Z coordinates */ for i in 0..m { P[i].z.one(); t1.copy(&work[i]); t1.sqr(); P[i].x.mul(&mut t1); t1.mul(&mut work[i]); P[i].y.mul(&mut t1); } } /* constant time multiply by small integer of length bts - use ladder */ pub fn
(&mut self,e: i32,bts: i32) -> ECP { if rom::CURVETYPE==rom::MONTGOMERY { return self.mul(&mut BIG::new_int(e as isize)); } else { let mut P=ECP::new(); let mut R0=ECP::new(); let mut R1=ECP::new(); R1.copy(&self); for i in (0..bts).rev() { let b=((e>>i)&1) as isize; P.copy(&R1); P.add(&mut R0); R0.cswap(&mut R1,b); R1.copy(&P); R0.dbl(); R0.cswap(&mut R1,b); } P.copy(&R0); P.affine();
pinmul
identifier_name
client.rs
use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; use crate::credential::{ Anonymous, CredentialsError, DefaultCredentialsProvider, ProvideAwsCredentials, StaticProvider, }; use crate::encoding::ContentEncoding; use crate::request::{DispatchSignedRequest, HttpClient, HttpDispatchError, HttpResponse}; use crate::signature::SignedRequest; use async_trait::async_trait; use lazy_static::lazy_static; use tokio::time; lazy_static! { static ref SHARED_CLIENT: Mutex<Weak<ClientInner<DefaultCredentialsProvider, HttpClient>>> = Mutex::new(Weak::new()); } /// Re-usable logic for all clients. #[derive(Clone)] pub struct Client { inner: Arc<dyn SignAndDispatch + Send + Sync>, } impl Client { /// Return the shared default client. pub fn shared() -> Self { let mut lock = SHARED_CLIENT.lock().unwrap(); if let Some(inner) = lock.upgrade() { return Client { inner }; } let credentials_provider = DefaultCredentialsProvider::new().expect("failed to create credentials provider"); let dispatcher = HttpClient::new().expect("failed to create request dispatcher"); let inner = Arc::new(ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }); *lock = Arc::downgrade(&inner); Client { inner } } /// Create a client from a credentials provider and request dispatcher. pub fn new_with<P, D>(credentials_provider: P, dispatcher: D) -> Self where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }; Client { inner: Arc::new(inner), } } /// Create a client from a request dispatcher without a credentials provider. The client will /// neither fetch any default credentials nor sign any requests. A non-signing client can be /// useful for calling APIs like `Sts::assume_role_with_web_identity` and /// `Sts::assume_role_with_saml` which do not require any request signing or when calling /// AWS compatible third party API endpoints which employ different authentication mechanisms. pub fn new_not_signing<D>(dispatcher: D) -> Self where D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner::<StaticProvider, D> { credentials_provider: None, dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }; Client { inner: Arc::new(inner), } } #[cfg(feature = "encoding")] /// Create a client with content encoding to compress payload before sending requests pub fn new_with_encoding<P, D>( credentials_provider: P, dispatcher: D, content_encoding: ContentEncoding, ) -> Self where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding, }; Client { inner: Arc::new(inner), } } /// Fetch credentials, sign the request and dispatch it. pub async fn sign_and_dispatch( &self, request: SignedRequest, ) -> Result<HttpResponse, SignAndDispatchError> { self.inner.sign_and_dispatch(request, None).await } } /// Error that occurs during `sign_and_dispatch` #[derive(Debug, PartialEq)] pub enum SignAndDispatchError { /// Error was due to bad credentials Credentials(CredentialsError), /// Error was due to http dispatch Dispatch(HttpDispatchError), } #[async_trait] trait SignAndDispatch { async fn sign_and_dispatch( &self, request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError>; } struct ClientInner<P, D> { credentials_provider: Option<Arc<P>>, dispatcher: Arc<D>, content_encoding: ContentEncoding, } impl<P, D> Clone for ClientInner<P, D> { fn clone(&self) -> Self { ClientInner { credentials_provider: self.credentials_provider.clone(), dispatcher: self.dispatcher.clone(), content_encoding: self.content_encoding.clone(), } } } async fn sign_and_dispatch<P, D>( client: ClientInner<P, D>, mut request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError> where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { client.content_encoding.encode(&mut request); if let Some(provider) = client.credentials_provider { let credentials = if let Some(to) = timeout { time::timeout(to, provider.credentials()) .await .map_err(|_| CredentialsError { message: "Timeout getting credentials".to_owned(), })
} else { provider.credentials().await } .map_err(SignAndDispatchError::Credentials)?; if credentials.is_anonymous() { request.complement(); } else { request.sign(&credentials); } } else { request.complement(); } client .dispatcher .dispatch(request, timeout) .await .map_err(SignAndDispatchError::Dispatch) } #[async_trait] impl<P, D> SignAndDispatch for ClientInner<P, D> where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { async fn sign_and_dispatch( &self, request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError> { sign_and_dispatch(self.clone(), request, timeout).await } } #[test] fn client_is_send_and_sync() { fn is_send_and_sync<T: Send + Sync>() {} is_send_and_sync::<Client>(); }
.and_then(std::convert::identity)
random_line_split
client.rs
use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; use crate::credential::{ Anonymous, CredentialsError, DefaultCredentialsProvider, ProvideAwsCredentials, StaticProvider, }; use crate::encoding::ContentEncoding; use crate::request::{DispatchSignedRequest, HttpClient, HttpDispatchError, HttpResponse}; use crate::signature::SignedRequest; use async_trait::async_trait; use lazy_static::lazy_static; use tokio::time; lazy_static! { static ref SHARED_CLIENT: Mutex<Weak<ClientInner<DefaultCredentialsProvider, HttpClient>>> = Mutex::new(Weak::new()); } /// Re-usable logic for all clients. #[derive(Clone)] pub struct Client { inner: Arc<dyn SignAndDispatch + Send + Sync>, } impl Client { /// Return the shared default client. pub fn shared() -> Self
/// Create a client from a credentials provider and request dispatcher. pub fn new_with<P, D>(credentials_provider: P, dispatcher: D) -> Self where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }; Client { inner: Arc::new(inner), } } /// Create a client from a request dispatcher without a credentials provider. The client will /// neither fetch any default credentials nor sign any requests. A non-signing client can be /// useful for calling APIs like `Sts::assume_role_with_web_identity` and /// `Sts::assume_role_with_saml` which do not require any request signing or when calling /// AWS compatible third party API endpoints which employ different authentication mechanisms. pub fn new_not_signing<D>(dispatcher: D) -> Self where D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner::<StaticProvider, D> { credentials_provider: None, dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }; Client { inner: Arc::new(inner), } } #[cfg(feature = "encoding")] /// Create a client with content encoding to compress payload before sending requests pub fn new_with_encoding<P, D>( credentials_provider: P, dispatcher: D, content_encoding: ContentEncoding, ) -> Self where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding, }; Client { inner: Arc::new(inner), } } /// Fetch credentials, sign the request and dispatch it. pub async fn sign_and_dispatch( &self, request: SignedRequest, ) -> Result<HttpResponse, SignAndDispatchError> { self.inner.sign_and_dispatch(request, None).await } } /// Error that occurs during `sign_and_dispatch` #[derive(Debug, PartialEq)] pub enum SignAndDispatchError { /// Error was due to bad credentials Credentials(CredentialsError), /// Error was due to http dispatch Dispatch(HttpDispatchError), } #[async_trait] trait SignAndDispatch { async fn sign_and_dispatch( &self, request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError>; } struct ClientInner<P, D> { credentials_provider: Option<Arc<P>>, dispatcher: Arc<D>, content_encoding: ContentEncoding, } impl<P, D> Clone for ClientInner<P, D> { fn clone(&self) -> Self { ClientInner { credentials_provider: self.credentials_provider.clone(), dispatcher: self.dispatcher.clone(), content_encoding: self.content_encoding.clone(), } } } async fn sign_and_dispatch<P, D>( client: ClientInner<P, D>, mut request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError> where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { client.content_encoding.encode(&mut request); if let Some(provider) = client.credentials_provider { let credentials = if let Some(to) = timeout { time::timeout(to, provider.credentials()) .await .map_err(|_| CredentialsError { message: "Timeout getting credentials".to_owned(), }) .and_then(std::convert::identity) } else { provider.credentials().await } .map_err(SignAndDispatchError::Credentials)?; if credentials.is_anonymous() { request.complement(); } else { request.sign(&credentials); } } else { request.complement(); } client .dispatcher .dispatch(request, timeout) .await .map_err(SignAndDispatchError::Dispatch) } #[async_trait] impl<P, D> SignAndDispatch for ClientInner<P, D> where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { async fn sign_and_dispatch( &self, request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError> { sign_and_dispatch(self.clone(), request, timeout).await } } #[test] fn client_is_send_and_sync() { fn is_send_and_sync<T: Send + Sync>() {} is_send_and_sync::<Client>(); }
{ let mut lock = SHARED_CLIENT.lock().unwrap(); if let Some(inner) = lock.upgrade() { return Client { inner }; } let credentials_provider = DefaultCredentialsProvider::new().expect("failed to create credentials provider"); let dispatcher = HttpClient::new().expect("failed to create request dispatcher"); let inner = Arc::new(ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }); *lock = Arc::downgrade(&inner); Client { inner } }
identifier_body
client.rs
use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; use crate::credential::{ Anonymous, CredentialsError, DefaultCredentialsProvider, ProvideAwsCredentials, StaticProvider, }; use crate::encoding::ContentEncoding; use crate::request::{DispatchSignedRequest, HttpClient, HttpDispatchError, HttpResponse}; use crate::signature::SignedRequest; use async_trait::async_trait; use lazy_static::lazy_static; use tokio::time; lazy_static! { static ref SHARED_CLIENT: Mutex<Weak<ClientInner<DefaultCredentialsProvider, HttpClient>>> = Mutex::new(Weak::new()); } /// Re-usable logic for all clients. #[derive(Clone)] pub struct Client { inner: Arc<dyn SignAndDispatch + Send + Sync>, } impl Client { /// Return the shared default client. pub fn shared() -> Self { let mut lock = SHARED_CLIENT.lock().unwrap(); if let Some(inner) = lock.upgrade() { return Client { inner }; } let credentials_provider = DefaultCredentialsProvider::new().expect("failed to create credentials provider"); let dispatcher = HttpClient::new().expect("failed to create request dispatcher"); let inner = Arc::new(ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }); *lock = Arc::downgrade(&inner); Client { inner } } /// Create a client from a credentials provider and request dispatcher. pub fn new_with<P, D>(credentials_provider: P, dispatcher: D) -> Self where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }; Client { inner: Arc::new(inner), } } /// Create a client from a request dispatcher without a credentials provider. The client will /// neither fetch any default credentials nor sign any requests. A non-signing client can be /// useful for calling APIs like `Sts::assume_role_with_web_identity` and /// `Sts::assume_role_with_saml` which do not require any request signing or when calling /// AWS compatible third party API endpoints which employ different authentication mechanisms. pub fn new_not_signing<D>(dispatcher: D) -> Self where D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner::<StaticProvider, D> { credentials_provider: None, dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }; Client { inner: Arc::new(inner), } } #[cfg(feature = "encoding")] /// Create a client with content encoding to compress payload before sending requests pub fn new_with_encoding<P, D>( credentials_provider: P, dispatcher: D, content_encoding: ContentEncoding, ) -> Self where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding, }; Client { inner: Arc::new(inner), } } /// Fetch credentials, sign the request and dispatch it. pub async fn sign_and_dispatch( &self, request: SignedRequest, ) -> Result<HttpResponse, SignAndDispatchError> { self.inner.sign_and_dispatch(request, None).await } } /// Error that occurs during `sign_and_dispatch` #[derive(Debug, PartialEq)] pub enum SignAndDispatchError { /// Error was due to bad credentials Credentials(CredentialsError), /// Error was due to http dispatch Dispatch(HttpDispatchError), } #[async_trait] trait SignAndDispatch { async fn sign_and_dispatch( &self, request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError>; } struct ClientInner<P, D> { credentials_provider: Option<Arc<P>>, dispatcher: Arc<D>, content_encoding: ContentEncoding, } impl<P, D> Clone for ClientInner<P, D> { fn clone(&self) -> Self { ClientInner { credentials_provider: self.credentials_provider.clone(), dispatcher: self.dispatcher.clone(), content_encoding: self.content_encoding.clone(), } } } async fn sign_and_dispatch<P, D>( client: ClientInner<P, D>, mut request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError> where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { client.content_encoding.encode(&mut request); if let Some(provider) = client.credentials_provider { let credentials = if let Some(to) = timeout
else { provider.credentials().await } .map_err(SignAndDispatchError::Credentials)?; if credentials.is_anonymous() { request.complement(); } else { request.sign(&credentials); } } else { request.complement(); } client .dispatcher .dispatch(request, timeout) .await .map_err(SignAndDispatchError::Dispatch) } #[async_trait] impl<P, D> SignAndDispatch for ClientInner<P, D> where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { async fn sign_and_dispatch( &self, request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError> { sign_and_dispatch(self.clone(), request, timeout).await } } #[test] fn client_is_send_and_sync() { fn is_send_and_sync<T: Send + Sync>() {} is_send_and_sync::<Client>(); }
{ time::timeout(to, provider.credentials()) .await .map_err(|_| CredentialsError { message: "Timeout getting credentials".to_owned(), }) .and_then(std::convert::identity) }
conditional_block
client.rs
use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; use crate::credential::{ Anonymous, CredentialsError, DefaultCredentialsProvider, ProvideAwsCredentials, StaticProvider, }; use crate::encoding::ContentEncoding; use crate::request::{DispatchSignedRequest, HttpClient, HttpDispatchError, HttpResponse}; use crate::signature::SignedRequest; use async_trait::async_trait; use lazy_static::lazy_static; use tokio::time; lazy_static! { static ref SHARED_CLIENT: Mutex<Weak<ClientInner<DefaultCredentialsProvider, HttpClient>>> = Mutex::new(Weak::new()); } /// Re-usable logic for all clients. #[derive(Clone)] pub struct Client { inner: Arc<dyn SignAndDispatch + Send + Sync>, } impl Client { /// Return the shared default client. pub fn shared() -> Self { let mut lock = SHARED_CLIENT.lock().unwrap(); if let Some(inner) = lock.upgrade() { return Client { inner }; } let credentials_provider = DefaultCredentialsProvider::new().expect("failed to create credentials provider"); let dispatcher = HttpClient::new().expect("failed to create request dispatcher"); let inner = Arc::new(ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }); *lock = Arc::downgrade(&inner); Client { inner } } /// Create a client from a credentials provider and request dispatcher. pub fn new_with<P, D>(credentials_provider: P, dispatcher: D) -> Self where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }; Client { inner: Arc::new(inner), } } /// Create a client from a request dispatcher without a credentials provider. The client will /// neither fetch any default credentials nor sign any requests. A non-signing client can be /// useful for calling APIs like `Sts::assume_role_with_web_identity` and /// `Sts::assume_role_with_saml` which do not require any request signing or when calling /// AWS compatible third party API endpoints which employ different authentication mechanisms. pub fn new_not_signing<D>(dispatcher: D) -> Self where D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner::<StaticProvider, D> { credentials_provider: None, dispatcher: Arc::new(dispatcher), content_encoding: Default::default(), }; Client { inner: Arc::new(inner), } } #[cfg(feature = "encoding")] /// Create a client with content encoding to compress payload before sending requests pub fn new_with_encoding<P, D>( credentials_provider: P, dispatcher: D, content_encoding: ContentEncoding, ) -> Self where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { let inner = ClientInner { credentials_provider: Some(Arc::new(credentials_provider)), dispatcher: Arc::new(dispatcher), content_encoding, }; Client { inner: Arc::new(inner), } } /// Fetch credentials, sign the request and dispatch it. pub async fn sign_and_dispatch( &self, request: SignedRequest, ) -> Result<HttpResponse, SignAndDispatchError> { self.inner.sign_and_dispatch(request, None).await } } /// Error that occurs during `sign_and_dispatch` #[derive(Debug, PartialEq)] pub enum
{ /// Error was due to bad credentials Credentials(CredentialsError), /// Error was due to http dispatch Dispatch(HttpDispatchError), } #[async_trait] trait SignAndDispatch { async fn sign_and_dispatch( &self, request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError>; } struct ClientInner<P, D> { credentials_provider: Option<Arc<P>>, dispatcher: Arc<D>, content_encoding: ContentEncoding, } impl<P, D> Clone for ClientInner<P, D> { fn clone(&self) -> Self { ClientInner { credentials_provider: self.credentials_provider.clone(), dispatcher: self.dispatcher.clone(), content_encoding: self.content_encoding.clone(), } } } async fn sign_and_dispatch<P, D>( client: ClientInner<P, D>, mut request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError> where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { client.content_encoding.encode(&mut request); if let Some(provider) = client.credentials_provider { let credentials = if let Some(to) = timeout { time::timeout(to, provider.credentials()) .await .map_err(|_| CredentialsError { message: "Timeout getting credentials".to_owned(), }) .and_then(std::convert::identity) } else { provider.credentials().await } .map_err(SignAndDispatchError::Credentials)?; if credentials.is_anonymous() { request.complement(); } else { request.sign(&credentials); } } else { request.complement(); } client .dispatcher .dispatch(request, timeout) .await .map_err(SignAndDispatchError::Dispatch) } #[async_trait] impl<P, D> SignAndDispatch for ClientInner<P, D> where P: ProvideAwsCredentials + Send + Sync +'static, D: DispatchSignedRequest + Send + Sync +'static, { async fn sign_and_dispatch( &self, request: SignedRequest, timeout: Option<Duration>, ) -> Result<HttpResponse, SignAndDispatchError> { sign_and_dispatch(self.clone(), request, timeout).await } } #[test] fn client_is_send_and_sync() { fn is_send_and_sync<T: Send + Sync>() {} is_send_and_sync::<Client>(); }
SignAndDispatchError
identifier_name
lint-missing-doc.rs
// Copyright 2013 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. // When denying at the crate level, be sure to not get random warnings from the // injected intrinsics by the compiler. #![deny(missing_docs)] #![allow(dead_code)] //! Some garbage docs for the crate here #![doc="More garbage"] type Typedef = String; pub type PubTypedef = String; //~ ERROR: missing documentation for a type alias struct Foo { a: isize, b: isize, } pub struct PubFoo { //~ ERROR: missing documentation for a struct pub a: isize, //~ ERROR: missing documentation for a struct field b: isize, } #[allow(missing_docs)] pub struct PubFoo2 { pub a: isize, pub c: isize, } mod module_no_dox {} pub mod pub_module_no_dox {} //~ ERROR: missing documentation for a module /// dox pub fn foo() {} pub fn foo2() {} //~ ERROR: missing documentation for a function fn foo3() {} #[allow(missing_docs)] pub fn foo4() {} /// dox pub trait A { /// dox fn foo(&self); /// dox fn foo_with_impl(&self) {} } #[allow(missing_docs)] trait B { fn foo(&self); fn foo_with_impl(&self) {} } pub trait C { //~ ERROR: missing documentation for a trait fn foo(&self); //~ ERROR: missing documentation for a type method fn foo_with_impl(&self) {} //~ ERROR: missing documentation for a method } #[allow(missing_docs)] pub trait D { fn dummy(&self) { } } /// dox pub trait E { type AssociatedType; //~ ERROR: missing documentation for an associated type type AssociatedTypeDef = Self; //~ ERROR: missing documentation for an associated type /// dox type DocumentedType; /// dox type DocumentedTypeDef = Self; /// dox fn dummy(&self) {} } impl Foo { pub fn foo() {} fn bar() {} } impl PubFoo { pub fn foo() {} //~ ERROR: missing documentation for a method /// dox pub fn foo1() {} fn foo2() {} #[allow(missing_docs)] pub fn foo3() {} } #[allow(missing_docs)] trait F { fn a(); fn b(&self); } // should need to redefine documentation for implementations of traits impl F for Foo { fn a() {} fn b(&self) {} } // It sure is nice if doc(hidden) implies allow(missing_docs), and that it // applies recursively #[doc(hidden)] mod a { pub fn baz() {} pub mod b { pub fn
() {} } } enum Baz { BazA { a: isize, b: isize }, BarB } pub enum PubBaz { //~ ERROR: missing documentation for an enum PubBazA { //~ ERROR: missing documentation for a variant a: isize, //~ ERROR: missing documentation for a struct field }, } /// dox pub enum PubBaz2 { /// dox PubBaz2A { /// dox a: isize, }, } #[allow(missing_docs)] pub enum PubBaz3 { PubBaz3A { b: isize }, } #[doc(hidden)] pub fn baz() {} mod internal_impl { /// dox pub fn documented() {} pub fn undocumented1() {} //~ ERROR: missing documentation for a function pub fn undocumented2() {} //~ ERROR: missing documentation for a function fn undocumented3() {} /// dox pub mod globbed { /// dox pub fn also_documented() {} pub fn also_undocumented1() {} //~ ERROR: missing documentation for a function fn also_undocumented2() {} } } /// dox pub mod public_interface { pub use internal_impl::documented as foo; pub use internal_impl::undocumented1 as bar; pub use internal_impl::{documented, undocumented2}; pub use internal_impl::globbed::*; } fn main() {}
baz
identifier_name
lint-missing-doc.rs
// Copyright 2013 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. // When denying at the crate level, be sure to not get random warnings from the // injected intrinsics by the compiler. #![deny(missing_docs)] #![allow(dead_code)] //! Some garbage docs for the crate here #![doc="More garbage"] type Typedef = String; pub type PubTypedef = String; //~ ERROR: missing documentation for a type alias struct Foo { a: isize, b: isize, } pub struct PubFoo { //~ ERROR: missing documentation for a struct pub a: isize, //~ ERROR: missing documentation for a struct field b: isize, } #[allow(missing_docs)] pub struct PubFoo2 { pub a: isize, pub c: isize, } mod module_no_dox {} pub mod pub_module_no_dox {} //~ ERROR: missing documentation for a module /// dox pub fn foo() {} pub fn foo2() {} //~ ERROR: missing documentation for a function fn foo3() {} #[allow(missing_docs)] pub fn foo4() {} /// dox pub trait A { /// dox fn foo(&self); /// dox fn foo_with_impl(&self) {} } #[allow(missing_docs)] trait B { fn foo(&self); fn foo_with_impl(&self) {} } pub trait C { //~ ERROR: missing documentation for a trait fn foo(&self); //~ ERROR: missing documentation for a type method fn foo_with_impl(&self) {} //~ ERROR: missing documentation for a method } #[allow(missing_docs)] pub trait D { fn dummy(&self) { } } /// dox pub trait E { type AssociatedType; //~ ERROR: missing documentation for an associated type type AssociatedTypeDef = Self; //~ ERROR: missing documentation for an associated type /// dox type DocumentedType; /// dox type DocumentedTypeDef = Self; /// dox fn dummy(&self) {} } impl Foo { pub fn foo() {} fn bar() {} } impl PubFoo { pub fn foo() {} //~ ERROR: missing documentation for a method /// dox pub fn foo1() {} fn foo2() {} #[allow(missing_docs)] pub fn foo3() {} } #[allow(missing_docs)] trait F { fn a(); fn b(&self); } // should need to redefine documentation for implementations of traits impl F for Foo { fn a() {} fn b(&self) {} } // It sure is nice if doc(hidden) implies allow(missing_docs), and that it // applies recursively #[doc(hidden)] mod a { pub fn baz() {} pub mod b { pub fn baz() {} } } enum Baz { BazA { a: isize, b: isize }, BarB } pub enum PubBaz { //~ ERROR: missing documentation for an enum PubBazA { //~ ERROR: missing documentation for a variant a: isize, //~ ERROR: missing documentation for a struct field }, } /// dox pub enum PubBaz2 { /// dox PubBaz2A { /// dox
#[allow(missing_docs)] pub enum PubBaz3 { PubBaz3A { b: isize }, } #[doc(hidden)] pub fn baz() {} mod internal_impl { /// dox pub fn documented() {} pub fn undocumented1() {} //~ ERROR: missing documentation for a function pub fn undocumented2() {} //~ ERROR: missing documentation for a function fn undocumented3() {} /// dox pub mod globbed { /// dox pub fn also_documented() {} pub fn also_undocumented1() {} //~ ERROR: missing documentation for a function fn also_undocumented2() {} } } /// dox pub mod public_interface { pub use internal_impl::documented as foo; pub use internal_impl::undocumented1 as bar; pub use internal_impl::{documented, undocumented2}; pub use internal_impl::globbed::*; } fn main() {}
a: isize, }, }
random_line_split
lint-missing-doc.rs
// Copyright 2013 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. // When denying at the crate level, be sure to not get random warnings from the // injected intrinsics by the compiler. #![deny(missing_docs)] #![allow(dead_code)] //! Some garbage docs for the crate here #![doc="More garbage"] type Typedef = String; pub type PubTypedef = String; //~ ERROR: missing documentation for a type alias struct Foo { a: isize, b: isize, } pub struct PubFoo { //~ ERROR: missing documentation for a struct pub a: isize, //~ ERROR: missing documentation for a struct field b: isize, } #[allow(missing_docs)] pub struct PubFoo2 { pub a: isize, pub c: isize, } mod module_no_dox {} pub mod pub_module_no_dox {} //~ ERROR: missing documentation for a module /// dox pub fn foo() {} pub fn foo2() {} //~ ERROR: missing documentation for a function fn foo3() {} #[allow(missing_docs)] pub fn foo4() {} /// dox pub trait A { /// dox fn foo(&self); /// dox fn foo_with_impl(&self) {} } #[allow(missing_docs)] trait B { fn foo(&self); fn foo_with_impl(&self) {} } pub trait C { //~ ERROR: missing documentation for a trait fn foo(&self); //~ ERROR: missing documentation for a type method fn foo_with_impl(&self) {} //~ ERROR: missing documentation for a method } #[allow(missing_docs)] pub trait D { fn dummy(&self) { } } /// dox pub trait E { type AssociatedType; //~ ERROR: missing documentation for an associated type type AssociatedTypeDef = Self; //~ ERROR: missing documentation for an associated type /// dox type DocumentedType; /// dox type DocumentedTypeDef = Self; /// dox fn dummy(&self) {} } impl Foo { pub fn foo() {} fn bar() {} } impl PubFoo { pub fn foo() {} //~ ERROR: missing documentation for a method /// dox pub fn foo1() {} fn foo2()
#[allow(missing_docs)] pub fn foo3() {} } #[allow(missing_docs)] trait F { fn a(); fn b(&self); } // should need to redefine documentation for implementations of traits impl F for Foo { fn a() {} fn b(&self) {} } // It sure is nice if doc(hidden) implies allow(missing_docs), and that it // applies recursively #[doc(hidden)] mod a { pub fn baz() {} pub mod b { pub fn baz() {} } } enum Baz { BazA { a: isize, b: isize }, BarB } pub enum PubBaz { //~ ERROR: missing documentation for an enum PubBazA { //~ ERROR: missing documentation for a variant a: isize, //~ ERROR: missing documentation for a struct field }, } /// dox pub enum PubBaz2 { /// dox PubBaz2A { /// dox a: isize, }, } #[allow(missing_docs)] pub enum PubBaz3 { PubBaz3A { b: isize }, } #[doc(hidden)] pub fn baz() {} mod internal_impl { /// dox pub fn documented() {} pub fn undocumented1() {} //~ ERROR: missing documentation for a function pub fn undocumented2() {} //~ ERROR: missing documentation for a function fn undocumented3() {} /// dox pub mod globbed { /// dox pub fn also_documented() {} pub fn also_undocumented1() {} //~ ERROR: missing documentation for a function fn also_undocumented2() {} } } /// dox pub mod public_interface { pub use internal_impl::documented as foo; pub use internal_impl::undocumented1 as bar; pub use internal_impl::{documented, undocumented2}; pub use internal_impl::globbed::*; } fn main() {}
{}
identifier_body
noop.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::io; use std::marker::Unpin; use futures_executor::block_on; use futures_io::AsyncRead; use futures_util::io::{copy, AllowStdIo}; use super::ExternalStorage; /// A storage saves files into void. /// It is mainly for test use. #[derive(Clone, Default)] pub struct NoopStorage {} impl NoopStorage {} fn url_for() -> url::Url { url::Url::parse("noop:///").unwrap() } const STORAGE_NAME: &str = "noop"; impl ExternalStorage for NoopStorage { fn name(&self) -> &'static str { STORAGE_NAME } fn url(&self) -> io::Result<url::Url> { Ok(url_for()) } fn write( &self, _name: &str, reader: Box<dyn AsyncRead + Send + Unpin>, _content_length: u64, ) -> io::Result<()>
fn read(&self, _name: &str) -> Box<dyn AsyncRead + Unpin> { Box::new(AllowStdIo::new(io::empty())) } } #[cfg(test)] mod tests { use super::*; use futures_util::io::AsyncReadExt; #[test] fn test_noop_storage() { let noop = NoopStorage::default(); // Test save_file let magic_contents: &[u8] = b"5678"; noop.write( "a.log", Box::new(magic_contents), magic_contents.len() as u64, ) .unwrap(); let mut reader = noop.read("a.log"); let mut buf = vec![]; block_on(reader.read_to_end(&mut buf)).unwrap(); assert!(buf.is_empty()); } #[test] fn test_url_of_backend() { assert_eq!(url_for().to_string(), "noop:///"); } }
{ // we must still process the entire reader to run the SHA-256 hasher. block_on(copy(reader, &mut AllowStdIo::new(io::sink()))).map(drop) }
identifier_body
noop.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::io; use std::marker::Unpin; use futures_executor::block_on; use futures_io::AsyncRead; use futures_util::io::{copy, AllowStdIo}; use super::ExternalStorage; /// A storage saves files into void. /// It is mainly for test use. #[derive(Clone, Default)] pub struct NoopStorage {} impl NoopStorage {} fn url_for() -> url::Url { url::Url::parse("noop:///").unwrap() } const STORAGE_NAME: &str = "noop"; impl ExternalStorage for NoopStorage { fn name(&self) -> &'static str { STORAGE_NAME } fn url(&self) -> io::Result<url::Url> { Ok(url_for()) } fn write( &self, _name: &str, reader: Box<dyn AsyncRead + Send + Unpin>, _content_length: u64, ) -> io::Result<()> { // we must still process the entire reader to run the SHA-256 hasher. block_on(copy(reader, &mut AllowStdIo::new(io::sink()))).map(drop) } fn read(&self, _name: &str) -> Box<dyn AsyncRead + Unpin> { Box::new(AllowStdIo::new(io::empty())) } } #[cfg(test)] mod tests { use super::*; use futures_util::io::AsyncReadExt; #[test] fn test_noop_storage() { let noop = NoopStorage::default(); // Test save_file let magic_contents: &[u8] = b"5678"; noop.write( "a.log", Box::new(magic_contents), magic_contents.len() as u64, ) .unwrap(); let mut reader = noop.read("a.log"); let mut buf = vec![]; block_on(reader.read_to_end(&mut buf)).unwrap(); assert!(buf.is_empty());
} #[test] fn test_url_of_backend() { assert_eq!(url_for().to_string(), "noop:///"); } }
random_line_split
noop.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::io; use std::marker::Unpin; use futures_executor::block_on; use futures_io::AsyncRead; use futures_util::io::{copy, AllowStdIo}; use super::ExternalStorage; /// A storage saves files into void. /// It is mainly for test use. #[derive(Clone, Default)] pub struct NoopStorage {} impl NoopStorage {} fn url_for() -> url::Url { url::Url::parse("noop:///").unwrap() } const STORAGE_NAME: &str = "noop"; impl ExternalStorage for NoopStorage { fn name(&self) -> &'static str { STORAGE_NAME } fn url(&self) -> io::Result<url::Url> { Ok(url_for()) } fn write( &self, _name: &str, reader: Box<dyn AsyncRead + Send + Unpin>, _content_length: u64, ) -> io::Result<()> { // we must still process the entire reader to run the SHA-256 hasher. block_on(copy(reader, &mut AllowStdIo::new(io::sink()))).map(drop) } fn read(&self, _name: &str) -> Box<dyn AsyncRead + Unpin> { Box::new(AllowStdIo::new(io::empty())) } } #[cfg(test)] mod tests { use super::*; use futures_util::io::AsyncReadExt; #[test] fn test_noop_storage() { let noop = NoopStorage::default(); // Test save_file let magic_contents: &[u8] = b"5678"; noop.write( "a.log", Box::new(magic_contents), magic_contents.len() as u64, ) .unwrap(); let mut reader = noop.read("a.log"); let mut buf = vec![]; block_on(reader.read_to_end(&mut buf)).unwrap(); assert!(buf.is_empty()); } #[test] fn
() { assert_eq!(url_for().to_string(), "noop:///"); } }
test_url_of_backend
identifier_name
toggle-trait-fn.rs
#![crate_name = "foo"] // Trait methods with documentation should be wrapped in a <details> toggle with an appropriate // summary. Trait methods with no documentation should not be wrapped. // // @has foo/trait.Foo.html // @has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'is_documented()' // @!has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'not_documented()' // @has - '//details[@class="rustdoc-toggle"]//*[@class="docblock"]' 'is_documented is documented' // @has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'is_documented_optional()' // @!has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'not_documented_optional()' // @has - '//details[@class="rustdoc-toggle"]//*[@class="docblock"]' 'is_documented_optional is documented' pub trait Foo { fn not_documented(); /// is_documented is documented fn is_documented(); fn not_documented_optional()
/// is_documented_optional is documented fn is_documented_optional() {} }
{}
identifier_body
toggle-trait-fn.rs
#![crate_name = "foo"] // Trait methods with documentation should be wrapped in a <details> toggle with an appropriate // summary. Trait methods with no documentation should not be wrapped. // // @has foo/trait.Foo.html // @has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'is_documented()' // @!has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'not_documented()' // @has - '//details[@class="rustdoc-toggle"]//*[@class="docblock"]' 'is_documented is documented' // @has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'is_documented_optional()' // @!has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'not_documented_optional()'
// @has - '//details[@class="rustdoc-toggle"]//*[@class="docblock"]' 'is_documented_optional is documented' pub trait Foo { fn not_documented(); /// is_documented is documented fn is_documented(); fn not_documented_optional() {} /// is_documented_optional is documented fn is_documented_optional() {} }
random_line_split
toggle-trait-fn.rs
#![crate_name = "foo"] // Trait methods with documentation should be wrapped in a <details> toggle with an appropriate // summary. Trait methods with no documentation should not be wrapped. // // @has foo/trait.Foo.html // @has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'is_documented()' // @!has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'not_documented()' // @has - '//details[@class="rustdoc-toggle"]//*[@class="docblock"]' 'is_documented is documented' // @has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'is_documented_optional()' // @!has - '//details[@class="rustdoc-toggle"]//summary//h4[@class="code-header"]' 'not_documented_optional()' // @has - '//details[@class="rustdoc-toggle"]//*[@class="docblock"]' 'is_documented_optional is documented' pub trait Foo { fn not_documented(); /// is_documented is documented fn is_documented(); fn not_documented_optional() {} /// is_documented_optional is documented fn
() {} }
is_documented_optional
identifier_name
box_blur.rs
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use librsvg::{ surface_utils::shared_surface::{ AlphaOnly, Horizontal, NotAlphaOnly, SharedImageSurface, SurfaceType, Vertical, }, IRect, }; const SURFACE_SIDE: i32 = 512; const BOUNDS: IRect = IRect { x0: 64, y0: 64, x1: 64 + 64, y1: 64 + 64, }; fn
(c: &mut Criterion) { let mut group = c.benchmark_group("box_blur 9"); for input in [(false, false), (false, true), (true, false), (true, true)].iter() { group.bench_with_input( BenchmarkId::from_parameter(format!("{:?}", input)), &input, |b, &(vertical, alpha_only)| { let surface_type = if *alpha_only { SurfaceType::AlphaOnly } else { SurfaceType::SRgb }; let input_surface = SharedImageSurface::empty(SURFACE_SIDE, SURFACE_SIDE, surface_type).unwrap(); let mut output_surface = cairo::ImageSurface::create(cairo::Format::ARgb32, SURFACE_SIDE, SURFACE_SIDE) .unwrap(); const KERNEL_SIZE: usize = 9; let f = match (vertical, alpha_only) { (true, true) => SharedImageSurface::box_blur_loop::<Vertical, AlphaOnly>, (true, false) => SharedImageSurface::box_blur_loop::<Vertical, NotAlphaOnly>, (false, true) => SharedImageSurface::box_blur_loop::<Horizontal, AlphaOnly>, (false, false) => SharedImageSurface::box_blur_loop::<Horizontal, NotAlphaOnly>, }; b.iter(|| { f( &input_surface, &mut output_surface, BOUNDS, KERNEL_SIZE, KERNEL_SIZE / 2, ) }) }, ); } } criterion_group!(benches, bench_box_blur); criterion_main!(benches);
bench_box_blur
identifier_name
box_blur.rs
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use librsvg::{ surface_utils::shared_surface::{ AlphaOnly, Horizontal, NotAlphaOnly, SharedImageSurface, SurfaceType, Vertical, }, IRect, }; const SURFACE_SIDE: i32 = 512; const BOUNDS: IRect = IRect { x0: 64, y0: 64, x1: 64 + 64, y1: 64 + 64, }; fn bench_box_blur(c: &mut Criterion)
let f = match (vertical, alpha_only) { (true, true) => SharedImageSurface::box_blur_loop::<Vertical, AlphaOnly>, (true, false) => SharedImageSurface::box_blur_loop::<Vertical, NotAlphaOnly>, (false, true) => SharedImageSurface::box_blur_loop::<Horizontal, AlphaOnly>, (false, false) => SharedImageSurface::box_blur_loop::<Horizontal, NotAlphaOnly>, }; b.iter(|| { f( &input_surface, &mut output_surface, BOUNDS, KERNEL_SIZE, KERNEL_SIZE / 2, ) }) }, ); } } criterion_group!(benches, bench_box_blur); criterion_main!(benches);
{ let mut group = c.benchmark_group("box_blur 9"); for input in [(false, false), (false, true), (true, false), (true, true)].iter() { group.bench_with_input( BenchmarkId::from_parameter(format!("{:?}", input)), &input, |b, &(vertical, alpha_only)| { let surface_type = if *alpha_only { SurfaceType::AlphaOnly } else { SurfaceType::SRgb }; let input_surface = SharedImageSurface::empty(SURFACE_SIDE, SURFACE_SIDE, surface_type).unwrap(); let mut output_surface = cairo::ImageSurface::create(cairo::Format::ARgb32, SURFACE_SIDE, SURFACE_SIDE) .unwrap(); const KERNEL_SIZE: usize = 9;
identifier_body
box_blur.rs
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use librsvg::{ surface_utils::shared_surface::{ AlphaOnly, Horizontal, NotAlphaOnly, SharedImageSurface, SurfaceType, Vertical, }, IRect, }; const SURFACE_SIDE: i32 = 512; const BOUNDS: IRect = IRect { x0: 64, y0: 64, x1: 64 + 64, y1: 64 + 64, }; fn bench_box_blur(c: &mut Criterion) { let mut group = c.benchmark_group("box_blur 9"); for input in [(false, false), (false, true), (true, false), (true, true)].iter() { group.bench_with_input( BenchmarkId::from_parameter(format!("{:?}", input)), &input, |b, &(vertical, alpha_only)| { let surface_type = if *alpha_only { SurfaceType::AlphaOnly } else { SurfaceType::SRgb }; let input_surface = SharedImageSurface::empty(SURFACE_SIDE, SURFACE_SIDE, surface_type).unwrap(); let mut output_surface = cairo::ImageSurface::create(cairo::Format::ARgb32, SURFACE_SIDE, SURFACE_SIDE) .unwrap(); const KERNEL_SIZE: usize = 9; let f = match (vertical, alpha_only) { (true, true) => SharedImageSurface::box_blur_loop::<Vertical, AlphaOnly>, (true, false) => SharedImageSurface::box_blur_loop::<Vertical, NotAlphaOnly>, (false, true) => SharedImageSurface::box_blur_loop::<Horizontal, AlphaOnly>, (false, false) => SharedImageSurface::box_blur_loop::<Horizontal, NotAlphaOnly>, }; b.iter(|| { f( &input_surface, &mut output_surface, BOUNDS, KERNEL_SIZE,
KERNEL_SIZE / 2, ) }) }, ); } } criterion_group!(benches, bench_box_blur); criterion_main!(benches);
random_line_split
csskeyframerule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use parking_lot::RwLock; use std::sync::Arc; use style::keyframes::Keyframe; use style_traits::ToCss; #[dom_struct] pub struct
{ cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] keyframerule: Arc<RwLock<Keyframe>>, } impl CSSKeyframeRule { fn new_inherited(parent: Option<&CSSStyleSheet>, keyframerule: Arc<RwLock<Keyframe>>) -> CSSKeyframeRule { CSSKeyframeRule { cssrule: CSSRule::new_inherited(parent), keyframerule: keyframerule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent: Option<&CSSStyleSheet>, keyframerule: Arc<RwLock<Keyframe>>) -> Root<CSSKeyframeRule> { reflect_dom_object(box CSSKeyframeRule::new_inherited(parent, keyframerule), window, CSSKeyframeRuleBinding::Wrap) } } impl SpecificCSSRule for CSSKeyframeRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::KEYFRAME_RULE } fn get_css(&self) -> DOMString { self.keyframerule.read().to_css_string().into() } }
CSSKeyframeRule
identifier_name
csskeyframerule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use parking_lot::RwLock; use std::sync::Arc; use style::keyframes::Keyframe; use style_traits::ToCss; #[dom_struct] pub struct CSSKeyframeRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] keyframerule: Arc<RwLock<Keyframe>>, } impl CSSKeyframeRule { fn new_inherited(parent: Option<&CSSStyleSheet>, keyframerule: Arc<RwLock<Keyframe>>) -> CSSKeyframeRule { CSSKeyframeRule { cssrule: CSSRule::new_inherited(parent), keyframerule: keyframerule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent: Option<&CSSStyleSheet>, keyframerule: Arc<RwLock<Keyframe>>) -> Root<CSSKeyframeRule> { reflect_dom_object(box CSSKeyframeRule::new_inherited(parent, keyframerule), window, CSSKeyframeRuleBinding::Wrap) } } impl SpecificCSSRule for CSSKeyframeRule { fn ty(&self) -> u16
fn get_css(&self) -> DOMString { self.keyframerule.read().to_css_string().into() } }
{ use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::KEYFRAME_RULE }
identifier_body
csskeyframerule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use parking_lot::RwLock; use std::sync::Arc; use style::keyframes::Keyframe; use style_traits::ToCss; #[dom_struct] pub struct CSSKeyframeRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] keyframerule: Arc<RwLock<Keyframe>>,
} impl CSSKeyframeRule { fn new_inherited(parent: Option<&CSSStyleSheet>, keyframerule: Arc<RwLock<Keyframe>>) -> CSSKeyframeRule { CSSKeyframeRule { cssrule: CSSRule::new_inherited(parent), keyframerule: keyframerule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent: Option<&CSSStyleSheet>, keyframerule: Arc<RwLock<Keyframe>>) -> Root<CSSKeyframeRule> { reflect_dom_object(box CSSKeyframeRule::new_inherited(parent, keyframerule), window, CSSKeyframeRuleBinding::Wrap) } } impl SpecificCSSRule for CSSKeyframeRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::KEYFRAME_RULE } fn get_css(&self) -> DOMString { self.keyframerule.read().to_css_string().into() } }
random_line_split
mod.rs
use std::sync::atomic::AtomicBool; use std::ptr; use std::ffi::CString; use std::collections::VecDeque; use std::sync::mpsc::Receiver; use libc; use {CreationError, Event, MouseCursor}; use BuilderAttribs; pub use self::headless::HeadlessContext; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; use user32; use kernel32; use gdi32; mod callback; mod event; mod gl; mod headless; mod init; mod make_current_guard; mod monitor; /// The Win32 implementation of the main `Window` object. pub struct Window { /// Main handle for the window. window: WindowWrapper, /// OpenGL context. context: ContextWrapper, /// Binded to `opengl32.dll`. /// /// `wglGetProcAddress` returns null for GL 1.1 functions because they are /// already defined by the system. This module contains them. gl_library: winapi::HMODULE, /// Receiver for the events dispatched by the window callback. events_receiver: Receiver<Event>, /// True if a `Closed` event has been received. is_closed: AtomicBool, } unsafe impl Send for Window {} unsafe impl Sync for Window {} /// A simple wrapper that destroys the context when it is destroyed. // FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[doc(hidden)] pub struct ContextWrapper(pub winapi::HGLRC); impl Drop for ContextWrapper { fn drop(&mut self) { unsafe { gl::wgl::DeleteContext(self.0 as *const libc::c_void); } } } /// A simple wrapper that destroys the window when it is destroyed. // FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[doc(hidden)] pub struct WindowWrapper(pub winapi::HWND, pub winapi::HDC); impl Drop for WindowWrapper { fn drop(&mut self) { unsafe { user32::DestroyWindow(self.0); } } } #[derive(Clone)] pub struct WindowProxy; impl WindowProxy { pub fn wakeup_event_loop(&self) { unimplemented!() } } impl Window { /// See the docs in the crate root file. pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { let (builder, sharing) = builder.extract_non_static(); let sharing = sharing.map(|w| init::ContextHack(w.context.0)); init::new_window(builder, sharing) } /// See the docs in the crate root file. pub fn is_closed(&self) -> bool { use std::sync::atomic::Ordering::Relaxed; self.is_closed.load(Relaxed) } /// See the docs in the crate root file. /// /// Calls SetWindowText on the HWND. pub fn set_title(&self, text: &str) { unsafe { user32::SetWindowTextW(self.window.0, text.utf16_units().chain(Some(0).into_iter()) .collect::<Vec<u16>>().as_ptr() as winapi::LPCWSTR); } } pub fn show(&self) { unsafe { user32::ShowWindow(self.window.0, winapi::SW_SHOW); } } pub fn hide(&self) { unsafe { user32::ShowWindow(self.window.0, winapi::SW_HIDE); } } /// See the docs in the crate root file. pub fn get_position(&self) -> Option<(i32, i32)> { use std::mem; let mut placement: winapi::WINDOWPLACEMENT = unsafe { mem::zeroed() }; placement.length = mem::size_of::<winapi::WINDOWPLACEMENT>() as winapi::UINT; if unsafe { user32::GetWindowPlacement(self.window.0, &mut placement) } == 0 { return None } let ref rect = placement.rcNormalPosition; Some((rect.left as i32, rect.top as i32)) } /// See the docs in the crate root file. pub fn set_position(&self, x: i32, y: i32) { use libc; unsafe { user32::SetWindowPos(self.window.0, ptr::null_mut(), x as libc::c_int, y as libc::c_int, 0, 0, winapi::SWP_NOZORDER | winapi::SWP_NOSIZE); user32::UpdateWindow(self.window.0); } } /// See the docs in the crate root file. pub fn get_inner_size(&self) -> Option<(u32, u32)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { user32::GetClientRect(self.window.0, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32 )) } /// See the docs in the crate root file. pub fn get_outer_size(&self) -> Option<(u32, u32)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { user32::GetWindowRect(self.window.0, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32 )) } /// See the docs in the crate root file. pub fn set_inner_size(&self, x: u32, y: u32) { use libc; unsafe { user32::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, x as libc::c_int, y as libc::c_int, winapi::SWP_NOZORDER | winapi::SWP_NOREPOSITION); user32::UpdateWindow(self.window.0); } } pub fn create_window_proxy(&self) -> WindowProxy { WindowProxy } /// See the docs in the crate root file. pub fn poll_events(&self) -> PollEventsIterator { PollEventsIterator { window: self, } } /// See the docs in the crate root file. pub fn wait_events(&self) -> WaitEventsIterator { WaitEventsIterator { window: self, } } /// See the docs in the crate root file. pub unsafe fn make_current(&self) { // TODO: check return value gl::wgl::MakeCurrent(self.window.1 as *const libc::c_void, self.context.0 as *const libc::c_void); } /// See the docs in the crate root file. pub fn is_current(&self) -> bool { unsafe { gl::wgl::GetCurrentContext() == self.context.0 as *const libc::c_void } } /// See the docs in the crate root file. pub fn get_proc_address(&self, addr: &str) -> *const () { let addr = CString::new(addr.as_bytes()).unwrap(); let addr = addr.as_ptr(); unsafe { let p = gl::wgl::GetProcAddress(addr) as *const (); if!p.is_null() { return p; } kernel32::GetProcAddress(self.gl_library, addr) as *const () } } /// See the docs in the crate root file. pub fn swap_buffers(&self) { unsafe { gdi32::SwapBuffers(self.window.1); } } pub fn platform_display(&self) -> *mut libc::c_void { unimplemented!() } pub fn platform_window(&self) -> *mut libc::c_void { self.window.0 as *mut libc::c_void } /// See the docs in the crate root file. pub fn get_api(&self) -> ::Api { ::Api::OpenGl } pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) { } pub fn set_cursor(&self, _cursor: MouseCursor) { unimplemented!() } pub fn hidpi_factor(&self) -> f32 { 1.0 } pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { let mut point = winapi::POINT { x: x, y: y, }; unsafe { if user32::ClientToScreen(self.window.0, &mut point) == 0 { return Err(()); } if user32::SetCursorPos(point.x, point.y) == 0 { return Err(()); } } Ok(()) } } pub struct PollEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for PollEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { use events::Event::Closed; match self.window.events_receiver.try_recv() { Ok(Closed) => { use std::sync::atomic::Ordering::Relaxed; self.window.is_closed.store(true, Relaxed); Some(Closed) }, Ok(ev) => Some(ev), Err(_) => None } } } pub struct WaitEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for WaitEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { use events::Event::Closed; match self.window.events_receiver.recv() { Ok(Closed) =>
, Ok(ev) => Some(ev), Err(_) => None } } } #[unsafe_destructor] impl Drop for Window { fn drop(&mut self) { unsafe { // we don't call MakeCurrent(0, 0) because we are not sure that the context // is still the current one user32::PostMessageW(self.window.0, winapi::WM_DESTROY, 0, 0); } } }
{ use std::sync::atomic::Ordering::Relaxed; self.window.is_closed.store(true, Relaxed); Some(Closed) }
conditional_block
mod.rs
use std::sync::atomic::AtomicBool; use std::ptr; use std::ffi::CString; use std::collections::VecDeque; use std::sync::mpsc::Receiver; use libc; use {CreationError, Event, MouseCursor}; use BuilderAttribs; pub use self::headless::HeadlessContext; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; use user32; use kernel32; use gdi32; mod callback; mod event; mod gl; mod headless; mod init; mod make_current_guard; mod monitor; /// The Win32 implementation of the main `Window` object. pub struct Window { /// Main handle for the window. window: WindowWrapper, /// OpenGL context. context: ContextWrapper, /// Binded to `opengl32.dll`. /// /// `wglGetProcAddress` returns null for GL 1.1 functions because they are /// already defined by the system. This module contains them. gl_library: winapi::HMODULE, /// Receiver for the events dispatched by the window callback. events_receiver: Receiver<Event>, /// True if a `Closed` event has been received. is_closed: AtomicBool, } unsafe impl Send for Window {} unsafe impl Sync for Window {} /// A simple wrapper that destroys the context when it is destroyed. // FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[doc(hidden)] pub struct ContextWrapper(pub winapi::HGLRC); impl Drop for ContextWrapper { fn drop(&mut self) { unsafe { gl::wgl::DeleteContext(self.0 as *const libc::c_void); } } } /// A simple wrapper that destroys the window when it is destroyed. // FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[doc(hidden)] pub struct WindowWrapper(pub winapi::HWND, pub winapi::HDC); impl Drop for WindowWrapper { fn drop(&mut self) { unsafe { user32::DestroyWindow(self.0); } } } #[derive(Clone)] pub struct WindowProxy; impl WindowProxy { pub fn wakeup_event_loop(&self) { unimplemented!() } } impl Window { /// See the docs in the crate root file. pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { let (builder, sharing) = builder.extract_non_static(); let sharing = sharing.map(|w| init::ContextHack(w.context.0)); init::new_window(builder, sharing) } /// See the docs in the crate root file. pub fn is_closed(&self) -> bool { use std::sync::atomic::Ordering::Relaxed; self.is_closed.load(Relaxed) } /// See the docs in the crate root file. /// /// Calls SetWindowText on the HWND. pub fn set_title(&self, text: &str) { unsafe { user32::SetWindowTextW(self.window.0, text.utf16_units().chain(Some(0).into_iter()) .collect::<Vec<u16>>().as_ptr() as winapi::LPCWSTR); } } pub fn show(&self) { unsafe { user32::ShowWindow(self.window.0, winapi::SW_SHOW); } } pub fn hide(&self) { unsafe { user32::ShowWindow(self.window.0, winapi::SW_HIDE); } } /// See the docs in the crate root file. pub fn get_position(&self) -> Option<(i32, i32)> { use std::mem; let mut placement: winapi::WINDOWPLACEMENT = unsafe { mem::zeroed() }; placement.length = mem::size_of::<winapi::WINDOWPLACEMENT>() as winapi::UINT; if unsafe { user32::GetWindowPlacement(self.window.0, &mut placement) } == 0 { return None } let ref rect = placement.rcNormalPosition; Some((rect.left as i32, rect.top as i32)) } /// See the docs in the crate root file. pub fn set_position(&self, x: i32, y: i32) { use libc; unsafe { user32::SetWindowPos(self.window.0, ptr::null_mut(), x as libc::c_int, y as libc::c_int, 0, 0, winapi::SWP_NOZORDER | winapi::SWP_NOSIZE); user32::UpdateWindow(self.window.0); } } /// See the docs in the crate root file. pub fn get_inner_size(&self) -> Option<(u32, u32)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { user32::GetClientRect(self.window.0, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32 )) } /// See the docs in the crate root file. pub fn get_outer_size(&self) -> Option<(u32, u32)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { user32::GetWindowRect(self.window.0, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32 )) } /// See the docs in the crate root file. pub fn set_inner_size(&self, x: u32, y: u32) { use libc; unsafe { user32::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, x as libc::c_int, y as libc::c_int, winapi::SWP_NOZORDER | winapi::SWP_NOREPOSITION); user32::UpdateWindow(self.window.0); } } pub fn create_window_proxy(&self) -> WindowProxy { WindowProxy } /// See the docs in the crate root file. pub fn poll_events(&self) -> PollEventsIterator { PollEventsIterator { window: self, } } /// See the docs in the crate root file. pub fn wait_events(&self) -> WaitEventsIterator { WaitEventsIterator { window: self, } } /// See the docs in the crate root file. pub unsafe fn make_current(&self) { // TODO: check return value gl::wgl::MakeCurrent(self.window.1 as *const libc::c_void, self.context.0 as *const libc::c_void); } /// See the docs in the crate root file. pub fn is_current(&self) -> bool { unsafe { gl::wgl::GetCurrentContext() == self.context.0 as *const libc::c_void } } /// See the docs in the crate root file. pub fn get_proc_address(&self, addr: &str) -> *const () { let addr = CString::new(addr.as_bytes()).unwrap(); let addr = addr.as_ptr(); unsafe { let p = gl::wgl::GetProcAddress(addr) as *const (); if!p.is_null() { return p; } kernel32::GetProcAddress(self.gl_library, addr) as *const () } } /// See the docs in the crate root file. pub fn swap_buffers(&self) { unsafe { gdi32::SwapBuffers(self.window.1); } } pub fn platform_display(&self) -> *mut libc::c_void { unimplemented!() } pub fn platform_window(&self) -> *mut libc::c_void { self.window.0 as *mut libc::c_void } /// See the docs in the crate root file. pub fn get_api(&self) -> ::Api { ::Api::OpenGl } pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) { } pub fn set_cursor(&self, _cursor: MouseCursor) { unimplemented!() } pub fn hidpi_factor(&self) -> f32 { 1.0 } pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { let mut point = winapi::POINT { x: x, y: y, }; unsafe { if user32::ClientToScreen(self.window.0, &mut point) == 0 { return Err(()); } if user32::SetCursorPos(point.x, point.y) == 0 { return Err(()); } } Ok(()) } } pub struct PollEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for PollEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { use events::Event::Closed; match self.window.events_receiver.try_recv() { Ok(Closed) => { use std::sync::atomic::Ordering::Relaxed; self.window.is_closed.store(true, Relaxed); Some(Closed) }, Ok(ev) => Some(ev), Err(_) => None } } } pub struct WaitEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for WaitEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event>
} #[unsafe_destructor] impl Drop for Window { fn drop(&mut self) { unsafe { // we don't call MakeCurrent(0, 0) because we are not sure that the context // is still the current one user32::PostMessageW(self.window.0, winapi::WM_DESTROY, 0, 0); } } }
{ use events::Event::Closed; match self.window.events_receiver.recv() { Ok(Closed) => { use std::sync::atomic::Ordering::Relaxed; self.window.is_closed.store(true, Relaxed); Some(Closed) }, Ok(ev) => Some(ev), Err(_) => None } }
identifier_body
mod.rs
use std::sync::atomic::AtomicBool; use std::ptr; use std::ffi::CString; use std::collections::VecDeque; use std::sync::mpsc::Receiver; use libc; use {CreationError, Event, MouseCursor}; use BuilderAttribs; pub use self::headless::HeadlessContext; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; use user32; use kernel32; use gdi32; mod callback; mod event; mod gl; mod headless; mod init; mod make_current_guard; mod monitor; /// The Win32 implementation of the main `Window` object. pub struct Window { /// Main handle for the window. window: WindowWrapper, /// OpenGL context. context: ContextWrapper, /// Binded to `opengl32.dll`. /// /// `wglGetProcAddress` returns null for GL 1.1 functions because they are /// already defined by the system. This module contains them. gl_library: winapi::HMODULE, /// Receiver for the events dispatched by the window callback. events_receiver: Receiver<Event>, /// True if a `Closed` event has been received. is_closed: AtomicBool, } unsafe impl Send for Window {} unsafe impl Sync for Window {} /// A simple wrapper that destroys the context when it is destroyed. // FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[doc(hidden)] pub struct ContextWrapper(pub winapi::HGLRC); impl Drop for ContextWrapper { fn drop(&mut self) { unsafe { gl::wgl::DeleteContext(self.0 as *const libc::c_void); } } } /// A simple wrapper that destroys the window when it is destroyed. // FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[doc(hidden)] pub struct WindowWrapper(pub winapi::HWND, pub winapi::HDC); impl Drop for WindowWrapper { fn drop(&mut self) { unsafe { user32::DestroyWindow(self.0); } } } #[derive(Clone)] pub struct WindowProxy; impl WindowProxy { pub fn wakeup_event_loop(&self) { unimplemented!() } } impl Window { /// See the docs in the crate root file. pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { let (builder, sharing) = builder.extract_non_static(); let sharing = sharing.map(|w| init::ContextHack(w.context.0)); init::new_window(builder, sharing) } /// See the docs in the crate root file. pub fn is_closed(&self) -> bool { use std::sync::atomic::Ordering::Relaxed; self.is_closed.load(Relaxed) } /// See the docs in the crate root file. /// /// Calls SetWindowText on the HWND. pub fn set_title(&self, text: &str) { unsafe { user32::SetWindowTextW(self.window.0, text.utf16_units().chain(Some(0).into_iter()) .collect::<Vec<u16>>().as_ptr() as winapi::LPCWSTR); } } pub fn show(&self) { unsafe { user32::ShowWindow(self.window.0, winapi::SW_SHOW); } } pub fn hide(&self) { unsafe { user32::ShowWindow(self.window.0, winapi::SW_HIDE); } } /// See the docs in the crate root file. pub fn get_position(&self) -> Option<(i32, i32)> { use std::mem; let mut placement: winapi::WINDOWPLACEMENT = unsafe { mem::zeroed() }; placement.length = mem::size_of::<winapi::WINDOWPLACEMENT>() as winapi::UINT; if unsafe { user32::GetWindowPlacement(self.window.0, &mut placement) } == 0 { return None } let ref rect = placement.rcNormalPosition; Some((rect.left as i32, rect.top as i32)) } /// See the docs in the crate root file. pub fn set_position(&self, x: i32, y: i32) { use libc; unsafe { user32::SetWindowPos(self.window.0, ptr::null_mut(), x as libc::c_int, y as libc::c_int, 0, 0, winapi::SWP_NOZORDER | winapi::SWP_NOSIZE); user32::UpdateWindow(self.window.0); } } /// See the docs in the crate root file. pub fn get_inner_size(&self) -> Option<(u32, u32)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { user32::GetClientRect(self.window.0, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32 )) } /// See the docs in the crate root file. pub fn get_outer_size(&self) -> Option<(u32, u32)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { user32::GetWindowRect(self.window.0, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32 )) } /// See the docs in the crate root file. pub fn set_inner_size(&self, x: u32, y: u32) { use libc; unsafe { user32::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, x as libc::c_int, y as libc::c_int, winapi::SWP_NOZORDER | winapi::SWP_NOREPOSITION); user32::UpdateWindow(self.window.0); } } pub fn create_window_proxy(&self) -> WindowProxy { WindowProxy } /// See the docs in the crate root file. pub fn poll_events(&self) -> PollEventsIterator { PollEventsIterator { window: self, } } /// See the docs in the crate root file. pub fn wait_events(&self) -> WaitEventsIterator { WaitEventsIterator { window: self, } } /// See the docs in the crate root file. pub unsafe fn make_current(&self) { // TODO: check return value gl::wgl::MakeCurrent(self.window.1 as *const libc::c_void, self.context.0 as *const libc::c_void); } /// See the docs in the crate root file. pub fn is_current(&self) -> bool { unsafe { gl::wgl::GetCurrentContext() == self.context.0 as *const libc::c_void } } /// See the docs in the crate root file. pub fn get_proc_address(&self, addr: &str) -> *const () { let addr = CString::new(addr.as_bytes()).unwrap(); let addr = addr.as_ptr(); unsafe { let p = gl::wgl::GetProcAddress(addr) as *const (); if!p.is_null() { return p; } kernel32::GetProcAddress(self.gl_library, addr) as *const () } } /// See the docs in the crate root file. pub fn swap_buffers(&self) { unsafe { gdi32::SwapBuffers(self.window.1); } } pub fn platform_display(&self) -> *mut libc::c_void { unimplemented!() } pub fn platform_window(&self) -> *mut libc::c_void { self.window.0 as *mut libc::c_void } /// See the docs in the crate root file. pub fn get_api(&self) -> ::Api { ::Api::OpenGl } pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) { } pub fn set_cursor(&self, _cursor: MouseCursor) { unimplemented!() } pub fn hidpi_factor(&self) -> f32 { 1.0 } pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { let mut point = winapi::POINT { x: x, y: y, }; unsafe { if user32::ClientToScreen(self.window.0, &mut point) == 0 { return Err(()); } if user32::SetCursorPos(point.x, point.y) == 0 { return Err(()); } } Ok(()) } }
impl<'a> Iterator for PollEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { use events::Event::Closed; match self.window.events_receiver.try_recv() { Ok(Closed) => { use std::sync::atomic::Ordering::Relaxed; self.window.is_closed.store(true, Relaxed); Some(Closed) }, Ok(ev) => Some(ev), Err(_) => None } } } pub struct WaitEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for WaitEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { use events::Event::Closed; match self.window.events_receiver.recv() { Ok(Closed) => { use std::sync::atomic::Ordering::Relaxed; self.window.is_closed.store(true, Relaxed); Some(Closed) }, Ok(ev) => Some(ev), Err(_) => None } } } #[unsafe_destructor] impl Drop for Window { fn drop(&mut self) { unsafe { // we don't call MakeCurrent(0, 0) because we are not sure that the context // is still the current one user32::PostMessageW(self.window.0, winapi::WM_DESTROY, 0, 0); } } }
pub struct PollEventsIterator<'a> { window: &'a Window, }
random_line_split
mod.rs
use std::sync::atomic::AtomicBool; use std::ptr; use std::ffi::CString; use std::collections::VecDeque; use std::sync::mpsc::Receiver; use libc; use {CreationError, Event, MouseCursor}; use BuilderAttribs; pub use self::headless::HeadlessContext; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; use user32; use kernel32; use gdi32; mod callback; mod event; mod gl; mod headless; mod init; mod make_current_guard; mod monitor; /// The Win32 implementation of the main `Window` object. pub struct Window { /// Main handle for the window. window: WindowWrapper, /// OpenGL context. context: ContextWrapper, /// Binded to `opengl32.dll`. /// /// `wglGetProcAddress` returns null for GL 1.1 functions because they are /// already defined by the system. This module contains them. gl_library: winapi::HMODULE, /// Receiver for the events dispatched by the window callback. events_receiver: Receiver<Event>, /// True if a `Closed` event has been received. is_closed: AtomicBool, } unsafe impl Send for Window {} unsafe impl Sync for Window {} /// A simple wrapper that destroys the context when it is destroyed. // FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[doc(hidden)] pub struct ContextWrapper(pub winapi::HGLRC); impl Drop for ContextWrapper { fn drop(&mut self) { unsafe { gl::wgl::DeleteContext(self.0 as *const libc::c_void); } } } /// A simple wrapper that destroys the window when it is destroyed. // FIXME: remove `pub` (https://github.com/rust-lang/rust/issues/23585) #[doc(hidden)] pub struct WindowWrapper(pub winapi::HWND, pub winapi::HDC); impl Drop for WindowWrapper { fn drop(&mut self) { unsafe { user32::DestroyWindow(self.0); } } } #[derive(Clone)] pub struct WindowProxy; impl WindowProxy { pub fn wakeup_event_loop(&self) { unimplemented!() } } impl Window { /// See the docs in the crate root file. pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> { let (builder, sharing) = builder.extract_non_static(); let sharing = sharing.map(|w| init::ContextHack(w.context.0)); init::new_window(builder, sharing) } /// See the docs in the crate root file. pub fn is_closed(&self) -> bool { use std::sync::atomic::Ordering::Relaxed; self.is_closed.load(Relaxed) } /// See the docs in the crate root file. /// /// Calls SetWindowText on the HWND. pub fn set_title(&self, text: &str) { unsafe { user32::SetWindowTextW(self.window.0, text.utf16_units().chain(Some(0).into_iter()) .collect::<Vec<u16>>().as_ptr() as winapi::LPCWSTR); } } pub fn show(&self) { unsafe { user32::ShowWindow(self.window.0, winapi::SW_SHOW); } } pub fn hide(&self) { unsafe { user32::ShowWindow(self.window.0, winapi::SW_HIDE); } } /// See the docs in the crate root file. pub fn get_position(&self) -> Option<(i32, i32)> { use std::mem; let mut placement: winapi::WINDOWPLACEMENT = unsafe { mem::zeroed() }; placement.length = mem::size_of::<winapi::WINDOWPLACEMENT>() as winapi::UINT; if unsafe { user32::GetWindowPlacement(self.window.0, &mut placement) } == 0 { return None } let ref rect = placement.rcNormalPosition; Some((rect.left as i32, rect.top as i32)) } /// See the docs in the crate root file. pub fn set_position(&self, x: i32, y: i32) { use libc; unsafe { user32::SetWindowPos(self.window.0, ptr::null_mut(), x as libc::c_int, y as libc::c_int, 0, 0, winapi::SWP_NOZORDER | winapi::SWP_NOSIZE); user32::UpdateWindow(self.window.0); } } /// See the docs in the crate root file. pub fn get_inner_size(&self) -> Option<(u32, u32)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { user32::GetClientRect(self.window.0, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32 )) } /// See the docs in the crate root file. pub fn get_outer_size(&self) -> Option<(u32, u32)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { user32::GetWindowRect(self.window.0, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32 )) } /// See the docs in the crate root file. pub fn set_inner_size(&self, x: u32, y: u32) { use libc; unsafe { user32::SetWindowPos(self.window.0, ptr::null_mut(), 0, 0, x as libc::c_int, y as libc::c_int, winapi::SWP_NOZORDER | winapi::SWP_NOREPOSITION); user32::UpdateWindow(self.window.0); } } pub fn
(&self) -> WindowProxy { WindowProxy } /// See the docs in the crate root file. pub fn poll_events(&self) -> PollEventsIterator { PollEventsIterator { window: self, } } /// See the docs in the crate root file. pub fn wait_events(&self) -> WaitEventsIterator { WaitEventsIterator { window: self, } } /// See the docs in the crate root file. pub unsafe fn make_current(&self) { // TODO: check return value gl::wgl::MakeCurrent(self.window.1 as *const libc::c_void, self.context.0 as *const libc::c_void); } /// See the docs in the crate root file. pub fn is_current(&self) -> bool { unsafe { gl::wgl::GetCurrentContext() == self.context.0 as *const libc::c_void } } /// See the docs in the crate root file. pub fn get_proc_address(&self, addr: &str) -> *const () { let addr = CString::new(addr.as_bytes()).unwrap(); let addr = addr.as_ptr(); unsafe { let p = gl::wgl::GetProcAddress(addr) as *const (); if!p.is_null() { return p; } kernel32::GetProcAddress(self.gl_library, addr) as *const () } } /// See the docs in the crate root file. pub fn swap_buffers(&self) { unsafe { gdi32::SwapBuffers(self.window.1); } } pub fn platform_display(&self) -> *mut libc::c_void { unimplemented!() } pub fn platform_window(&self) -> *mut libc::c_void { self.window.0 as *mut libc::c_void } /// See the docs in the crate root file. pub fn get_api(&self) -> ::Api { ::Api::OpenGl } pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) { } pub fn set_cursor(&self, _cursor: MouseCursor) { unimplemented!() } pub fn hidpi_factor(&self) -> f32 { 1.0 } pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> { let mut point = winapi::POINT { x: x, y: y, }; unsafe { if user32::ClientToScreen(self.window.0, &mut point) == 0 { return Err(()); } if user32::SetCursorPos(point.x, point.y) == 0 { return Err(()); } } Ok(()) } } pub struct PollEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for PollEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { use events::Event::Closed; match self.window.events_receiver.try_recv() { Ok(Closed) => { use std::sync::atomic::Ordering::Relaxed; self.window.is_closed.store(true, Relaxed); Some(Closed) }, Ok(ev) => Some(ev), Err(_) => None } } } pub struct WaitEventsIterator<'a> { window: &'a Window, } impl<'a> Iterator for WaitEventsIterator<'a> { type Item = Event; fn next(&mut self) -> Option<Event> { use events::Event::Closed; match self.window.events_receiver.recv() { Ok(Closed) => { use std::sync::atomic::Ordering::Relaxed; self.window.is_closed.store(true, Relaxed); Some(Closed) }, Ok(ev) => Some(ev), Err(_) => None } } } #[unsafe_destructor] impl Drop for Window { fn drop(&mut self) { unsafe { // we don't call MakeCurrent(0, 0) because we are not sure that the context // is still the current one user32::PostMessageW(self.window.0, winapi::WM_DESTROY, 0, 0); } } }
create_window_proxy
identifier_name
regions-infer-borrow-scope-too-big.rs
// Copyright 2012 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. struct point { x: isize, y: isize, } fn x_coord<'r>(p: &'r point) -> &'r isize { return &p.x; } fn foo<'a>(p: Box<point>) -> &'a isize { let xc = x_coord(&*p); //~ ERROR `*p` does not live long enough assert_eq!(*xc, 3); return xc; } fn
() {}
main
identifier_name
regions-infer-borrow-scope-too-big.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// option. This file may not be copied, modified, or distributed // except according to those terms. struct point { x: isize, y: isize, } fn x_coord<'r>(p: &'r point) -> &'r isize { return &p.x; } fn foo<'a>(p: Box<point>) -> &'a isize { let xc = x_coord(&*p); //~ ERROR `*p` does not live long enough assert_eq!(*xc, 3); return xc; } fn main() {}
// // 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
random_line_split
mod.rs
Data<'tcx>) { let mut glcx = GatherLoanCtxt { bccx: bccx, all_loans: Vec::new(), item_ub: region::CodeExtent::from_node_id(body.id), move_data: MoveData::new(), move_error_collector: move_error::MoveErrorCollector::new(), }; let param_env = ty::ParameterEnvironment::for_item(bccx.tcx, fn_id); { let mut euv = euv::ExprUseVisitor::new(&mut glcx, &param_env); euv.walk_fn(decl, body); } glcx.report_potential_errors(); let GatherLoanCtxt { all_loans, move_data,.. } = glcx; (all_loans, move_data) } struct GatherLoanCtxt<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, move_data: move_data::MoveData<'tcx>, move_error_collector: move_error::MoveErrorCollector<'tcx>, all_loans: Vec<Loan<'tcx>>, /// `item_ub` is used as an upper-bound on the lifetime whenever we /// ask for the scope of an expression categorized as an upvar. item_ub: region::CodeExtent, } impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { fn consume(&mut self, consume_id: ast::NodeId, _consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("consume(consume_id={}, cmt={}, mode={:?})", consume_id, cmt.repr(self.tcx()), mode); match mode { euv::Move(move_reason) => { gather_moves::gather_move_from_expr( self.bccx, &self.move_data, &self.move_error_collector, consume_id, cmt, move_reason);
fn matched_pat(&mut self, matched_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { debug!("matched_pat(matched_pat={}, cmt={}, mode={:?})", matched_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); if let mc::cat_downcast(..) = cmt.cat { gather_moves::gather_match_variant( self.bccx, &self.move_data, &self.move_error_collector, matched_pat, cmt, mode); } } fn consume_pat(&mut self, consume_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("consume_pat(consume_pat={}, cmt={}, mode={:?})", consume_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); match mode { euv::Copy => { return; } euv::Move(_) => { } } gather_moves::gather_move_from_pat( self.bccx, &self.move_data, &self.move_error_collector, consume_pat, cmt); } fn borrow(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt<'tcx>, loan_region: ty::Region, bk: ty::BorrowKind, loan_cause: euv::LoanCause) { debug!("borrow(borrow_id={}, cmt={}, loan_region={:?}, \ bk={:?}, loan_cause={:?})", borrow_id, cmt.repr(self.tcx()), loan_region, bk, loan_cause); self.guarantee_valid(borrow_id, borrow_span, cmt, bk, loan_region, loan_cause); } fn mutate(&mut self, assignment_id: ast::NodeId, assignment_span: Span, assignee_cmt: mc::cmt<'tcx>, mode: euv::MutateMode) { let opt_lp = opt_loan_path(&assignee_cmt); debug!("mutate(assignment_id={}, assignee_cmt={}) opt_lp={:?}", assignment_id, assignee_cmt.repr(self.tcx()), opt_lp); match opt_lp { Some(lp) => { gather_moves::gather_assignment(self.bccx, &self.move_data, assignment_id, assignment_span, lp, assignee_cmt.id, mode); } None => { // This can occur with e.g. `*foo() = 5`. In such // cases, there is no need to check for conflicts // with moves etc, just ignore. } } } fn decl_without_init(&mut self, id: ast::NodeId, span: Span) { gather_moves::gather_decl(self.bccx, &self.move_data, id, span, id); } } /// Implements the A-* rules in README.md. fn check_aliasability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, borrow_span: Span, loan_cause: euv::LoanCause, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind) -> Result<(),()> { let aliasability = cmt.freely_aliasable(bccx.tcx); debug!("check_aliasability aliasability={:?} req_kind={:?}", aliasability, req_kind); match (aliasability, req_kind) { (mc::Aliasability::NonAliasable, _) => { /* Uniquely accessible path -- OK for `&` and `&mut` */ Ok(()) } (mc::Aliasability::FreelyAliasable(mc::AliasableStatic), ty::ImmBorrow) => { // Borrow of an immutable static item. Ok(()) } (mc::Aliasability::FreelyAliasable(mc::AliasableStaticMut), _) => { // Even touching a static mut is considered unsafe. We assume the // user knows what they're doing in these cases. Ok(()) } (mc::Aliasability::ImmutableUnique(_), ty::MutBorrow) => { bccx.report_aliasability_violation( borrow_span, BorrowViolation(loan_cause), mc::AliasableReason::UnaliasableImmutable); Err(()) } (mc::Aliasability::FreelyAliasable(alias_cause), ty::UniqueImmBorrow) | (mc::Aliasability::FreelyAliasable(alias_cause), ty::MutBorrow) => { bccx.report_aliasability_violation( borrow_span, BorrowViolation(loan_cause), alias_cause); Err(()) } (_, _) => { Ok(()) } } } impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.bccx.tcx } /// Guarantees that `addr_of(cmt)` will be valid for the duration of `static_scope_r`, or /// reports an error. This may entail taking out loans, which will be added to the /// `req_loan_map`. fn guarantee_valid(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind, loan_region: ty::Region, cause: euv::LoanCause) { debug!("guarantee_valid(borrow_id={}, cmt={}, \ req_mutbl={:?}, loan_region={:?})", borrow_id, cmt.repr(self.tcx()), req_kind, loan_region); // a loan for the empty region can never be dereferenced, so // it is always safe if loan_region == ty::ReEmpty { return; } // Check that the lifetime of the borrow does not exceed // the lifetime of the data being borrowed. if lifetime::guarantee_lifetime(self.bccx, self.item_ub, borrow_span, cause, cmt.clone(), loan_region, req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Check that we don't allow mutable borrows of non-mutable data. if check_mutability(self.bccx, borrow_span, cause, cmt.clone(), req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Check that we don't allow mutable borrows of aliasable data. if check_aliasability(self.bccx, borrow_span, cause, cmt.clone(), req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Compute the restrictions that are required to enforce the // loan is safe. let restr = restrictions::compute_restrictions( self.bccx, borrow_span, cause, cmt.clone(), loan_region); debug!("guarantee_valid(): restrictions={:?}", restr); // Create the loan record (if needed). let loan = match restr { restrictions::Safe => { // No restrictions---no loan record necessary return; } restrictions::SafeIf(loan_path, restricted_paths) => { let loan_scope = match loan_region { ty::ReScope(scope) => scope, ty::ReFree(ref fr) => fr.scope.to_code_extent(), ty::ReStatic => { // If we get here, an error must have been // reported in // `lifetime::guarantee_lifetime()`, because // the only legal ways to have a borrow with a // static lifetime should not require // restrictions. To avoid reporting derived // errors, we just return here without adding // any loans. return; } ty::ReEmpty | ty::ReLateBound(..) | ty::ReEarlyBound(..) | ty::ReInfer(..) => { self.tcx().sess.span_bug( cmt.span, &format!("invalid borrow lifetime: {:?}", loan_region)); } }; debug!("loan_scope = {:?}", loan_scope); let borrow_scope = region::CodeExtent::from_node_id(borrow_id); let gen_scope = self.compute_gen_scope(borrow_scope, loan_scope); debug!("gen_scope = {:?}", gen_scope); let kill_scope = self.compute_kill_scope(loan_scope, &*loan_path); debug!("kill_scope = {:?}", kill_scope); if req_kind == ty::MutBorrow { self.mark_loan_path_as_mutated(&*loan_path); } Loan { index: self.all_loans.len(), loan_path: loan_path, kind: req_kind, gen_scope: gen_scope, kill_scope: kill_scope, span: borrow_span, restricted_paths: restricted_paths, cause: cause, } } }; debug!("guarantee_valid(borrow_id={}), loan={}", borrow_id, loan.repr(self.tcx())); // let loan_path = loan.loan_path; // let loan_gen_scope = loan.gen_scope; // let loan_kill_scope = loan.kill_scope; self.all_loans.push(loan); // if loan_gen_scope!= borrow_id { // FIXME(#6268) Nested method calls // // Typically, the scope of the loan includes the point at // which the loan is originated. This // This is a subtle case. See the test case // <compile-fail/borrowck-bad-nested-calls-free.rs> // to see what we are guarding against. //let restr = restrictions::compute_restrictions( // self.bccx, borrow_span, cmt, RESTR_EMPTY); //let loan = { // let all_loans = &mut *self.all_loans; // FIXME(#5074) // Loan { // index: all_loans.len(), // loan_path: loan_path, // cmt: cmt, // mutbl: ConstMutability, // gen_scope: borrow_id, // kill_scope: kill_scope, // span: borrow_span, // restrictions: restrictions // } // } fn check_mutability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, borrow_span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind) -> Result<(),()> { //! Implements the M-* rules in README.md. debug!("check_mutability(cause={:?} cmt={} req_kind={:?}", cause, cmt.repr(bccx.tcx), req_kind); match req_kind { ty::UniqueImmBorrow | ty::ImmBorrow => { match cmt.mutbl { // I am intentionally leaving this here to help // refactoring if, in the future, we should add new // kinds of mutability. mc::McImmutable | mc::McDeclared | mc::McInherited => { // both imm and mut data can be lent as imm; // for mutable data, this is a freeze Ok(()) } } } ty::MutBorrow => { // Only mutable data can be lent as mutable. if!cmt.mutbl.is_mutable() { Err(bccx.report(BckError { span: borrow_span, cause: cause, cmt: cmt, code: err_mutbl })) } else { Ok(()) } } } } } pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) { //! For mutable loans of content whose mutability derives //! from a local variable, mark the mutability decl as necessary. match loan_path.kind { LpVar(local_id) | LpUpvar(ty::UpvarId{ var_id: local_id, closure_expr_id: _ }) => { self.tcx().used_mut_nodes.borrow_mut().insert(local_id); } LpDowncast(ref base, _) | LpExtend(ref base, mc::McInherited, _) | LpExtend(ref base, mc::McDeclared, _) => { self.mark_loan_path_as_mutated(&**base); } LpExtend(_, mc::McImmutable, _) => { // Nothing to do. } } } pub fn compute_gen_scope(&self, borrow_scope: region::CodeExtent, loan_scope: region::CodeExtent)
} euv::Copy => { } } }
random_line_split
mod.rs
); } glcx.report_potential_errors(); let GatherLoanCtxt { all_loans, move_data,.. } = glcx; (all_loans, move_data) } struct GatherLoanCtxt<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, move_data: move_data::MoveData<'tcx>, move_error_collector: move_error::MoveErrorCollector<'tcx>, all_loans: Vec<Loan<'tcx>>, /// `item_ub` is used as an upper-bound on the lifetime whenever we /// ask for the scope of an expression categorized as an upvar. item_ub: region::CodeExtent, } impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { fn consume(&mut self, consume_id: ast::NodeId, _consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("consume(consume_id={}, cmt={}, mode={:?})", consume_id, cmt.repr(self.tcx()), mode); match mode { euv::Move(move_reason) => { gather_moves::gather_move_from_expr( self.bccx, &self.move_data, &self.move_error_collector, consume_id, cmt, move_reason); } euv::Copy => { } } } fn matched_pat(&mut self, matched_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { debug!("matched_pat(matched_pat={}, cmt={}, mode={:?})", matched_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); if let mc::cat_downcast(..) = cmt.cat { gather_moves::gather_match_variant( self.bccx, &self.move_data, &self.move_error_collector, matched_pat, cmt, mode); } } fn consume_pat(&mut self, consume_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("consume_pat(consume_pat={}, cmt={}, mode={:?})", consume_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); match mode { euv::Copy => { return; } euv::Move(_) => { } } gather_moves::gather_move_from_pat( self.bccx, &self.move_data, &self.move_error_collector, consume_pat, cmt); } fn borrow(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt<'tcx>, loan_region: ty::Region, bk: ty::BorrowKind, loan_cause: euv::LoanCause) { debug!("borrow(borrow_id={}, cmt={}, loan_region={:?}, \ bk={:?}, loan_cause={:?})", borrow_id, cmt.repr(self.tcx()), loan_region, bk, loan_cause); self.guarantee_valid(borrow_id, borrow_span, cmt, bk, loan_region, loan_cause); } fn mutate(&mut self, assignment_id: ast::NodeId, assignment_span: Span, assignee_cmt: mc::cmt<'tcx>, mode: euv::MutateMode) { let opt_lp = opt_loan_path(&assignee_cmt); debug!("mutate(assignment_id={}, assignee_cmt={}) opt_lp={:?}", assignment_id, assignee_cmt.repr(self.tcx()), opt_lp); match opt_lp { Some(lp) => { gather_moves::gather_assignment(self.bccx, &self.move_data, assignment_id, assignment_span, lp, assignee_cmt.id, mode); } None => { // This can occur with e.g. `*foo() = 5`. In such // cases, there is no need to check for conflicts // with moves etc, just ignore. } } } fn decl_without_init(&mut self, id: ast::NodeId, span: Span) { gather_moves::gather_decl(self.bccx, &self.move_data, id, span, id); } } /// Implements the A-* rules in README.md. fn check_aliasability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, borrow_span: Span, loan_cause: euv::LoanCause, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind) -> Result<(),()> { let aliasability = cmt.freely_aliasable(bccx.tcx); debug!("check_aliasability aliasability={:?} req_kind={:?}", aliasability, req_kind); match (aliasability, req_kind) { (mc::Aliasability::NonAliasable, _) => { /* Uniquely accessible path -- OK for `&` and `&mut` */ Ok(()) } (mc::Aliasability::FreelyAliasable(mc::AliasableStatic), ty::ImmBorrow) => { // Borrow of an immutable static item. Ok(()) } (mc::Aliasability::FreelyAliasable(mc::AliasableStaticMut), _) => { // Even touching a static mut is considered unsafe. We assume the // user knows what they're doing in these cases. Ok(()) } (mc::Aliasability::ImmutableUnique(_), ty::MutBorrow) => { bccx.report_aliasability_violation( borrow_span, BorrowViolation(loan_cause), mc::AliasableReason::UnaliasableImmutable); Err(()) } (mc::Aliasability::FreelyAliasable(alias_cause), ty::UniqueImmBorrow) | (mc::Aliasability::FreelyAliasable(alias_cause), ty::MutBorrow) => { bccx.report_aliasability_violation( borrow_span, BorrowViolation(loan_cause), alias_cause); Err(()) } (_, _) => { Ok(()) } } } impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.bccx.tcx } /// Guarantees that `addr_of(cmt)` will be valid for the duration of `static_scope_r`, or /// reports an error. This may entail taking out loans, which will be added to the /// `req_loan_map`. fn guarantee_valid(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind, loan_region: ty::Region, cause: euv::LoanCause) { debug!("guarantee_valid(borrow_id={}, cmt={}, \ req_mutbl={:?}, loan_region={:?})", borrow_id, cmt.repr(self.tcx()), req_kind, loan_region); // a loan for the empty region can never be dereferenced, so // it is always safe if loan_region == ty::ReEmpty { return; } // Check that the lifetime of the borrow does not exceed // the lifetime of the data being borrowed. if lifetime::guarantee_lifetime(self.bccx, self.item_ub, borrow_span, cause, cmt.clone(), loan_region, req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Check that we don't allow mutable borrows of non-mutable data. if check_mutability(self.bccx, borrow_span, cause, cmt.clone(), req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Check that we don't allow mutable borrows of aliasable data. if check_aliasability(self.bccx, borrow_span, cause, cmt.clone(), req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Compute the restrictions that are required to enforce the // loan is safe. let restr = restrictions::compute_restrictions( self.bccx, borrow_span, cause, cmt.clone(), loan_region); debug!("guarantee_valid(): restrictions={:?}", restr); // Create the loan record (if needed). let loan = match restr { restrictions::Safe => { // No restrictions---no loan record necessary return; } restrictions::SafeIf(loan_path, restricted_paths) => { let loan_scope = match loan_region { ty::ReScope(scope) => scope, ty::ReFree(ref fr) => fr.scope.to_code_extent(), ty::ReStatic => { // If we get here, an error must have been // reported in // `lifetime::guarantee_lifetime()`, because // the only legal ways to have a borrow with a // static lifetime should not require // restrictions. To avoid reporting derived // errors, we just return here without adding // any loans. return; } ty::ReEmpty | ty::ReLateBound(..) | ty::ReEarlyBound(..) | ty::ReInfer(..) => { self.tcx().sess.span_bug( cmt.span, &format!("invalid borrow lifetime: {:?}", loan_region)); } }; debug!("loan_scope = {:?}", loan_scope); let borrow_scope = region::CodeExtent::from_node_id(borrow_id); let gen_scope = self.compute_gen_scope(borrow_scope, loan_scope); debug!("gen_scope = {:?}", gen_scope); let kill_scope = self.compute_kill_scope(loan_scope, &*loan_path); debug!("kill_scope = {:?}", kill_scope); if req_kind == ty::MutBorrow { self.mark_loan_path_as_mutated(&*loan_path); } Loan { index: self.all_loans.len(), loan_path: loan_path, kind: req_kind, gen_scope: gen_scope, kill_scope: kill_scope, span: borrow_span, restricted_paths: restricted_paths, cause: cause, } } }; debug!("guarantee_valid(borrow_id={}), loan={}", borrow_id, loan.repr(self.tcx())); // let loan_path = loan.loan_path; // let loan_gen_scope = loan.gen_scope; // let loan_kill_scope = loan.kill_scope; self.all_loans.push(loan); // if loan_gen_scope!= borrow_id { // FIXME(#6268) Nested method calls // // Typically, the scope of the loan includes the point at // which the loan is originated. This // This is a subtle case. See the test case // <compile-fail/borrowck-bad-nested-calls-free.rs> // to see what we are guarding against. //let restr = restrictions::compute_restrictions( // self.bccx, borrow_span, cmt, RESTR_EMPTY); //let loan = { // let all_loans = &mut *self.all_loans; // FIXME(#5074) // Loan { // index: all_loans.len(), // loan_path: loan_path, // cmt: cmt, // mutbl: ConstMutability, // gen_scope: borrow_id, // kill_scope: kill_scope, // span: borrow_span, // restrictions: restrictions // } // } fn check_mutability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, borrow_span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind) -> Result<(),()> { //! Implements the M-* rules in README.md. debug!("check_mutability(cause={:?} cmt={} req_kind={:?}", cause, cmt.repr(bccx.tcx), req_kind); match req_kind { ty::UniqueImmBorrow | ty::ImmBorrow => { match cmt.mutbl { // I am intentionally leaving this here to help // refactoring if, in the future, we should add new // kinds of mutability. mc::McImmutable | mc::McDeclared | mc::McInherited => { // both imm and mut data can be lent as imm; // for mutable data, this is a freeze Ok(()) } } } ty::MutBorrow => { // Only mutable data can be lent as mutable. if!cmt.mutbl.is_mutable() { Err(bccx.report(BckError { span: borrow_span, cause: cause, cmt: cmt, code: err_mutbl })) } else { Ok(()) } } } } } pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) { //! For mutable loans of content whose mutability derives //! from a local variable, mark the mutability decl as necessary. match loan_path.kind { LpVar(local_id) | LpUpvar(ty::UpvarId{ var_id: local_id, closure_expr_id: _ }) => { self.tcx().used_mut_nodes.borrow_mut().insert(local_id); } LpDowncast(ref base, _) | LpExtend(ref base, mc::McInherited, _) | LpExtend(ref base, mc::McDeclared, _) => { self.mark_loan_path_as_mutated(&**base); } LpExtend(_, mc::McImmutable, _) => { // Nothing to do. } } } pub fn compute_gen_scope(&self, borrow_scope: region::CodeExtent, loan_scope: region::CodeExtent) -> region::CodeExtent { //! Determine when to introduce the loan. Typically the loan //! is introduced at the point of the borrow, but in some cases, //! notably method arguments, the loan may be introduced only //! later, once it comes into scope. if self.bccx.tcx.region_maps.is_subscope_of(borrow_scope, loan_scope) { borrow_scope } else { loan_scope } } pub fn
compute_kill_scope
identifier_name
mod.rs
<'tcx>) { let mut glcx = GatherLoanCtxt { bccx: bccx, all_loans: Vec::new(), item_ub: region::CodeExtent::from_node_id(body.id), move_data: MoveData::new(), move_error_collector: move_error::MoveErrorCollector::new(), }; let param_env = ty::ParameterEnvironment::for_item(bccx.tcx, fn_id); { let mut euv = euv::ExprUseVisitor::new(&mut glcx, &param_env); euv.walk_fn(decl, body); } glcx.report_potential_errors(); let GatherLoanCtxt { all_loans, move_data,.. } = glcx; (all_loans, move_data) } struct GatherLoanCtxt<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, move_data: move_data::MoveData<'tcx>, move_error_collector: move_error::MoveErrorCollector<'tcx>, all_loans: Vec<Loan<'tcx>>, /// `item_ub` is used as an upper-bound on the lifetime whenever we /// ask for the scope of an expression categorized as an upvar. item_ub: region::CodeExtent, } impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { fn consume(&mut self, consume_id: ast::NodeId, _consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("consume(consume_id={}, cmt={}, mode={:?})", consume_id, cmt.repr(self.tcx()), mode); match mode { euv::Move(move_reason) => { gather_moves::gather_move_from_expr( self.bccx, &self.move_data, &self.move_error_collector, consume_id, cmt, move_reason); } euv::Copy => { } } } fn matched_pat(&mut self, matched_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { debug!("matched_pat(matched_pat={}, cmt={}, mode={:?})", matched_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); if let mc::cat_downcast(..) = cmt.cat { gather_moves::gather_match_variant( self.bccx, &self.move_data, &self.move_error_collector, matched_pat, cmt, mode); } } fn consume_pat(&mut self, consume_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("consume_pat(consume_pat={}, cmt={}, mode={:?})", consume_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); match mode { euv::Copy => { return; } euv::Move(_) => { } } gather_moves::gather_move_from_pat( self.bccx, &self.move_data, &self.move_error_collector, consume_pat, cmt); } fn borrow(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt<'tcx>, loan_region: ty::Region, bk: ty::BorrowKind, loan_cause: euv::LoanCause) { debug!("borrow(borrow_id={}, cmt={}, loan_region={:?}, \ bk={:?}, loan_cause={:?})", borrow_id, cmt.repr(self.tcx()), loan_region, bk, loan_cause); self.guarantee_valid(borrow_id, borrow_span, cmt, bk, loan_region, loan_cause); } fn mutate(&mut self, assignment_id: ast::NodeId, assignment_span: Span, assignee_cmt: mc::cmt<'tcx>, mode: euv::MutateMode) { let opt_lp = opt_loan_path(&assignee_cmt); debug!("mutate(assignment_id={}, assignee_cmt={}) opt_lp={:?}", assignment_id, assignee_cmt.repr(self.tcx()), opt_lp); match opt_lp { Some(lp) => { gather_moves::gather_assignment(self.bccx, &self.move_data, assignment_id, assignment_span, lp, assignee_cmt.id, mode); } None => { // This can occur with e.g. `*foo() = 5`. In such // cases, there is no need to check for conflicts // with moves etc, just ignore. } } } fn decl_without_init(&mut self, id: ast::NodeId, span: Span)
} /// Implements the A-* rules in README.md. fn check_aliasability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, borrow_span: Span, loan_cause: euv::LoanCause, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind) -> Result<(),()> { let aliasability = cmt.freely_aliasable(bccx.tcx); debug!("check_aliasability aliasability={:?} req_kind={:?}", aliasability, req_kind); match (aliasability, req_kind) { (mc::Aliasability::NonAliasable, _) => { /* Uniquely accessible path -- OK for `&` and `&mut` */ Ok(()) } (mc::Aliasability::FreelyAliasable(mc::AliasableStatic), ty::ImmBorrow) => { // Borrow of an immutable static item. Ok(()) } (mc::Aliasability::FreelyAliasable(mc::AliasableStaticMut), _) => { // Even touching a static mut is considered unsafe. We assume the // user knows what they're doing in these cases. Ok(()) } (mc::Aliasability::ImmutableUnique(_), ty::MutBorrow) => { bccx.report_aliasability_violation( borrow_span, BorrowViolation(loan_cause), mc::AliasableReason::UnaliasableImmutable); Err(()) } (mc::Aliasability::FreelyAliasable(alias_cause), ty::UniqueImmBorrow) | (mc::Aliasability::FreelyAliasable(alias_cause), ty::MutBorrow) => { bccx.report_aliasability_violation( borrow_span, BorrowViolation(loan_cause), alias_cause); Err(()) } (_, _) => { Ok(()) } } } impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.bccx.tcx } /// Guarantees that `addr_of(cmt)` will be valid for the duration of `static_scope_r`, or /// reports an error. This may entail taking out loans, which will be added to the /// `req_loan_map`. fn guarantee_valid(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind, loan_region: ty::Region, cause: euv::LoanCause) { debug!("guarantee_valid(borrow_id={}, cmt={}, \ req_mutbl={:?}, loan_region={:?})", borrow_id, cmt.repr(self.tcx()), req_kind, loan_region); // a loan for the empty region can never be dereferenced, so // it is always safe if loan_region == ty::ReEmpty { return; } // Check that the lifetime of the borrow does not exceed // the lifetime of the data being borrowed. if lifetime::guarantee_lifetime(self.bccx, self.item_ub, borrow_span, cause, cmt.clone(), loan_region, req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Check that we don't allow mutable borrows of non-mutable data. if check_mutability(self.bccx, borrow_span, cause, cmt.clone(), req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Check that we don't allow mutable borrows of aliasable data. if check_aliasability(self.bccx, borrow_span, cause, cmt.clone(), req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Compute the restrictions that are required to enforce the // loan is safe. let restr = restrictions::compute_restrictions( self.bccx, borrow_span, cause, cmt.clone(), loan_region); debug!("guarantee_valid(): restrictions={:?}", restr); // Create the loan record (if needed). let loan = match restr { restrictions::Safe => { // No restrictions---no loan record necessary return; } restrictions::SafeIf(loan_path, restricted_paths) => { let loan_scope = match loan_region { ty::ReScope(scope) => scope, ty::ReFree(ref fr) => fr.scope.to_code_extent(), ty::ReStatic => { // If we get here, an error must have been // reported in // `lifetime::guarantee_lifetime()`, because // the only legal ways to have a borrow with a // static lifetime should not require // restrictions. To avoid reporting derived // errors, we just return here without adding // any loans. return; } ty::ReEmpty | ty::ReLateBound(..) | ty::ReEarlyBound(..) | ty::ReInfer(..) => { self.tcx().sess.span_bug( cmt.span, &format!("invalid borrow lifetime: {:?}", loan_region)); } }; debug!("loan_scope = {:?}", loan_scope); let borrow_scope = region::CodeExtent::from_node_id(borrow_id); let gen_scope = self.compute_gen_scope(borrow_scope, loan_scope); debug!("gen_scope = {:?}", gen_scope); let kill_scope = self.compute_kill_scope(loan_scope, &*loan_path); debug!("kill_scope = {:?}", kill_scope); if req_kind == ty::MutBorrow { self.mark_loan_path_as_mutated(&*loan_path); } Loan { index: self.all_loans.len(), loan_path: loan_path, kind: req_kind, gen_scope: gen_scope, kill_scope: kill_scope, span: borrow_span, restricted_paths: restricted_paths, cause: cause, } } }; debug!("guarantee_valid(borrow_id={}), loan={}", borrow_id, loan.repr(self.tcx())); // let loan_path = loan.loan_path; // let loan_gen_scope = loan.gen_scope; // let loan_kill_scope = loan.kill_scope; self.all_loans.push(loan); // if loan_gen_scope!= borrow_id { // FIXME(#6268) Nested method calls // // Typically, the scope of the loan includes the point at // which the loan is originated. This // This is a subtle case. See the test case // <compile-fail/borrowck-bad-nested-calls-free.rs> // to see what we are guarding against. //let restr = restrictions::compute_restrictions( // self.bccx, borrow_span, cmt, RESTR_EMPTY); //let loan = { // let all_loans = &mut *self.all_loans; // FIXME(#5074) // Loan { // index: all_loans.len(), // loan_path: loan_path, // cmt: cmt, // mutbl: ConstMutability, // gen_scope: borrow_id, // kill_scope: kill_scope, // span: borrow_span, // restrictions: restrictions // } // } fn check_mutability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, borrow_span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind) -> Result<(),()> { //! Implements the M-* rules in README.md. debug!("check_mutability(cause={:?} cmt={} req_kind={:?}", cause, cmt.repr(bccx.tcx), req_kind); match req_kind { ty::UniqueImmBorrow | ty::ImmBorrow => { match cmt.mutbl { // I am intentionally leaving this here to help // refactoring if, in the future, we should add new // kinds of mutability. mc::McImmutable | mc::McDeclared | mc::McInherited => { // both imm and mut data can be lent as imm; // for mutable data, this is a freeze Ok(()) } } } ty::MutBorrow => { // Only mutable data can be lent as mutable. if!cmt.mutbl.is_mutable() { Err(bccx.report(BckError { span: borrow_span, cause: cause, cmt: cmt, code: err_mutbl })) } else { Ok(()) } } } } } pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) { //! For mutable loans of content whose mutability derives //! from a local variable, mark the mutability decl as necessary. match loan_path.kind { LpVar(local_id) | LpUpvar(ty::UpvarId{ var_id: local_id, closure_expr_id: _ }) => { self.tcx().used_mut_nodes.borrow_mut().insert(local_id); } LpDowncast(ref base, _) | LpExtend(ref base, mc::McInherited, _) | LpExtend(ref base, mc::McDeclared, _) => { self.mark_loan_path_as_mutated(&**base); } LpExtend(_, mc::McImmutable, _) => { // Nothing to do. } } } pub fn compute_gen_scope(&self, borrow_scope: region::CodeExtent, loan_scope: region::CodeExtent)
{ gather_moves::gather_decl(self.bccx, &self.move_data, id, span, id); }
identifier_body
mod.rs
<'tcx>) { let mut glcx = GatherLoanCtxt { bccx: bccx, all_loans: Vec::new(), item_ub: region::CodeExtent::from_node_id(body.id), move_data: MoveData::new(), move_error_collector: move_error::MoveErrorCollector::new(), }; let param_env = ty::ParameterEnvironment::for_item(bccx.tcx, fn_id); { let mut euv = euv::ExprUseVisitor::new(&mut glcx, &param_env); euv.walk_fn(decl, body); } glcx.report_potential_errors(); let GatherLoanCtxt { all_loans, move_data,.. } = glcx; (all_loans, move_data) } struct GatherLoanCtxt<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, move_data: move_data::MoveData<'tcx>, move_error_collector: move_error::MoveErrorCollector<'tcx>, all_loans: Vec<Loan<'tcx>>, /// `item_ub` is used as an upper-bound on the lifetime whenever we /// ask for the scope of an expression categorized as an upvar. item_ub: region::CodeExtent, } impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { fn consume(&mut self, consume_id: ast::NodeId, _consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("consume(consume_id={}, cmt={}, mode={:?})", consume_id, cmt.repr(self.tcx()), mode); match mode { euv::Move(move_reason) => { gather_moves::gather_move_from_expr( self.bccx, &self.move_data, &self.move_error_collector, consume_id, cmt, move_reason); } euv::Copy => { } } } fn matched_pat(&mut self, matched_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { debug!("matched_pat(matched_pat={}, cmt={}, mode={:?})", matched_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); if let mc::cat_downcast(..) = cmt.cat { gather_moves::gather_match_variant( self.bccx, &self.move_data, &self.move_error_collector, matched_pat, cmt, mode); } } fn consume_pat(&mut self, consume_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("consume_pat(consume_pat={}, cmt={}, mode={:?})", consume_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); match mode { euv::Copy => { return; } euv::Move(_) => { } } gather_moves::gather_move_from_pat( self.bccx, &self.move_data, &self.move_error_collector, consume_pat, cmt); } fn borrow(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt<'tcx>, loan_region: ty::Region, bk: ty::BorrowKind, loan_cause: euv::LoanCause) { debug!("borrow(borrow_id={}, cmt={}, loan_region={:?}, \ bk={:?}, loan_cause={:?})", borrow_id, cmt.repr(self.tcx()), loan_region, bk, loan_cause); self.guarantee_valid(borrow_id, borrow_span, cmt, bk, loan_region, loan_cause); } fn mutate(&mut self, assignment_id: ast::NodeId, assignment_span: Span, assignee_cmt: mc::cmt<'tcx>, mode: euv::MutateMode) { let opt_lp = opt_loan_path(&assignee_cmt); debug!("mutate(assignment_id={}, assignee_cmt={}) opt_lp={:?}", assignment_id, assignee_cmt.repr(self.tcx()), opt_lp); match opt_lp { Some(lp) => { gather_moves::gather_assignment(self.bccx, &self.move_data, assignment_id, assignment_span, lp, assignee_cmt.id, mode); } None => { // This can occur with e.g. `*foo() = 5`. In such // cases, there is no need to check for conflicts // with moves etc, just ignore. } } } fn decl_without_init(&mut self, id: ast::NodeId, span: Span) { gather_moves::gather_decl(self.bccx, &self.move_data, id, span, id); } } /// Implements the A-* rules in README.md. fn check_aliasability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, borrow_span: Span, loan_cause: euv::LoanCause, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind) -> Result<(),()> { let aliasability = cmt.freely_aliasable(bccx.tcx); debug!("check_aliasability aliasability={:?} req_kind={:?}", aliasability, req_kind); match (aliasability, req_kind) { (mc::Aliasability::NonAliasable, _) => { /* Uniquely accessible path -- OK for `&` and `&mut` */ Ok(()) } (mc::Aliasability::FreelyAliasable(mc::AliasableStatic), ty::ImmBorrow) => { // Borrow of an immutable static item. Ok(()) } (mc::Aliasability::FreelyAliasable(mc::AliasableStaticMut), _) => { // Even touching a static mut is considered unsafe. We assume the // user knows what they're doing in these cases. Ok(()) } (mc::Aliasability::ImmutableUnique(_), ty::MutBorrow) => { bccx.report_aliasability_violation( borrow_span, BorrowViolation(loan_cause), mc::AliasableReason::UnaliasableImmutable); Err(()) } (mc::Aliasability::FreelyAliasable(alias_cause), ty::UniqueImmBorrow) | (mc::Aliasability::FreelyAliasable(alias_cause), ty::MutBorrow) => { bccx.report_aliasability_violation( borrow_span, BorrowViolation(loan_cause), alias_cause); Err(()) } (_, _) => { Ok(()) } } } impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { pub fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.bccx.tcx } /// Guarantees that `addr_of(cmt)` will be valid for the duration of `static_scope_r`, or /// reports an error. This may entail taking out loans, which will be added to the /// `req_loan_map`. fn guarantee_valid(&mut self, borrow_id: ast::NodeId, borrow_span: Span, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind, loan_region: ty::Region, cause: euv::LoanCause) { debug!("guarantee_valid(borrow_id={}, cmt={}, \ req_mutbl={:?}, loan_region={:?})", borrow_id, cmt.repr(self.tcx()), req_kind, loan_region); // a loan for the empty region can never be dereferenced, so // it is always safe if loan_region == ty::ReEmpty { return; } // Check that the lifetime of the borrow does not exceed // the lifetime of the data being borrowed. if lifetime::guarantee_lifetime(self.bccx, self.item_ub, borrow_span, cause, cmt.clone(), loan_region, req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Check that we don't allow mutable borrows of non-mutable data. if check_mutability(self.bccx, borrow_span, cause, cmt.clone(), req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Check that we don't allow mutable borrows of aliasable data. if check_aliasability(self.bccx, borrow_span, cause, cmt.clone(), req_kind).is_err() { return; // reported an error, no sense in reporting more. } // Compute the restrictions that are required to enforce the // loan is safe. let restr = restrictions::compute_restrictions( self.bccx, borrow_span, cause, cmt.clone(), loan_region); debug!("guarantee_valid(): restrictions={:?}", restr); // Create the loan record (if needed). let loan = match restr { restrictions::Safe => { // No restrictions---no loan record necessary return; } restrictions::SafeIf(loan_path, restricted_paths) => { let loan_scope = match loan_region { ty::ReScope(scope) => scope, ty::ReFree(ref fr) => fr.scope.to_code_extent(), ty::ReStatic => { // If we get here, an error must have been // reported in // `lifetime::guarantee_lifetime()`, because // the only legal ways to have a borrow with a // static lifetime should not require // restrictions. To avoid reporting derived // errors, we just return here without adding // any loans. return; } ty::ReEmpty | ty::ReLateBound(..) | ty::ReEarlyBound(..) | ty::ReInfer(..) => { self.tcx().sess.span_bug( cmt.span, &format!("invalid borrow lifetime: {:?}", loan_region)); } }; debug!("loan_scope = {:?}", loan_scope); let borrow_scope = region::CodeExtent::from_node_id(borrow_id); let gen_scope = self.compute_gen_scope(borrow_scope, loan_scope); debug!("gen_scope = {:?}", gen_scope); let kill_scope = self.compute_kill_scope(loan_scope, &*loan_path); debug!("kill_scope = {:?}", kill_scope); if req_kind == ty::MutBorrow { self.mark_loan_path_as_mutated(&*loan_path); } Loan { index: self.all_loans.len(), loan_path: loan_path, kind: req_kind, gen_scope: gen_scope, kill_scope: kill_scope, span: borrow_span, restricted_paths: restricted_paths, cause: cause, } } }; debug!("guarantee_valid(borrow_id={}), loan={}", borrow_id, loan.repr(self.tcx())); // let loan_path = loan.loan_path; // let loan_gen_scope = loan.gen_scope; // let loan_kill_scope = loan.kill_scope; self.all_loans.push(loan); // if loan_gen_scope!= borrow_id { // FIXME(#6268) Nested method calls // // Typically, the scope of the loan includes the point at // which the loan is originated. This // This is a subtle case. See the test case // <compile-fail/borrowck-bad-nested-calls-free.rs> // to see what we are guarding against. //let restr = restrictions::compute_restrictions( // self.bccx, borrow_span, cmt, RESTR_EMPTY); //let loan = { // let all_loans = &mut *self.all_loans; // FIXME(#5074) // Loan { // index: all_loans.len(), // loan_path: loan_path, // cmt: cmt, // mutbl: ConstMutability, // gen_scope: borrow_id, // kill_scope: kill_scope, // span: borrow_span, // restrictions: restrictions // } // } fn check_mutability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, borrow_span: Span, cause: euv::LoanCause, cmt: mc::cmt<'tcx>, req_kind: ty::BorrowKind) -> Result<(),()> { //! Implements the M-* rules in README.md. debug!("check_mutability(cause={:?} cmt={} req_kind={:?}", cause, cmt.repr(bccx.tcx), req_kind); match req_kind { ty::UniqueImmBorrow | ty::ImmBorrow => { match cmt.mutbl { // I am intentionally leaving this here to help // refactoring if, in the future, we should add new // kinds of mutability. mc::McImmutable | mc::McDeclared | mc::McInherited => { // both imm and mut data can be lent as imm; // for mutable data, this is a freeze Ok(()) } } } ty::MutBorrow => { // Only mutable data can be lent as mutable. if!cmt.mutbl.is_mutable() { Err(bccx.report(BckError { span: borrow_span, cause: cause, cmt: cmt, code: err_mutbl })) } else
} } } } pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) { //! For mutable loans of content whose mutability derives //! from a local variable, mark the mutability decl as necessary. match loan_path.kind { LpVar(local_id) | LpUpvar(ty::UpvarId{ var_id: local_id, closure_expr_id: _ }) => { self.tcx().used_mut_nodes.borrow_mut().insert(local_id); } LpDowncast(ref base, _) | LpExtend(ref base, mc::McInherited, _) | LpExtend(ref base, mc::McDeclared, _) => { self.mark_loan_path_as_mutated(&**base); } LpExtend(_, mc::McImmutable, _) => { // Nothing to do. } } } pub fn compute_gen_scope(&self, borrow_scope: region::CodeExtent, loan_scope: region::CodeExtent)
{ Ok(()) }
conditional_block
for-loop-bogosity.rs
// Copyright 2014 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. struct
{ x: int, y: int, } impl MyStruct { fn next(&mut self) -> Option<int> { Some(self.x) } } pub fn main() { let mut bogus = MyStruct { x: 1, y: 2, }; for x in bogus { //~ ERROR has type `MyStruct` which does not implement the `Iterator` trait drop(x); } }
MyStruct
identifier_name
for-loop-bogosity.rs
// Copyright 2014 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. struct MyStruct { x: int, y: int, } impl MyStruct { fn next(&mut self) -> Option<int> { Some(self.x) } } pub fn main() { let mut bogus = MyStruct { x: 1, y: 2, }; for x in bogus { //~ ERROR has type `MyStruct` which does not implement the `Iterator` trait
}
drop(x); }
random_line_split
for-loop-bogosity.rs
// Copyright 2014 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. struct MyStruct { x: int, y: int, } impl MyStruct { fn next(&mut self) -> Option<int>
} pub fn main() { let mut bogus = MyStruct { x: 1, y: 2, }; for x in bogus { //~ ERROR has type `MyStruct` which does not implement the `Iterator` trait drop(x); } }
{ Some(self.x) }
identifier_body
filters.rs
// Copyright (C) 2020 Jason Ish // // 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. use crate::eve::eve::EveJson; use crate::prelude::*; use crate::rules::RuleMap; use serde_json::json; use std::sync::Arc;
CustomFieldFilter(CustomFieldFilter), AddRuleFilter(AddRuleFilter), Filters(Arc<Vec<EveFilter>>), } impl EveFilter { pub fn run(&self, event: &mut EveJson) { match self { EveFilter::GeoIP(geoip) => { geoip.add_geoip_to_eve(event); } EveFilter::EveBoxMetadataFilter(filter) => { filter.run(event); } EveFilter::CustomFieldFilter(filter) => { filter.run(event); } EveFilter::AddRuleFilter(filter) => { filter.run(event); } EveFilter::Filters(filters) => { for filter in filters.iter() { filter.run(event); } } } } } #[derive(Debug, Default)] pub struct EveBoxMetadataFilter { pub filename: Option<String>, } impl EveBoxMetadataFilter { pub fn run(&self, event: &mut EveJson) { // Create the "evebox" object. if let EveJson::Null = event["evebox"] { event["evebox"] = json!({}); } // Add fields to the EveBox object. if let EveJson::Object(_) = &event["evebox"] { if let Some(filename) = &self.filename { event["evebox"]["filename"] = filename.to_string().into(); } } // Add a tags object. event["tags"] = serde_json::Value::Array(vec![]); } } impl From<EveBoxMetadataFilter> for EveFilter { fn from(filter: EveBoxMetadataFilter) -> Self { EveFilter::EveBoxMetadataFilter(filter) } } pub struct CustomFieldFilter { pub field: String, pub value: String, } impl CustomFieldFilter { pub fn new(field: &str, value: &str) -> Self { Self { field: field.to_string(), value: value.to_string(), } } pub fn run(&self, event: &mut EveJson) { event[&self.field] = self.value.clone().into(); } } impl From<CustomFieldFilter> for EveFilter { fn from(filter: CustomFieldFilter) -> Self { EveFilter::CustomFieldFilter(filter) } } pub struct AddRuleFilter { pub map: Arc<RuleMap>, } impl AddRuleFilter { pub fn run(&self, event: &mut EveJson) { if let EveJson::String(_) = event["alert"]["rule"] { return; } if let Some(sid) = &event["alert"]["signature_id"].as_u64() { if let Some(rule) = self.map.find_by_sid(*sid) { event["alert"]["rule"] = rule.into(); } else { trace!("Failed to find rule for SID {}", sid); } } } }
pub enum EveFilter { GeoIP(crate::geoip::GeoIP), EveBoxMetadataFilter(EveBoxMetadataFilter),
random_line_split
filters.rs
// Copyright (C) 2020 Jason Ish // // 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. use crate::eve::eve::EveJson; use crate::prelude::*; use crate::rules::RuleMap; use serde_json::json; use std::sync::Arc; pub enum EveFilter { GeoIP(crate::geoip::GeoIP), EveBoxMetadataFilter(EveBoxMetadataFilter), CustomFieldFilter(CustomFieldFilter), AddRuleFilter(AddRuleFilter), Filters(Arc<Vec<EveFilter>>), } impl EveFilter { pub fn run(&self, event: &mut EveJson) { match self { EveFilter::GeoIP(geoip) => { geoip.add_geoip_to_eve(event); } EveFilter::EveBoxMetadataFilter(filter) => { filter.run(event); } EveFilter::CustomFieldFilter(filter) => { filter.run(event); } EveFilter::AddRuleFilter(filter) => { filter.run(event); } EveFilter::Filters(filters) => { for filter in filters.iter() { filter.run(event); } } } } } #[derive(Debug, Default)] pub struct EveBoxMetadataFilter { pub filename: Option<String>, } impl EveBoxMetadataFilter { pub fn run(&self, event: &mut EveJson) { // Create the "evebox" object. if let EveJson::Null = event["evebox"] { event["evebox"] = json!({}); } // Add fields to the EveBox object. if let EveJson::Object(_) = &event["evebox"] { if let Some(filename) = &self.filename { event["evebox"]["filename"] = filename.to_string().into(); } } // Add a tags object. event["tags"] = serde_json::Value::Array(vec![]); } } impl From<EveBoxMetadataFilter> for EveFilter { fn from(filter: EveBoxMetadataFilter) -> Self { EveFilter::EveBoxMetadataFilter(filter) } } pub struct
{ pub field: String, pub value: String, } impl CustomFieldFilter { pub fn new(field: &str, value: &str) -> Self { Self { field: field.to_string(), value: value.to_string(), } } pub fn run(&self, event: &mut EveJson) { event[&self.field] = self.value.clone().into(); } } impl From<CustomFieldFilter> for EveFilter { fn from(filter: CustomFieldFilter) -> Self { EveFilter::CustomFieldFilter(filter) } } pub struct AddRuleFilter { pub map: Arc<RuleMap>, } impl AddRuleFilter { pub fn run(&self, event: &mut EveJson) { if let EveJson::String(_) = event["alert"]["rule"] { return; } if let Some(sid) = &event["alert"]["signature_id"].as_u64() { if let Some(rule) = self.map.find_by_sid(*sid) { event["alert"]["rule"] = rule.into(); } else { trace!("Failed to find rule for SID {}", sid); } } } }
CustomFieldFilter
identifier_name
filters.rs
// Copyright (C) 2020 Jason Ish // // 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. use crate::eve::eve::EveJson; use crate::prelude::*; use crate::rules::RuleMap; use serde_json::json; use std::sync::Arc; pub enum EveFilter { GeoIP(crate::geoip::GeoIP), EveBoxMetadataFilter(EveBoxMetadataFilter), CustomFieldFilter(CustomFieldFilter), AddRuleFilter(AddRuleFilter), Filters(Arc<Vec<EveFilter>>), } impl EveFilter { pub fn run(&self, event: &mut EveJson) { match self { EveFilter::GeoIP(geoip) => { geoip.add_geoip_to_eve(event); } EveFilter::EveBoxMetadataFilter(filter) => { filter.run(event); } EveFilter::CustomFieldFilter(filter) =>
EveFilter::AddRuleFilter(filter) => { filter.run(event); } EveFilter::Filters(filters) => { for filter in filters.iter() { filter.run(event); } } } } } #[derive(Debug, Default)] pub struct EveBoxMetadataFilter { pub filename: Option<String>, } impl EveBoxMetadataFilter { pub fn run(&self, event: &mut EveJson) { // Create the "evebox" object. if let EveJson::Null = event["evebox"] { event["evebox"] = json!({}); } // Add fields to the EveBox object. if let EveJson::Object(_) = &event["evebox"] { if let Some(filename) = &self.filename { event["evebox"]["filename"] = filename.to_string().into(); } } // Add a tags object. event["tags"] = serde_json::Value::Array(vec![]); } } impl From<EveBoxMetadataFilter> for EveFilter { fn from(filter: EveBoxMetadataFilter) -> Self { EveFilter::EveBoxMetadataFilter(filter) } } pub struct CustomFieldFilter { pub field: String, pub value: String, } impl CustomFieldFilter { pub fn new(field: &str, value: &str) -> Self { Self { field: field.to_string(), value: value.to_string(), } } pub fn run(&self, event: &mut EveJson) { event[&self.field] = self.value.clone().into(); } } impl From<CustomFieldFilter> for EveFilter { fn from(filter: CustomFieldFilter) -> Self { EveFilter::CustomFieldFilter(filter) } } pub struct AddRuleFilter { pub map: Arc<RuleMap>, } impl AddRuleFilter { pub fn run(&self, event: &mut EveJson) { if let EveJson::String(_) = event["alert"]["rule"] { return; } if let Some(sid) = &event["alert"]["signature_id"].as_u64() { if let Some(rule) = self.map.find_by_sid(*sid) { event["alert"]["rule"] = rule.into(); } else { trace!("Failed to find rule for SID {}", sid); } } } }
{ filter.run(event); }
conditional_block
filters.rs
// Copyright (C) 2020 Jason Ish // // 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. use crate::eve::eve::EveJson; use crate::prelude::*; use crate::rules::RuleMap; use serde_json::json; use std::sync::Arc; pub enum EveFilter { GeoIP(crate::geoip::GeoIP), EveBoxMetadataFilter(EveBoxMetadataFilter), CustomFieldFilter(CustomFieldFilter), AddRuleFilter(AddRuleFilter), Filters(Arc<Vec<EveFilter>>), } impl EveFilter { pub fn run(&self, event: &mut EveJson) { match self { EveFilter::GeoIP(geoip) => { geoip.add_geoip_to_eve(event); } EveFilter::EveBoxMetadataFilter(filter) => { filter.run(event); } EveFilter::CustomFieldFilter(filter) => { filter.run(event); } EveFilter::AddRuleFilter(filter) => { filter.run(event); } EveFilter::Filters(filters) => { for filter in filters.iter() { filter.run(event); } } } } } #[derive(Debug, Default)] pub struct EveBoxMetadataFilter { pub filename: Option<String>, } impl EveBoxMetadataFilter { pub fn run(&self, event: &mut EveJson) { // Create the "evebox" object. if let EveJson::Null = event["evebox"] { event["evebox"] = json!({}); } // Add fields to the EveBox object. if let EveJson::Object(_) = &event["evebox"] { if let Some(filename) = &self.filename { event["evebox"]["filename"] = filename.to_string().into(); } } // Add a tags object. event["tags"] = serde_json::Value::Array(vec![]); } } impl From<EveBoxMetadataFilter> for EveFilter { fn from(filter: EveBoxMetadataFilter) -> Self { EveFilter::EveBoxMetadataFilter(filter) } } pub struct CustomFieldFilter { pub field: String, pub value: String, } impl CustomFieldFilter { pub fn new(field: &str, value: &str) -> Self { Self { field: field.to_string(), value: value.to_string(), } } pub fn run(&self, event: &mut EveJson) { event[&self.field] = self.value.clone().into(); } } impl From<CustomFieldFilter> for EveFilter { fn from(filter: CustomFieldFilter) -> Self { EveFilter::CustomFieldFilter(filter) } } pub struct AddRuleFilter { pub map: Arc<RuleMap>, } impl AddRuleFilter { pub fn run(&self, event: &mut EveJson)
}
{ if let EveJson::String(_) = event["alert"]["rule"] { return; } if let Some(sid) = &event["alert"]["signature_id"].as_u64() { if let Some(rule) = self.map.find_by_sid(*sid) { event["alert"]["rule"] = rule.into(); } else { trace!("Failed to find rule for SID {}", sid); } } }
identifier_body
small-enums-with-fields.rs
// Copyright 2013 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
use std::mem::size_of; #[deriving(Eq, Show)] enum Either<T, U> { Left(T), Right(U) } macro_rules! check { ($t:ty, $sz:expr, $($e:expr, $s:expr),*) => {{ assert_eq!(size_of::<$t>(), $sz); $({ static S: $t = $e; let v: $t = $e; assert_eq!(S, v); assert_eq!(format!("{:?}", v), ~$s); assert_eq!(format!("{:?}", S), ~$s); });* }} } pub fn main() { check!(Option<u8>, 2, None, "None", Some(129u8), "Some(129u8)"); check!(Option<i16>, 4, None, "None", Some(-20000i16), "Some(-20000i16)"); check!(Either<u8, i8>, 2, Left(132u8), "Left(132u8)", Right(-32i8), "Right(-32i8)"); check!(Either<u8, i16>, 4, Left(132u8), "Left(132u8)", Right(-20000i16), "Right(-20000i16)"); }
// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(macro_rules)]
random_line_split
small-enums-with-fields.rs
// Copyright 2013 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. #![feature(macro_rules)] use std::mem::size_of; #[deriving(Eq, Show)] enum
<T, U> { Left(T), Right(U) } macro_rules! check { ($t:ty, $sz:expr, $($e:expr, $s:expr),*) => {{ assert_eq!(size_of::<$t>(), $sz); $({ static S: $t = $e; let v: $t = $e; assert_eq!(S, v); assert_eq!(format!("{:?}", v), ~$s); assert_eq!(format!("{:?}", S), ~$s); });* }} } pub fn main() { check!(Option<u8>, 2, None, "None", Some(129u8), "Some(129u8)"); check!(Option<i16>, 4, None, "None", Some(-20000i16), "Some(-20000i16)"); check!(Either<u8, i8>, 2, Left(132u8), "Left(132u8)", Right(-32i8), "Right(-32i8)"); check!(Either<u8, i16>, 4, Left(132u8), "Left(132u8)", Right(-20000i16), "Right(-20000i16)"); }
Either
identifier_name
generator.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <[email protected]>, // Nathan Zadoks <[email protected]> // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. extern crate fringe; use fringe::{SliceStack, OwnedStack, OsStack}; use fringe::generator::{Generator, Yielder}; fn add_one_fn(yielder: &mut Yielder<i32, i32>, mut input: i32) { loop { if input == 0 { break } input = yielder.suspend(input + 1) } } fn new_add_one() -> Generator<i32, i32, OsStack> { let stack = OsStack::new(0).unwrap(); Generator::new(stack, add_one_fn) } #[test] fn generator() { let mut add_one = new_add_one(); assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); assert_eq!(add_one.resume(0), None); } #[test] fn move_after_new() { let mut add_one = new_add_one(); assert_eq!(add_one.resume(1), Some(2)); #[inline(never)] fn run_moved(mut add_one: Generator<i32, i32, OsStack>) { assert_eq!(add_one.resume(2), Some(3)); assert_eq!(add_one.resume(3), Some(4)); assert_eq!(add_one.resume(0), None); } run_moved(add_one); } #[test] #[should_panic] fn panic_safety() { struct Wrapper { gen: Generator<(), (), OsStack> } impl Drop for Wrapper { fn drop(&mut self) { self.gen.resume(()); } } let stack = OsStack::new(4 << 20).unwrap(); let gen = Generator::new(stack, move |_yielder, ()| { panic!("foo") }); let mut wrapper = Wrapper { gen: gen }; wrapper.gen.resume(()); } #[test]
let stack = SliceStack(&mut memory); let mut add_one = unsafe { Generator::unsafe_new(stack, add_one_fn) }; assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); } #[test] fn with_owned_stack() { let stack = OwnedStack::new(1024); let mut add_one = unsafe { Generator::unsafe_new(stack, add_one_fn) }; assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); } #[test] fn forget_yielded() { struct Dropper(*mut bool); unsafe impl Send for Dropper {} impl Drop for Dropper { fn drop(&mut self) { unsafe { if *self.0 { panic!("double drop!") } *self.0 = true; } } } let stack = fringe::OsStack::new(1<<16).unwrap(); let mut generator = Generator::new(stack, |yielder, ()| { let mut flag = false; yielder.suspend(Dropper(&mut flag as *mut bool)); }); generator.resume(()); generator.resume(()); }
fn with_slice_stack() { let mut memory = [0; 1024];
random_line_split
generator.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <[email protected]>, // Nathan Zadoks <[email protected]> // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. extern crate fringe; use fringe::{SliceStack, OwnedStack, OsStack}; use fringe::generator::{Generator, Yielder}; fn add_one_fn(yielder: &mut Yielder<i32, i32>, mut input: i32) { loop { if input == 0 { break } input = yielder.suspend(input + 1) } } fn new_add_one() -> Generator<i32, i32, OsStack> { let stack = OsStack::new(0).unwrap(); Generator::new(stack, add_one_fn) } #[test] fn generator() { let mut add_one = new_add_one(); assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); assert_eq!(add_one.resume(0), None); } #[test] fn move_after_new() { let mut add_one = new_add_one(); assert_eq!(add_one.resume(1), Some(2)); #[inline(never)] fn run_moved(mut add_one: Generator<i32, i32, OsStack>)
run_moved(add_one); } #[test] #[should_panic] fn panic_safety() { struct Wrapper { gen: Generator<(), (), OsStack> } impl Drop for Wrapper { fn drop(&mut self) { self.gen.resume(()); } } let stack = OsStack::new(4 << 20).unwrap(); let gen = Generator::new(stack, move |_yielder, ()| { panic!("foo") }); let mut wrapper = Wrapper { gen: gen }; wrapper.gen.resume(()); } #[test] fn with_slice_stack() { let mut memory = [0; 1024]; let stack = SliceStack(&mut memory); let mut add_one = unsafe { Generator::unsafe_new(stack, add_one_fn) }; assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); } #[test] fn with_owned_stack() { let stack = OwnedStack::new(1024); let mut add_one = unsafe { Generator::unsafe_new(stack, add_one_fn) }; assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); } #[test] fn forget_yielded() { struct Dropper(*mut bool); unsafe impl Send for Dropper {} impl Drop for Dropper { fn drop(&mut self) { unsafe { if *self.0 { panic!("double drop!") } *self.0 = true; } } } let stack = fringe::OsStack::new(1<<16).unwrap(); let mut generator = Generator::new(stack, |yielder, ()| { let mut flag = false; yielder.suspend(Dropper(&mut flag as *mut bool)); }); generator.resume(()); generator.resume(()); }
{ assert_eq!(add_one.resume(2), Some(3)); assert_eq!(add_one.resume(3), Some(4)); assert_eq!(add_one.resume(0), None); }
identifier_body
generator.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <[email protected]>, // Nathan Zadoks <[email protected]> // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. extern crate fringe; use fringe::{SliceStack, OwnedStack, OsStack}; use fringe::generator::{Generator, Yielder}; fn add_one_fn(yielder: &mut Yielder<i32, i32>, mut input: i32) { loop { if input == 0 { break } input = yielder.suspend(input + 1) } } fn new_add_one() -> Generator<i32, i32, OsStack> { let stack = OsStack::new(0).unwrap(); Generator::new(stack, add_one_fn) } #[test] fn generator() { let mut add_one = new_add_one(); assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); assert_eq!(add_one.resume(0), None); } #[test] fn move_after_new() { let mut add_one = new_add_one(); assert_eq!(add_one.resume(1), Some(2)); #[inline(never)] fn run_moved(mut add_one: Generator<i32, i32, OsStack>) { assert_eq!(add_one.resume(2), Some(3)); assert_eq!(add_one.resume(3), Some(4)); assert_eq!(add_one.resume(0), None); } run_moved(add_one); } #[test] #[should_panic] fn panic_safety() { struct Wrapper { gen: Generator<(), (), OsStack> } impl Drop for Wrapper { fn drop(&mut self) { self.gen.resume(()); } } let stack = OsStack::new(4 << 20).unwrap(); let gen = Generator::new(stack, move |_yielder, ()| { panic!("foo") }); let mut wrapper = Wrapper { gen: gen }; wrapper.gen.resume(()); } #[test] fn with_slice_stack() { let mut memory = [0; 1024]; let stack = SliceStack(&mut memory); let mut add_one = unsafe { Generator::unsafe_new(stack, add_one_fn) }; assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); } #[test] fn with_owned_stack() { let stack = OwnedStack::new(1024); let mut add_one = unsafe { Generator::unsafe_new(stack, add_one_fn) }; assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); } #[test] fn forget_yielded() { struct Dropper(*mut bool); unsafe impl Send for Dropper {} impl Drop for Dropper { fn drop(&mut self) { unsafe { if *self.0
*self.0 = true; } } } let stack = fringe::OsStack::new(1<<16).unwrap(); let mut generator = Generator::new(stack, |yielder, ()| { let mut flag = false; yielder.suspend(Dropper(&mut flag as *mut bool)); }); generator.resume(()); generator.resume(()); }
{ panic!("double drop!") }
conditional_block
generator.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <[email protected]>, // Nathan Zadoks <[email protected]> // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. extern crate fringe; use fringe::{SliceStack, OwnedStack, OsStack}; use fringe::generator::{Generator, Yielder}; fn add_one_fn(yielder: &mut Yielder<i32, i32>, mut input: i32) { loop { if input == 0 { break } input = yielder.suspend(input + 1) } } fn new_add_one() -> Generator<i32, i32, OsStack> { let stack = OsStack::new(0).unwrap(); Generator::new(stack, add_one_fn) } #[test] fn generator() { let mut add_one = new_add_one(); assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); assert_eq!(add_one.resume(0), None); } #[test] fn
() { let mut add_one = new_add_one(); assert_eq!(add_one.resume(1), Some(2)); #[inline(never)] fn run_moved(mut add_one: Generator<i32, i32, OsStack>) { assert_eq!(add_one.resume(2), Some(3)); assert_eq!(add_one.resume(3), Some(4)); assert_eq!(add_one.resume(0), None); } run_moved(add_one); } #[test] #[should_panic] fn panic_safety() { struct Wrapper { gen: Generator<(), (), OsStack> } impl Drop for Wrapper { fn drop(&mut self) { self.gen.resume(()); } } let stack = OsStack::new(4 << 20).unwrap(); let gen = Generator::new(stack, move |_yielder, ()| { panic!("foo") }); let mut wrapper = Wrapper { gen: gen }; wrapper.gen.resume(()); } #[test] fn with_slice_stack() { let mut memory = [0; 1024]; let stack = SliceStack(&mut memory); let mut add_one = unsafe { Generator::unsafe_new(stack, add_one_fn) }; assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); } #[test] fn with_owned_stack() { let stack = OwnedStack::new(1024); let mut add_one = unsafe { Generator::unsafe_new(stack, add_one_fn) }; assert_eq!(add_one.resume(1), Some(2)); assert_eq!(add_one.resume(2), Some(3)); } #[test] fn forget_yielded() { struct Dropper(*mut bool); unsafe impl Send for Dropper {} impl Drop for Dropper { fn drop(&mut self) { unsafe { if *self.0 { panic!("double drop!") } *self.0 = true; } } } let stack = fringe::OsStack::new(1<<16).unwrap(); let mut generator = Generator::new(stack, |yielder, ()| { let mut flag = false; yielder.suspend(Dropper(&mut flag as *mut bool)); }); generator.resume(()); generator.resume(()); }
move_after_new
identifier_name
build.rs
// Copyright 2016 The Kythe Authors. All rights reserved. // // 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. use std::env; use std::fs; use std::path::Path; fn main()
{ let out_dir = env::var("OUT_DIR").expect("OUT_DIR variable must be set"); let dep_dir = Path::new(&out_dir).join("../../../deps"); let cargo_home = env::var("CARGO_HOME").expect("CARGO_HOME variable must be set"); let so_folder = Path::new(&cargo_home).join("kythe"); let indexer = fs::read_dir(dep_dir).expect("deps folder not found").find(|entry| { entry.as_ref().unwrap().file_name().to_string_lossy().starts_with("libkythe_indexer") }); let indexer = indexer.expect("indexer not found").unwrap(); fs::create_dir_all(so_folder.as_path()).expect("failed to create kythe directory"); fs::copy(indexer.path(), so_folder.join(indexer.file_name())) .expect("failed to copy indexer to kythe directory"); }
identifier_body
build.rs
// Copyright 2016 The Kythe Authors. All rights reserved. // // 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. use std::env; use std::fs; use std::path::Path; fn
() { let out_dir = env::var("OUT_DIR").expect("OUT_DIR variable must be set"); let dep_dir = Path::new(&out_dir).join("../../../deps"); let cargo_home = env::var("CARGO_HOME").expect("CARGO_HOME variable must be set"); let so_folder = Path::new(&cargo_home).join("kythe"); let indexer = fs::read_dir(dep_dir).expect("deps folder not found").find(|entry| { entry.as_ref().unwrap().file_name().to_string_lossy().starts_with("libkythe_indexer") }); let indexer = indexer.expect("indexer not found").unwrap(); fs::create_dir_all(so_folder.as_path()).expect("failed to create kythe directory"); fs::copy(indexer.path(), so_folder.join(indexer.file_name())) .expect("failed to copy indexer to kythe directory"); }
main
identifier_name
build.rs
// Copyright 2016 The Kythe Authors. All rights reserved. // // 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. use std::env; use std::fs; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").expect("OUT_DIR variable must be set"); let dep_dir = Path::new(&out_dir).join("../../../deps"); let cargo_home = env::var("CARGO_HOME").expect("CARGO_HOME variable must be set"); let so_folder = Path::new(&cargo_home).join("kythe"); let indexer = fs::read_dir(dep_dir).expect("deps folder not found").find(|entry| { entry.as_ref().unwrap().file_name().to_string_lossy().starts_with("libkythe_indexer") }); let indexer = indexer.expect("indexer not found").unwrap();
.expect("failed to copy indexer to kythe directory"); }
fs::create_dir_all(so_folder.as_path()).expect("failed to create kythe directory"); fs::copy(indexer.path(), so_folder.join(indexer.file_name()))
random_line_split
count_fast.rs
use crate::word_count::WordCount; use super::WordCountable; #[cfg(any(target_os = "linux", target_os = "android"))] use std::fs::OpenOptions; use std::io::{self, ErrorKind, Read}; #[cfg(unix)] use libc::S_IFREG; #[cfg(unix)] use nix::sys::stat; #[cfg(any(target_os = "linux", target_os = "android"))] use std::os::unix::io::AsRawFd; #[cfg(any(target_os = "linux", target_os = "android"))] use libc::S_IFIFO; #[cfg(any(target_os = "linux", target_os = "android"))] use uucore::pipes::{pipe, splice, splice_exact}; const BUF_SIZE: usize = 16 * 1024; #[cfg(any(target_os = "linux", target_os = "android"))] const SPLICE_SIZE: usize = 128 * 1024; /// This is a Linux-specific function to count the number of bytes using the /// `splice` system call, which is faster than using `read`. /// /// On error it returns the number of bytes it did manage to read, since the /// caller will fall back to a simpler method. #[inline] #[cfg(any(target_os = "linux", target_os = "android"))] fn count_bytes_using_splice(fd: &impl AsRawFd) -> Result<usize, usize> { let null_file = OpenOptions::new() .write(true) .open("/dev/null") .map_err(|_| 0_usize)?; let null_rdev = stat::fstat(null_file.as_raw_fd()) .map_err(|_| 0_usize)? .st_rdev; if (stat::major(null_rdev), stat::minor(null_rdev))!= (1, 3) { // This is not a proper /dev/null, writing to it is probably bad // Bit of an edge case, but it has been known to happen return Err(0); } let (pipe_rd, pipe_wr) = pipe().map_err(|_| 0_usize)?; let mut byte_count = 0; loop { match splice(fd, &pipe_wr, SPLICE_SIZE) { Ok(0) => break, Ok(res) => { byte_count += res; // Silent the warning as we want to the error message #[allow(clippy::question_mark)] if splice_exact(&pipe_rd, &null_file, res).is_err() { return Err(byte_count); } } Err(_) => return Err(byte_count), }; } Ok(byte_count) } /// In the special case where we only need to count the number of bytes. There /// are several optimizations we can do: /// 1. On Unix, we can simply `stat` the file if it is regular. /// 2. On Linux -- if the above did not work -- we can use splice to count /// the number of bytes if the file is a FIFO. /// 3. Otherwise, we just read normally, but without the overhead of counting /// other things such as lines and words. #[inline] pub(crate) fn count_bytes_fast<T: WordCountable>(handle: &mut T) -> (usize, Option<io::Error>) { let mut byte_count = 0; #[cfg(unix)] { let fd = handle.as_raw_fd(); if let Ok(stat) = stat::fstat(fd) { // If the file is regular, then the `st_size` should hold // the file's size in bytes. // If stat.st_size = 0 then // - either the size is 0 // - or the size is unknown. // The second case happens for files in pseudo-filesystems. For // example with /proc/version and /sys/kernel/profiling. So, // if it is 0 we don't report that and instead do a full read. if (stat.st_mode & S_IFREG)!= 0 && stat.st_size > 0 { return (stat.st_size as usize, None); } #[cfg(any(target_os = "linux", target_os = "android"))] { // Else, if we're on Linux and our file is a FIFO pipe // (or stdin), we use splice to count the number of bytes. if (stat.st_mode & S_IFIFO)!= 0 { match count_bytes_using_splice(handle) { Ok(n) => return (n, None), Err(n) => byte_count = n, } } } } } // Fall back on `read`, but without the overhead of counting words and lines. let mut buf = [0_u8; BUF_SIZE]; loop { match handle.read(&mut buf) { Ok(0) => return (byte_count, None), Ok(n) => { byte_count += n; } Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return (byte_count, Some(e)), } } } pub(crate) fn
<R: Read>( handle: &mut R, ) -> (WordCount, Option<io::Error>) { let mut total = WordCount::default(); let mut buf = [0; BUF_SIZE]; loop { match handle.read(&mut buf) { Ok(0) => return (total, None), Ok(n) => { total.bytes += n; total.lines += bytecount::count(&buf[..n], b'\n'); } Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return (total, Some(e)), } } }
count_bytes_and_lines_fast
identifier_name
count_fast.rs
use crate::word_count::WordCount; use super::WordCountable; #[cfg(any(target_os = "linux", target_os = "android"))] use std::fs::OpenOptions; use std::io::{self, ErrorKind, Read}; #[cfg(unix)] use libc::S_IFREG; #[cfg(unix)] use nix::sys::stat; #[cfg(any(target_os = "linux", target_os = "android"))] use std::os::unix::io::AsRawFd; #[cfg(any(target_os = "linux", target_os = "android"))] use libc::S_IFIFO; #[cfg(any(target_os = "linux", target_os = "android"))] use uucore::pipes::{pipe, splice, splice_exact}; const BUF_SIZE: usize = 16 * 1024; #[cfg(any(target_os = "linux", target_os = "android"))] const SPLICE_SIZE: usize = 128 * 1024; /// This is a Linux-specific function to count the number of bytes using the /// `splice` system call, which is faster than using `read`. /// /// On error it returns the number of bytes it did manage to read, since the /// caller will fall back to a simpler method. #[inline] #[cfg(any(target_os = "linux", target_os = "android"))] fn count_bytes_using_splice(fd: &impl AsRawFd) -> Result<usize, usize> { let null_file = OpenOptions::new() .write(true) .open("/dev/null") .map_err(|_| 0_usize)?; let null_rdev = stat::fstat(null_file.as_raw_fd()) .map_err(|_| 0_usize)? .st_rdev; if (stat::major(null_rdev), stat::minor(null_rdev))!= (1, 3) { // This is not a proper /dev/null, writing to it is probably bad // Bit of an edge case, but it has been known to happen return Err(0); } let (pipe_rd, pipe_wr) = pipe().map_err(|_| 0_usize)?; let mut byte_count = 0; loop { match splice(fd, &pipe_wr, SPLICE_SIZE) { Ok(0) => break, Ok(res) => { byte_count += res; // Silent the warning as we want to the error message #[allow(clippy::question_mark)] if splice_exact(&pipe_rd, &null_file, res).is_err() { return Err(byte_count); } } Err(_) => return Err(byte_count), }; } Ok(byte_count) } /// In the special case where we only need to count the number of bytes. There /// are several optimizations we can do: /// 1. On Unix, we can simply `stat` the file if it is regular. /// 2. On Linux -- if the above did not work -- we can use splice to count /// the number of bytes if the file is a FIFO. /// 3. Otherwise, we just read normally, but without the overhead of counting /// other things such as lines and words. #[inline] pub(crate) fn count_bytes_fast<T: WordCountable>(handle: &mut T) -> (usize, Option<io::Error>) { let mut byte_count = 0; #[cfg(unix)] { let fd = handle.as_raw_fd(); if let Ok(stat) = stat::fstat(fd) { // If the file is regular, then the `st_size` should hold // the file's size in bytes. // If stat.st_size = 0 then // - either the size is 0 // - or the size is unknown. // The second case happens for files in pseudo-filesystems. For // example with /proc/version and /sys/kernel/profiling. So, // if it is 0 we don't report that and instead do a full read. if (stat.st_mode & S_IFREG)!= 0 && stat.st_size > 0 { return (stat.st_size as usize, None); } #[cfg(any(target_os = "linux", target_os = "android"))] { // Else, if we're on Linux and our file is a FIFO pipe // (or stdin), we use splice to count the number of bytes. if (stat.st_mode & S_IFIFO)!= 0 { match count_bytes_using_splice(handle) { Ok(n) => return (n, None), Err(n) => byte_count = n, } } } } } // Fall back on `read`, but without the overhead of counting words and lines. let mut buf = [0_u8; BUF_SIZE]; loop { match handle.read(&mut buf) { Ok(0) => return (byte_count, None), Ok(n) =>
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return (byte_count, Some(e)), } } } pub(crate) fn count_bytes_and_lines_fast<R: Read>( handle: &mut R, ) -> (WordCount, Option<io::Error>) { let mut total = WordCount::default(); let mut buf = [0; BUF_SIZE]; loop { match handle.read(&mut buf) { Ok(0) => return (total, None), Ok(n) => { total.bytes += n; total.lines += bytecount::count(&buf[..n], b'\n'); } Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return (total, Some(e)), } } }
{ byte_count += n; }
conditional_block
count_fast.rs
use crate::word_count::WordCount; use super::WordCountable; #[cfg(any(target_os = "linux", target_os = "android"))] use std::fs::OpenOptions; use std::io::{self, ErrorKind, Read}; #[cfg(unix)] use libc::S_IFREG; #[cfg(unix)] use nix::sys::stat; #[cfg(any(target_os = "linux", target_os = "android"))] use std::os::unix::io::AsRawFd; #[cfg(any(target_os = "linux", target_os = "android"))] use libc::S_IFIFO; #[cfg(any(target_os = "linux", target_os = "android"))] use uucore::pipes::{pipe, splice, splice_exact}; const BUF_SIZE: usize = 16 * 1024; #[cfg(any(target_os = "linux", target_os = "android"))] const SPLICE_SIZE: usize = 128 * 1024; /// This is a Linux-specific function to count the number of bytes using the /// `splice` system call, which is faster than using `read`. /// /// On error it returns the number of bytes it did manage to read, since the /// caller will fall back to a simpler method. #[inline] #[cfg(any(target_os = "linux", target_os = "android"))] fn count_bytes_using_splice(fd: &impl AsRawFd) -> Result<usize, usize> { let null_file = OpenOptions::new() .write(true) .open("/dev/null") .map_err(|_| 0_usize)?; let null_rdev = stat::fstat(null_file.as_raw_fd()) .map_err(|_| 0_usize)? .st_rdev; if (stat::major(null_rdev), stat::minor(null_rdev))!= (1, 3) { // This is not a proper /dev/null, writing to it is probably bad // Bit of an edge case, but it has been known to happen return Err(0); } let (pipe_rd, pipe_wr) = pipe().map_err(|_| 0_usize)?; let mut byte_count = 0; loop { match splice(fd, &pipe_wr, SPLICE_SIZE) { Ok(0) => break, Ok(res) => { byte_count += res; // Silent the warning as we want to the error message #[allow(clippy::question_mark)] if splice_exact(&pipe_rd, &null_file, res).is_err() { return Err(byte_count); } } Err(_) => return Err(byte_count), }; } Ok(byte_count) } /// In the special case where we only need to count the number of bytes. There /// are several optimizations we can do: /// 1. On Unix, we can simply `stat` the file if it is regular. /// 2. On Linux -- if the above did not work -- we can use splice to count /// the number of bytes if the file is a FIFO. /// 3. Otherwise, we just read normally, but without the overhead of counting /// other things such as lines and words. #[inline] pub(crate) fn count_bytes_fast<T: WordCountable>(handle: &mut T) -> (usize, Option<io::Error>)
// Else, if we're on Linux and our file is a FIFO pipe // (or stdin), we use splice to count the number of bytes. if (stat.st_mode & S_IFIFO)!= 0 { match count_bytes_using_splice(handle) { Ok(n) => return (n, None), Err(n) => byte_count = n, } } } } } // Fall back on `read`, but without the overhead of counting words and lines. let mut buf = [0_u8; BUF_SIZE]; loop { match handle.read(&mut buf) { Ok(0) => return (byte_count, None), Ok(n) => { byte_count += n; } Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return (byte_count, Some(e)), } } } pub(crate) fn count_bytes_and_lines_fast<R: Read>( handle: &mut R, ) -> (WordCount, Option<io::Error>) { let mut total = WordCount::default(); let mut buf = [0; BUF_SIZE]; loop { match handle.read(&mut buf) { Ok(0) => return (total, None), Ok(n) => { total.bytes += n; total.lines += bytecount::count(&buf[..n], b'\n'); } Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return (total, Some(e)), } } }
{ let mut byte_count = 0; #[cfg(unix)] { let fd = handle.as_raw_fd(); if let Ok(stat) = stat::fstat(fd) { // If the file is regular, then the `st_size` should hold // the file's size in bytes. // If stat.st_size = 0 then // - either the size is 0 // - or the size is unknown. // The second case happens for files in pseudo-filesystems. For // example with /proc/version and /sys/kernel/profiling. So, // if it is 0 we don't report that and instead do a full read. if (stat.st_mode & S_IFREG) != 0 && stat.st_size > 0 { return (stat.st_size as usize, None); } #[cfg(any(target_os = "linux", target_os = "android"))] {
identifier_body