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
callback.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/. */ //! Base classes to work with IDL callbacks. use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::global_root_from_object; use dom::bindings::reflector::Reflectable; use js::jsapi::GetGlobalForObjectCrossCompartment; use js::jsapi::JSAutoCompartment; use js::jsapi::{Heap, MutableHandleObject, RootedObject, RootedValue}; use js::jsapi::{IsCallable, JSContext, JSObject, JS_WrapObject}; use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment}; use js::jsapi::{JS_BeginRequest, JS_EndRequest}; use js::jsapi::{JS_GetProperty, JS_IsExceptionPending, JS_ReportPendingException}; use js::jsapi::{JS_RestoreFrameChain, JS_SaveFrameChain}; use js::jsval::{JSVal, UndefinedValue}; use std::default::Default; use std::ffi::CString; use std::intrinsics::return_address; use std::ptr; use std::rc::Rc; /// The exception handling used for a call. #[derive(Copy, Clone, PartialEq)] pub enum ExceptionHandling { /// Report any exception and don't throw it to the caller code. Report, /// Throw any exception to the caller code. Rethrow, } /// A common base class for representing IDL callback function types. #[derive(JSTraceable, PartialEq)] pub struct CallbackFunction { object: CallbackObject, } impl CallbackFunction { /// Create a new `CallbackFunction` for this object. pub fn new() -> CallbackFunction { CallbackFunction { object: CallbackObject { callback: Heap::default(), }, } } /// Initialize the callback function with a value. /// Should be called once this object is done moving. pub fn init(&mut self, callback: *mut JSObject) { self.object.callback.set(callback); } } /// A common base class for representing IDL callback interface types. #[derive(JSTraceable, PartialEq)] pub struct CallbackInterface { object: CallbackObject, } /// A common base class for representing IDL callback function and /// callback interface types. #[allow(raw_pointer_derive)] #[derive(JSTraceable)] struct CallbackObject { /// The underlying `JSObject`. callback: Heap<*mut JSObject>, } impl PartialEq for CallbackObject { fn eq(&self, other: &CallbackObject) -> bool { self.callback.get() == other.callback.get() } } /// A trait to be implemented by concrete IDL callback function and /// callback interface types. pub trait CallbackContainer { /// Create a new CallbackContainer object for the given `JSObject`. fn new(callback: *mut JSObject) -> Rc<Self>; /// Returns the underlying `JSObject`. fn callback(&self) -> *mut JSObject; } impl CallbackInterface { /// Returns the underlying `JSObject`. pub fn callback(&self) -> *mut JSObject { self.object.callback.get() } } impl CallbackFunction { /// Returns the underlying `JSObject`. pub fn callback(&self) -> *mut JSObject { self.object.callback.get() } } impl CallbackInterface { /// Create a new CallbackInterface object for the given `JSObject`. pub fn new() -> CallbackInterface { CallbackInterface { object: CallbackObject { callback: Heap::default(), }, } } /// Initialize the callback function with a value. /// Should be called once this object is done moving. pub fn init(&mut self, callback: *mut JSObject) { self.object.callback.set(callback); } /// Returns the property with the given `name`, if it is a callable object, /// or an error otherwise. pub fn get_callable_property(&self, cx: *mut JSContext, name: &str) -> Fallible<JSVal> { let mut callable = RootedValue::new(cx, UndefinedValue()); let obj = RootedObject::new(cx, self.callback()); unsafe { let c_name = CString::new(name).unwrap(); if!JS_GetProperty(cx, obj.handle(), c_name.as_ptr(), callable.handle_mut()) { return Err(Error::JSFailed); } if!callable.ptr.is_object() ||!IsCallable(callable.ptr.to_object()) { return Err(Error::Type(format!("The value of the {} property is not callable", name))); } } Ok(callable.ptr) } } /// Wraps the reflector for `p` into the compartment of `cx`. pub fn wrap_call_this_object<T: Reflectable>(cx: *mut JSContext, p: &T, rval: MutableHandleObject) { rval.set(p.reflector().get_jsobject().get()); assert!(!rval.get().is_null()); unsafe { if!JS_WrapObject(cx, rval) { rval.set(ptr::null_mut()); } } } /// A class that performs whatever setup we need to safely make a call while /// this class is on the stack. After `new` returns, the call is safe to make. pub struct CallSetup { /// The compartment for reporting exceptions. /// As a RootedObject, this must be the first field in order to /// determine the final address on the stack correctly. exception_compartment: RootedObject, /// The `JSContext` used for the call. cx: *mut JSContext, /// The compartment we were in before the call. old_compartment: *mut JSCompartment, /// The exception handling used for the call. handling: ExceptionHandling, } impl CallSetup { /// Performs the setup needed to make a call. #[allow(unrooted_must_root)] pub fn
<T: CallbackContainer>(callback: &T, handling: ExceptionHandling) -> CallSetup { let global = global_root_from_object(callback.callback()); let cx = global.r().get_cx(); unsafe { JS_BeginRequest(cx); } let exception_compartment = unsafe { GetGlobalForObjectCrossCompartment(callback.callback()) }; CallSetup { exception_compartment: RootedObject::new_with_addr(cx, exception_compartment, unsafe { return_address() }), cx: cx, old_compartment: unsafe { JS_EnterCompartment(cx, callback.callback()) }, handling: handling, } } /// Returns the `JSContext` used for the call. pub fn get_context(&self) -> *mut JSContext { self.cx } } impl Drop for CallSetup { fn drop(&mut self) { unsafe { JS_LeaveCompartment(self.cx, self.old_compartment); } let need_to_deal_with_exception = self.handling == ExceptionHandling::Report && unsafe { JS_IsExceptionPending(self.cx) }; if need_to_deal_with_exception { unsafe { let old_global = RootedObject::new(self.cx, self.exception_compartment.ptr); let saved = JS_SaveFrameChain(self.cx); { let _ac = JSAutoCompartment::new(self.cx, old_global.ptr); JS_ReportPendingException(self.cx); } if saved { JS_RestoreFrameChain(self.cx); } } } unsafe { JS_EndRequest(self.cx); } } }
new
identifier_name
vec.rs
use super::{AssertionFailure, Spec}; pub trait VecAssertions { fn has_length(&mut self, expected: usize); fn is_empty(&mut self); } impl<'s, T> VecAssertions for Spec<'s, Vec<T>> { /// Asserts that the length of the subject vector is equal to the provided length. The subject /// type must be of `Vec`. /// /// ```rust,ignore /// assert_that(&vec![1, 2, 3, 4]).has_length(4); /// ``` fn has_length(&mut self, expected: usize) { let length = self.subject.len(); if length!= expected { AssertionFailure::from_spec(self) .with_expected(format!("vec to have length <{}>", expected)) .with_actual(format!("<{}>", length)) .fail(); } } /// Asserts that the subject vector is empty. The subject type must be of `Vec`. /// /// ```rust,ignore /// let test_vec: Vec<u8> = vec![]; /// assert_that(&test_vec).is_empty(); /// ``` fn is_empty(&mut self) { let subject = self.subject; if!subject.is_empty()
} } #[cfg(test)] mod tests { use super::super::prelude::*; #[test] fn should_not_panic_if_vec_length_matches_expected() { let test_vec = vec![1, 2, 3]; assert_that(&test_vec).has_length(3); } #[test] #[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")] fn should_panic_if_vec_length_does_not_match_expected() { let test_vec = vec![1, 2, 3]; assert_that(&test_vec).has_length(1); } #[test] fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() { let test_vec: Vec<u8> = vec![]; assert_that(&test_vec).is_empty(); } #[test] #[should_panic(expected = "\n\texpected: an empty vec\ \n\t but was: a vec with length <1>")] fn should_panic_if_vec_was_expected_to_be_empty_and_is_not() { assert_that(&vec![1]).is_empty(); } }
{ AssertionFailure::from_spec(self) .with_expected(format!("an empty vec")) .with_actual(format!("a vec with length <{:?}>", subject.len())) .fail(); }
conditional_block
vec.rs
use super::{AssertionFailure, Spec}; pub trait VecAssertions { fn has_length(&mut self, expected: usize); fn is_empty(&mut self); } impl<'s, T> VecAssertions for Spec<'s, Vec<T>> { /// Asserts that the length of the subject vector is equal to the provided length. The subject /// type must be of `Vec`. /// /// ```rust,ignore /// assert_that(&vec![1, 2, 3, 4]).has_length(4); /// ```
fn has_length(&mut self, expected: usize) { let length = self.subject.len(); if length!= expected { AssertionFailure::from_spec(self) .with_expected(format!("vec to have length <{}>", expected)) .with_actual(format!("<{}>", length)) .fail(); } } /// Asserts that the subject vector is empty. The subject type must be of `Vec`. /// /// ```rust,ignore /// let test_vec: Vec<u8> = vec![]; /// assert_that(&test_vec).is_empty(); /// ``` fn is_empty(&mut self) { let subject = self.subject; if!subject.is_empty() { AssertionFailure::from_spec(self) .with_expected(format!("an empty vec")) .with_actual(format!("a vec with length <{:?}>", subject.len())) .fail(); } } } #[cfg(test)] mod tests { use super::super::prelude::*; #[test] fn should_not_panic_if_vec_length_matches_expected() { let test_vec = vec![1, 2, 3]; assert_that(&test_vec).has_length(3); } #[test] #[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")] fn should_panic_if_vec_length_does_not_match_expected() { let test_vec = vec![1, 2, 3]; assert_that(&test_vec).has_length(1); } #[test] fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() { let test_vec: Vec<u8> = vec![]; assert_that(&test_vec).is_empty(); } #[test] #[should_panic(expected = "\n\texpected: an empty vec\ \n\t but was: a vec with length <1>")] fn should_panic_if_vec_was_expected_to_be_empty_and_is_not() { assert_that(&vec![1]).is_empty(); } }
random_line_split
vec.rs
use super::{AssertionFailure, Spec}; pub trait VecAssertions { fn has_length(&mut self, expected: usize); fn is_empty(&mut self); } impl<'s, T> VecAssertions for Spec<'s, Vec<T>> { /// Asserts that the length of the subject vector is equal to the provided length. The subject /// type must be of `Vec`. /// /// ```rust,ignore /// assert_that(&vec![1, 2, 3, 4]).has_length(4); /// ``` fn has_length(&mut self, expected: usize) { let length = self.subject.len(); if length!= expected { AssertionFailure::from_spec(self) .with_expected(format!("vec to have length <{}>", expected)) .with_actual(format!("<{}>", length)) .fail(); } } /// Asserts that the subject vector is empty. The subject type must be of `Vec`. /// /// ```rust,ignore /// let test_vec: Vec<u8> = vec![]; /// assert_that(&test_vec).is_empty(); /// ``` fn is_empty(&mut self) { let subject = self.subject; if!subject.is_empty() { AssertionFailure::from_spec(self) .with_expected(format!("an empty vec")) .with_actual(format!("a vec with length <{:?}>", subject.len())) .fail(); } } } #[cfg(test)] mod tests { use super::super::prelude::*; #[test] fn should_not_panic_if_vec_length_matches_expected() { let test_vec = vec![1, 2, 3]; assert_that(&test_vec).has_length(3); } #[test] #[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")] fn should_panic_if_vec_length_does_not_match_expected()
#[test] fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() { let test_vec: Vec<u8> = vec![]; assert_that(&test_vec).is_empty(); } #[test] #[should_panic(expected = "\n\texpected: an empty vec\ \n\t but was: a vec with length <1>")] fn should_panic_if_vec_was_expected_to_be_empty_and_is_not() { assert_that(&vec![1]).is_empty(); } }
{ let test_vec = vec![1, 2, 3]; assert_that(&test_vec).has_length(1); }
identifier_body
vec.rs
use super::{AssertionFailure, Spec}; pub trait VecAssertions { fn has_length(&mut self, expected: usize); fn is_empty(&mut self); } impl<'s, T> VecAssertions for Spec<'s, Vec<T>> { /// Asserts that the length of the subject vector is equal to the provided length. The subject /// type must be of `Vec`. /// /// ```rust,ignore /// assert_that(&vec![1, 2, 3, 4]).has_length(4); /// ``` fn has_length(&mut self, expected: usize) { let length = self.subject.len(); if length!= expected { AssertionFailure::from_spec(self) .with_expected(format!("vec to have length <{}>", expected)) .with_actual(format!("<{}>", length)) .fail(); } } /// Asserts that the subject vector is empty. The subject type must be of `Vec`. /// /// ```rust,ignore /// let test_vec: Vec<u8> = vec![]; /// assert_that(&test_vec).is_empty(); /// ``` fn is_empty(&mut self) { let subject = self.subject; if!subject.is_empty() { AssertionFailure::from_spec(self) .with_expected(format!("an empty vec")) .with_actual(format!("a vec with length <{:?}>", subject.len())) .fail(); } } } #[cfg(test)] mod tests { use super::super::prelude::*; #[test] fn
() { let test_vec = vec![1, 2, 3]; assert_that(&test_vec).has_length(3); } #[test] #[should_panic(expected = "\n\texpected: vec to have length <1>\n\t but was: <3>")] fn should_panic_if_vec_length_does_not_match_expected() { let test_vec = vec![1, 2, 3]; assert_that(&test_vec).has_length(1); } #[test] fn should_not_panic_if_vec_was_expected_to_be_empty_and_is() { let test_vec: Vec<u8> = vec![]; assert_that(&test_vec).is_empty(); } #[test] #[should_panic(expected = "\n\texpected: an empty vec\ \n\t but was: a vec with length <1>")] fn should_panic_if_vec_was_expected_to_be_empty_and_is_not() { assert_that(&vec![1]).is_empty(); } }
should_not_panic_if_vec_length_matches_expected
identifier_name
dragon.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Almost direct (but slightly optimized) Rust translation of Figure 3 of [1]. [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116. */ use prelude::v1::*; use cmp::Ordering; use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; use num::flt2dec::estimator::estimate_scaling_factor; use num::bignum::Digit32 as Digit; use num::bignum::Big32x40 as Big; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; // precalculated arrays of `Digit`s for 10^(2^n) static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; static POW10TO128: [Digit; 14] = [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e]; static POW10TO256: [Digit; 27] = [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big { debug_assert!(n < 512); if n & 7!= 0 { x.mul_small(POW10[n & 7]); } if n & 8!= 0 { x.mul_small(POW10[8]); } if n & 16!= 0 { x.mul_digits(&POW10TO16); } if n & 32!= 0 { x.mul_digits(&POW10TO32); } if n & 64!= 0 { x.mul_digits(&POW10TO64); } if n & 128!= 0 { x.mul_digits(&POW10TO128); } if n & 256!= 0 { x.mul_digits(&POW10TO256); } x } fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); n -= largest; } x.div_rem_small(TWOPOW10[n]); x } // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)` fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big, scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) { let mut d = 0; if *x >= *scale8 { x.sub(scale8); d += 8; } if *x >= *scale4 { x.sub(scale4); d += 4; } if *x >= *scale2 { x.sub(scale2); d += 2; } if *x >= *scale { x.sub(scale); d += 1; } debug_assert!(*x < *scale); (d, x) } /// The shortest mode implementation for Dragon. pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) { // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); assert!(buf.len() >= MAX_SIG_DIGITS); // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}` let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal}; // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`. // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later. let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp); // convert `{mant, plus, minus} * 2^exp` into the fractional form so that: // - `v = mant / scale` // - `low = (mant - minus) / scale` // - `high = (mant + plus) / scale` let mut mant = Big::from_u64(d.mant); let mut minus = Big::from_u64(d.minus); let mut plus = Big::from_u64(d.plus); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); minus.mul_pow2(d.exp as usize); plus.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); mul_pow10(&mut minus, -k as usize); mul_pow10(&mut plus, -k as usize); } // fixup when `mant + plus > scale` (or `>=`). // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // now `scale < mant + plus <= scale * 10` and we are ready to generate digits. // // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`. // in this case rounding-up condition (`up` below) will be triggered immediately. if scale.cmp(mant.clone().add(&plus)) < rounding { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // cache `(2, 4, 8) * scale` for digit generation. let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); let mut down; let mut up; let mut i = 0; loop { // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` // - `high - v = plus / scale * 10^(k-n-1)` // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`) // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) +... + d[j-1] * 10 + d[j]`. // generate one digit: `d[n] = floor(mant / scale) < 10`. let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8); debug_assert!(d < 10); buf[i] = b'0' + d; i += 1; // this is a simplified description of the modified Dragon algorithm. // many intermediate derivations and completeness arguments are omitted for convenience. // // start with modified invariants, as we've updated `n`: // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n)` // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // // the second condition simplifies to `2 * mant <= scale`. // solving invariants in terms of `mant`, `low` and `high` yields // a simpler version of the first condition: `-plus < mant < minus`. // since `-plus < 0 <= mant`, we have the correct shortest representation // when `mant < minus` and `2 * mant <= scale`. // (the former becomes `mant <= minus` when the original mantissa is even.) // // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit. // this is enough for restoring that condition: we already know that // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`. // in this case, the first condition becomes `-plus < mant - scale < minus`. // since `mant < scale` after the generation, we have `scale < mant + plus`. // (again, this becomes `scale <= mant + plus` when the original mantissa is even.) // // in short: // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`). // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`). // - keep generating otherwise. down = mant.cmp(&minus) < rounding; up = scale.cmp(mant.clone().add(&plus)) < rounding; if down || up { break; } // we have the shortest representation, proceed to the rounding // restore the invariants. // this makes the algorithm always terminating: `minus` and `plus` always increases, // but `mant` is clipped modulo `scale` and `scale` is fixed. mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // rounding up happens when // i) only the rounding-up condition was triggered, or // ii) both conditions were triggered and tie breaking prefers rounding up. if up && (!down || *mant.mul_pow2(1) >= scale) { // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. if let Some(c) = round_up(buf, i) { buf[i] = c; i += 1; k += 1; } } (i, k) } /// The exact and fixed mode implementation for Dragon. pub fn
(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`. let mut k = estimate_scaling_factor(d.mant, d.exp); // `v = mant / scale`. let mut mant = Big::from_u64(d.mant); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); } // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`. // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`. // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up. if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); } // if we are working with the last-digit limitation, we need to shorten the buffer // before the actual rendering in order to avoid double rounding. // note that we have to enlarge the buffer again when rounding up happens! let mut len = if k < limit { // oops, we cannot even produce *one* digit. // this is possible when, say, we've got something like 9.5 and it's being rounded to 10. // we return an empty buffer, with an exception of the later rounding-up case // which occurs when `k == limit` and has to produce exactly one digit. 0 } else if ((k as i32 - limit as i32) as usize) < buf.len() { (k - limit) as usize } else { buf.len() }; if len > 0 { // cache `(2, 4, 8) * scale` for digit generation. // (this can be expensive, so do not calculate them when the buffer is empty.) let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); for i in 0..len { if mant.is_zero() { // following digits are all zeroes, we stop here // do *not* try to perform rounding! rather, fill remaining digits. for c in &mut buf[i..len] { *c = b'0'; } return (len, k); } let mut d = 0; if mant >= scale8 { mant.sub(&scale8); d += 8; } if mant >= scale4 { mant.sub(&scale4); d += 4; } if mant >= scale2 { mant.sub(&scale2); d += 2; } if mant >= scale { mant.sub(&scale); d += 1; } debug_assert!(mant < scale); debug_assert!(d < 10); buf[i] = b'0' + d; mant.mul_small(10); } } // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e. avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... if let Some(c) = round_up(buf, len) { //...unless we've been requested the fixed precision instead. // we also need to check that, if the original buffer was empty, // the additional digit can only be added when `k == limit` (edge case). k += 1; if k > limit && len < buf.len() { buf[len] = c; len += 1; } } } (len, k) }
format_exact
identifier_name
dragon.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Almost direct (but slightly optimized) Rust translation of Figure 3 of [1]. [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116. */ use prelude::v1::*; use cmp::Ordering; use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; use num::flt2dec::estimator::estimate_scaling_factor; use num::bignum::Digit32 as Digit; use num::bignum::Big32x40 as Big; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; // precalculated arrays of `Digit`s for 10^(2^n) static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2];
static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; static POW10TO128: [Digit; 14] = [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e]; static POW10TO256: [Digit; 27] = [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big { debug_assert!(n < 512); if n & 7!= 0 { x.mul_small(POW10[n & 7]); } if n & 8!= 0 { x.mul_small(POW10[8]); } if n & 16!= 0 { x.mul_digits(&POW10TO16); } if n & 32!= 0 { x.mul_digits(&POW10TO32); } if n & 64!= 0 { x.mul_digits(&POW10TO64); } if n & 128!= 0 { x.mul_digits(&POW10TO128); } if n & 256!= 0 { x.mul_digits(&POW10TO256); } x } fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); n -= largest; } x.div_rem_small(TWOPOW10[n]); x } // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)` fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big, scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) { let mut d = 0; if *x >= *scale8 { x.sub(scale8); d += 8; } if *x >= *scale4 { x.sub(scale4); d += 4; } if *x >= *scale2 { x.sub(scale2); d += 2; } if *x >= *scale { x.sub(scale); d += 1; } debug_assert!(*x < *scale); (d, x) } /// The shortest mode implementation for Dragon. pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) { // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); assert!(buf.len() >= MAX_SIG_DIGITS); // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}` let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal}; // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`. // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later. let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp); // convert `{mant, plus, minus} * 2^exp` into the fractional form so that: // - `v = mant / scale` // - `low = (mant - minus) / scale` // - `high = (mant + plus) / scale` let mut mant = Big::from_u64(d.mant); let mut minus = Big::from_u64(d.minus); let mut plus = Big::from_u64(d.plus); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); minus.mul_pow2(d.exp as usize); plus.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); mul_pow10(&mut minus, -k as usize); mul_pow10(&mut plus, -k as usize); } // fixup when `mant + plus > scale` (or `>=`). // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // now `scale < mant + plus <= scale * 10` and we are ready to generate digits. // // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`. // in this case rounding-up condition (`up` below) will be triggered immediately. if scale.cmp(mant.clone().add(&plus)) < rounding { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // cache `(2, 4, 8) * scale` for digit generation. let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); let mut down; let mut up; let mut i = 0; loop { // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` // - `high - v = plus / scale * 10^(k-n-1)` // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`) // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) +... + d[j-1] * 10 + d[j]`. // generate one digit: `d[n] = floor(mant / scale) < 10`. let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8); debug_assert!(d < 10); buf[i] = b'0' + d; i += 1; // this is a simplified description of the modified Dragon algorithm. // many intermediate derivations and completeness arguments are omitted for convenience. // // start with modified invariants, as we've updated `n`: // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n)` // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // // the second condition simplifies to `2 * mant <= scale`. // solving invariants in terms of `mant`, `low` and `high` yields // a simpler version of the first condition: `-plus < mant < minus`. // since `-plus < 0 <= mant`, we have the correct shortest representation // when `mant < minus` and `2 * mant <= scale`. // (the former becomes `mant <= minus` when the original mantissa is even.) // // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit. // this is enough for restoring that condition: we already know that // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`. // in this case, the first condition becomes `-plus < mant - scale < minus`. // since `mant < scale` after the generation, we have `scale < mant + plus`. // (again, this becomes `scale <= mant + plus` when the original mantissa is even.) // // in short: // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`). // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`). // - keep generating otherwise. down = mant.cmp(&minus) < rounding; up = scale.cmp(mant.clone().add(&plus)) < rounding; if down || up { break; } // we have the shortest representation, proceed to the rounding // restore the invariants. // this makes the algorithm always terminating: `minus` and `plus` always increases, // but `mant` is clipped modulo `scale` and `scale` is fixed. mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // rounding up happens when // i) only the rounding-up condition was triggered, or // ii) both conditions were triggered and tie breaking prefers rounding up. if up && (!down || *mant.mul_pow2(1) >= scale) { // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. if let Some(c) = round_up(buf, i) { buf[i] = c; i += 1; k += 1; } } (i, k) } /// The exact and fixed mode implementation for Dragon. pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`. let mut k = estimate_scaling_factor(d.mant, d.exp); // `v = mant / scale`. let mut mant = Big::from_u64(d.mant); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); } // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`. // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`. // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up. if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); } // if we are working with the last-digit limitation, we need to shorten the buffer // before the actual rendering in order to avoid double rounding. // note that we have to enlarge the buffer again when rounding up happens! let mut len = if k < limit { // oops, we cannot even produce *one* digit. // this is possible when, say, we've got something like 9.5 and it's being rounded to 10. // we return an empty buffer, with an exception of the later rounding-up case // which occurs when `k == limit` and has to produce exactly one digit. 0 } else if ((k as i32 - limit as i32) as usize) < buf.len() { (k - limit) as usize } else { buf.len() }; if len > 0 { // cache `(2, 4, 8) * scale` for digit generation. // (this can be expensive, so do not calculate them when the buffer is empty.) let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); for i in 0..len { if mant.is_zero() { // following digits are all zeroes, we stop here // do *not* try to perform rounding! rather, fill remaining digits. for c in &mut buf[i..len] { *c = b'0'; } return (len, k); } let mut d = 0; if mant >= scale8 { mant.sub(&scale8); d += 8; } if mant >= scale4 { mant.sub(&scale4); d += 4; } if mant >= scale2 { mant.sub(&scale2); d += 2; } if mant >= scale { mant.sub(&scale); d += 1; } debug_assert!(mant < scale); debug_assert!(d < 10); buf[i] = b'0' + d; mant.mul_small(10); } } // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e. avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... if let Some(c) = round_up(buf, len) { //...unless we've been requested the fixed precision instead. // we also need to check that, if the original buffer was empty, // the additional digit can only be added when `k == limit` (edge case). k += 1; if k > limit && len < buf.len() { buf[len] = c; len += 1; } } } (len, k) }
static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee];
random_line_split
dragon.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Almost direct (but slightly optimized) Rust translation of Figure 3 of [1]. [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116. */ use prelude::v1::*; use cmp::Ordering; use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; use num::flt2dec::estimator::estimate_scaling_factor; use num::bignum::Digit32 as Digit; use num::bignum::Big32x40 as Big; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; // precalculated arrays of `Digit`s for 10^(2^n) static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; static POW10TO128: [Digit; 14] = [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e]; static POW10TO256: [Digit; 27] = [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big { debug_assert!(n < 512); if n & 7!= 0 { x.mul_small(POW10[n & 7]); } if n & 8!= 0 { x.mul_small(POW10[8]); } if n & 16!= 0 { x.mul_digits(&POW10TO16); } if n & 32!= 0 { x.mul_digits(&POW10TO32); } if n & 64!= 0 { x.mul_digits(&POW10TO64); } if n & 128!= 0 { x.mul_digits(&POW10TO128); } if n & 256!= 0 { x.mul_digits(&POW10TO256); } x } fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); n -= largest; } x.div_rem_small(TWOPOW10[n]); x } // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)` fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big, scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) { let mut d = 0; if *x >= *scale8 { x.sub(scale8); d += 8; } if *x >= *scale4 { x.sub(scale4); d += 4; } if *x >= *scale2 { x.sub(scale2); d += 2; } if *x >= *scale { x.sub(scale); d += 1; } debug_assert!(*x < *scale); (d, x) } /// The shortest mode implementation for Dragon. pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16)
// `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}` let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal}; // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`. // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later. let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp); // convert `{mant, plus, minus} * 2^exp` into the fractional form so that: // - `v = mant / scale` // - `low = (mant - minus) / scale` // - `high = (mant + plus) / scale` let mut mant = Big::from_u64(d.mant); let mut minus = Big::from_u64(d.minus); let mut plus = Big::from_u64(d.plus); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); minus.mul_pow2(d.exp as usize); plus.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); mul_pow10(&mut minus, -k as usize); mul_pow10(&mut plus, -k as usize); } // fixup when `mant + plus > scale` (or `>=`). // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // now `scale < mant + plus <= scale * 10` and we are ready to generate digits. // // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`. // in this case rounding-up condition (`up` below) will be triggered immediately. if scale.cmp(mant.clone().add(&plus)) < rounding { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // cache `(2, 4, 8) * scale` for digit generation. let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); let mut down; let mut up; let mut i = 0; loop { // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` // - `high - v = plus / scale * 10^(k-n-1)` // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`) // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) +... + d[j-1] * 10 + d[j]`. // generate one digit: `d[n] = floor(mant / scale) < 10`. let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8); debug_assert!(d < 10); buf[i] = b'0' + d; i += 1; // this is a simplified description of the modified Dragon algorithm. // many intermediate derivations and completeness arguments are omitted for convenience. // // start with modified invariants, as we've updated `n`: // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n)` // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // // the second condition simplifies to `2 * mant <= scale`. // solving invariants in terms of `mant`, `low` and `high` yields // a simpler version of the first condition: `-plus < mant < minus`. // since `-plus < 0 <= mant`, we have the correct shortest representation // when `mant < minus` and `2 * mant <= scale`. // (the former becomes `mant <= minus` when the original mantissa is even.) // // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit. // this is enough for restoring that condition: we already know that // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`. // in this case, the first condition becomes `-plus < mant - scale < minus`. // since `mant < scale` after the generation, we have `scale < mant + plus`. // (again, this becomes `scale <= mant + plus` when the original mantissa is even.) // // in short: // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`). // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`). // - keep generating otherwise. down = mant.cmp(&minus) < rounding; up = scale.cmp(mant.clone().add(&plus)) < rounding; if down || up { break; } // we have the shortest representation, proceed to the rounding // restore the invariants. // this makes the algorithm always terminating: `minus` and `plus` always increases, // but `mant` is clipped modulo `scale` and `scale` is fixed. mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // rounding up happens when // i) only the rounding-up condition was triggered, or // ii) both conditions were triggered and tie breaking prefers rounding up. if up && (!down || *mant.mul_pow2(1) >= scale) { // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. if let Some(c) = round_up(buf, i) { buf[i] = c; i += 1; k += 1; } } (i, k) } /// The exact and fixed mode implementation for Dragon. pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`. let mut k = estimate_scaling_factor(d.mant, d.exp); // `v = mant / scale`. let mut mant = Big::from_u64(d.mant); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); } // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`. // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`. // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up. if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); } // if we are working with the last-digit limitation, we need to shorten the buffer // before the actual rendering in order to avoid double rounding. // note that we have to enlarge the buffer again when rounding up happens! let mut len = if k < limit { // oops, we cannot even produce *one* digit. // this is possible when, say, we've got something like 9.5 and it's being rounded to 10. // we return an empty buffer, with an exception of the later rounding-up case // which occurs when `k == limit` and has to produce exactly one digit. 0 } else if ((k as i32 - limit as i32) as usize) < buf.len() { (k - limit) as usize } else { buf.len() }; if len > 0 { // cache `(2, 4, 8) * scale` for digit generation. // (this can be expensive, so do not calculate them when the buffer is empty.) let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); for i in 0..len { if mant.is_zero() { // following digits are all zeroes, we stop here // do *not* try to perform rounding! rather, fill remaining digits. for c in &mut buf[i..len] { *c = b'0'; } return (len, k); } let mut d = 0; if mant >= scale8 { mant.sub(&scale8); d += 8; } if mant >= scale4 { mant.sub(&scale4); d += 4; } if mant >= scale2 { mant.sub(&scale2); d += 2; } if mant >= scale { mant.sub(&scale); d += 1; } debug_assert!(mant < scale); debug_assert!(d < 10); buf[i] = b'0' + d; mant.mul_small(10); } } // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e. avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... if let Some(c) = round_up(buf, len) { //...unless we've been requested the fixed precision instead. // we also need to check that, if the original buffer was empty, // the additional digit can only be added when `k == limit` (edge case). k += 1; if k > limit && len < buf.len() { buf[len] = c; len += 1; } } } (len, k) }
{ // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); assert!(buf.len() >= MAX_SIG_DIGITS);
identifier_body
dragon.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! Almost direct (but slightly optimized) Rust translation of Figure 3 of [1]. [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116. */ use prelude::v1::*; use cmp::Ordering; use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; use num::flt2dec::estimator::estimate_scaling_factor; use num::bignum::Digit32 as Digit; use num::bignum::Big32x40 as Big; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; // precalculated arrays of `Digit`s for 10^(2^n) static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; static POW10TO128: [Digit; 14] = [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e]; static POW10TO256: [Digit; 27] = [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big { debug_assert!(n < 512); if n & 7!= 0 { x.mul_small(POW10[n & 7]); } if n & 8!= 0 { x.mul_small(POW10[8]); } if n & 16!= 0 { x.mul_digits(&POW10TO16); } if n & 32!= 0 { x.mul_digits(&POW10TO32); } if n & 64!= 0 { x.mul_digits(&POW10TO64); } if n & 128!= 0 { x.mul_digits(&POW10TO128); } if n & 256!= 0 { x.mul_digits(&POW10TO256); } x } fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); n -= largest; } x.div_rem_small(TWOPOW10[n]); x } // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)` fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big, scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) { let mut d = 0; if *x >= *scale8 { x.sub(scale8); d += 8; } if *x >= *scale4 { x.sub(scale4); d += 4; } if *x >= *scale2 { x.sub(scale2); d += 2; } if *x >= *scale { x.sub(scale); d += 1; } debug_assert!(*x < *scale); (d, x) } /// The shortest mode implementation for Dragon. pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) { // the number `v` to format is known to be: // - equal to `mant * 2^exp`; // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); assert!(buf.len() >= MAX_SIG_DIGITS); // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}` let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal}; // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`. // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later. let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp); // convert `{mant, plus, minus} * 2^exp` into the fractional form so that: // - `v = mant / scale` // - `low = (mant - minus) / scale` // - `high = (mant + plus) / scale` let mut mant = Big::from_u64(d.mant); let mut minus = Big::from_u64(d.minus); let mut plus = Big::from_u64(d.plus); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); minus.mul_pow2(d.exp as usize); plus.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); mul_pow10(&mut minus, -k as usize); mul_pow10(&mut plus, -k as usize); } // fixup when `mant + plus > scale` (or `>=`). // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // now `scale < mant + plus <= scale * 10` and we are ready to generate digits. // // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`. // in this case rounding-up condition (`up` below) will be triggered immediately. if scale.cmp(mant.clone().add(&plus)) < rounding { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // cache `(2, 4, 8) * scale` for digit generation. let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); let mut down; let mut up; let mut i = 0; loop { // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` // - `high - v = plus / scale * 10^(k-n-1)` // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`) // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) +... + d[j-1] * 10 + d[j]`. // generate one digit: `d[n] = floor(mant / scale) < 10`. let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8); debug_assert!(d < 10); buf[i] = b'0' + d; i += 1; // this is a simplified description of the modified Dragon algorithm. // many intermediate derivations and completeness arguments are omitted for convenience. // // start with modified invariants, as we've updated `n`: // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n)` // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // // the second condition simplifies to `2 * mant <= scale`. // solving invariants in terms of `mant`, `low` and `high` yields // a simpler version of the first condition: `-plus < mant < minus`. // since `-plus < 0 <= mant`, we have the correct shortest representation // when `mant < minus` and `2 * mant <= scale`. // (the former becomes `mant <= minus` when the original mantissa is even.) // // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit. // this is enough for restoring that condition: we already know that // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`. // in this case, the first condition becomes `-plus < mant - scale < minus`. // since `mant < scale` after the generation, we have `scale < mant + plus`. // (again, this becomes `scale <= mant + plus` when the original mantissa is even.) // // in short: // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`). // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`). // - keep generating otherwise. down = mant.cmp(&minus) < rounding; up = scale.cmp(mant.clone().add(&plus)) < rounding; if down || up { break; } // we have the shortest representation, proceed to the rounding // restore the invariants. // this makes the algorithm always terminating: `minus` and `plus` always increases, // but `mant` is clipped modulo `scale` and `scale` is fixed. mant.mul_small(10); minus.mul_small(10); plus.mul_small(10); } // rounding up happens when // i) only the rounding-up condition was triggered, or // ii) both conditions were triggered and tie breaking prefers rounding up. if up && (!down || *mant.mul_pow2(1) >= scale) { // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. if let Some(c) = round_up(buf, i) { buf[i] = c; i += 1; k += 1; } } (i, k) } /// The exact and fixed mode implementation for Dragon. pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) { assert!(d.mant > 0); assert!(d.minus > 0); assert!(d.plus > 0); assert!(d.mant.checked_add(d.plus).is_some()); assert!(d.mant.checked_sub(d.minus).is_some()); // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`. let mut k = estimate_scaling_factor(d.mant, d.exp); // `v = mant / scale`. let mut mant = Big::from_u64(d.mant); let mut scale = Big::from_small(1); if d.exp < 0 { scale.mul_pow2(-d.exp as usize); } else { mant.mul_pow2(d.exp as usize); } // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`. if k >= 0 { mul_pow10(&mut scale, k as usize); } else { mul_pow10(&mut mant, -k as usize); } // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`. // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`. // we are not actually modifying `scale`, since we can skip the initial multiplication instead. // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up. if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale { // equivalent to scaling `scale` by 10 k += 1; } else { mant.mul_small(10); } // if we are working with the last-digit limitation, we need to shorten the buffer // before the actual rendering in order to avoid double rounding. // note that we have to enlarge the buffer again when rounding up happens! let mut len = if k < limit { // oops, we cannot even produce *one* digit. // this is possible when, say, we've got something like 9.5 and it's being rounded to 10. // we return an empty buffer, with an exception of the later rounding-up case // which occurs when `k == limit` and has to produce exactly one digit. 0 } else if ((k as i32 - limit as i32) as usize) < buf.len()
else { buf.len() }; if len > 0 { // cache `(2, 4, 8) * scale` for digit generation. // (this can be expensive, so do not calculate them when the buffer is empty.) let mut scale2 = scale.clone(); scale2.mul_pow2(1); let mut scale4 = scale.clone(); scale4.mul_pow2(2); let mut scale8 = scale.clone(); scale8.mul_pow2(3); for i in 0..len { if mant.is_zero() { // following digits are all zeroes, we stop here // do *not* try to perform rounding! rather, fill remaining digits. for c in &mut buf[i..len] { *c = b'0'; } return (len, k); } let mut d = 0; if mant >= scale8 { mant.sub(&scale8); d += 8; } if mant >= scale4 { mant.sub(&scale4); d += 4; } if mant >= scale2 { mant.sub(&scale2); d += 2; } if mant >= scale { mant.sub(&scale); d += 1; } debug_assert!(mant < scale); debug_assert!(d < 10); buf[i] = b'0' + d; mant.mul_small(10); } } // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e. avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... if let Some(c) = round_up(buf, len) { //...unless we've been requested the fixed precision instead. // we also need to check that, if the original buffer was empty, // the additional digit can only be added when `k == limit` (edge case). k += 1; if k > limit && len < buf.len() { buf[len] = c; len += 1; } } } (len, k) }
{ (k - limit) as usize }
conditional_block
scalar.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashMap; use std::usize; use test::{black_box, Bencher}; use tipb::ScalarFuncSig; fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) { // Only select some functions to benchmark let (min_args, max_args) = match sig { ScalarFuncSig::LtInt => (2, 2), ScalarFuncSig::CastIntAsInt => (1, 1), ScalarFuncSig::IfInt => (3, 3), ScalarFuncSig::JsonArraySig => (0, usize::MAX), ScalarFuncSig::CoalesceDecimal => (1, usize::MAX), ScalarFuncSig::JsonExtractSig => (2, usize::MAX), ScalarFuncSig::JsonSetSig => (3, usize::MAX), _ => (0, 0), }; (min_args, max_args) } fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> { let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default(); let tbls = vec![ (ScalarFuncSig::LtInt, (2, 2)), (ScalarFuncSig::CastIntAsInt, (1, 1)), (ScalarFuncSig::IfInt, (3, 3)), (ScalarFuncSig::JsonArraySig, (0, usize::MAX)), (ScalarFuncSig::CoalesceDecimal, (1, usize::MAX)), (ScalarFuncSig::JsonExtractSig, (2, usize::MAX)), (ScalarFuncSig::JsonSetSig, (3, usize::MAX)), (ScalarFuncSig::Acos, (0, 0)), ]; for tbl in tbls { m.insert(tbl.0, tbl.1); } m } fn get_scalar_args_with_map( m: &HashMap<ScalarFuncSig, (usize, usize)>, sig: ScalarFuncSig, ) -> (usize, usize) { if let Some((min_args, max_args)) = m.get(&sig).cloned()
(0, 0) } #[bench] fn bench_get_scalar_args_with_match(b: &mut Bencher) { b.iter(|| { for _ in 0..1000 { black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt))); } }) } #[bench] fn bench_get_scalar_args_with_map(b: &mut Bencher) { let m = init_scalar_args_map(); b.iter(|| { for _ in 0..1000 { black_box(get_scalar_args_with_map( black_box(&m), black_box(ScalarFuncSig::AbsInt), )); } }) }
{ return (min_args, max_args); }
conditional_block
scalar.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashMap; use std::usize; use test::{black_box, Bencher}; use tipb::ScalarFuncSig; fn
(sig: ScalarFuncSig) -> (usize, usize) { // Only select some functions to benchmark let (min_args, max_args) = match sig { ScalarFuncSig::LtInt => (2, 2), ScalarFuncSig::CastIntAsInt => (1, 1), ScalarFuncSig::IfInt => (3, 3), ScalarFuncSig::JsonArraySig => (0, usize::MAX), ScalarFuncSig::CoalesceDecimal => (1, usize::MAX), ScalarFuncSig::JsonExtractSig => (2, usize::MAX), ScalarFuncSig::JsonSetSig => (3, usize::MAX), _ => (0, 0), }; (min_args, max_args) } fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> { let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default(); let tbls = vec![ (ScalarFuncSig::LtInt, (2, 2)), (ScalarFuncSig::CastIntAsInt, (1, 1)), (ScalarFuncSig::IfInt, (3, 3)), (ScalarFuncSig::JsonArraySig, (0, usize::MAX)), (ScalarFuncSig::CoalesceDecimal, (1, usize::MAX)), (ScalarFuncSig::JsonExtractSig, (2, usize::MAX)), (ScalarFuncSig::JsonSetSig, (3, usize::MAX)), (ScalarFuncSig::Acos, (0, 0)), ]; for tbl in tbls { m.insert(tbl.0, tbl.1); } m } fn get_scalar_args_with_map( m: &HashMap<ScalarFuncSig, (usize, usize)>, sig: ScalarFuncSig, ) -> (usize, usize) { if let Some((min_args, max_args)) = m.get(&sig).cloned() { return (min_args, max_args); } (0, 0) } #[bench] fn bench_get_scalar_args_with_match(b: &mut Bencher) { b.iter(|| { for _ in 0..1000 { black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt))); } }) } #[bench] fn bench_get_scalar_args_with_map(b: &mut Bencher) { let m = init_scalar_args_map(); b.iter(|| { for _ in 0..1000 { black_box(get_scalar_args_with_map( black_box(&m), black_box(ScalarFuncSig::AbsInt), )); } }) }
get_scalar_args_with_match
identifier_name
scalar.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashMap; use std::usize; use test::{black_box, Bencher}; use tipb::ScalarFuncSig; fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) { // Only select some functions to benchmark let (min_args, max_args) = match sig { ScalarFuncSig::LtInt => (2, 2), ScalarFuncSig::CastIntAsInt => (1, 1), ScalarFuncSig::IfInt => (3, 3), ScalarFuncSig::JsonArraySig => (0, usize::MAX), ScalarFuncSig::CoalesceDecimal => (1, usize::MAX), ScalarFuncSig::JsonExtractSig => (2, usize::MAX), ScalarFuncSig::JsonSetSig => (3, usize::MAX), _ => (0, 0), }; (min_args, max_args) } fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> { let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default(); let tbls = vec![ (ScalarFuncSig::LtInt, (2, 2)), (ScalarFuncSig::CastIntAsInt, (1, 1)), (ScalarFuncSig::IfInt, (3, 3)), (ScalarFuncSig::JsonArraySig, (0, usize::MAX)), (ScalarFuncSig::CoalesceDecimal, (1, usize::MAX)), (ScalarFuncSig::JsonExtractSig, (2, usize::MAX)), (ScalarFuncSig::JsonSetSig, (3, usize::MAX)), (ScalarFuncSig::Acos, (0, 0)), ]; for tbl in tbls { m.insert(tbl.0, tbl.1); } m } fn get_scalar_args_with_map( m: &HashMap<ScalarFuncSig, (usize, usize)>, sig: ScalarFuncSig, ) -> (usize, usize) { if let Some((min_args, max_args)) = m.get(&sig).cloned() { return (min_args, max_args); } (0, 0) } #[bench] fn bench_get_scalar_args_with_match(b: &mut Bencher) { b.iter(|| { for _ in 0..1000 { black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt))); } }) } #[bench] fn bench_get_scalar_args_with_map(b: &mut Bencher)
{ let m = init_scalar_args_map(); b.iter(|| { for _ in 0..1000 { black_box(get_scalar_args_with_map( black_box(&m), black_box(ScalarFuncSig::AbsInt), )); } }) }
identifier_body
scalar.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashMap; use std::usize; use test::{black_box, Bencher}; use tipb::ScalarFuncSig; fn get_scalar_args_with_match(sig: ScalarFuncSig) -> (usize, usize) { // Only select some functions to benchmark let (min_args, max_args) = match sig { ScalarFuncSig::LtInt => (2, 2), ScalarFuncSig::CastIntAsInt => (1, 1), ScalarFuncSig::IfInt => (3, 3), ScalarFuncSig::JsonArraySig => (0, usize::MAX), ScalarFuncSig::CoalesceDecimal => (1, usize::MAX), ScalarFuncSig::JsonExtractSig => (2, usize::MAX), ScalarFuncSig::JsonSetSig => (3, usize::MAX),
} fn init_scalar_args_map() -> HashMap<ScalarFuncSig, (usize, usize)> { let mut m: HashMap<ScalarFuncSig, (usize, usize)> = HashMap::default(); let tbls = vec![ (ScalarFuncSig::LtInt, (2, 2)), (ScalarFuncSig::CastIntAsInt, (1, 1)), (ScalarFuncSig::IfInt, (3, 3)), (ScalarFuncSig::JsonArraySig, (0, usize::MAX)), (ScalarFuncSig::CoalesceDecimal, (1, usize::MAX)), (ScalarFuncSig::JsonExtractSig, (2, usize::MAX)), (ScalarFuncSig::JsonSetSig, (3, usize::MAX)), (ScalarFuncSig::Acos, (0, 0)), ]; for tbl in tbls { m.insert(tbl.0, tbl.1); } m } fn get_scalar_args_with_map( m: &HashMap<ScalarFuncSig, (usize, usize)>, sig: ScalarFuncSig, ) -> (usize, usize) { if let Some((min_args, max_args)) = m.get(&sig).cloned() { return (min_args, max_args); } (0, 0) } #[bench] fn bench_get_scalar_args_with_match(b: &mut Bencher) { b.iter(|| { for _ in 0..1000 { black_box(get_scalar_args_with_match(black_box(ScalarFuncSig::AbsInt))); } }) } #[bench] fn bench_get_scalar_args_with_map(b: &mut Bencher) { let m = init_scalar_args_map(); b.iter(|| { for _ in 0..1000 { black_box(get_scalar_args_with_map( black_box(&m), black_box(ScalarFuncSig::AbsInt), )); } }) }
_ => (0, 0), }; (min_args, max_args)
random_line_split
libstdbuf.rs
#![crate_name = "libstdbuf"] #![crate_type = "staticlib"] #![feature(core, libc, os)] extern crate libc; use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf}; use std::ptr; use std::os; #[path = "../common/util.rs"] #[macro_use] mod util; extern { static stdin: *mut FILE; static stdout: *mut FILE; static stderr: *mut FILE; } static NAME: &'static str = "libstdbuf"; fn set_buffer(stream: *mut FILE, value: &str) { let (mode, size): (c_int, size_t) = match value { "0" => (_IONBF, 0 as size_t), "L" => (_IOLBF, 0 as size_t), input => { let buff_size: usize = match input.parse() { Ok(num) => num, Err(e) => crash!(1, "incorrect size of buffer!: {}", e) }; (_IOFBF, buff_size as size_t) } }; let mut res: c_int; unsafe { let buffer: *mut c_char = ptr::null_mut(); assert!(buffer.is_null()); res = libc::setvbuf(stream, buffer, mode, size); } if res!= 0 { crash!(res, "error while calling setvbuf!"); } }
pub extern fn stdbuf() { if let Some(val) = os::getenv("_STDBUF_E") { set_buffer(stderr, val.as_slice()); } if let Some(val) = os::getenv("_STDBUF_I") { set_buffer(stdin, val.as_slice()); } if let Some(val) = os::getenv("_STDBUF_O") { set_buffer(stdout, val.as_slice()); } }
#[no_mangle]
random_line_split
libstdbuf.rs
#![crate_name = "libstdbuf"] #![crate_type = "staticlib"] #![feature(core, libc, os)] extern crate libc; use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf}; use std::ptr; use std::os; #[path = "../common/util.rs"] #[macro_use] mod util; extern { static stdin: *mut FILE; static stdout: *mut FILE; static stderr: *mut FILE; } static NAME: &'static str = "libstdbuf"; fn set_buffer(stream: *mut FILE, value: &str) { let (mode, size): (c_int, size_t) = match value { "0" => (_IONBF, 0 as size_t), "L" => (_IOLBF, 0 as size_t), input => { let buff_size: usize = match input.parse() { Ok(num) => num, Err(e) => crash!(1, "incorrect size of buffer!: {}", e) }; (_IOFBF, buff_size as size_t) } }; let mut res: c_int; unsafe { let buffer: *mut c_char = ptr::null_mut(); assert!(buffer.is_null()); res = libc::setvbuf(stream, buffer, mode, size); } if res!= 0 { crash!(res, "error while calling setvbuf!"); } } #[no_mangle] pub extern fn stdbuf()
{ if let Some(val) = os::getenv("_STDBUF_E") { set_buffer(stderr, val.as_slice()); } if let Some(val) = os::getenv("_STDBUF_I") { set_buffer(stdin, val.as_slice()); } if let Some(val) = os::getenv("_STDBUF_O") { set_buffer(stdout, val.as_slice()); } }
identifier_body
libstdbuf.rs
#![crate_name = "libstdbuf"] #![crate_type = "staticlib"] #![feature(core, libc, os)] extern crate libc; use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf}; use std::ptr; use std::os; #[path = "../common/util.rs"] #[macro_use] mod util; extern { static stdin: *mut FILE; static stdout: *mut FILE; static stderr: *mut FILE; } static NAME: &'static str = "libstdbuf"; fn set_buffer(stream: *mut FILE, value: &str) { let (mode, size): (c_int, size_t) = match value { "0" => (_IONBF, 0 as size_t), "L" => (_IOLBF, 0 as size_t), input => { let buff_size: usize = match input.parse() { Ok(num) => num, Err(e) => crash!(1, "incorrect size of buffer!: {}", e) }; (_IOFBF, buff_size as size_t) } }; let mut res: c_int; unsafe { let buffer: *mut c_char = ptr::null_mut(); assert!(buffer.is_null()); res = libc::setvbuf(stream, buffer, mode, size); } if res!= 0 { crash!(res, "error while calling setvbuf!"); } } #[no_mangle] pub extern fn stdbuf() { if let Some(val) = os::getenv("_STDBUF_E") { set_buffer(stderr, val.as_slice()); } if let Some(val) = os::getenv("_STDBUF_I") { set_buffer(stdin, val.as_slice()); } if let Some(val) = os::getenv("_STDBUF_O")
}
{ set_buffer(stdout, val.as_slice()); }
conditional_block
libstdbuf.rs
#![crate_name = "libstdbuf"] #![crate_type = "staticlib"] #![feature(core, libc, os)] extern crate libc; use libc::{c_int, size_t, c_char, FILE, _IOFBF, _IONBF, _IOLBF, setvbuf}; use std::ptr; use std::os; #[path = "../common/util.rs"] #[macro_use] mod util; extern { static stdin: *mut FILE; static stdout: *mut FILE; static stderr: *mut FILE; } static NAME: &'static str = "libstdbuf"; fn set_buffer(stream: *mut FILE, value: &str) { let (mode, size): (c_int, size_t) = match value { "0" => (_IONBF, 0 as size_t), "L" => (_IOLBF, 0 as size_t), input => { let buff_size: usize = match input.parse() { Ok(num) => num, Err(e) => crash!(1, "incorrect size of buffer!: {}", e) }; (_IOFBF, buff_size as size_t) } }; let mut res: c_int; unsafe { let buffer: *mut c_char = ptr::null_mut(); assert!(buffer.is_null()); res = libc::setvbuf(stream, buffer, mode, size); } if res!= 0 { crash!(res, "error while calling setvbuf!"); } } #[no_mangle] pub extern fn
() { if let Some(val) = os::getenv("_STDBUF_E") { set_buffer(stderr, val.as_slice()); } if let Some(val) = os::getenv("_STDBUF_I") { set_buffer(stdin, val.as_slice()); } if let Some(val) = os::getenv("_STDBUF_O") { set_buffer(stdout, val.as_slice()); } }
stdbuf
identifier_name
main.rs
extern crate rustc_serialize; extern crate hyper; use rustc_serialize::json; use rustc_serialize::json::Json; #[macro_use] extern crate nickel; use nickel::status::StatusCode; use nickel::{Nickel, HttpRouter, MediaType, JsonBody}; #[derive(RustcDecodable, RustcEncodable)] struct
{ status: i32, title: String, } fn main() { let mut server = Nickel::new(); let mut router = Nickel::router(); // index router.get("/api/todos", middleware! { |_, mut _res| let mut v: Vec<Todo> = vec![]; let todo1 = Todo{ status: 0, title: "Shopping".to_string(), }; v.push(todo1); let todo2 = Todo{ status: 1, title: "Movie".to_string(), }; v.push(todo2); let json_obj = json::encode(&v).unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Ok); return _res.send(json_obj); }); // detail router.get("/api/todos/:id", middleware! { |_req, mut _res| let id = _req.param("id"); println!("id: {:?}", id); let todo1 = Todo{ status: 0, title: "Shopping".to_string(), }; let json_obj = json::encode(&todo1).unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Ok); return _res.send(json_obj); }); // delete router.delete("/api/todos/:id", middleware! { |_req, mut _res| let id = _req.param("id"); println!("delete id: {:?}", id); let json_obj = Json::from_str("{}").unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Ok); return _res.send(json_obj); }); // create router.post("/api/todos", middleware! { |_req, mut _res| let todo = _req.json_as::<Todo>().unwrap(); let status = todo.status; let title = todo.title.to_string(); println!("create status {:?} title {}", status, title); let json_obj = Json::from_str("{}").unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Created); return _res.send(json_obj); }); // update router.put("/api/todos/:id", middleware! { |_req, mut _res| let todo = _req.json_as::<Todo>().unwrap(); let status = todo.status; let title = todo.title.to_string(); println!("update status {:?} title {}", status, title); let json_obj = Json::from_str("{}").unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Ok); return _res.send(json_obj); }); server.utilize(router); server.listen("127.0.0.1:6767"); }
Todo
identifier_name
main.rs
extern crate rustc_serialize; extern crate hyper; use rustc_serialize::json; use rustc_serialize::json::Json; #[macro_use] extern crate nickel; use nickel::status::StatusCode; use nickel::{Nickel, HttpRouter, MediaType, JsonBody}; #[derive(RustcDecodable, RustcEncodable)] struct Todo { status: i32, title: String, } fn main() { let mut server = Nickel::new(); let mut router = Nickel::router(); // index router.get("/api/todos", middleware! { |_, mut _res| let mut v: Vec<Todo> = vec![]; let todo1 = Todo{ status: 0, title: "Shopping".to_string(), }; v.push(todo1); let todo2 = Todo{ status: 1, title: "Movie".to_string(), }; v.push(todo2); let json_obj = json::encode(&v).unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Ok); return _res.send(json_obj); }); // detail router.get("/api/todos/:id", middleware! { |_req, mut _res| let id = _req.param("id"); println!("id: {:?}", id); let todo1 = Todo{ status: 0, title: "Shopping".to_string(), }; let json_obj = json::encode(&todo1).unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Ok); return _res.send(json_obj); }); // delete router.delete("/api/todos/:id", middleware! { |_req, mut _res| let id = _req.param("id"); println!("delete id: {:?}", id); let json_obj = Json::from_str("{}").unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Ok); return _res.send(json_obj); });
let todo = _req.json_as::<Todo>().unwrap(); let status = todo.status; let title = todo.title.to_string(); println!("create status {:?} title {}", status, title); let json_obj = Json::from_str("{}").unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Created); return _res.send(json_obj); }); // update router.put("/api/todos/:id", middleware! { |_req, mut _res| let todo = _req.json_as::<Todo>().unwrap(); let status = todo.status; let title = todo.title.to_string(); println!("update status {:?} title {}", status, title); let json_obj = Json::from_str("{}").unwrap(); _res.set(MediaType::Json); _res.set(StatusCode::Ok); return _res.send(json_obj); }); server.utilize(router); server.listen("127.0.0.1:6767"); }
// create router.post("/api/todos", middleware! { |_req, mut _res|
random_line_split
issue-14845.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 { a: [u8; 1] } fn
() { let x = X { a: [0] }; let _f = &x.a as *mut u8; //~^ ERROR mismatched types //~| expected `*mut u8` //~| found `&[u8; 1]` //~| expected u8 //~| found array of 1 elements let local = [0u8]; let _v = &local as *mut u8; //~^ ERROR mismatched types //~| expected `*mut u8` //~| found `&[u8; 1]` //~| expected u8, //~| found array of 1 elements }
main
identifier_name
issue-14845.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 { a: [u8; 1] } fn main() { let x = X { a: [0] }; let _f = &x.a as *mut u8; //~^ ERROR mismatched types //~| expected `*mut u8` //~| found `&[u8; 1]` //~| expected u8 //~| found array of 1 elements let local = [0u8]; let _v = &local as *mut u8; //~^ ERROR mismatched types //~| expected `*mut u8` //~| found `&[u8; 1]` //~| expected u8, //~| found array of 1 elements
}
random_line_split
lib.rs
extern crate lexer; use lexer::{Item, StateFn, Lexer}; #[derive(Debug, PartialEq)] pub enum ItemType { Comma, Text, Comment, EOF } fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { if l.remaining_input().starts_with("//") { l.emit_nonempty(ItemType::Text); l.next(); return Some(StateFn(lex_comment)); } match l.next() { None => break, Some(',') => { l.backup(); l.emit_nonempty(ItemType::Text); l.next(); l.emit(ItemType::Comma); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Text); l.emit(ItemType::EOF); None } fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { match l.next() { None => break, Some('\n') => { l.backup(); l.emit_nonempty(ItemType::Comment); l.next(); l.ignore(); return Some(StateFn(lex_text)); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Comment); l.emit(ItemType::EOF); None } #[test] fn test_lexer() { let data = "foo,bar,baz // some comment\nfoo,bar"; let items = lexer::lex(data, lex_text); let expected_items = vec!( Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1}, Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1}, Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1}, Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2}, Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2} ); for (item, expected) in items.iter().zip(expected_items.iter()) { println!("ITEM: {:?}", item); assert_eq!(item, expected); }
assert_eq!(items, expected_items); }
random_line_split
lib.rs
extern crate lexer; use lexer::{Item, StateFn, Lexer}; #[derive(Debug, PartialEq)] pub enum ItemType { Comma, Text, Comment, EOF } fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { if l.remaining_input().starts_with("//") { l.emit_nonempty(ItemType::Text); l.next(); return Some(StateFn(lex_comment)); } match l.next() { None => break, Some(',') => { l.backup(); l.emit_nonempty(ItemType::Text); l.next(); l.emit(ItemType::Comma); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Text); l.emit(ItemType::EOF); None } fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>>
#[test] fn test_lexer() { let data = "foo,bar,baz // some comment\nfoo,bar"; let items = lexer::lex(data, lex_text); let expected_items = vec!( Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1}, Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1}, Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1}, Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2}, Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2} ); for (item, expected) in items.iter().zip(expected_items.iter()) { println!("ITEM: {:?}", item); assert_eq!(item, expected); } assert_eq!(items, expected_items); }
{ loop { match l.next() { None => break, Some('\n') => { l.backup(); l.emit_nonempty(ItemType::Comment); l.next(); l.ignore(); return Some(StateFn(lex_text)); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Comment); l.emit(ItemType::EOF); None }
identifier_body
lib.rs
extern crate lexer; use lexer::{Item, StateFn, Lexer}; #[derive(Debug, PartialEq)] pub enum
{ Comma, Text, Comment, EOF } fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { if l.remaining_input().starts_with("//") { l.emit_nonempty(ItemType::Text); l.next(); return Some(StateFn(lex_comment)); } match l.next() { None => break, Some(',') => { l.backup(); l.emit_nonempty(ItemType::Text); l.next(); l.emit(ItemType::Comma); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Text); l.emit(ItemType::EOF); None } fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { match l.next() { None => break, Some('\n') => { l.backup(); l.emit_nonempty(ItemType::Comment); l.next(); l.ignore(); return Some(StateFn(lex_text)); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Comment); l.emit(ItemType::EOF); None } #[test] fn test_lexer() { let data = "foo,bar,baz // some comment\nfoo,bar"; let items = lexer::lex(data, lex_text); let expected_items = vec!( Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1}, Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1}, Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1}, Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2}, Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2} ); for (item, expected) in items.iter().zip(expected_items.iter()) { println!("ITEM: {:?}", item); assert_eq!(item, expected); } assert_eq!(items, expected_items); }
ItemType
identifier_name
lib.rs
extern crate lexer; use lexer::{Item, StateFn, Lexer}; #[derive(Debug, PartialEq)] pub enum ItemType { Comma, Text, Comment, EOF } fn lex_text(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { if l.remaining_input().starts_with("//") { l.emit_nonempty(ItemType::Text); l.next(); return Some(StateFn(lex_comment)); } match l.next() { None => break, Some(',') => { l.backup(); l.emit_nonempty(ItemType::Text); l.next(); l.emit(ItemType::Comma); }, Some(_) => {}, } } l.emit_nonempty(ItemType::Text); l.emit(ItemType::EOF); None } fn lex_comment(l: &mut Lexer<ItemType>) -> Option<StateFn<ItemType>> { loop { match l.next() { None => break, Some('\n') =>
, Some(_) => {}, } } l.emit_nonempty(ItemType::Comment); l.emit(ItemType::EOF); None } #[test] fn test_lexer() { let data = "foo,bar,baz // some comment\nfoo,bar"; let items = lexer::lex(data, lex_text); let expected_items = vec!( Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 1}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 1}, Item{typ: ItemType::Comma, val: ",", col: 8, lineno: 1}, Item{typ: ItemType::Text, val: "baz ", col: 9, lineno: 1}, Item{typ: ItemType::Comment, val: "// some comment", col: 13, lineno: 1}, Item{typ: ItemType::Text, val: "foo", col: 1, lineno: 2}, Item{typ: ItemType::Comma, val: ",", col: 4, lineno: 2}, Item{typ: ItemType::Text, val: "bar", col: 5, lineno: 2}, Item{typ: ItemType::EOF, val: "", col: 8, lineno: 2} ); for (item, expected) in items.iter().zip(expected_items.iter()) { println!("ITEM: {:?}", item); assert_eq!(item, expected); } assert_eq!(items, expected_items); }
{ l.backup(); l.emit_nonempty(ItemType::Comment); l.next(); l.ignore(); return Some(StateFn(lex_text)); }
conditional_block
mod.rs
extern crate sodiumoxide; extern crate serialize; extern crate sync; extern crate extra; use std::io::{Listener, Acceptor}; use std::io::{MemReader, BufReader}; use std::io::net::ip::{SocketAddr}; use std::io::net::tcp::{TcpListener, TcpStream}; use std::from_str::{from_str}; use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader}; use capnp::serialize_packed; use sync::Arc; use sodiumoxide::crypto::asymmetricbox::{PublicKey, SecretKey, open, seal, gen_keypair}; use helpers::{KeyBytes, bytes_to_pubkey, bytes_to_nonce}; use super::comm; fn process_new_connection(client: TcpStream, my_pubkey: Arc<PublicKey>, my_privkey: Arc<SecretKey>) { use capnp::serialize_packed; use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader}; let mut client = client; println!("New connection from '{:s}'", client.peer_name().unwrap().to_str()); let hellopack = client.read_bytes(9).unwrap(); if (hellopack.as_slice() == comm::bare_msgs::HELLOBYTES)
else { fail!("sad :("); } client.write(comm::bare_msgs::HELLOBYTES); client.write(my_pubkey.get().key_bytes()); let client_pubkey = ~{ let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap(); let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>(); let mut bufreader = BufReader::new(pack.get_data()); let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap(); let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>(); match packdata.which() { Some(comm::pack_capnp::PackData::Pubkey(key)) => bytes_to_pubkey(key), _ => { println!("Client didn't send pubkey, disconnecting"); return; } } }; println!("got client key:\n{:?}", client_pubkey); let mut clientname = ~""; loop { let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap(); let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>(); let nonce = bytes_to_nonce(pack.get_nonce()); let databytes = match open(pack.get_data(), &nonce, client_pubkey, my_privkey.get()) { Some(bytes) => bytes, None => { println!("WARNING! Decrypt failed! "); continue; } }; let mut bufreader = BufReader::new(databytes); let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap(); let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>(); match packdata.which() { Some(comm::pack_capnp::PackData::Login(login)) => { println!("{:s} logged in", login.get_name()); clientname = login.get_name().to_owned(); }, Some(comm::pack_capnp::PackData::Message(message)) => { println!("<{:s}>{:s}", clientname, message.get_message()); }, Some(comm::pack_capnp::PackData::Quit(reason)) => { println!("quitreason: {:s}", reason); break; }, _ => println!("wut") } } } fn writer_task() { } fn setup_sync_task() { } pub fn main() { sodiumoxide::init(); let (s_pubkey, s_privkey) = gen_keypair(); let a_pubkey = Arc::new(s_pubkey); let a_privkey = Arc::new(s_privkey); let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap(); let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind"); let mut s_acceptor = s_listener.listen().ok().expect("Failed to create connection listener"); loop { let pub_clone = a_pubkey.clone(); let priv_clone = a_privkey.clone(); match s_acceptor.accept() { Ok(c_sock) => spawn(proc(){process_new_connection(c_sock, pub_clone, priv_clone)}), Err(err) => println!("Failed connection attempt: {:?}", err) } } }
{ println!("Connection hello received"); }
conditional_block
mod.rs
extern crate sodiumoxide; extern crate serialize; extern crate sync; extern crate extra; use std::io::{Listener, Acceptor}; use std::io::{MemReader, BufReader}; use std::io::net::ip::{SocketAddr}; use std::io::net::tcp::{TcpListener, TcpStream}; use std::from_str::{from_str}; use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader}; use capnp::serialize_packed; use sync::Arc; use sodiumoxide::crypto::asymmetricbox::{PublicKey, SecretKey, open, seal, gen_keypair}; use helpers::{KeyBytes, bytes_to_pubkey, bytes_to_nonce}; use super::comm; fn process_new_connection(client: TcpStream, my_pubkey: Arc<PublicKey>, my_privkey: Arc<SecretKey>) { use capnp::serialize_packed; use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader}; let mut client = client; println!("New connection from '{:s}'", client.peer_name().unwrap().to_str()); let hellopack = client.read_bytes(9).unwrap(); if (hellopack.as_slice() == comm::bare_msgs::HELLOBYTES) { println!("Connection hello received"); } else { fail!("sad :("); } client.write(comm::bare_msgs::HELLOBYTES); client.write(my_pubkey.get().key_bytes()); let client_pubkey = ~{ let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap(); let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>(); let mut bufreader = BufReader::new(pack.get_data()); let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap(); let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>(); match packdata.which() { Some(comm::pack_capnp::PackData::Pubkey(key)) => bytes_to_pubkey(key), _ => { println!("Client didn't send pubkey, disconnecting"); return; } } }; println!("got client key:\n{:?}", client_pubkey); let mut clientname = ~""; loop { let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap(); let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>(); let nonce = bytes_to_nonce(pack.get_nonce()); let databytes = match open(pack.get_data(), &nonce, client_pubkey, my_privkey.get()) { Some(bytes) => bytes, None => { println!("WARNING! Decrypt failed! "); continue; } }; let mut bufreader = BufReader::new(databytes); let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap(); let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>(); match packdata.which() { Some(comm::pack_capnp::PackData::Login(login)) => { println!("{:s} logged in", login.get_name()); clientname = login.get_name().to_owned(); }, Some(comm::pack_capnp::PackData::Message(message)) => { println!("<{:s}>{:s}", clientname, message.get_message()); }, Some(comm::pack_capnp::PackData::Quit(reason)) => { println!("quitreason: {:s}", reason); break; }, _ => println!("wut") } } } fn writer_task() { } fn setup_sync_task() { } pub fn
() { sodiumoxide::init(); let (s_pubkey, s_privkey) = gen_keypair(); let a_pubkey = Arc::new(s_pubkey); let a_privkey = Arc::new(s_privkey); let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap(); let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind"); let mut s_acceptor = s_listener.listen().ok().expect("Failed to create connection listener"); loop { let pub_clone = a_pubkey.clone(); let priv_clone = a_privkey.clone(); match s_acceptor.accept() { Ok(c_sock) => spawn(proc(){process_new_connection(c_sock, pub_clone, priv_clone)}), Err(err) => println!("Failed connection attempt: {:?}", err) } } }
main
identifier_name
mod.rs
extern crate sodiumoxide; extern crate serialize; extern crate sync; extern crate extra; use std::io::{Listener, Acceptor}; use std::io::{MemReader, BufReader}; use std::io::net::ip::{SocketAddr}; use std::io::net::tcp::{TcpListener, TcpStream}; use std::from_str::{from_str}; use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader}; use capnp::serialize_packed; use sync::Arc; use sodiumoxide::crypto::asymmetricbox::{PublicKey, SecretKey, open, seal, gen_keypair}; use helpers::{KeyBytes, bytes_to_pubkey, bytes_to_nonce}; use super::comm; fn process_new_connection(client: TcpStream, my_pubkey: Arc<PublicKey>, my_privkey: Arc<SecretKey>) { use capnp::serialize_packed; use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader}; let mut client = client; println!("New connection from '{:s}'", client.peer_name().unwrap().to_str()); let hellopack = client.read_bytes(9).unwrap(); if (hellopack.as_slice() == comm::bare_msgs::HELLOBYTES) { println!("Connection hello received"); } else { fail!("sad :("); } client.write(comm::bare_msgs::HELLOBYTES); client.write(my_pubkey.get().key_bytes()); let client_pubkey = ~{ let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap(); let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>(); let mut bufreader = BufReader::new(pack.get_data()); let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap(); let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>(); match packdata.which() { Some(comm::pack_capnp::PackData::Pubkey(key)) => bytes_to_pubkey(key), _ => { println!("Client didn't send pubkey, disconnecting"); return; } } }; println!("got client key:\n{:?}", client_pubkey); let mut clientname = ~""; loop { let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap(); let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>(); let nonce = bytes_to_nonce(pack.get_nonce()); let databytes = match open(pack.get_data(), &nonce, client_pubkey, my_privkey.get()) { Some(bytes) => bytes, None => { println!("WARNING! Decrypt failed! "); continue; } }; let mut bufreader = BufReader::new(databytes); let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap(); let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>(); match packdata.which() { Some(comm::pack_capnp::PackData::Login(login)) => { println!("{:s} logged in", login.get_name()); clientname = login.get_name().to_owned(); }, Some(comm::pack_capnp::PackData::Message(message)) => { println!("<{:s}>{:s}", clientname, message.get_message()); }, Some(comm::pack_capnp::PackData::Quit(reason)) => { println!("quitreason: {:s}", reason); break; }, _ => println!("wut") } } } fn writer_task() { } fn setup_sync_task()
pub fn main() { sodiumoxide::init(); let (s_pubkey, s_privkey) = gen_keypair(); let a_pubkey = Arc::new(s_pubkey); let a_privkey = Arc::new(s_privkey); let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap(); let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind"); let mut s_acceptor = s_listener.listen().ok().expect("Failed to create connection listener"); loop { let pub_clone = a_pubkey.clone(); let priv_clone = a_privkey.clone(); match s_acceptor.accept() { Ok(c_sock) => spawn(proc(){process_new_connection(c_sock, pub_clone, priv_clone)}), Err(err) => println!("Failed connection attempt: {:?}", err) } } }
{ }
identifier_body
mod.rs
extern crate sodiumoxide; extern crate serialize; extern crate sync; extern crate extra; use std::io::{Listener, Acceptor}; use std::io::{MemReader, BufReader}; use std::io::net::ip::{SocketAddr}; use std::io::net::tcp::{TcpListener, TcpStream}; use std::from_str::{from_str}; use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader}; use capnp::serialize_packed; use sync::Arc; use sodiumoxide::crypto::asymmetricbox::{PublicKey, SecretKey, open, seal, gen_keypair}; use helpers::{KeyBytes, bytes_to_pubkey, bytes_to_nonce}; use super::comm; fn process_new_connection(client: TcpStream, my_pubkey: Arc<PublicKey>, my_privkey: Arc<SecretKey>) { use capnp::serialize_packed; use capnp::message::{MallocMessageBuilder, MessageBuilder, DEFAULT_READER_OPTIONS, MessageReader}; let mut client = client; println!("New connection from '{:s}'", client.peer_name().unwrap().to_str()); let hellopack = client.read_bytes(9).unwrap(); if (hellopack.as_slice() == comm::bare_msgs::HELLOBYTES) { println!("Connection hello received"); } else { fail!("sad :("); } client.write(comm::bare_msgs::HELLOBYTES); client.write(my_pubkey.get().key_bytes()); let client_pubkey = ~{ let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap(); let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>(); let mut bufreader = BufReader::new(pack.get_data()); let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap(); let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>(); match packdata.which() { Some(comm::pack_capnp::PackData::Pubkey(key)) => bytes_to_pubkey(key), _ => { println!("Client didn't send pubkey, disconnecting"); return; } } }; println!("got client key:\n{:?}", client_pubkey); let mut clientname = ~""; loop { let reader = serialize_packed::new_reader_unbuffered(&mut client, DEFAULT_READER_OPTIONS).unwrap(); let pack = reader.get_root::<comm::pack_capnp::Pack::Reader>(); let nonce = bytes_to_nonce(pack.get_nonce()); let databytes = match open(pack.get_data(), &nonce, client_pubkey, my_privkey.get()) { Some(bytes) => bytes, None => { println!("WARNING! Decrypt failed! "); continue; } }; let mut bufreader = BufReader::new(databytes); let datareader = serialize_packed::new_reader_unbuffered(&mut bufreader, DEFAULT_READER_OPTIONS).unwrap(); let packdata = datareader.get_root::<comm::pack_capnp::PackData::Reader>(); match packdata.which() { Some(comm::pack_capnp::PackData::Login(login)) => { println!("{:s} logged in", login.get_name()); clientname = login.get_name().to_owned(); }, Some(comm::pack_capnp::PackData::Message(message)) => { println!("<{:s}>{:s}", clientname, message.get_message()); }, Some(comm::pack_capnp::PackData::Quit(reason)) => { println!("quitreason: {:s}", reason); break; }, _ => println!("wut") } } } fn writer_task() { } fn setup_sync_task() { } pub fn main() { sodiumoxide::init();
let (s_pubkey, s_privkey) = gen_keypair(); let a_pubkey = Arc::new(s_pubkey); let a_privkey = Arc::new(s_privkey); let bind_addr : SocketAddr = from_str("0.0.0.0:44944").unwrap(); let s_listener = TcpListener::bind(bind_addr).ok().expect("Failed to bind"); let mut s_acceptor = s_listener.listen().ok().expect("Failed to create connection listener"); loop { let pub_clone = a_pubkey.clone(); let priv_clone = a_privkey.clone(); match s_acceptor.accept() { Ok(c_sock) => spawn(proc(){process_new_connection(c_sock, pub_clone, priv_clone)}), Err(err) => println!("Failed connection attempt: {:?}", err) } } }
random_line_split
where-clauses-no-bounds-or-predicates.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. // compile-flags: -Z parse-only fn equal1<T>(_: &T, _: &T) -> bool where
fn equal2<T>(_: &T, _: &T) -> bool where T: { //~^ ERROR each predicate in a `where` clause must have at least one bound true } fn main() { }
{ //~^ ERROR a `where` clause must have at least one predicate in it true }
identifier_body
where-clauses-no-bounds-or-predicates.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. // compile-flags: -Z parse-only fn equal1<T>(_: &T, _: &T) -> bool where { //~^ ERROR a `where` clause must have at least one predicate in it true } fn
<T>(_: &T, _: &T) -> bool where T: { //~^ ERROR each predicate in a `where` clause must have at least one bound true } fn main() { }
equal2
identifier_name
where-clauses-no-bounds-or-predicates.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.
true } fn equal2<T>(_: &T, _: &T) -> bool where T: { //~^ ERROR each predicate in a `where` clause must have at least one bound true } fn main() { }
// compile-flags: -Z parse-only fn equal1<T>(_: &T, _: &T) -> bool where { //~^ ERROR a `where` clause must have at least one predicate in it
random_line_split
vertex_outside.rs
use crate::mock_graph::{ arbitrary::{GuidedArbGraph, Limit}, MockVertex, TestGraph, }; use graphene::{ core::{Ensure, Graph}, impl_ensurer, }; use quickcheck::{Arbitrary, Gen}; use std::collections::HashSet; /// An arbitrary graph and a vertex that is guaranteed to not be in it. #[derive(Clone, Debug)] pub struct VertexOutside<G>(pub G, pub MockVertex) where G: GuidedArbGraph, G::Graph: TestGraph; impl<G> Ensure for VertexOutside<G> where G: GuidedArbGraph, G::Graph: TestGraph, { fn ensure_unvalidated(_c: Self::Ensured, _: ()) -> Self { unimplemented!() } fn validate(_c: &Self::Ensured, _: &()) -> bool { unimplemented!() } } impl_ensurer! { use<G> VertexOutside<G>: Ensure as (self.0): G where G: GuidedArbGraph, G::Graph: TestGraph, } impl<Gr> GuidedArbGraph for VertexOutside<Gr> where Gr: GuidedArbGraph, Gr::Graph: TestGraph, { fn choose_size<G: Gen>( g: &mut G, v_min: usize, v_max: usize, e_min: usize, e_max: usize, ) -> (usize, usize) { Gr::choose_size(g, v_min, v_max, e_min, e_max) } fn
<G: Gen>(g: &mut G, v_count: usize, e_count: usize) -> Self { let graph = Gr::arbitrary_fixed(g, v_count, e_count); // Find a vertex that isn't in the graph let mut v = MockVertex::arbitrary(g); while graph.graph().contains_vertex(v) { v = MockVertex::arbitrary(g); } Self(graph, v) } fn shrink_guided(&self, limits: HashSet<Limit>) -> Box<dyn Iterator<Item = Self>> { let mut result = Vec::new(); // First shrink the graph, keeping only the shrunk ones where the vertex // stays invalid result.extend( self.0 .shrink_guided(limits) .filter(|g|!g.graph().contains_vertex(self.1)) .map(|g| Self(g, self.1)), ); // We then shrink the vertex, keeping only the shrunk values // that are invalid in the graph result.extend( self.1 .shrink() .filter(|&v| self.0.graph().contains_vertex(v)) .map(|v| Self(self.0.clone(), v)), ); Box::new(result.into_iter()) } }
arbitrary_fixed
identifier_name
vertex_outside.rs
use crate::mock_graph::{ arbitrary::{GuidedArbGraph, Limit}, MockVertex, TestGraph, }; use graphene::{ core::{Ensure, Graph}, impl_ensurer, }; use quickcheck::{Arbitrary, Gen}; use std::collections::HashSet; /// An arbitrary graph and a vertex that is guaranteed to not be in it. #[derive(Clone, Debug)] pub struct VertexOutside<G>(pub G, pub MockVertex) where G: GuidedArbGraph, G::Graph: TestGraph; impl<G> Ensure for VertexOutside<G> where G: GuidedArbGraph,
{ fn ensure_unvalidated(_c: Self::Ensured, _: ()) -> Self { unimplemented!() } fn validate(_c: &Self::Ensured, _: &()) -> bool { unimplemented!() } } impl_ensurer! { use<G> VertexOutside<G>: Ensure as (self.0): G where G: GuidedArbGraph, G::Graph: TestGraph, } impl<Gr> GuidedArbGraph for VertexOutside<Gr> where Gr: GuidedArbGraph, Gr::Graph: TestGraph, { fn choose_size<G: Gen>( g: &mut G, v_min: usize, v_max: usize, e_min: usize, e_max: usize, ) -> (usize, usize) { Gr::choose_size(g, v_min, v_max, e_min, e_max) } fn arbitrary_fixed<G: Gen>(g: &mut G, v_count: usize, e_count: usize) -> Self { let graph = Gr::arbitrary_fixed(g, v_count, e_count); // Find a vertex that isn't in the graph let mut v = MockVertex::arbitrary(g); while graph.graph().contains_vertex(v) { v = MockVertex::arbitrary(g); } Self(graph, v) } fn shrink_guided(&self, limits: HashSet<Limit>) -> Box<dyn Iterator<Item = Self>> { let mut result = Vec::new(); // First shrink the graph, keeping only the shrunk ones where the vertex // stays invalid result.extend( self.0 .shrink_guided(limits) .filter(|g|!g.graph().contains_vertex(self.1)) .map(|g| Self(g, self.1)), ); // We then shrink the vertex, keeping only the shrunk values // that are invalid in the graph result.extend( self.1 .shrink() .filter(|&v| self.0.graph().contains_vertex(v)) .map(|v| Self(self.0.clone(), v)), ); Box::new(result.into_iter()) } }
G::Graph: TestGraph,
random_line_split
vertex_outside.rs
use crate::mock_graph::{ arbitrary::{GuidedArbGraph, Limit}, MockVertex, TestGraph, }; use graphene::{ core::{Ensure, Graph}, impl_ensurer, }; use quickcheck::{Arbitrary, Gen}; use std::collections::HashSet; /// An arbitrary graph and a vertex that is guaranteed to not be in it. #[derive(Clone, Debug)] pub struct VertexOutside<G>(pub G, pub MockVertex) where G: GuidedArbGraph, G::Graph: TestGraph; impl<G> Ensure for VertexOutside<G> where G: GuidedArbGraph, G::Graph: TestGraph, { fn ensure_unvalidated(_c: Self::Ensured, _: ()) -> Self { unimplemented!() } fn validate(_c: &Self::Ensured, _: &()) -> bool { unimplemented!() } } impl_ensurer! { use<G> VertexOutside<G>: Ensure as (self.0): G where G: GuidedArbGraph, G::Graph: TestGraph, } impl<Gr> GuidedArbGraph for VertexOutside<Gr> where Gr: GuidedArbGraph, Gr::Graph: TestGraph, { fn choose_size<G: Gen>( g: &mut G, v_min: usize, v_max: usize, e_min: usize, e_max: usize, ) -> (usize, usize) { Gr::choose_size(g, v_min, v_max, e_min, e_max) } fn arbitrary_fixed<G: Gen>(g: &mut G, v_count: usize, e_count: usize) -> Self
fn shrink_guided(&self, limits: HashSet<Limit>) -> Box<dyn Iterator<Item = Self>> { let mut result = Vec::new(); // First shrink the graph, keeping only the shrunk ones where the vertex // stays invalid result.extend( self.0 .shrink_guided(limits) .filter(|g|!g.graph().contains_vertex(self.1)) .map(|g| Self(g, self.1)), ); // We then shrink the vertex, keeping only the shrunk values // that are invalid in the graph result.extend( self.1 .shrink() .filter(|&v| self.0.graph().contains_vertex(v)) .map(|v| Self(self.0.clone(), v)), ); Box::new(result.into_iter()) } }
{ let graph = Gr::arbitrary_fixed(g, v_count, e_count); // Find a vertex that isn't in the graph let mut v = MockVertex::arbitrary(g); while graph.graph().contains_vertex(v) { v = MockVertex::arbitrary(g); } Self(graph, v) }
identifier_body
glib_gobject.rs
// GObject Introspection Rust bindings. // Copyright (C) 2014 Luis Araujo <[email protected]> // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA extern crate libc; use glib_gobject::libc ::{c_void, c_char, c_int, c_uint, c_float, c_long, c_ulong, c_double, size_t}; /* GObject */ pub type GType = size_t; pub type GBoolean = c_int; pub type GPointer = *c_void; pub type GQuark = c_uint; pub enum GData {} #[deriving(Show, FromPrimitive)] pub enum GParamFlags { GParamReadable = 1 << 0, GParamWritable = 1 << 1, GParamConstruct = 1 << 2, GParamConstructOnly = 1 << 3, GParamLaxValidation = 1 << 4, GParamStaticName = 1 << 5, GParamStaticNick = 1 << 6, GParamSTaticBlurb = 1 << 7, /* User defined flags go up to 30 */ GParamDeprecated = 1 << 31 } #[deriving(Show, FromPrimitive)] pub enum GSignalFlags { GSignalRunFirst = 1 << 0, GSignalRunLast = 1 << 1, GSignalRunCleanup = 1 << 2, GSignalNoRecurse = 1 << 3, GSignalDetailed = 1 << 4, GSignalAction = 1 << 5, GSignalNoHooks = 1 << 6, GSignalMustCollect = 1 << 7, GSignalDeprecated = 1 << 8 } pub struct GObject { g_type_instance: GTypeInstance, /*< private >*/ // volatile guint ref_count; ref_count: c_uint, qdata: *GData } struct GTypeInstance { /*< private >*/ g_class: *GTypeClass } struct GTypeClass { /*< private >*/ g_type: GType } pub enum GValueData { GValueDataVInt(c_int), GValueDataVUInt(c_uint), GValueDataVLong(c_long), GValueDataVULong(c_ulong), GValueDataVInt64(i64), GValueDataVUInt64(u64), GValueDataVFloat(c_float), GValueDataVDouble(c_double), GValueDataVPointer(GPointer) } pub struct GValue { /*< private >*/ g_type: GType, /* public for GTypeValueTable methods */ data: [GValueData,..2] } /* GLib */ pub enum
{} pub enum GMappedFile {} /* TODO: Get higher level structs for lists using generics */ pub struct GSList { data: GPointer, next: *GSList } pub struct GList { data: GPointer, next: *GList, prev: *GList } pub struct GError { domain: GQuark, code: c_int, message: *c_char }
GOptionGroup
identifier_name
glib_gobject.rs
// GObject Introspection Rust bindings. // Copyright (C) 2014 Luis Araujo <[email protected]> // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA extern crate libc; use glib_gobject::libc ::{c_void, c_char, c_int, c_uint, c_float, c_long, c_ulong, c_double, size_t}; /* GObject */ pub type GType = size_t; pub type GBoolean = c_int; pub type GPointer = *c_void; pub type GQuark = c_uint; pub enum GData {} #[deriving(Show, FromPrimitive)] pub enum GParamFlags { GParamReadable = 1 << 0, GParamWritable = 1 << 1, GParamConstruct = 1 << 2, GParamConstructOnly = 1 << 3, GParamLaxValidation = 1 << 4, GParamStaticName = 1 << 5, GParamStaticNick = 1 << 6, GParamSTaticBlurb = 1 << 7, /* User defined flags go up to 30 */ GParamDeprecated = 1 << 31 } #[deriving(Show, FromPrimitive)] pub enum GSignalFlags { GSignalRunFirst = 1 << 0, GSignalRunLast = 1 << 1, GSignalRunCleanup = 1 << 2, GSignalNoRecurse = 1 << 3, GSignalDetailed = 1 << 4, GSignalAction = 1 << 5, GSignalNoHooks = 1 << 6, GSignalMustCollect = 1 << 7, GSignalDeprecated = 1 << 8 } pub struct GObject { g_type_instance: GTypeInstance, /*< private >*/ // volatile guint ref_count; ref_count: c_uint, qdata: *GData } struct GTypeInstance { /*< private >*/ g_class: *GTypeClass } struct GTypeClass { /*< private >*/ g_type: GType } pub enum GValueData { GValueDataVInt(c_int), GValueDataVUInt(c_uint), GValueDataVLong(c_long), GValueDataVULong(c_ulong), GValueDataVInt64(i64),
pub struct GValue { /*< private >*/ g_type: GType, /* public for GTypeValueTable methods */ data: [GValueData,..2] } /* GLib */ pub enum GOptionGroup {} pub enum GMappedFile {} /* TODO: Get higher level structs for lists using generics */ pub struct GSList { data: GPointer, next: *GSList } pub struct GList { data: GPointer, next: *GList, prev: *GList } pub struct GError { domain: GQuark, code: c_int, message: *c_char }
GValueDataVUInt64(u64), GValueDataVFloat(c_float), GValueDataVDouble(c_double), GValueDataVPointer(GPointer) }
random_line_split
labeled-break.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. // pretty-expanded FIXME #23616 pub fn main() { 'foo: loop { loop { break 'foo; } } 'bar: for _ in 0..100 { loop { break 'bar;
break 'foobar; } } }
} } 'foobar: while 1 + 1 == 2 { loop {
random_line_split
labeled-break.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. // pretty-expanded FIXME #23616 pub fn main()
{ 'foo: loop { loop { break 'foo; } } 'bar: for _ in 0..100 { loop { break 'bar; } } 'foobar: while 1 + 1 == 2 { loop { break 'foobar; } } }
identifier_body
labeled-break.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. // pretty-expanded FIXME #23616 pub fn
() { 'foo: loop { loop { break 'foo; } } 'bar: for _ in 0..100 { loop { break 'bar; } } 'foobar: while 1 + 1 == 2 { loop { break 'foobar; } } }
main
identifier_name
objdetect.rs
//! Various object detection algorithms, such as Haar feature-based cascade //! classifier for object detection and histogram of oriented gradients (HOG). use super::core::*; use super::errors::*; use super::*; use failure::Error; use std::ffi::CString; use std::os::raw::{c_char, c_double, c_int}; use std::path::Path; use std::vec::Vec; enum CCascadeClassifier {} extern "C" { fn cv_cascade_classifier_new() -> *mut CCascadeClassifier; fn cv_cascade_classifier_load(cc: *mut CCascadeClassifier, p: *const c_char) -> bool; fn cv_cascade_classifier_drop(p: *mut CCascadeClassifier); fn cv_cascade_classifier_detect( cc: *mut CCascadeClassifier, cmat: *mut CMat, vec_of_rect: *mut CVec<Rect>, scale_factor: c_double, min_neighbors: c_int, flags: c_int, min_size: Size2i, max_size: Size2i, ); } /// We can safely send the classifier (a mutable pointer) to a different thread unsafe impl Send for CascadeClassifier {} /// An object detect trait. pub trait ObjectDetect { /// Detects the object inside this image and returns a list of detections /// with their confidence. fn detect(&self, image: &Mat) -> Vec<(Rect, f64)>; } /// Cascade classifier class for object detection. #[derive(Debug)] pub struct CascadeClassifier { inner: *mut CCascadeClassifier, } impl ObjectDetect for CascadeClassifier { fn detect(&self, image: &Mat) -> Vec<(Rect, f64)> { self.detect_multiscale(image) .into_iter() .map(|r| (r, 0f64)) .collect::<Vec<_>>() } } impl CascadeClassifier { /// Creates a cascade classifier, uninitialized. Before use, call load. pub fn new() -> CascadeClassifier { CascadeClassifier { inner: unsafe { cv_cascade_classifier_new() }, } } /// Creates a cascade classifier using the model specified. pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Error> { let cc = CascadeClassifier::new(); cc.load(path)?; Ok(cc) } /// Loads the classifier model from a path. pub fn load<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { if let Some(p) = path.as_ref().to_str() { let s = CString::new(p)?; if unsafe { cv_cascade_classifier_load(self.inner, (&s).as_ptr()) } { return Ok(()); } } Err(CvError::InvalidPath(path.as_ref().to_path_buf()).into()) } /// The default detection uses scale factor 1.1, minNeighbors 3, no min size /// or max size. pub fn detect_multiscale(&self, mat: &Mat) -> Vec<Rect> { self.detect_with_params(mat, 1.1, 3, Size2i::default(), Size2i::default()) } /// Detects the object using parameters specified. /// /// * `mat` - Matrix of the type CV_8U containing an image where objects are /// detected. /// * `scale_factor` - Parameter specifying how much the image size is /// reduced at each image scale. /// * `min_neighbors` - Parameter specifying how many neighbors each /// candidate rectangle should have to retain it. /// * `min_size` - Minimum possible object size. Objects smaller than that /// are ignored. /// * `max_size` - Maximum possible object size. Objects larger than that /// are ignored /// /// OpenCV has a parameter (`flags`) that's not used at all. pub fn detect_with_params( &self, mat: &Mat, scale_factor: f32, min_neighbors: c_int, min_size: Size2i, max_size: Size2i, ) -> Vec<Rect> { let mut c_result = CVec::<Rect>::default(); unsafe { cv_cascade_classifier_detect( self.inner, mat.inner, &mut c_result, scale_factor as c_double, min_neighbors, 0, min_size, max_size, ) } c_result.unpack() } } impl Drop for CascadeClassifier { fn drop(&mut self) { unsafe { cv_cascade_classifier_drop(self.inner); } } } #[derive(Debug, Clone, Copy)] /// Opaque type for C/C++ SvmDetector object pub enum CSvmDetector {} /// SvmDetector #[derive(Debug)] pub struct SvmDetector { /// Pointer to the inner data structure pub(crate) inner: *mut CSvmDetector, } extern "C" { fn cv_hog_default_people_detector() -> *mut CSvmDetector; fn cv_hog_daimler_people_detector() -> *mut CSvmDetector; fn cv_hog_detector_drop(d: *mut CSvmDetector); } impl SvmDetector { /// The built-in people detector. /// /// The size of the default people detector is 64x128, that mean that the /// people you would want to detect have to be atleast 64x128. pub fn default_people_detector() -> SvmDetector { SvmDetector { inner: unsafe { cv_hog_default_people_detector() }, } } /// Returns the Daimler people detector. pub fn daimler_people_detector() -> SvmDetector { SvmDetector { inner: unsafe { cv_hog_daimler_people_detector() }, } } } impl Drop for SvmDetector { fn drop(&mut self) { unsafe { cv_hog_detector_drop(self.inner); } } } /// Parameters that controls the behavior of HOG. #[derive(Debug, Clone, Copy)] pub struct HogParams { /// Detection window size. Align to block size and block stride. The default /// is 64x128, trained the same as original paper. pub win_size: Size2i, /// Block size in pixels. Align to cell size. Only (16,16) is supported for /// now (at least for GPU). pub block_size: Size2i, /// Block stride. It must be a multiple of cell size. pub block_stride: Size2i, /// Cell size. Only (8, 8) is supported for now. pub cell_size: Size2i, /// Number of bins. Only 9 bins per cell are supported for now. pub nbins: c_int, /// Gaussian smoothing window parameter. Default -1 for CPU and 4.0 for GPU. pub win_sigma: f64, /// L2-Hys normalization method shrinkage. Default 0.2. pub l2hys_threshold: f64, /// Flag to specify whether the gamma correction preprocessing is required /// or not. Default false. pub gamma_correction: bool, /// Maximum number of detection window increases (HOG scales). Default: 64. pub nlevels: usize, // ======================================================================= // Functions from detect function // ======================================================================= /// Threshold for the distance between features and SVM classifying /// plane. Usually it is 0 and should be specfied in the detector /// coefficients (as the last free coefficient). But if the free coefficient /// is omitted (which is allowed), you can specify it manually here. pub hit_threshold: f64, /// Window stride. It must be a multiple of block stride. pub win_stride: Size2i, /// Padding pub padding: Size2i, /// Coefficient of the detection window increase. pub scale: f64, /// Coefficient to regulate the similarity threshold. When detected, some /// objects can be covered by many rectangles. 0 means not to perform /// grouping. pub group_threshold: c_int, /// The useMeanShiftGrouping parameter is a boolean indicating whether or /// not mean-shift grouping should be performed to handle potential /// overlapping bounding boxes. While this value should not be set and users /// should employ non-maxima suppression instead, we support setting it as a /// library function. pub use_meanshift_grouping: bool, /// The `finalThreshold` parameter is mainly used to select the clusters /// that have at least `finalThreshold + 1` rectangles. This parameter is /// passed when meanShift is enabled; the function rejects the small /// clusters containing less than or equal to `finalThreshold` rectangles, /// computes the average rectangle size for the rest of the accepted /// clusters and adds those to the output rectangle list. pub final_threshold: f64, } const DEFAULT_WIN_SIGMA: f64 = -1f64; const DEFAULT_NLEVELS: usize = 64; impl Default for HogParams { fn default() -> HogParams { let win_sigma = { if cfg!(feature = "cuda") { 4.0 } else { DEFAULT_WIN_SIGMA } }; HogParams { win_size: Size2i::new(64, 128), block_size: Size2i::new(16, 16), block_stride: Size2i::new(8, 8), cell_size: Size2i::new(8, 8), nbins: 9, win_sigma: win_sigma, l2hys_threshold: 0.2, gamma_correction: false, nlevels: DEFAULT_NLEVELS, hit_threshold: 0f64, win_stride: Size2i::new(8, 8), padding: Size2i::default(), scale: 1.05, group_threshold: 2, final_threshold: 2.0, use_meanshift_grouping: false, } } } enum CHogDescriptor {} /// `HogDescriptor` implements Histogram of Oriented Gradients. #[derive(Debug)] pub struct HogDescriptor { inner: *mut CHogDescriptor, /// Hog parameters. pub params: HogParams, } unsafe impl Send for HogDescriptor {} extern "C" { fn cv_hog_new() -> *mut CHogDescriptor; fn cv_hog_drop(hog: *mut CHogDescriptor); fn cv_hog_set_svm_detector(hog: *mut CHogDescriptor, svm: *mut CSvmDetector); fn cv_hog_detect( hog: *mut CHogDescriptor, image: *mut CMat, objs: *mut CVec<Rect>, weights: *mut CVec<c_double>, win_stride: Size2i, padding: Size2i, scale: c_double, final_threshold: c_double, use_means_shift: bool, ); } impl Default for HogDescriptor { fn default() -> HogDescriptor { HogDescriptor { inner: unsafe { cv_hog_new() }, params: HogParams::default(), } } } impl ObjectDetect for HogDescriptor { fn detect(&self, image: &Mat) -> Vec<(Rect, f64)> { let mut detected = CVec::<Rect>::default(); let mut weights = CVec::<c_double>::default(); unsafe { cv_hog_detect( self.inner, image.inner, &mut detected, &mut weights, self.params.win_stride, self.params.padding, self.params.scale, self.params.final_threshold, self.params.use_meanshift_grouping, ) } let results = detected.unpack(); let weights = weights.unpack(); results.into_iter().zip(weights).collect::<Vec<_>>() } } impl HogDescriptor { /// Creates a HogDescriptor with provided parameters. pub fn with_params(params: HogParams) -> HogDescriptor { HogDescriptor { inner: unsafe { cv_hog_new() }, params: params, } }
impl Drop for HogDescriptor { fn drop(&mut self) { unsafe { cv_hog_drop(self.inner) } } }
/// Sets the SVM detector. pub fn set_svm_detector(&mut self, detector: SvmDetector) { unsafe { cv_hog_set_svm_detector(self.inner, detector.inner) } } }
random_line_split
objdetect.rs
//! Various object detection algorithms, such as Haar feature-based cascade //! classifier for object detection and histogram of oriented gradients (HOG). use super::core::*; use super::errors::*; use super::*; use failure::Error; use std::ffi::CString; use std::os::raw::{c_char, c_double, c_int}; use std::path::Path; use std::vec::Vec; enum CCascadeClassifier {} extern "C" { fn cv_cascade_classifier_new() -> *mut CCascadeClassifier; fn cv_cascade_classifier_load(cc: *mut CCascadeClassifier, p: *const c_char) -> bool; fn cv_cascade_classifier_drop(p: *mut CCascadeClassifier); fn cv_cascade_classifier_detect( cc: *mut CCascadeClassifier, cmat: *mut CMat, vec_of_rect: *mut CVec<Rect>, scale_factor: c_double, min_neighbors: c_int, flags: c_int, min_size: Size2i, max_size: Size2i, ); } /// We can safely send the classifier (a mutable pointer) to a different thread unsafe impl Send for CascadeClassifier {} /// An object detect trait. pub trait ObjectDetect { /// Detects the object inside this image and returns a list of detections /// with their confidence. fn detect(&self, image: &Mat) -> Vec<(Rect, f64)>; } /// Cascade classifier class for object detection. #[derive(Debug)] pub struct CascadeClassifier { inner: *mut CCascadeClassifier, } impl ObjectDetect for CascadeClassifier { fn detect(&self, image: &Mat) -> Vec<(Rect, f64)> { self.detect_multiscale(image) .into_iter() .map(|r| (r, 0f64)) .collect::<Vec<_>>() } } impl CascadeClassifier { /// Creates a cascade classifier, uninitialized. Before use, call load. pub fn new() -> CascadeClassifier { CascadeClassifier { inner: unsafe { cv_cascade_classifier_new() }, } } /// Creates a cascade classifier using the model specified. pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Error> { let cc = CascadeClassifier::new(); cc.load(path)?; Ok(cc) } /// Loads the classifier model from a path. pub fn load<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { if let Some(p) = path.as_ref().to_str() { let s = CString::new(p)?; if unsafe { cv_cascade_classifier_load(self.inner, (&s).as_ptr()) } { return Ok(()); } } Err(CvError::InvalidPath(path.as_ref().to_path_buf()).into()) } /// The default detection uses scale factor 1.1, minNeighbors 3, no min size /// or max size. pub fn detect_multiscale(&self, mat: &Mat) -> Vec<Rect> { self.detect_with_params(mat, 1.1, 3, Size2i::default(), Size2i::default()) } /// Detects the object using parameters specified. /// /// * `mat` - Matrix of the type CV_8U containing an image where objects are /// detected. /// * `scale_factor` - Parameter specifying how much the image size is /// reduced at each image scale. /// * `min_neighbors` - Parameter specifying how many neighbors each /// candidate rectangle should have to retain it. /// * `min_size` - Minimum possible object size. Objects smaller than that /// are ignored. /// * `max_size` - Maximum possible object size. Objects larger than that /// are ignored /// /// OpenCV has a parameter (`flags`) that's not used at all. pub fn detect_with_params( &self, mat: &Mat, scale_factor: f32, min_neighbors: c_int, min_size: Size2i, max_size: Size2i, ) -> Vec<Rect> { let mut c_result = CVec::<Rect>::default(); unsafe { cv_cascade_classifier_detect( self.inner, mat.inner, &mut c_result, scale_factor as c_double, min_neighbors, 0, min_size, max_size, ) } c_result.unpack() } } impl Drop for CascadeClassifier { fn drop(&mut self) { unsafe { cv_cascade_classifier_drop(self.inner); } } } #[derive(Debug, Clone, Copy)] /// Opaque type for C/C++ SvmDetector object pub enum CSvmDetector {} /// SvmDetector #[derive(Debug)] pub struct SvmDetector { /// Pointer to the inner data structure pub(crate) inner: *mut CSvmDetector, } extern "C" { fn cv_hog_default_people_detector() -> *mut CSvmDetector; fn cv_hog_daimler_people_detector() -> *mut CSvmDetector; fn cv_hog_detector_drop(d: *mut CSvmDetector); } impl SvmDetector { /// The built-in people detector. /// /// The size of the default people detector is 64x128, that mean that the /// people you would want to detect have to be atleast 64x128. pub fn default_people_detector() -> SvmDetector { SvmDetector { inner: unsafe { cv_hog_default_people_detector() }, } } /// Returns the Daimler people detector. pub fn daimler_people_detector() -> SvmDetector { SvmDetector { inner: unsafe { cv_hog_daimler_people_detector() }, } } } impl Drop for SvmDetector { fn drop(&mut self) { unsafe { cv_hog_detector_drop(self.inner); } } } /// Parameters that controls the behavior of HOG. #[derive(Debug, Clone, Copy)] pub struct HogParams { /// Detection window size. Align to block size and block stride. The default /// is 64x128, trained the same as original paper. pub win_size: Size2i, /// Block size in pixels. Align to cell size. Only (16,16) is supported for /// now (at least for GPU). pub block_size: Size2i, /// Block stride. It must be a multiple of cell size. pub block_stride: Size2i, /// Cell size. Only (8, 8) is supported for now. pub cell_size: Size2i, /// Number of bins. Only 9 bins per cell are supported for now. pub nbins: c_int, /// Gaussian smoothing window parameter. Default -1 for CPU and 4.0 for GPU. pub win_sigma: f64, /// L2-Hys normalization method shrinkage. Default 0.2. pub l2hys_threshold: f64, /// Flag to specify whether the gamma correction preprocessing is required /// or not. Default false. pub gamma_correction: bool, /// Maximum number of detection window increases (HOG scales). Default: 64. pub nlevels: usize, // ======================================================================= // Functions from detect function // ======================================================================= /// Threshold for the distance between features and SVM classifying /// plane. Usually it is 0 and should be specfied in the detector /// coefficients (as the last free coefficient). But if the free coefficient /// is omitted (which is allowed), you can specify it manually here. pub hit_threshold: f64, /// Window stride. It must be a multiple of block stride. pub win_stride: Size2i, /// Padding pub padding: Size2i, /// Coefficient of the detection window increase. pub scale: f64, /// Coefficient to regulate the similarity threshold. When detected, some /// objects can be covered by many rectangles. 0 means not to perform /// grouping. pub group_threshold: c_int, /// The useMeanShiftGrouping parameter is a boolean indicating whether or /// not mean-shift grouping should be performed to handle potential /// overlapping bounding boxes. While this value should not be set and users /// should employ non-maxima suppression instead, we support setting it as a /// library function. pub use_meanshift_grouping: bool, /// The `finalThreshold` parameter is mainly used to select the clusters /// that have at least `finalThreshold + 1` rectangles. This parameter is /// passed when meanShift is enabled; the function rejects the small /// clusters containing less than or equal to `finalThreshold` rectangles, /// computes the average rectangle size for the rest of the accepted /// clusters and adds those to the output rectangle list. pub final_threshold: f64, } const DEFAULT_WIN_SIGMA: f64 = -1f64; const DEFAULT_NLEVELS: usize = 64; impl Default for HogParams { fn default() -> HogParams { let win_sigma = { if cfg!(feature = "cuda") { 4.0 } else { DEFAULT_WIN_SIGMA } }; HogParams { win_size: Size2i::new(64, 128), block_size: Size2i::new(16, 16), block_stride: Size2i::new(8, 8), cell_size: Size2i::new(8, 8), nbins: 9, win_sigma: win_sigma, l2hys_threshold: 0.2, gamma_correction: false, nlevels: DEFAULT_NLEVELS, hit_threshold: 0f64, win_stride: Size2i::new(8, 8), padding: Size2i::default(), scale: 1.05, group_threshold: 2, final_threshold: 2.0, use_meanshift_grouping: false, } } } enum CHogDescriptor {} /// `HogDescriptor` implements Histogram of Oriented Gradients. #[derive(Debug)] pub struct
{ inner: *mut CHogDescriptor, /// Hog parameters. pub params: HogParams, } unsafe impl Send for HogDescriptor {} extern "C" { fn cv_hog_new() -> *mut CHogDescriptor; fn cv_hog_drop(hog: *mut CHogDescriptor); fn cv_hog_set_svm_detector(hog: *mut CHogDescriptor, svm: *mut CSvmDetector); fn cv_hog_detect( hog: *mut CHogDescriptor, image: *mut CMat, objs: *mut CVec<Rect>, weights: *mut CVec<c_double>, win_stride: Size2i, padding: Size2i, scale: c_double, final_threshold: c_double, use_means_shift: bool, ); } impl Default for HogDescriptor { fn default() -> HogDescriptor { HogDescriptor { inner: unsafe { cv_hog_new() }, params: HogParams::default(), } } } impl ObjectDetect for HogDescriptor { fn detect(&self, image: &Mat) -> Vec<(Rect, f64)> { let mut detected = CVec::<Rect>::default(); let mut weights = CVec::<c_double>::default(); unsafe { cv_hog_detect( self.inner, image.inner, &mut detected, &mut weights, self.params.win_stride, self.params.padding, self.params.scale, self.params.final_threshold, self.params.use_meanshift_grouping, ) } let results = detected.unpack(); let weights = weights.unpack(); results.into_iter().zip(weights).collect::<Vec<_>>() } } impl HogDescriptor { /// Creates a HogDescriptor with provided parameters. pub fn with_params(params: HogParams) -> HogDescriptor { HogDescriptor { inner: unsafe { cv_hog_new() }, params: params, } } /// Sets the SVM detector. pub fn set_svm_detector(&mut self, detector: SvmDetector) { unsafe { cv_hog_set_svm_detector(self.inner, detector.inner) } } } impl Drop for HogDescriptor { fn drop(&mut self) { unsafe { cv_hog_drop(self.inner) } } }
HogDescriptor
identifier_name
objdetect.rs
//! Various object detection algorithms, such as Haar feature-based cascade //! classifier for object detection and histogram of oriented gradients (HOG). use super::core::*; use super::errors::*; use super::*; use failure::Error; use std::ffi::CString; use std::os::raw::{c_char, c_double, c_int}; use std::path::Path; use std::vec::Vec; enum CCascadeClassifier {} extern "C" { fn cv_cascade_classifier_new() -> *mut CCascadeClassifier; fn cv_cascade_classifier_load(cc: *mut CCascadeClassifier, p: *const c_char) -> bool; fn cv_cascade_classifier_drop(p: *mut CCascadeClassifier); fn cv_cascade_classifier_detect( cc: *mut CCascadeClassifier, cmat: *mut CMat, vec_of_rect: *mut CVec<Rect>, scale_factor: c_double, min_neighbors: c_int, flags: c_int, min_size: Size2i, max_size: Size2i, ); } /// We can safely send the classifier (a mutable pointer) to a different thread unsafe impl Send for CascadeClassifier {} /// An object detect trait. pub trait ObjectDetect { /// Detects the object inside this image and returns a list of detections /// with their confidence. fn detect(&self, image: &Mat) -> Vec<(Rect, f64)>; } /// Cascade classifier class for object detection. #[derive(Debug)] pub struct CascadeClassifier { inner: *mut CCascadeClassifier, } impl ObjectDetect for CascadeClassifier { fn detect(&self, image: &Mat) -> Vec<(Rect, f64)> { self.detect_multiscale(image) .into_iter() .map(|r| (r, 0f64)) .collect::<Vec<_>>() } } impl CascadeClassifier { /// Creates a cascade classifier, uninitialized. Before use, call load. pub fn new() -> CascadeClassifier { CascadeClassifier { inner: unsafe { cv_cascade_classifier_new() }, } } /// Creates a cascade classifier using the model specified. pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Error> { let cc = CascadeClassifier::new(); cc.load(path)?; Ok(cc) } /// Loads the classifier model from a path. pub fn load<P: AsRef<Path>>(&self, path: P) -> Result<(), Error>
/// The default detection uses scale factor 1.1, minNeighbors 3, no min size /// or max size. pub fn detect_multiscale(&self, mat: &Mat) -> Vec<Rect> { self.detect_with_params(mat, 1.1, 3, Size2i::default(), Size2i::default()) } /// Detects the object using parameters specified. /// /// * `mat` - Matrix of the type CV_8U containing an image where objects are /// detected. /// * `scale_factor` - Parameter specifying how much the image size is /// reduced at each image scale. /// * `min_neighbors` - Parameter specifying how many neighbors each /// candidate rectangle should have to retain it. /// * `min_size` - Minimum possible object size. Objects smaller than that /// are ignored. /// * `max_size` - Maximum possible object size. Objects larger than that /// are ignored /// /// OpenCV has a parameter (`flags`) that's not used at all. pub fn detect_with_params( &self, mat: &Mat, scale_factor: f32, min_neighbors: c_int, min_size: Size2i, max_size: Size2i, ) -> Vec<Rect> { let mut c_result = CVec::<Rect>::default(); unsafe { cv_cascade_classifier_detect( self.inner, mat.inner, &mut c_result, scale_factor as c_double, min_neighbors, 0, min_size, max_size, ) } c_result.unpack() } } impl Drop for CascadeClassifier { fn drop(&mut self) { unsafe { cv_cascade_classifier_drop(self.inner); } } } #[derive(Debug, Clone, Copy)] /// Opaque type for C/C++ SvmDetector object pub enum CSvmDetector {} /// SvmDetector #[derive(Debug)] pub struct SvmDetector { /// Pointer to the inner data structure pub(crate) inner: *mut CSvmDetector, } extern "C" { fn cv_hog_default_people_detector() -> *mut CSvmDetector; fn cv_hog_daimler_people_detector() -> *mut CSvmDetector; fn cv_hog_detector_drop(d: *mut CSvmDetector); } impl SvmDetector { /// The built-in people detector. /// /// The size of the default people detector is 64x128, that mean that the /// people you would want to detect have to be atleast 64x128. pub fn default_people_detector() -> SvmDetector { SvmDetector { inner: unsafe { cv_hog_default_people_detector() }, } } /// Returns the Daimler people detector. pub fn daimler_people_detector() -> SvmDetector { SvmDetector { inner: unsafe { cv_hog_daimler_people_detector() }, } } } impl Drop for SvmDetector { fn drop(&mut self) { unsafe { cv_hog_detector_drop(self.inner); } } } /// Parameters that controls the behavior of HOG. #[derive(Debug, Clone, Copy)] pub struct HogParams { /// Detection window size. Align to block size and block stride. The default /// is 64x128, trained the same as original paper. pub win_size: Size2i, /// Block size in pixels. Align to cell size. Only (16,16) is supported for /// now (at least for GPU). pub block_size: Size2i, /// Block stride. It must be a multiple of cell size. pub block_stride: Size2i, /// Cell size. Only (8, 8) is supported for now. pub cell_size: Size2i, /// Number of bins. Only 9 bins per cell are supported for now. pub nbins: c_int, /// Gaussian smoothing window parameter. Default -1 for CPU and 4.0 for GPU. pub win_sigma: f64, /// L2-Hys normalization method shrinkage. Default 0.2. pub l2hys_threshold: f64, /// Flag to specify whether the gamma correction preprocessing is required /// or not. Default false. pub gamma_correction: bool, /// Maximum number of detection window increases (HOG scales). Default: 64. pub nlevels: usize, // ======================================================================= // Functions from detect function // ======================================================================= /// Threshold for the distance between features and SVM classifying /// plane. Usually it is 0 and should be specfied in the detector /// coefficients (as the last free coefficient). But if the free coefficient /// is omitted (which is allowed), you can specify it manually here. pub hit_threshold: f64, /// Window stride. It must be a multiple of block stride. pub win_stride: Size2i, /// Padding pub padding: Size2i, /// Coefficient of the detection window increase. pub scale: f64, /// Coefficient to regulate the similarity threshold. When detected, some /// objects can be covered by many rectangles. 0 means not to perform /// grouping. pub group_threshold: c_int, /// The useMeanShiftGrouping parameter is a boolean indicating whether or /// not mean-shift grouping should be performed to handle potential /// overlapping bounding boxes. While this value should not be set and users /// should employ non-maxima suppression instead, we support setting it as a /// library function. pub use_meanshift_grouping: bool, /// The `finalThreshold` parameter is mainly used to select the clusters /// that have at least `finalThreshold + 1` rectangles. This parameter is /// passed when meanShift is enabled; the function rejects the small /// clusters containing less than or equal to `finalThreshold` rectangles, /// computes the average rectangle size for the rest of the accepted /// clusters and adds those to the output rectangle list. pub final_threshold: f64, } const DEFAULT_WIN_SIGMA: f64 = -1f64; const DEFAULT_NLEVELS: usize = 64; impl Default for HogParams { fn default() -> HogParams { let win_sigma = { if cfg!(feature = "cuda") { 4.0 } else { DEFAULT_WIN_SIGMA } }; HogParams { win_size: Size2i::new(64, 128), block_size: Size2i::new(16, 16), block_stride: Size2i::new(8, 8), cell_size: Size2i::new(8, 8), nbins: 9, win_sigma: win_sigma, l2hys_threshold: 0.2, gamma_correction: false, nlevels: DEFAULT_NLEVELS, hit_threshold: 0f64, win_stride: Size2i::new(8, 8), padding: Size2i::default(), scale: 1.05, group_threshold: 2, final_threshold: 2.0, use_meanshift_grouping: false, } } } enum CHogDescriptor {} /// `HogDescriptor` implements Histogram of Oriented Gradients. #[derive(Debug)] pub struct HogDescriptor { inner: *mut CHogDescriptor, /// Hog parameters. pub params: HogParams, } unsafe impl Send for HogDescriptor {} extern "C" { fn cv_hog_new() -> *mut CHogDescriptor; fn cv_hog_drop(hog: *mut CHogDescriptor); fn cv_hog_set_svm_detector(hog: *mut CHogDescriptor, svm: *mut CSvmDetector); fn cv_hog_detect( hog: *mut CHogDescriptor, image: *mut CMat, objs: *mut CVec<Rect>, weights: *mut CVec<c_double>, win_stride: Size2i, padding: Size2i, scale: c_double, final_threshold: c_double, use_means_shift: bool, ); } impl Default for HogDescriptor { fn default() -> HogDescriptor { HogDescriptor { inner: unsafe { cv_hog_new() }, params: HogParams::default(), } } } impl ObjectDetect for HogDescriptor { fn detect(&self, image: &Mat) -> Vec<(Rect, f64)> { let mut detected = CVec::<Rect>::default(); let mut weights = CVec::<c_double>::default(); unsafe { cv_hog_detect( self.inner, image.inner, &mut detected, &mut weights, self.params.win_stride, self.params.padding, self.params.scale, self.params.final_threshold, self.params.use_meanshift_grouping, ) } let results = detected.unpack(); let weights = weights.unpack(); results.into_iter().zip(weights).collect::<Vec<_>>() } } impl HogDescriptor { /// Creates a HogDescriptor with provided parameters. pub fn with_params(params: HogParams) -> HogDescriptor { HogDescriptor { inner: unsafe { cv_hog_new() }, params: params, } } /// Sets the SVM detector. pub fn set_svm_detector(&mut self, detector: SvmDetector) { unsafe { cv_hog_set_svm_detector(self.inner, detector.inner) } } } impl Drop for HogDescriptor { fn drop(&mut self) { unsafe { cv_hog_drop(self.inner) } } }
{ if let Some(p) = path.as_ref().to_str() { let s = CString::new(p)?; if unsafe { cv_cascade_classifier_load(self.inner, (&s).as_ptr()) } { return Ok(()); } } Err(CvError::InvalidPath(path.as_ref().to_path_buf()).into()) }
identifier_body
objdetect.rs
//! Various object detection algorithms, such as Haar feature-based cascade //! classifier for object detection and histogram of oriented gradients (HOG). use super::core::*; use super::errors::*; use super::*; use failure::Error; use std::ffi::CString; use std::os::raw::{c_char, c_double, c_int}; use std::path::Path; use std::vec::Vec; enum CCascadeClassifier {} extern "C" { fn cv_cascade_classifier_new() -> *mut CCascadeClassifier; fn cv_cascade_classifier_load(cc: *mut CCascadeClassifier, p: *const c_char) -> bool; fn cv_cascade_classifier_drop(p: *mut CCascadeClassifier); fn cv_cascade_classifier_detect( cc: *mut CCascadeClassifier, cmat: *mut CMat, vec_of_rect: *mut CVec<Rect>, scale_factor: c_double, min_neighbors: c_int, flags: c_int, min_size: Size2i, max_size: Size2i, ); } /// We can safely send the classifier (a mutable pointer) to a different thread unsafe impl Send for CascadeClassifier {} /// An object detect trait. pub trait ObjectDetect { /// Detects the object inside this image and returns a list of detections /// with their confidence. fn detect(&self, image: &Mat) -> Vec<(Rect, f64)>; } /// Cascade classifier class for object detection. #[derive(Debug)] pub struct CascadeClassifier { inner: *mut CCascadeClassifier, } impl ObjectDetect for CascadeClassifier { fn detect(&self, image: &Mat) -> Vec<(Rect, f64)> { self.detect_multiscale(image) .into_iter() .map(|r| (r, 0f64)) .collect::<Vec<_>>() } } impl CascadeClassifier { /// Creates a cascade classifier, uninitialized. Before use, call load. pub fn new() -> CascadeClassifier { CascadeClassifier { inner: unsafe { cv_cascade_classifier_new() }, } } /// Creates a cascade classifier using the model specified. pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Error> { let cc = CascadeClassifier::new(); cc.load(path)?; Ok(cc) } /// Loads the classifier model from a path. pub fn load<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> { if let Some(p) = path.as_ref().to_str()
Err(CvError::InvalidPath(path.as_ref().to_path_buf()).into()) } /// The default detection uses scale factor 1.1, minNeighbors 3, no min size /// or max size. pub fn detect_multiscale(&self, mat: &Mat) -> Vec<Rect> { self.detect_with_params(mat, 1.1, 3, Size2i::default(), Size2i::default()) } /// Detects the object using parameters specified. /// /// * `mat` - Matrix of the type CV_8U containing an image where objects are /// detected. /// * `scale_factor` - Parameter specifying how much the image size is /// reduced at each image scale. /// * `min_neighbors` - Parameter specifying how many neighbors each /// candidate rectangle should have to retain it. /// * `min_size` - Minimum possible object size. Objects smaller than that /// are ignored. /// * `max_size` - Maximum possible object size. Objects larger than that /// are ignored /// /// OpenCV has a parameter (`flags`) that's not used at all. pub fn detect_with_params( &self, mat: &Mat, scale_factor: f32, min_neighbors: c_int, min_size: Size2i, max_size: Size2i, ) -> Vec<Rect> { let mut c_result = CVec::<Rect>::default(); unsafe { cv_cascade_classifier_detect( self.inner, mat.inner, &mut c_result, scale_factor as c_double, min_neighbors, 0, min_size, max_size, ) } c_result.unpack() } } impl Drop for CascadeClassifier { fn drop(&mut self) { unsafe { cv_cascade_classifier_drop(self.inner); } } } #[derive(Debug, Clone, Copy)] /// Opaque type for C/C++ SvmDetector object pub enum CSvmDetector {} /// SvmDetector #[derive(Debug)] pub struct SvmDetector { /// Pointer to the inner data structure pub(crate) inner: *mut CSvmDetector, } extern "C" { fn cv_hog_default_people_detector() -> *mut CSvmDetector; fn cv_hog_daimler_people_detector() -> *mut CSvmDetector; fn cv_hog_detector_drop(d: *mut CSvmDetector); } impl SvmDetector { /// The built-in people detector. /// /// The size of the default people detector is 64x128, that mean that the /// people you would want to detect have to be atleast 64x128. pub fn default_people_detector() -> SvmDetector { SvmDetector { inner: unsafe { cv_hog_default_people_detector() }, } } /// Returns the Daimler people detector. pub fn daimler_people_detector() -> SvmDetector { SvmDetector { inner: unsafe { cv_hog_daimler_people_detector() }, } } } impl Drop for SvmDetector { fn drop(&mut self) { unsafe { cv_hog_detector_drop(self.inner); } } } /// Parameters that controls the behavior of HOG. #[derive(Debug, Clone, Copy)] pub struct HogParams { /// Detection window size. Align to block size and block stride. The default /// is 64x128, trained the same as original paper. pub win_size: Size2i, /// Block size in pixels. Align to cell size. Only (16,16) is supported for /// now (at least for GPU). pub block_size: Size2i, /// Block stride. It must be a multiple of cell size. pub block_stride: Size2i, /// Cell size. Only (8, 8) is supported for now. pub cell_size: Size2i, /// Number of bins. Only 9 bins per cell are supported for now. pub nbins: c_int, /// Gaussian smoothing window parameter. Default -1 for CPU and 4.0 for GPU. pub win_sigma: f64, /// L2-Hys normalization method shrinkage. Default 0.2. pub l2hys_threshold: f64, /// Flag to specify whether the gamma correction preprocessing is required /// or not. Default false. pub gamma_correction: bool, /// Maximum number of detection window increases (HOG scales). Default: 64. pub nlevels: usize, // ======================================================================= // Functions from detect function // ======================================================================= /// Threshold for the distance between features and SVM classifying /// plane. Usually it is 0 and should be specfied in the detector /// coefficients (as the last free coefficient). But if the free coefficient /// is omitted (which is allowed), you can specify it manually here. pub hit_threshold: f64, /// Window stride. It must be a multiple of block stride. pub win_stride: Size2i, /// Padding pub padding: Size2i, /// Coefficient of the detection window increase. pub scale: f64, /// Coefficient to regulate the similarity threshold. When detected, some /// objects can be covered by many rectangles. 0 means not to perform /// grouping. pub group_threshold: c_int, /// The useMeanShiftGrouping parameter is a boolean indicating whether or /// not mean-shift grouping should be performed to handle potential /// overlapping bounding boxes. While this value should not be set and users /// should employ non-maxima suppression instead, we support setting it as a /// library function. pub use_meanshift_grouping: bool, /// The `finalThreshold` parameter is mainly used to select the clusters /// that have at least `finalThreshold + 1` rectangles. This parameter is /// passed when meanShift is enabled; the function rejects the small /// clusters containing less than or equal to `finalThreshold` rectangles, /// computes the average rectangle size for the rest of the accepted /// clusters and adds those to the output rectangle list. pub final_threshold: f64, } const DEFAULT_WIN_SIGMA: f64 = -1f64; const DEFAULT_NLEVELS: usize = 64; impl Default for HogParams { fn default() -> HogParams { let win_sigma = { if cfg!(feature = "cuda") { 4.0 } else { DEFAULT_WIN_SIGMA } }; HogParams { win_size: Size2i::new(64, 128), block_size: Size2i::new(16, 16), block_stride: Size2i::new(8, 8), cell_size: Size2i::new(8, 8), nbins: 9, win_sigma: win_sigma, l2hys_threshold: 0.2, gamma_correction: false, nlevels: DEFAULT_NLEVELS, hit_threshold: 0f64, win_stride: Size2i::new(8, 8), padding: Size2i::default(), scale: 1.05, group_threshold: 2, final_threshold: 2.0, use_meanshift_grouping: false, } } } enum CHogDescriptor {} /// `HogDescriptor` implements Histogram of Oriented Gradients. #[derive(Debug)] pub struct HogDescriptor { inner: *mut CHogDescriptor, /// Hog parameters. pub params: HogParams, } unsafe impl Send for HogDescriptor {} extern "C" { fn cv_hog_new() -> *mut CHogDescriptor; fn cv_hog_drop(hog: *mut CHogDescriptor); fn cv_hog_set_svm_detector(hog: *mut CHogDescriptor, svm: *mut CSvmDetector); fn cv_hog_detect( hog: *mut CHogDescriptor, image: *mut CMat, objs: *mut CVec<Rect>, weights: *mut CVec<c_double>, win_stride: Size2i, padding: Size2i, scale: c_double, final_threshold: c_double, use_means_shift: bool, ); } impl Default for HogDescriptor { fn default() -> HogDescriptor { HogDescriptor { inner: unsafe { cv_hog_new() }, params: HogParams::default(), } } } impl ObjectDetect for HogDescriptor { fn detect(&self, image: &Mat) -> Vec<(Rect, f64)> { let mut detected = CVec::<Rect>::default(); let mut weights = CVec::<c_double>::default(); unsafe { cv_hog_detect( self.inner, image.inner, &mut detected, &mut weights, self.params.win_stride, self.params.padding, self.params.scale, self.params.final_threshold, self.params.use_meanshift_grouping, ) } let results = detected.unpack(); let weights = weights.unpack(); results.into_iter().zip(weights).collect::<Vec<_>>() } } impl HogDescriptor { /// Creates a HogDescriptor with provided parameters. pub fn with_params(params: HogParams) -> HogDescriptor { HogDescriptor { inner: unsafe { cv_hog_new() }, params: params, } } /// Sets the SVM detector. pub fn set_svm_detector(&mut self, detector: SvmDetector) { unsafe { cv_hog_set_svm_detector(self.inner, detector.inner) } } } impl Drop for HogDescriptor { fn drop(&mut self) { unsafe { cv_hog_drop(self.inner) } } }
{ let s = CString::new(p)?; if unsafe { cv_cascade_classifier_load(self.inner, (&s).as_ptr()) } { return Ok(()); } }
conditional_block
users.rs
#![crate_name = "uu_users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // Allow dead code here in order to keep all fields, constants here, for consistency. #![allow(dead_code)] extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use getopts::Options; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use uucore::utmpx::*; extern { fn getutxent() -> *const c_utmp; fn getutxid(ut: *const c_utmp) -> *const c_utmp; fn getutxline(ut: *const c_utmp) -> *const c_utmp; fn pututxline(ut: *const c_utmp) -> *const c_utmp; fn setutxent(); fn endutxent(); #[cfg(any(target_os = "macos", target_os = "linux"))] fn utmpxname(file: *const libc::c_char) -> libc::c_int; } #[cfg(target_os = "freebsd")] unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int { 0 } static NAME: &'static str = "users"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("{}", f), }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {} [OPTION]... [FILE]", NAME); println!(""); println!("{}", opts.usage("Output who is currently logged in according to FILE.")); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let filename = if!matches.free.is_empty() { matches.free[0].as_ref() } else { DEFAULT_FILE }; exec(filename); 0 } fn exec(filename: &str)
} } endutxent(); } if!users.is_empty() { users.sort(); println!("{}", users.join(" ")); } }
{ unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent(); loop { let line = getutxent(); if line == ptr::null() { break; } if (*line).ut_type == USER_PROCESS { let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string(); users.push(user);
identifier_body
users.rs
#![crate_name = "uu_users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // Allow dead code here in order to keep all fields, constants here, for consistency. #![allow(dead_code)] extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use getopts::Options; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use uucore::utmpx::*; extern { fn getutxent() -> *const c_utmp; fn getutxid(ut: *const c_utmp) -> *const c_utmp; fn getutxline(ut: *const c_utmp) -> *const c_utmp; fn pututxline(ut: *const c_utmp) -> *const c_utmp; fn setutxent(); fn endutxent(); #[cfg(any(target_os = "macos", target_os = "linux"))] fn utmpxname(file: *const libc::c_char) -> libc::c_int; } #[cfg(target_os = "freebsd")] unsafe extern fn utmpxname(_file: *const libc::c_char) -> libc::c_int { 0 } static NAME: &'static str = "users"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("{}", f), }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {} [OPTION]... [FILE]", NAME); println!(""); println!("{}", opts.usage("Output who is currently logged in according to FILE.")); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let filename = if!matches.free.is_empty() { matches.free[0].as_ref() } else { DEFAULT_FILE }; exec(filename); 0 } fn exec(filename: &str) { unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent(); loop { let line = getutxent(); if line == ptr::null() { break; } if (*line).ut_type == USER_PROCESS { let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string(); users.push(user); } } endutxent(); } if!users.is_empty() {
users.sort(); println!("{}", users.join(" ")); } }
random_line_split
users.rs
#![crate_name = "uu_users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // Allow dead code here in order to keep all fields, constants here, for consistency. #![allow(dead_code)] extern crate getopts; extern crate libc; #[macro_use] extern crate uucore; use getopts::Options; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use uucore::utmpx::*; extern { fn getutxent() -> *const c_utmp; fn getutxid(ut: *const c_utmp) -> *const c_utmp; fn getutxline(ut: *const c_utmp) -> *const c_utmp; fn pututxline(ut: *const c_utmp) -> *const c_utmp; fn setutxent(); fn endutxent(); #[cfg(any(target_os = "macos", target_os = "linux"))] fn utmpxname(file: *const libc::c_char) -> libc::c_int; } #[cfg(target_os = "freebsd")] unsafe extern fn
(_file: *const libc::c_char) -> libc::c_int { 0 } static NAME: &'static str = "users"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!("{}", f), }; if matches.opt_present("help") { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); println!(" {} [OPTION]... [FILE]", NAME); println!(""); println!("{}", opts.usage("Output who is currently logged in according to FILE.")); return 0; } if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } let filename = if!matches.free.is_empty() { matches.free[0].as_ref() } else { DEFAULT_FILE }; exec(filename); 0 } fn exec(filename: &str) { unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent(); loop { let line = getutxent(); if line == ptr::null() { break; } if (*line).ut_type == USER_PROCESS { let user = String::from_utf8_lossy(CStr::from_ptr(mem::transmute(&(*line).ut_user)).to_bytes()).to_string(); users.push(user); } } endutxent(); } if!users.is_empty() { users.sort(); println!("{}", users.join(" ")); } }
utmpxname
identifier_name
mod.rs
pub mod message; use std::net::TcpStream; use std::io; use std::io::{BufReader, Write, BufRead, Error}; use irc::message::{Message, MessageError}; /// Contains methods that handle common IRC functionality. pub trait Irc { /// Sends login credentials to the server. fn login(&mut self, username: &str, oauth: &str) -> Result<(), io::Error>; } impl Irc for TcpStream { fn login(&mut self, username: &str, oauth: &str) -> Result<(), io::Error> { writeln!(self, "USER {} 0 * :{}", username, username)?; writeln!(self, "PASS {}", oauth)?; writeln!(self, "NICK {}", username)?; writeln!(self, "CAP REQ :twitch.tv/membership")?; Ok(()) } } pub trait StreamUtil { /// Sends a `&str` to the server immediately. fn send_line(&mut self, string: &str) -> Result<(), io::Error>; } impl StreamUtil for TcpStream { fn send_line(&mut self, string: &str) -> Result<(), io::Error>
} /// Represents an error caused by reading a [`Message`] from the server. /// [`Message`]: message/enum.Message.html #[derive(Debug)] pub enum ReadLineError { /// The error is related to the connection. Connection(Error), /// The error is related to the attempt to parse the message received from the server. Message(MessageError), } pub trait ReaderUtil { /// Reads a line directly from the connected server. fn read_line_raw(&mut self) -> Result<String, Error>; /// Reads a line from the server and parses a [`Message`] from it. /// [`Message`]: message/enum.Message.html fn read_message(&mut self) -> Result<Message, ReadLineError>; } impl ReaderUtil for BufReader<TcpStream> { fn read_line_raw(&mut self) -> Result<String, Error> { let mut line = String::new(); self.read_line(&mut line)?; Ok(line) } fn read_message(&mut self) -> Result<Message, ReadLineError> { self.read_line_raw() .map_err(ReadLineError::Connection) .and_then(|line| Message::parse(&line).map_err(ReadLineError::Message)) } }
{ writeln!(self, "{}", string)?; self.flush() }
identifier_body
mod.rs
pub mod message; use std::net::TcpStream; use std::io; use std::io::{BufReader, Write, BufRead, Error}; use irc::message::{Message, MessageError}; /// Contains methods that handle common IRC functionality. pub trait Irc { /// Sends login credentials to the server. fn login(&mut self, username: &str, oauth: &str) -> Result<(), io::Error>; } impl Irc for TcpStream { fn login(&mut self, username: &str, oauth: &str) -> Result<(), io::Error> { writeln!(self, "USER {} 0 * :{}", username, username)?; writeln!(self, "PASS {}", oauth)?; writeln!(self, "NICK {}", username)?; writeln!(self, "CAP REQ :twitch.tv/membership")?; Ok(()) } } pub trait StreamUtil { /// Sends a `&str` to the server immediately. fn send_line(&mut self, string: &str) -> Result<(), io::Error>; } impl StreamUtil for TcpStream { fn send_line(&mut self, string: &str) -> Result<(), io::Error> { writeln!(self, "{}", string)?; self.flush() } } /// Represents an error caused by reading a [`Message`] from the server. /// [`Message`]: message/enum.Message.html #[derive(Debug)] pub enum
{ /// The error is related to the connection. Connection(Error), /// The error is related to the attempt to parse the message received from the server. Message(MessageError), } pub trait ReaderUtil { /// Reads a line directly from the connected server. fn read_line_raw(&mut self) -> Result<String, Error>; /// Reads a line from the server and parses a [`Message`] from it. /// [`Message`]: message/enum.Message.html fn read_message(&mut self) -> Result<Message, ReadLineError>; } impl ReaderUtil for BufReader<TcpStream> { fn read_line_raw(&mut self) -> Result<String, Error> { let mut line = String::new(); self.read_line(&mut line)?; Ok(line) } fn read_message(&mut self) -> Result<Message, ReadLineError> { self.read_line_raw() .map_err(ReadLineError::Connection) .and_then(|line| Message::parse(&line).map_err(ReadLineError::Message)) } }
ReadLineError
identifier_name
mod.rs
pub mod message; use std::net::TcpStream; use std::io; use std::io::{BufReader, Write, BufRead, Error}; use irc::message::{Message, MessageError}; /// Contains methods that handle common IRC functionality. pub trait Irc { /// Sends login credentials to the server. fn login(&mut self, username: &str, oauth: &str) -> Result<(), io::Error>; } impl Irc for TcpStream { fn login(&mut self, username: &str, oauth: &str) -> Result<(), io::Error> { writeln!(self, "USER {} 0 * :{}", username, username)?; writeln!(self, "PASS {}", oauth)?; writeln!(self, "NICK {}", username)?; writeln!(self, "CAP REQ :twitch.tv/membership")?; Ok(()) } } pub trait StreamUtil { /// Sends a `&str` to the server immediately. fn send_line(&mut self, string: &str) -> Result<(), io::Error>; } impl StreamUtil for TcpStream {
/// Represents an error caused by reading a [`Message`] from the server. /// [`Message`]: message/enum.Message.html #[derive(Debug)] pub enum ReadLineError { /// The error is related to the connection. Connection(Error), /// The error is related to the attempt to parse the message received from the server. Message(MessageError), } pub trait ReaderUtil { /// Reads a line directly from the connected server. fn read_line_raw(&mut self) -> Result<String, Error>; /// Reads a line from the server and parses a [`Message`] from it. /// [`Message`]: message/enum.Message.html fn read_message(&mut self) -> Result<Message, ReadLineError>; } impl ReaderUtil for BufReader<TcpStream> { fn read_line_raw(&mut self) -> Result<String, Error> { let mut line = String::new(); self.read_line(&mut line)?; Ok(line) } fn read_message(&mut self) -> Result<Message, ReadLineError> { self.read_line_raw() .map_err(ReadLineError::Connection) .and_then(|line| Message::parse(&line).map_err(ReadLineError::Message)) } }
fn send_line(&mut self, string: &str) -> Result<(), io::Error> { writeln!(self, "{}", string)?; self.flush() } }
random_line_split
anyid.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::num::NonZeroU64; #[cfg(any(test, feature = "for-tests"))] use quickcheck_arbitrary_derive::Arbitrary; use serde_derive::Deserialize; use serde_derive::Serialize; use type_macros::auto_wire; use types::HgId; use crate::AnyFileContentId; use crate::IndexableId; use crate::UploadToken; blake2_hash!(BonsaiChangesetId); #[auto_wire] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub enum AnyId { #[id(1)] AnyFileContentId(AnyFileContentId), #[id(2)] HgFilenodeId(HgId), #[id(3)] HgTreeId(HgId), #[id(4)] HgChangesetId(HgId), #[id(5)] BonsaiChangesetId(BonsaiChangesetId), } impl Default for AnyId { fn
() -> Self { Self::AnyFileContentId(AnyFileContentId::default()) } } #[auto_wire] #[derive(Clone, Default, Debug, Serialize, Deserialize, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub struct LookupRequest { #[id(1)] pub id: AnyId, #[id(2)] pub bubble_id: Option<NonZeroU64>, /// If present and the original id is not, lookup will also look into this /// bubble, and if the id is present, copy it to the requested bubble. #[id(3)] pub copy_from_bubble_id: Option<NonZeroU64>, } #[auto_wire] #[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub enum LookupResult { /// Id was present, upload token for it is returned #[id(1)] Present(UploadToken), /// Id was not present, only its id is returned #[id(2)] NotPresent(IndexableId), // Possible to add an Error variant in the future if we don't want to // swallow the errors } impl Default for LookupResult { fn default() -> Self { Self::NotPresent(Default::default()) } } #[auto_wire] #[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub struct LookupResponse { #[id(3)] pub result: LookupResult, }
default
identifier_name
anyid.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::num::NonZeroU64; #[cfg(any(test, feature = "for-tests"))] use quickcheck_arbitrary_derive::Arbitrary; use serde_derive::Deserialize; use serde_derive::Serialize; use type_macros::auto_wire; use types::HgId; use crate::AnyFileContentId; use crate::IndexableId; use crate::UploadToken;
blake2_hash!(BonsaiChangesetId); #[auto_wire] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub enum AnyId { #[id(1)] AnyFileContentId(AnyFileContentId), #[id(2)] HgFilenodeId(HgId), #[id(3)] HgTreeId(HgId), #[id(4)] HgChangesetId(HgId), #[id(5)] BonsaiChangesetId(BonsaiChangesetId), } impl Default for AnyId { fn default() -> Self { Self::AnyFileContentId(AnyFileContentId::default()) } } #[auto_wire] #[derive(Clone, Default, Debug, Serialize, Deserialize, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub struct LookupRequest { #[id(1)] pub id: AnyId, #[id(2)] pub bubble_id: Option<NonZeroU64>, /// If present and the original id is not, lookup will also look into this /// bubble, and if the id is present, copy it to the requested bubble. #[id(3)] pub copy_from_bubble_id: Option<NonZeroU64>, } #[auto_wire] #[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub enum LookupResult { /// Id was present, upload token for it is returned #[id(1)] Present(UploadToken), /// Id was not present, only its id is returned #[id(2)] NotPresent(IndexableId), // Possible to add an Error variant in the future if we don't want to // swallow the errors } impl Default for LookupResult { fn default() -> Self { Self::NotPresent(Default::default()) } } #[auto_wire] #[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub struct LookupResponse { #[id(3)] pub result: LookupResult, }
random_line_split
anyid.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::num::NonZeroU64; #[cfg(any(test, feature = "for-tests"))] use quickcheck_arbitrary_derive::Arbitrary; use serde_derive::Deserialize; use serde_derive::Serialize; use type_macros::auto_wire; use types::HgId; use crate::AnyFileContentId; use crate::IndexableId; use crate::UploadToken; blake2_hash!(BonsaiChangesetId); #[auto_wire] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub enum AnyId { #[id(1)] AnyFileContentId(AnyFileContentId), #[id(2)] HgFilenodeId(HgId), #[id(3)] HgTreeId(HgId), #[id(4)] HgChangesetId(HgId), #[id(5)] BonsaiChangesetId(BonsaiChangesetId), } impl Default for AnyId { fn default() -> Self
} #[auto_wire] #[derive(Clone, Default, Debug, Serialize, Deserialize, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub struct LookupRequest { #[id(1)] pub id: AnyId, #[id(2)] pub bubble_id: Option<NonZeroU64>, /// If present and the original id is not, lookup will also look into this /// bubble, and if the id is present, copy it to the requested bubble. #[id(3)] pub copy_from_bubble_id: Option<NonZeroU64>, } #[auto_wire] #[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub enum LookupResult { /// Id was present, upload token for it is returned #[id(1)] Present(UploadToken), /// Id was not present, only its id is returned #[id(2)] NotPresent(IndexableId), // Possible to add an Error variant in the future if we don't want to // swallow the errors } impl Default for LookupResult { fn default() -> Self { Self::NotPresent(Default::default()) } } #[auto_wire] #[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)] #[cfg_attr(any(test, feature = "for-tests"), derive(Arbitrary))] pub struct LookupResponse { #[id(3)] pub result: LookupResult, }
{ Self::AnyFileContentId(AnyFileContentId::default()) }
identifier_body
cargo_pkgid.rs
use ops; use core::{MultiShell, Source, PackageIdSpec}; use sources::{PathSource}; use util::{CargoResult, human}; pub fn pkgid(manifest_path: &Path, spec: Option<&str>, _shell: &mut MultiShell) -> CargoResult<PackageIdSpec> { let mut source = try!(PathSource::for_path(&manifest_path.dir_path())); try!(source.update()); let package = try!(source.get_root_package()); let lockfile = package.get_root().join("Cargo.lock"); let source_id = package.get_package_id().get_source_id(); let resolve = match try!(ops::load_lockfile(&lockfile, source_id)) { Some(resolve) => resolve, None => return Err(human("A Cargo.lock must exist for this command")) }; let pkgid = match spec { Some(spec) => try!(resolve.query(spec)), None => package.get_package_id(), };
Ok(PackageIdSpec::from_package_id(pkgid)) }
random_line_split
cargo_pkgid.rs
use ops; use core::{MultiShell, Source, PackageIdSpec}; use sources::{PathSource}; use util::{CargoResult, human}; pub fn pkgid(manifest_path: &Path, spec: Option<&str>, _shell: &mut MultiShell) -> CargoResult<PackageIdSpec>
{ let mut source = try!(PathSource::for_path(&manifest_path.dir_path())); try!(source.update()); let package = try!(source.get_root_package()); let lockfile = package.get_root().join("Cargo.lock"); let source_id = package.get_package_id().get_source_id(); let resolve = match try!(ops::load_lockfile(&lockfile, source_id)) { Some(resolve) => resolve, None => return Err(human("A Cargo.lock must exist for this command")) }; let pkgid = match spec { Some(spec) => try!(resolve.query(spec)), None => package.get_package_id(), }; Ok(PackageIdSpec::from_package_id(pkgid)) }
identifier_body
cargo_pkgid.rs
use ops; use core::{MultiShell, Source, PackageIdSpec}; use sources::{PathSource}; use util::{CargoResult, human}; pub fn
(manifest_path: &Path, spec: Option<&str>, _shell: &mut MultiShell) -> CargoResult<PackageIdSpec> { let mut source = try!(PathSource::for_path(&manifest_path.dir_path())); try!(source.update()); let package = try!(source.get_root_package()); let lockfile = package.get_root().join("Cargo.lock"); let source_id = package.get_package_id().get_source_id(); let resolve = match try!(ops::load_lockfile(&lockfile, source_id)) { Some(resolve) => resolve, None => return Err(human("A Cargo.lock must exist for this command")) }; let pkgid = match spec { Some(spec) => try!(resolve.query(spec)), None => package.get_package_id(), }; Ok(PackageIdSpec::from_package_id(pkgid)) }
pkgid
identifier_name
webglbuffer.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 https://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use crate::dom::bindings::codegen::Bindings::WebGLBufferBinding; use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglobject::WebGLObject; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::{WebGLBufferId, WebGLCommand, WebGLError, WebGLResult}; use dom_struct::dom_struct; use ipc_channel::ipc; use std::cell::Cell; #[dom_struct] pub struct WebGLBuffer { webgl_object: WebGLObject, id: WebGLBufferId, /// The target to which this buffer was bound the first time target: Cell<Option<u32>>, capacity: Cell<usize>, marked_for_deletion: Cell<bool>, attached_counter: Cell<u32>, /// https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glGetBufferParameteriv.xml usage: Cell<u32>, } impl WebGLBuffer { fn new_inherited(context: &WebGLRenderingContext, id: WebGLBufferId) -> Self { Self { webgl_object: WebGLObject::new_inherited(context), id, target: Default::default(), capacity: Default::default(), marked_for_deletion: Default::default(), attached_counter: Default::default(), usage: Cell::new(WebGLRenderingContextConstants::STATIC_DRAW), } } pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateBuffer(sender)); receiver .recv() .unwrap() .map(|id| WebGLBuffer::new(context, id)) } pub fn new(context: &WebGLRenderingContext, id: WebGLBufferId) -> DomRoot<Self> { reflect_dom_object( Box::new(WebGLBuffer::new_inherited(context, id)), &*context.global(), WebGLBufferBinding::Wrap, ) } } impl WebGLBuffer { pub fn id(&self) -> WebGLBufferId { self.id } pub fn buffer_data(&self, data: &[u8], usage: u32) -> WebGLResult<()> { match usage { WebGLRenderingContextConstants::STREAM_DRAW | WebGLRenderingContextConstants::STATIC_DRAW | WebGLRenderingContextConstants::DYNAMIC_DRAW => (), _ => return Err(WebGLError::InvalidEnum), } self.capacity.set(data.len()); self.usage.set(usage); let (sender, receiver) = ipc::bytes_channel().unwrap(); self.upcast::<WebGLObject>() .context() .send_command(WebGLCommand::BufferData( self.target.get().unwrap(), receiver, usage, )); sender.send(data).unwrap(); Ok(()) } pub fn capacity(&self) -> usize { self.capacity.get() } pub fn mark_for_deletion(&self, fallible: bool) { if self.marked_for_deletion.get() { return; } self.marked_for_deletion.set(true); if self.is_deleted() { self.delete(fallible); } } fn delete(&self, fallible: bool) { assert!(self.is_deleted()); let context = self.upcast::<WebGLObject>().context(); let cmd = WebGLCommand::DeleteBuffer(self.id); if fallible { context.send_command_ignored(cmd); } else { context.send_command(cmd); } } pub fn is_marked_for_deletion(&self) -> bool { self.marked_for_deletion.get() } pub fn is_deleted(&self) -> bool { self.marked_for_deletion.get() &&!self.is_attached() } pub fn target(&self) -> Option<u32> { self.target.get() } pub fn set_target(&self, target: u32) -> WebGLResult<()> { if self.target.get().map_or(false, |t| t!= target) { return Err(WebGLError::InvalidOperation); } self.target.set(Some(target)); Ok(()) } pub fn is_attached(&self) -> bool { self.attached_counter.get()!= 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set( self.attached_counter .get() .checked_add(1) .expect("refcount overflowed"), ); } pub fn decrement_attached_counter(&self) { self.attached_counter.set( self.attached_counter .get() .checked_sub(1) .expect("refcount underflowed"), ); if self.is_deleted()
} pub fn usage(&self) -> u32 { self.usage.get() } } impl Drop for WebGLBuffer { fn drop(&mut self) { self.mark_for_deletion(true); } }
{ self.delete(false); }
conditional_block
webglbuffer.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 https://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use crate::dom::bindings::codegen::Bindings::WebGLBufferBinding; use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglobject::WebGLObject; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::{WebGLBufferId, WebGLCommand, WebGLError, WebGLResult}; use dom_struct::dom_struct; use ipc_channel::ipc; use std::cell::Cell; #[dom_struct] pub struct WebGLBuffer { webgl_object: WebGLObject, id: WebGLBufferId, /// The target to which this buffer was bound the first time target: Cell<Option<u32>>, capacity: Cell<usize>, marked_for_deletion: Cell<bool>, attached_counter: Cell<u32>, /// https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glGetBufferParameteriv.xml usage: Cell<u32>, } impl WebGLBuffer { fn new_inherited(context: &WebGLRenderingContext, id: WebGLBufferId) -> Self { Self { webgl_object: WebGLObject::new_inherited(context), id, target: Default::default(), capacity: Default::default(), marked_for_deletion: Default::default(), attached_counter: Default::default(), usage: Cell::new(WebGLRenderingContextConstants::STATIC_DRAW), } } pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateBuffer(sender)); receiver .recv() .unwrap() .map(|id| WebGLBuffer::new(context, id)) } pub fn new(context: &WebGLRenderingContext, id: WebGLBufferId) -> DomRoot<Self> { reflect_dom_object( Box::new(WebGLBuffer::new_inherited(context, id)), &*context.global(), WebGLBufferBinding::Wrap, ) } } impl WebGLBuffer { pub fn id(&self) -> WebGLBufferId { self.id } pub fn buffer_data(&self, data: &[u8], usage: u32) -> WebGLResult<()> { match usage { WebGLRenderingContextConstants::STREAM_DRAW | WebGLRenderingContextConstants::STATIC_DRAW | WebGLRenderingContextConstants::DYNAMIC_DRAW => (), _ => return Err(WebGLError::InvalidEnum), } self.capacity.set(data.len()); self.usage.set(usage); let (sender, receiver) = ipc::bytes_channel().unwrap(); self.upcast::<WebGLObject>() .context() .send_command(WebGLCommand::BufferData( self.target.get().unwrap(), receiver, usage, )); sender.send(data).unwrap(); Ok(()) } pub fn capacity(&self) -> usize { self.capacity.get() } pub fn mark_for_deletion(&self, fallible: bool) { if self.marked_for_deletion.get() { return; } self.marked_for_deletion.set(true); if self.is_deleted() { self.delete(fallible); } }
assert!(self.is_deleted()); let context = self.upcast::<WebGLObject>().context(); let cmd = WebGLCommand::DeleteBuffer(self.id); if fallible { context.send_command_ignored(cmd); } else { context.send_command(cmd); } } pub fn is_marked_for_deletion(&self) -> bool { self.marked_for_deletion.get() } pub fn is_deleted(&self) -> bool { self.marked_for_deletion.get() &&!self.is_attached() } pub fn target(&self) -> Option<u32> { self.target.get() } pub fn set_target(&self, target: u32) -> WebGLResult<()> { if self.target.get().map_or(false, |t| t!= target) { return Err(WebGLError::InvalidOperation); } self.target.set(Some(target)); Ok(()) } pub fn is_attached(&self) -> bool { self.attached_counter.get()!= 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set( self.attached_counter .get() .checked_add(1) .expect("refcount overflowed"), ); } pub fn decrement_attached_counter(&self) { self.attached_counter.set( self.attached_counter .get() .checked_sub(1) .expect("refcount underflowed"), ); if self.is_deleted() { self.delete(false); } } pub fn usage(&self) -> u32 { self.usage.get() } } impl Drop for WebGLBuffer { fn drop(&mut self) { self.mark_for_deletion(true); } }
fn delete(&self, fallible: bool) {
random_line_split
webglbuffer.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 https://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use crate::dom::bindings::codegen::Bindings::WebGLBufferBinding; use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglobject::WebGLObject; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::{WebGLBufferId, WebGLCommand, WebGLError, WebGLResult}; use dom_struct::dom_struct; use ipc_channel::ipc; use std::cell::Cell; #[dom_struct] pub struct WebGLBuffer { webgl_object: WebGLObject, id: WebGLBufferId, /// The target to which this buffer was bound the first time target: Cell<Option<u32>>, capacity: Cell<usize>, marked_for_deletion: Cell<bool>, attached_counter: Cell<u32>, /// https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glGetBufferParameteriv.xml usage: Cell<u32>, } impl WebGLBuffer { fn new_inherited(context: &WebGLRenderingContext, id: WebGLBufferId) -> Self { Self { webgl_object: WebGLObject::new_inherited(context), id, target: Default::default(), capacity: Default::default(), marked_for_deletion: Default::default(), attached_counter: Default::default(), usage: Cell::new(WebGLRenderingContextConstants::STATIC_DRAW), } } pub fn maybe_new(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateBuffer(sender)); receiver .recv() .unwrap() .map(|id| WebGLBuffer::new(context, id)) } pub fn new(context: &WebGLRenderingContext, id: WebGLBufferId) -> DomRoot<Self> { reflect_dom_object( Box::new(WebGLBuffer::new_inherited(context, id)), &*context.global(), WebGLBufferBinding::Wrap, ) } } impl WebGLBuffer { pub fn id(&self) -> WebGLBufferId { self.id } pub fn buffer_data(&self, data: &[u8], usage: u32) -> WebGLResult<()> { match usage { WebGLRenderingContextConstants::STREAM_DRAW | WebGLRenderingContextConstants::STATIC_DRAW | WebGLRenderingContextConstants::DYNAMIC_DRAW => (), _ => return Err(WebGLError::InvalidEnum), } self.capacity.set(data.len()); self.usage.set(usage); let (sender, receiver) = ipc::bytes_channel().unwrap(); self.upcast::<WebGLObject>() .context() .send_command(WebGLCommand::BufferData( self.target.get().unwrap(), receiver, usage, )); sender.send(data).unwrap(); Ok(()) } pub fn capacity(&self) -> usize { self.capacity.get() } pub fn mark_for_deletion(&self, fallible: bool) { if self.marked_for_deletion.get() { return; } self.marked_for_deletion.set(true); if self.is_deleted() { self.delete(fallible); } } fn delete(&self, fallible: bool) { assert!(self.is_deleted()); let context = self.upcast::<WebGLObject>().context(); let cmd = WebGLCommand::DeleteBuffer(self.id); if fallible { context.send_command_ignored(cmd); } else { context.send_command(cmd); } } pub fn is_marked_for_deletion(&self) -> bool { self.marked_for_deletion.get() } pub fn is_deleted(&self) -> bool { self.marked_for_deletion.get() &&!self.is_attached() } pub fn target(&self) -> Option<u32> { self.target.get() } pub fn set_target(&self, target: u32) -> WebGLResult<()> { if self.target.get().map_or(false, |t| t!= target) { return Err(WebGLError::InvalidOperation); } self.target.set(Some(target)); Ok(()) } pub fn is_attached(&self) -> bool { self.attached_counter.get()!= 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set( self.attached_counter .get() .checked_add(1) .expect("refcount overflowed"), ); } pub fn decrement_attached_counter(&self) { self.attached_counter.set( self.attached_counter .get() .checked_sub(1) .expect("refcount underflowed"), ); if self.is_deleted() { self.delete(false); } } pub fn usage(&self) -> u32 { self.usage.get() } } impl Drop for WebGLBuffer { fn drop(&mut self)
}
{ self.mark_for_deletion(true); }
identifier_body
webglbuffer.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 https://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use crate::dom::bindings::codegen::Bindings::WebGLBufferBinding; use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::DomRoot; use crate::dom::webglobject::WebGLObject; use crate::dom::webglrenderingcontext::WebGLRenderingContext; use canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::{WebGLBufferId, WebGLCommand, WebGLError, WebGLResult}; use dom_struct::dom_struct; use ipc_channel::ipc; use std::cell::Cell; #[dom_struct] pub struct WebGLBuffer { webgl_object: WebGLObject, id: WebGLBufferId, /// The target to which this buffer was bound the first time target: Cell<Option<u32>>, capacity: Cell<usize>, marked_for_deletion: Cell<bool>, attached_counter: Cell<u32>, /// https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glGetBufferParameteriv.xml usage: Cell<u32>, } impl WebGLBuffer { fn new_inherited(context: &WebGLRenderingContext, id: WebGLBufferId) -> Self { Self { webgl_object: WebGLObject::new_inherited(context), id, target: Default::default(), capacity: Default::default(), marked_for_deletion: Default::default(), attached_counter: Default::default(), usage: Cell::new(WebGLRenderingContextConstants::STATIC_DRAW), } } pub fn
(context: &WebGLRenderingContext) -> Option<DomRoot<Self>> { let (sender, receiver) = webgl_channel().unwrap(); context.send_command(WebGLCommand::CreateBuffer(sender)); receiver .recv() .unwrap() .map(|id| WebGLBuffer::new(context, id)) } pub fn new(context: &WebGLRenderingContext, id: WebGLBufferId) -> DomRoot<Self> { reflect_dom_object( Box::new(WebGLBuffer::new_inherited(context, id)), &*context.global(), WebGLBufferBinding::Wrap, ) } } impl WebGLBuffer { pub fn id(&self) -> WebGLBufferId { self.id } pub fn buffer_data(&self, data: &[u8], usage: u32) -> WebGLResult<()> { match usage { WebGLRenderingContextConstants::STREAM_DRAW | WebGLRenderingContextConstants::STATIC_DRAW | WebGLRenderingContextConstants::DYNAMIC_DRAW => (), _ => return Err(WebGLError::InvalidEnum), } self.capacity.set(data.len()); self.usage.set(usage); let (sender, receiver) = ipc::bytes_channel().unwrap(); self.upcast::<WebGLObject>() .context() .send_command(WebGLCommand::BufferData( self.target.get().unwrap(), receiver, usage, )); sender.send(data).unwrap(); Ok(()) } pub fn capacity(&self) -> usize { self.capacity.get() } pub fn mark_for_deletion(&self, fallible: bool) { if self.marked_for_deletion.get() { return; } self.marked_for_deletion.set(true); if self.is_deleted() { self.delete(fallible); } } fn delete(&self, fallible: bool) { assert!(self.is_deleted()); let context = self.upcast::<WebGLObject>().context(); let cmd = WebGLCommand::DeleteBuffer(self.id); if fallible { context.send_command_ignored(cmd); } else { context.send_command(cmd); } } pub fn is_marked_for_deletion(&self) -> bool { self.marked_for_deletion.get() } pub fn is_deleted(&self) -> bool { self.marked_for_deletion.get() &&!self.is_attached() } pub fn target(&self) -> Option<u32> { self.target.get() } pub fn set_target(&self, target: u32) -> WebGLResult<()> { if self.target.get().map_or(false, |t| t!= target) { return Err(WebGLError::InvalidOperation); } self.target.set(Some(target)); Ok(()) } pub fn is_attached(&self) -> bool { self.attached_counter.get()!= 0 } pub fn increment_attached_counter(&self) { self.attached_counter.set( self.attached_counter .get() .checked_add(1) .expect("refcount overflowed"), ); } pub fn decrement_attached_counter(&self) { self.attached_counter.set( self.attached_counter .get() .checked_sub(1) .expect("refcount underflowed"), ); if self.is_deleted() { self.delete(false); } } pub fn usage(&self) -> u32 { self.usage.get() } } impl Drop for WebGLBuffer { fn drop(&mut self) { self.mark_for_deletion(true); } }
maybe_new
identifier_name
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod macros; #[derive(Debug, StructOpt)] #[structopt(name = "cargo")] enum Cli { #[structopt(name = "ssearch", about = "cargo search on steroids")] Ssearch { /// how many packages to display #[structopt(long = "limit", short = "l", default_value = "10")] limit: usize, /// the crates.io search result page to display #[structopt(long = "page", default_value = "1")] page: usize, /// quiet output, display only crate, version and downloads #[structopt(long = "quiet", short = "q")] quiet: bool, /// sort by recent downloads instead of overall downloads #[structopt(long = "recent", short = "r")] recent: bool, /// query string for crates.io query: String, }, } #[derive(Debug, Deserialize)] struct Args { flag_info: bool, arg_query: String, } #[derive(Debug, Serialize, Deserialize)] struct Meta { total: i32, } #[derive(Debug, Serialize, Deserialize)] struct Response { crates: Vec<EncodableCrate>, meta: Meta, } // structs from crates.io backend #[derive(Debug, Serialize, Deserialize)] struct EncodableCrate { id: String, name: String, updated_at: String, versions: Option<Vec<i32>>, created_at: String, downloads: i32, max_version: String, description: Option<String>, homepage: Option<String>, documentation: Option<String>, keywords: Option<Vec<String>>, license: Option<String>, repository: Option<String>, links: CrateLinks, } #[derive(Debug, Serialize, Deserialize)] struct CrateLinks { version_downloads: String, versions: Option<String>, owners: Option<String>, reverse_dependencies: String, } fn query_crates_io( query: &str, page: usize, per_page: usize, recent: bool, ) -> Result<(i32, Vec<EncodableCrate>)> { let sort = if recent { "recent-downloads" } else { "downloads" }; let url = Url::parse_with_params( "https://crates.io/api/v1/crates", &[ ("q", query), ("page", &page.to_string()), ("per_page", &per_page.to_string()), ("sort", &sort), ], )?; let body = reqwest::get(url)?.text()?; let data: Response = serde_json::from_str(&body)?; Ok((data.meta.total, data.crates)) }
" = \"{}\" \t(downloads: {})\n", cr.max_version, cr.downloads ); if!quiet { cr.description .as_ref() .map(|description| p_yellow!(t, " -> {}\n", description.clone().trim())); cr.documentation .as_ref() .map(|documentation| p_white!(t, " docs: {}\n", documentation)); cr.homepage .as_ref() .map(|homepage| p_white!(t, " home: {}\n", homepage)); p_white!(t, "\n"); } } main!(|args: Cli| { let Cli::Ssearch { query, page, limit, quiet, recent, } = args; let mut t = term::stdout().unwrap(); // TODO: Add decoding of updated_at and allow to use it for sorting let (total, crates) = query_crates_io(&query, page, limit, recent).unwrap_or_else(|e| { p_red!(t, "[error]: {}.\n", e); t.reset().unwrap(); process::exit(1) }); if total == 0 { p_white!(t, "No crate matching \"{}\" has been found.\n", query); t.reset().unwrap(); process::exit(0); } p_white!( t, "Displaying {} crates from page {} out of the {} found.\n\n", crates.len(), page, total, ); let max_len = (&crates).iter().map(|ref cr| cr.name.len()).max().unwrap(); for cr in &crates { show_crate(&mut t, &cr, quiet, max_len); } t.reset().unwrap(); });
fn show_crate(t: &mut Box<term::StdoutTerminal>, cr: &EncodableCrate, quiet: bool, max_len: usize) { p_green!(t, "{}", cr.name.pad_to_width(max_len)); p_white!( t,
random_line_split
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod macros; #[derive(Debug, StructOpt)] #[structopt(name = "cargo")] enum Cli { #[structopt(name = "ssearch", about = "cargo search on steroids")] Ssearch { /// how many packages to display #[structopt(long = "limit", short = "l", default_value = "10")] limit: usize, /// the crates.io search result page to display #[structopt(long = "page", default_value = "1")] page: usize, /// quiet output, display only crate, version and downloads #[structopt(long = "quiet", short = "q")] quiet: bool, /// sort by recent downloads instead of overall downloads #[structopt(long = "recent", short = "r")] recent: bool, /// query string for crates.io query: String, }, } #[derive(Debug, Deserialize)] struct Args { flag_info: bool, arg_query: String, } #[derive(Debug, Serialize, Deserialize)] struct Meta { total: i32, } #[derive(Debug, Serialize, Deserialize)] struct Response { crates: Vec<EncodableCrate>, meta: Meta, } // structs from crates.io backend #[derive(Debug, Serialize, Deserialize)] struct EncodableCrate { id: String, name: String, updated_at: String, versions: Option<Vec<i32>>, created_at: String, downloads: i32, max_version: String, description: Option<String>, homepage: Option<String>, documentation: Option<String>, keywords: Option<Vec<String>>, license: Option<String>, repository: Option<String>, links: CrateLinks, } #[derive(Debug, Serialize, Deserialize)] struct CrateLinks { version_downloads: String, versions: Option<String>, owners: Option<String>, reverse_dependencies: String, } fn query_crates_io( query: &str, page: usize, per_page: usize, recent: bool, ) -> Result<(i32, Vec<EncodableCrate>)> { let sort = if recent { "recent-downloads" } else { "downloads" }; let url = Url::parse_with_params( "https://crates.io/api/v1/crates", &[ ("q", query), ("page", &page.to_string()), ("per_page", &per_page.to_string()), ("sort", &sort), ], )?; let body = reqwest::get(url)?.text()?; let data: Response = serde_json::from_str(&body)?; Ok((data.meta.total, data.crates)) } fn show_crate(t: &mut Box<term::StdoutTerminal>, cr: &EncodableCrate, quiet: bool, max_len: usize) { p_green!(t, "{}", cr.name.pad_to_width(max_len)); p_white!( t, " = \"{}\" \t(downloads: {})\n", cr.max_version, cr.downloads ); if!quiet
} main!(|args: Cli| { let Cli::Ssearch { query, page, limit, quiet, recent, } = args; let mut t = term::stdout().unwrap(); // TODO: Add decoding of updated_at and allow to use it for sorting let (total, crates) = query_crates_io(&query, page, limit, recent).unwrap_or_else(|e| { p_red!(t, "[error]: {}.\n", e); t.reset().unwrap(); process::exit(1) }); if total == 0 { p_white!(t, "No crate matching \"{}\" has been found.\n", query); t.reset().unwrap(); process::exit(0); } p_white!( t, "Displaying {} crates from page {} out of the {} found.\n\n", crates.len(), page, total, ); let max_len = (&crates).iter().map(|ref cr| cr.name.len()).max().unwrap(); for cr in &crates { show_crate(&mut t, &cr, quiet, max_len); } t.reset().unwrap(); });
{ cr.description .as_ref() .map(|description| p_yellow!(t, " -> {}\n", description.clone().trim())); cr.documentation .as_ref() .map(|documentation| p_white!(t, " docs: {}\n", documentation)); cr.homepage .as_ref() .map(|homepage| p_white!(t, " home: {}\n", homepage)); p_white!(t, "\n"); }
conditional_block
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod macros; #[derive(Debug, StructOpt)] #[structopt(name = "cargo")] enum Cli { #[structopt(name = "ssearch", about = "cargo search on steroids")] Ssearch { /// how many packages to display #[structopt(long = "limit", short = "l", default_value = "10")] limit: usize, /// the crates.io search result page to display #[structopt(long = "page", default_value = "1")] page: usize, /// quiet output, display only crate, version and downloads #[structopt(long = "quiet", short = "q")] quiet: bool, /// sort by recent downloads instead of overall downloads #[structopt(long = "recent", short = "r")] recent: bool, /// query string for crates.io query: String, }, } #[derive(Debug, Deserialize)] struct Args { flag_info: bool, arg_query: String, } #[derive(Debug, Serialize, Deserialize)] struct Meta { total: i32, } #[derive(Debug, Serialize, Deserialize)] struct Response { crates: Vec<EncodableCrate>, meta: Meta, } // structs from crates.io backend #[derive(Debug, Serialize, Deserialize)] struct EncodableCrate { id: String, name: String, updated_at: String, versions: Option<Vec<i32>>, created_at: String, downloads: i32, max_version: String, description: Option<String>, homepage: Option<String>, documentation: Option<String>, keywords: Option<Vec<String>>, license: Option<String>, repository: Option<String>, links: CrateLinks, } #[derive(Debug, Serialize, Deserialize)] struct CrateLinks { version_downloads: String, versions: Option<String>, owners: Option<String>, reverse_dependencies: String, } fn
( query: &str, page: usize, per_page: usize, recent: bool, ) -> Result<(i32, Vec<EncodableCrate>)> { let sort = if recent { "recent-downloads" } else { "downloads" }; let url = Url::parse_with_params( "https://crates.io/api/v1/crates", &[ ("q", query), ("page", &page.to_string()), ("per_page", &per_page.to_string()), ("sort", &sort), ], )?; let body = reqwest::get(url)?.text()?; let data: Response = serde_json::from_str(&body)?; Ok((data.meta.total, data.crates)) } fn show_crate(t: &mut Box<term::StdoutTerminal>, cr: &EncodableCrate, quiet: bool, max_len: usize) { p_green!(t, "{}", cr.name.pad_to_width(max_len)); p_white!( t, " = \"{}\" \t(downloads: {})\n", cr.max_version, cr.downloads ); if!quiet { cr.description .as_ref() .map(|description| p_yellow!(t, " -> {}\n", description.clone().trim())); cr.documentation .as_ref() .map(|documentation| p_white!(t, " docs: {}\n", documentation)); cr.homepage .as_ref() .map(|homepage| p_white!(t, " home: {}\n", homepage)); p_white!(t, "\n"); } } main!(|args: Cli| { let Cli::Ssearch { query, page, limit, quiet, recent, } = args; let mut t = term::stdout().unwrap(); // TODO: Add decoding of updated_at and allow to use it for sorting let (total, crates) = query_crates_io(&query, page, limit, recent).unwrap_or_else(|e| { p_red!(t, "[error]: {}.\n", e); t.reset().unwrap(); process::exit(1) }); if total == 0 { p_white!(t, "No crate matching \"{}\" has been found.\n", query); t.reset().unwrap(); process::exit(0); } p_white!( t, "Displaying {} crates from page {} out of the {} found.\n\n", crates.len(), page, total, ); let max_len = (&crates).iter().map(|ref cr| cr.name.len()).max().unwrap(); for cr in &crates { show_crate(&mut t, &cr, quiet, max_len); } t.reset().unwrap(); });
query_crates_io
identifier_name
compositionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct CompositionEvent { uievent: UIEvent, data: DOMString, } impl CompositionEvent { pub fn new_inherited() -> CompositionEvent { CompositionEvent { uievent: UIEvent::new_inherited(), data: DOMString::new(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> { reflect_dom_object( Box::new(CompositionEvent::new_inherited()), window, CompositionEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent>
#[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.as_deref(), init.parent.detail, init.data.clone(), ); Ok(event) } pub fn data(&self) -> &str { &*self.data } } impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
{ let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev }
identifier_body
compositionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct CompositionEvent { uievent: UIEvent, data: DOMString, }
uievent: UIEvent::new_inherited(), data: DOMString::new(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> { reflect_dom_object( Box::new(CompositionEvent::new_inherited()), window, CompositionEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent> { let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.as_deref(), init.parent.detail, init.data.clone(), ); Ok(event) } pub fn data(&self) -> &str { &*self.data } } impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
impl CompositionEvent { pub fn new_inherited() -> CompositionEvent { CompositionEvent {
random_line_split
compositionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct
{ uievent: UIEvent, data: DOMString, } impl CompositionEvent { pub fn new_inherited() -> CompositionEvent { CompositionEvent { uievent: UIEvent::new_inherited(), data: DOMString::new(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> { reflect_dom_object( Box::new(CompositionEvent::new_inherited()), window, CompositionEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent> { let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.as_deref(), init.parent.detail, init.data.clone(), ); Ok(event) } pub fn data(&self) -> &str { &*self.data } } impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
CompositionEvent
identifier_name
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn chop<T: Ord>(item : T, slice : &[T]) -> i32
} width /= 2; } return -1; } fn main() { println!("{}", chop(3, &[1,3,5])); } #[test] fn test_chop() { assert_eq!(-1, chop(3, &[])); assert_eq!(-1, chop(3, &[1])); assert_eq!(0, chop(1, &[1])); assert_eq!(0, chop(1, &[1, 3, 5])); assert_eq!(1, chop(3, &[1, 3, 5])); assert_eq!(2, chop(5, &[1, 3, 5])); assert_eq!(-1, chop(0, &[1, 3, 5])); assert_eq!(-1, chop(2, &[1, 3, 5])); assert_eq!(-1, chop(4, &[1, 3, 5])); assert_eq!(-1, chop(6, &[1, 3, 5])); assert_eq!(0, chop(1, &[1, 3, 5, 7])); assert_eq!(1, chop(3, &[1, 3, 5, 7])); assert_eq!(2, chop(5, &[1, 3, 5, 7])); assert_eq!(3, chop(7, &[1, 3, 5, 7])); assert_eq!(-1, chop(0, &[1, 3, 5, 7])); assert_eq!(-1, chop(2, &[1, 3, 5, 7])); assert_eq!(-1, chop(4, &[1, 3, 5, 7])); assert_eq!(-1, chop(6, &[1, 3, 5, 7])); assert_eq!(-1, chop(8, &[1, 3, 5, 7])); }
{ let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low + (width / 2); let comparison = item.cmp(&slice[mid_index]); match comparison { Less => (), Greater => { low = mid_index + 1; width -= 1; } Equal => return mid_index as i32
identifier_body
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn chop<T: Ord>(item : T, slice : &[T]) -> i32 { let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low + (width / 2); let comparison = item.cmp(&slice[mid_index]); match comparison { Less => (), Greater => { low = mid_index + 1; width -= 1; }
return -1; } fn main() { println!("{}", chop(3, &[1,3,5])); } #[test] fn test_chop() { assert_eq!(-1, chop(3, &[])); assert_eq!(-1, chop(3, &[1])); assert_eq!(0, chop(1, &[1])); assert_eq!(0, chop(1, &[1, 3, 5])); assert_eq!(1, chop(3, &[1, 3, 5])); assert_eq!(2, chop(5, &[1, 3, 5])); assert_eq!(-1, chop(0, &[1, 3, 5])); assert_eq!(-1, chop(2, &[1, 3, 5])); assert_eq!(-1, chop(4, &[1, 3, 5])); assert_eq!(-1, chop(6, &[1, 3, 5])); assert_eq!(0, chop(1, &[1, 3, 5, 7])); assert_eq!(1, chop(3, &[1, 3, 5, 7])); assert_eq!(2, chop(5, &[1, 3, 5, 7])); assert_eq!(3, chop(7, &[1, 3, 5, 7])); assert_eq!(-1, chop(0, &[1, 3, 5, 7])); assert_eq!(-1, chop(2, &[1, 3, 5, 7])); assert_eq!(-1, chop(4, &[1, 3, 5, 7])); assert_eq!(-1, chop(6, &[1, 3, 5, 7])); assert_eq!(-1, chop(8, &[1, 3, 5, 7])); }
Equal => return mid_index as i32 } width /= 2; }
random_line_split
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn
<T: Ord>(item : T, slice : &[T]) -> i32 { let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low + (width / 2); let comparison = item.cmp(&slice[mid_index]); match comparison { Less => (), Greater => { low = mid_index + 1; width -= 1; } Equal => return mid_index as i32 } width /= 2; } return -1; } fn main() { println!("{}", chop(3, &[1,3,5])); } #[test] fn test_chop() { assert_eq!(-1, chop(3, &[])); assert_eq!(-1, chop(3, &[1])); assert_eq!(0, chop(1, &[1])); assert_eq!(0, chop(1, &[1, 3, 5])); assert_eq!(1, chop(3, &[1, 3, 5])); assert_eq!(2, chop(5, &[1, 3, 5])); assert_eq!(-1, chop(0, &[1, 3, 5])); assert_eq!(-1, chop(2, &[1, 3, 5])); assert_eq!(-1, chop(4, &[1, 3, 5])); assert_eq!(-1, chop(6, &[1, 3, 5])); assert_eq!(0, chop(1, &[1, 3, 5, 7])); assert_eq!(1, chop(3, &[1, 3, 5, 7])); assert_eq!(2, chop(5, &[1, 3, 5, 7])); assert_eq!(3, chop(7, &[1, 3, 5, 7])); assert_eq!(-1, chop(0, &[1, 3, 5, 7])); assert_eq!(-1, chop(2, &[1, 3, 5, 7])); assert_eq!(-1, chop(4, &[1, 3, 5, 7])); assert_eq!(-1, chop(6, &[1, 3, 5, 7])); assert_eq!(-1, chop(8, &[1, 3, 5, 7])); }
chop
identifier_name
borrowck-unboxed-closures.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. #![feature(overloaded_calls, unboxed_closures)] fn a<F:Fn(isize, isize) -> isize>(mut f: F) { let g = &mut f; f(1, 2); //~ ERROR cannot borrow `f` as immutable //~^ ERROR cannot borrow `f` as immutable } fn b<F:FnMut(isize, isize) -> isize>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable local variable } fn c<F:FnOnce(isize, isize) -> isize>(f: F) { f(1, 2); f(1, 2); //~ ERROR use of moved value } fn main()
{}
identifier_body
borrowck-unboxed-closures.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. #![feature(overloaded_calls, unboxed_closures)] fn a<F:Fn(isize, isize) -> isize>(mut f: F) { let g = &mut f; f(1, 2); //~ ERROR cannot borrow `f` as immutable //~^ ERROR cannot borrow `f` as immutable } fn b<F:FnMut(isize, isize) -> isize>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable local variable } fn c<F:FnOnce(isize, isize) -> isize>(f: F) { f(1, 2);
f(1, 2); //~ ERROR use of moved value } fn main() {}
random_line_split
borrowck-unboxed-closures.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. #![feature(overloaded_calls, unboxed_closures)] fn a<F:Fn(isize, isize) -> isize>(mut f: F) { let g = &mut f; f(1, 2); //~ ERROR cannot borrow `f` as immutable //~^ ERROR cannot borrow `f` as immutable } fn
<F:FnMut(isize, isize) -> isize>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable local variable } fn c<F:FnOnce(isize, isize) -> isize>(f: F) { f(1, 2); f(1, 2); //~ ERROR use of moved value } fn main() {}
b
identifier_name
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::master::{Scanner, ScanResult}; //------------ Srv --------------------------------------------------------- #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> { priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weight(&self) -> u16 { self.weight } pub fn port(&self) -> u16 { self.port } pub fn target(&self) -> &N { &self.target } } impl<'a> Srv<ParsedDName<'a>> { fn parse_always(parser: &mut Parser<'a>) -> ParseResult<Self> { Ok(Self::new(try!(parser.parse_u16()), try!(parser.parse_u16()), try!(parser.parse_u16()), try!(ParsedDName::parse(parser)))) } } impl Srv<DNameBuf> { pub fn scan<S: Scanner>(scanner: &mut S, origin: Option<&DNameSlice>) -> ScanResult<Self> { Ok(Self::new(try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(DNameBuf::scan(scanner, origin)))) } } impl<N: DName> RecordData for Srv<N> { fn rtype(&self) -> Rtype { Rtype::Srv } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { target.as_mut().compose_u16(self.priority)?; target.as_mut().compose_u16(self.weight)?; target.as_mut().compose_u16(self.port)?; self.target.compose(target) } } impl<'a> ParsedRecordData<'a> for Srv<ParsedDName<'a>> { fn parse(rtype: Rtype, parser: &mut Parser<'a>) -> ParseResult<Option<Self>> { if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else { Ok(None) } } } impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
fmt
identifier_name
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::master::{Scanner, ScanResult}; //------------ Srv --------------------------------------------------------- #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> { priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weight(&self) -> u16 { self.weight } pub fn port(&self) -> u16 { self.port } pub fn target(&self) -> &N { &self.target } } impl<'a> Srv<ParsedDName<'a>> { fn parse_always(parser: &mut Parser<'a>) -> ParseResult<Self> { Ok(Self::new(try!(parser.parse_u16()), try!(parser.parse_u16()), try!(parser.parse_u16()), try!(ParsedDName::parse(parser)))) } } impl Srv<DNameBuf> { pub fn scan<S: Scanner>(scanner: &mut S, origin: Option<&DNameSlice>) -> ScanResult<Self> { Ok(Self::new(try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(DNameBuf::scan(scanner, origin)))) } } impl<N: DName> RecordData for Srv<N> { fn rtype(&self) -> Rtype { Rtype::Srv } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { target.as_mut().compose_u16(self.priority)?; target.as_mut().compose_u16(self.weight)?; target.as_mut().compose_u16(self.port)?; self.target.compose(target) } } impl<'a> ParsedRecordData<'a> for Srv<ParsedDName<'a>> { fn parse(rtype: Rtype, parser: &mut Parser<'a>) -> ParseResult<Option<Self>> { if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else
} } impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
{ Ok(None) }
conditional_block
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::master::{Scanner, ScanResult}; //------------ Srv --------------------------------------------------------- #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> { priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weight(&self) -> u16 { self.weight } pub fn port(&self) -> u16 { self.port } pub fn target(&self) -> &N { &self.target } } impl<'a> Srv<ParsedDName<'a>> { fn parse_always(parser: &mut Parser<'a>) -> ParseResult<Self> { Ok(Self::new(try!(parser.parse_u16()), try!(parser.parse_u16()), try!(parser.parse_u16()), try!(ParsedDName::parse(parser)))) } } impl Srv<DNameBuf> { pub fn scan<S: Scanner>(scanner: &mut S, origin: Option<&DNameSlice>) -> ScanResult<Self> { Ok(Self::new(try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(DNameBuf::scan(scanner, origin)))) } } impl<N: DName> RecordData for Srv<N> { fn rtype(&self) -> Rtype { Rtype::Srv } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { target.as_mut().compose_u16(self.priority)?; target.as_mut().compose_u16(self.weight)?; target.as_mut().compose_u16(self.port)?; self.target.compose(target) } } impl<'a> ParsedRecordData<'a> for Srv<ParsedDName<'a>> { fn parse(rtype: Rtype, parser: &mut Parser<'a>) -> ParseResult<Option<Self>>
} impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
{ if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else { Ok(None) } }
identifier_body
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::master::{Scanner, ScanResult}; //------------ Srv ---------------------------------------------------------
priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weight(&self) -> u16 { self.weight } pub fn port(&self) -> u16 { self.port } pub fn target(&self) -> &N { &self.target } } impl<'a> Srv<ParsedDName<'a>> { fn parse_always(parser: &mut Parser<'a>) -> ParseResult<Self> { Ok(Self::new(try!(parser.parse_u16()), try!(parser.parse_u16()), try!(parser.parse_u16()), try!(ParsedDName::parse(parser)))) } } impl Srv<DNameBuf> { pub fn scan<S: Scanner>(scanner: &mut S, origin: Option<&DNameSlice>) -> ScanResult<Self> { Ok(Self::new(try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(DNameBuf::scan(scanner, origin)))) } } impl<N: DName> RecordData for Srv<N> { fn rtype(&self) -> Rtype { Rtype::Srv } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { target.as_mut().compose_u16(self.priority)?; target.as_mut().compose_u16(self.weight)?; target.as_mut().compose_u16(self.port)?; self.target.compose(target) } } impl<'a> ParsedRecordData<'a> for Srv<ParsedDName<'a>> { fn parse(rtype: Rtype, parser: &mut Parser<'a>) -> ParseResult<Option<Self>> { if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else { Ok(None) } } } impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> {
random_line_split
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl PartialEq<InternedStr> for InternedStr { fn eq(&self, other: &InternedStr) -> bool { self.as_ptr() == other.as_ptr() } } impl<'a> PartialEq<&'a str> for InternedStr { fn eq(&self, other: &&'a str) -> bool { **self == **other } } impl PartialOrd for InternedStr { fn partial_cmp(&self, other: &InternedStr) -> Option<Ordering> { self.as_ptr().partial_cmp(&other.as_ptr()) } } impl Ord for InternedStr { fn cmp(&self, other: &InternedStr) -> Ordering { self.as_ptr().cmp(&other.as_ptr()) } } impl Hash for InternedStr { fn hash<H>(&self, hasher: &mut H) where H: Hasher, { self.as_ptr().hash(hasher) } } unsafe impl Sync for InternedStr {} impl Deref for InternedStr { type Target = str; fn deref(&self) -> &str { &self.0 } } impl AsRef<str> for InternedStr { fn as_ref(&self) -> &str { &self.0 } } impl InternedStr { pub fn inner(&self) -> GcPtr<Str> { self.0 } } pub struct Interner { // For this map and this map only we can't use InternedStr as keys since the hash should // not be expected to be the same as ordinary strings, we use a transmute to &'static str to // have the keys as strings without any unsafety as the keys do not escape the interner and they // live as long as their values indexes: FnvMap<&'static str, InternedStr>, } impl Traverseable for Interner { fn traverse(&self, gc: &mut Gc) { for (_, v) in self.indexes.iter() { v.0.traverse(gc); } } } impl Interner { pub fn new() -> Interner { Interner { indexes: FnvMap::default() } } pub fn intern(&mut self, gc: &mut Gc, s: &str) -> Result<InternedStr> { match self.indexes.get(s) { Some(interned_str) => return Ok(*interned_str), None => (), } let gc_str = InternedStr(try!(gc.alloc(s))); // The key will live as long as the value it refers to and the static str never escapes // outside interner so this is safe let key: &'static str = unsafe { ::std::mem::transmute::<&str, &'static str>(&gc_str) }; self.indexes.insert(key, gc_str); Ok(gc_str) } } impl fmt::Debug for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "InternedStr({:?})", self.0) } } impl fmt::Display for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
}
{ write!(f, "{}", &self[..]) }
identifier_body
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl PartialEq<InternedStr> for InternedStr { fn eq(&self, other: &InternedStr) -> bool { self.as_ptr() == other.as_ptr() } } impl<'a> PartialEq<&'a str> for InternedStr { fn eq(&self, other: &&'a str) -> bool { **self == **other } } impl PartialOrd for InternedStr { fn partial_cmp(&self, other: &InternedStr) -> Option<Ordering> { self.as_ptr().partial_cmp(&other.as_ptr()) } } impl Ord for InternedStr { fn cmp(&self, other: &InternedStr) -> Ordering { self.as_ptr().cmp(&other.as_ptr()) } } impl Hash for InternedStr { fn hash<H>(&self, hasher: &mut H) where H: Hasher, { self.as_ptr().hash(hasher) } } unsafe impl Sync for InternedStr {} impl Deref for InternedStr { type Target = str; fn deref(&self) -> &str { &self.0 } } impl AsRef<str> for InternedStr { fn as_ref(&self) -> &str { &self.0 } } impl InternedStr { pub fn inner(&self) -> GcPtr<Str> { self.0 } } pub struct Interner { // For this map and this map only we can't use InternedStr as keys since the hash should // not be expected to be the same as ordinary strings, we use a transmute to &'static str to // have the keys as strings without any unsafety as the keys do not escape the interner and they // live as long as their values indexes: FnvMap<&'static str, InternedStr>, } impl Traverseable for Interner { fn traverse(&self, gc: &mut Gc) { for (_, v) in self.indexes.iter() { v.0.traverse(gc); } } } impl Interner { pub fn new() -> Interner { Interner { indexes: FnvMap::default() } } pub fn intern(&mut self, gc: &mut Gc, s: &str) -> Result<InternedStr> { match self.indexes.get(s) { Some(interned_str) => return Ok(*interned_str), None => (), } let gc_str = InternedStr(try!(gc.alloc(s))); // The key will live as long as the value it refers to and the static str never escapes // outside interner so this is safe let key: &'static str = unsafe { ::std::mem::transmute::<&str, &'static str>(&gc_str) }; self.indexes.insert(key, gc_str); Ok(gc_str) } } impl fmt::Debug for InternedStr { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "InternedStr({:?})", self.0) } } impl fmt::Display for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self[..]) } }
fmt
identifier_name
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl PartialEq<InternedStr> for InternedStr { fn eq(&self, other: &InternedStr) -> bool { self.as_ptr() == other.as_ptr() } } impl<'a> PartialEq<&'a str> for InternedStr { fn eq(&self, other: &&'a str) -> bool { **self == **other } }
impl PartialOrd for InternedStr { fn partial_cmp(&self, other: &InternedStr) -> Option<Ordering> { self.as_ptr().partial_cmp(&other.as_ptr()) } } impl Ord for InternedStr { fn cmp(&self, other: &InternedStr) -> Ordering { self.as_ptr().cmp(&other.as_ptr()) } } impl Hash for InternedStr { fn hash<H>(&self, hasher: &mut H) where H: Hasher, { self.as_ptr().hash(hasher) } } unsafe impl Sync for InternedStr {} impl Deref for InternedStr { type Target = str; fn deref(&self) -> &str { &self.0 } } impl AsRef<str> for InternedStr { fn as_ref(&self) -> &str { &self.0 } } impl InternedStr { pub fn inner(&self) -> GcPtr<Str> { self.0 } } pub struct Interner { // For this map and this map only we can't use InternedStr as keys since the hash should // not be expected to be the same as ordinary strings, we use a transmute to &'static str to // have the keys as strings without any unsafety as the keys do not escape the interner and they // live as long as their values indexes: FnvMap<&'static str, InternedStr>, } impl Traverseable for Interner { fn traverse(&self, gc: &mut Gc) { for (_, v) in self.indexes.iter() { v.0.traverse(gc); } } } impl Interner { pub fn new() -> Interner { Interner { indexes: FnvMap::default() } } pub fn intern(&mut self, gc: &mut Gc, s: &str) -> Result<InternedStr> { match self.indexes.get(s) { Some(interned_str) => return Ok(*interned_str), None => (), } let gc_str = InternedStr(try!(gc.alloc(s))); // The key will live as long as the value it refers to and the static str never escapes // outside interner so this is safe let key: &'static str = unsafe { ::std::mem::transmute::<&str, &'static str>(&gc_str) }; self.indexes.insert(key, gc_str); Ok(gc_str) } } impl fmt::Debug for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "InternedStr({:?})", self.0) } } impl fmt::Display for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self[..]) } }
random_line_split
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn build() -> App<'static,'static> { App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcommand(SubCommand::with_name("digraph") .about("Digraph lookup and resolution") .setting(AppSettings::AllowLeadingHyphen) .setting(AppSettings::UnifiedHelpMessage) .arg(Arg::with_name("convert") .help("Converts a digraph sequence or a character to the other") .long("convert") .short("c") .takes_value(true)) .arg(Arg::with_name("filter") .help("Prints information about matching digraphs")
.short("f") .takes_value(true)) .arg(Arg::with_name("description") .help("Prints results with description") .long("description") .short("d") .requires("filter")) .group(ArgGroup::with_name("modes") .args(&["convert", "filter"]) .required(true))) }
.long("filter")
random_line_split
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn build() -> App<'static,'static>
.arg(Arg::with_name("description") .help("Prints results with description") .long("description") .short("d") .requires("filter")) .group(ArgGroup::with_name("modes") .args(&["convert", "filter"]) .required(true))) }
{ App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcommand(SubCommand::with_name("digraph") .about("Digraph lookup and resolution") .setting(AppSettings::AllowLeadingHyphen) .setting(AppSettings::UnifiedHelpMessage) .arg(Arg::with_name("convert") .help("Converts a digraph sequence or a character to the other") .long("convert") .short("c") .takes_value(true)) .arg(Arg::with_name("filter") .help("Prints information about matching digraphs") .long("filter") .short("f") .takes_value(true))
identifier_body
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn
() -> App<'static,'static> { App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcommand(SubCommand::with_name("digraph") .about("Digraph lookup and resolution") .setting(AppSettings::AllowLeadingHyphen) .setting(AppSettings::UnifiedHelpMessage) .arg(Arg::with_name("convert") .help("Converts a digraph sequence or a character to the other") .long("convert") .short("c") .takes_value(true)) .arg(Arg::with_name("filter") .help("Prints information about matching digraphs") .long("filter") .short("f") .takes_value(true)) .arg(Arg::with_name("description") .help("Prints results with description") .long("description") .short("d") .requires("filter")) .group(ArgGroup::with_name("modes") .args(&["convert", "filter"]) .required(true))) }
build
identifier_name
sip.rs
/* Copyright (C) 2019-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // written by Giuseppe Longo <[email protected]> extern crate nom; use crate::applayer::{self, *}; use crate::core; use crate::core::{sc_detect_engine_state_free, AppProto, Flow, ALPROTO_UNKNOWN}; use crate::sip::parser::*; use std; use std::ffi::{CStr, CString}; #[repr(u32)] pub enum SIPEvent { IncompleteData = 0, InvalidData, } impl SIPEvent { fn from_i32(value: i32) -> Option<SIPEvent> { match value { 0 => Some(SIPEvent::IncompleteData), 1 => Some(SIPEvent::InvalidData), _ => None, } } } pub struct SIPState { transactions: Vec<SIPTransaction>, tx_id: u64, } pub struct SIPTransaction { id: u64, pub request: Option<Request>, pub response: Option<Response>, pub request_line: Option<String>, pub response_line: Option<String>, de_state: Option<*mut core::DetectEngineState>, events: *mut core::AppLayerDecoderEvents, tx_data: applayer::AppLayerTxData, } impl SIPState { pub fn new() -> SIPState { SIPState { transactions: Vec::new(), tx_id: 0, } } pub fn free(&mut self) { self.transactions.clear(); } fn new_tx(&mut self) -> SIPTransaction { self.tx_id += 1; SIPTransaction::new(self.tx_id) } fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&SIPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64) { let tx = self .transactions .iter() .position(|ref tx| tx.id == tx_id + 1); debug_assert!(tx!= None); if let Some(idx) = tx { let _ = self.transactions.remove(idx); } } fn set_event(&mut self, event: SIPEvent) { if let Some(tx) = self.transactions.last_mut() { let ev = event as u8; core::sc_app_layer_decoder_events_set_event_raw(&mut tx.events, ev); } } fn parse_request(&mut self, input: &[u8]) -> bool { match sip_parse_request(input) { Ok((_, request)) => { let mut tx = self.new_tx(); tx.request = Some(request); if let Ok((_, req_line)) = sip_take_line(input) { tx.request_line = req_line; } self.transactions.push(tx); return true; } Err(nom::Err::Incomplete(_)) => { self.set_event(SIPEvent::IncompleteData); return false; } Err(_) => { self.set_event(SIPEvent::InvalidData); return false; } } } fn parse_response(&mut self, input: &[u8]) -> bool { match sip_parse_response(input) { Ok((_, response)) => { let mut tx = self.new_tx(); tx.response = Some(response); if let Ok((_, resp_line)) = sip_take_line(input) { tx.response_line = resp_line; } self.transactions.push(tx); return true; } Err(nom::Err::Incomplete(_)) => { self.set_event(SIPEvent::IncompleteData); return false; } Err(_) => { self.set_event(SIPEvent::InvalidData); return false; } } } } impl SIPTransaction { pub fn new(id: u64) -> SIPTransaction { SIPTransaction { id: id, de_state: None, request: None, response: None, request_line: None, response_line: None, events: std::ptr::null_mut(), tx_data: applayer::AppLayerTxData::new(), } } } impl Drop for SIPTransaction { fn drop(&mut self) { if self.events!= std::ptr::null_mut() { core::sc_app_layer_decoder_events_free_events(&mut self.events); } if let Some(state) = self.de_state { sc_detect_engine_state_free(state); } } } #[no_mangle] pub extern "C" fn rs_sip_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void { let state = SIPState::new(); let boxed = Box::new(state); return unsafe { std::mem::transmute(boxed) }; } #[no_mangle] pub extern "C" fn rs_sip_state_free(state: *mut std::os::raw::c_void) { let mut state: Box<SIPState> = unsafe { std::mem::transmute(state) }; state.free(); } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx( state: *mut std::os::raw::c_void, tx_id: u64, ) -> *mut std::os::raw::c_void { let state = cast_pointer!(state, SIPState); match state.get_tx_by_id(tx_id) { Some(tx) => unsafe { std::mem::transmute(tx) }, None => std::ptr::null_mut(), } } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 { let state = cast_pointer!(state, SIPState); state.tx_id } #[no_mangle] pub extern "C" fn rs_sip_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) { let state = cast_pointer!(state, SIPState); state.free_tx(tx_id); } #[no_mangle] pub extern "C" fn rs_sip_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int { return 1; } #[no_mangle] pub extern "C" fn rs_sip_tx_get_alstate_progress( _tx: *mut std::os::raw::c_void, _direction: u8, ) -> std::os::raw::c_int { 1 } #[no_mangle] pub extern "C" fn rs_sip_state_set_tx_detect_state( tx: *mut std::os::raw::c_void, de_state: &mut core::DetectEngineState, ) -> std::os::raw::c_int { let tx = cast_pointer!(tx, SIPTransaction); tx.de_state = Some(de_state); 0 } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx_detect_state( tx: *mut std::os::raw::c_void, ) -> *mut core::DetectEngineState { let tx = cast_pointer!(tx, SIPTransaction); match tx.de_state { Some(ds) => ds, None => std::ptr::null_mut(), } } #[no_mangle] pub extern "C" fn rs_sip_state_get_events( tx: *mut std::os::raw::c_void, ) -> *mut core::AppLayerDecoderEvents { let tx = cast_pointer!(tx, SIPTransaction); return tx.events; } #[no_mangle] pub extern "C" fn rs_sip_state_get_event_info( event_name: *const std::os::raw::c_char, event_id: *mut std::os::raw::c_int, event_type: *mut core::AppLayerEventType, ) -> std::os::raw::c_int { if event_name == std::ptr::null() { return -1; } let c_event_name: &CStr = unsafe { CStr::from_ptr(event_name) }; let event = match c_event_name.to_str() { Ok(s) => { match s { "incomplete_data" => SIPEvent::IncompleteData as i32, "invalid_data" => SIPEvent::InvalidData as i32, _ => -1, // unknown event } } Err(_) => -1, // UTF-8 conversion failed }; unsafe { *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION; *event_id = event as std::os::raw::c_int; }; 0 } #[no_mangle] pub extern "C" fn rs_sip_state_get_event_info_by_id( event_id: std::os::raw::c_int, event_name: *mut *const std::os::raw::c_char, event_type: *mut core::AppLayerEventType, ) -> i8 { if let Some(e) = SIPEvent::from_i32(event_id as i32) { let estr = match e { SIPEvent::IncompleteData => "incomplete_data\0", SIPEvent::InvalidData => "invalid_data\0", }; unsafe { *event_name = estr.as_ptr() as *const std::os::raw::c_char; *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION; }; 0 } else { -1 } } static mut ALPROTO_SIP: AppProto = ALPROTO_UNKNOWN; #[no_mangle] pub extern "C" fn rs_sip_probing_parser_ts( _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8, ) -> AppProto { let buf = build_slice!(input, input_len as usize); if sip_parse_request(buf).is_ok() { return unsafe { ALPROTO_SIP }; } return ALPROTO_UNKNOWN; } #[no_mangle] pub extern "C" fn rs_sip_probing_parser_tc( _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8, ) -> AppProto { let buf = build_slice!(input, input_len as usize); if sip_parse_response(buf).is_ok() { return unsafe { ALPROTO_SIP }; } return ALPROTO_UNKNOWN; } #[no_mangle] pub extern "C" fn rs_sip_parse_request( _flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8, ) -> AppLayerResult { let buf = build_slice!(input, input_len as usize); let state = cast_pointer!(state, SIPState); state.parse_request(buf).into() } #[no_mangle] pub extern "C" fn rs_sip_parse_response( _flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8, ) -> AppLayerResult { let buf = build_slice!(input, input_len as usize); let state = cast_pointer!(state, SIPState); state.parse_response(buf).into() }
#[no_mangle] pub unsafe extern "C" fn rs_sip_register_parser() { let default_port = CString::new("5060").unwrap(); let parser = RustParser { name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port: default_port.as_ptr(), ipproto: core::IPPROTO_UDP, probe_ts: Some(rs_sip_probing_parser_ts), probe_tc: Some(rs_sip_probing_parser_tc), min_depth: 0, max_depth: 16, state_new: rs_sip_state_new, state_free: rs_sip_state_free, tx_free: rs_sip_state_tx_free, parse_ts: rs_sip_parse_request, parse_tc: rs_sip_parse_response, get_tx_count: rs_sip_state_get_tx_count, get_tx: rs_sip_state_get_tx, tx_get_comp_st: rs_sip_state_progress_completion_status, tx_get_progress: rs_sip_tx_get_alstate_progress, get_de_state: rs_sip_state_get_tx_detect_state, set_de_state: rs_sip_state_set_tx_detect_state, get_events: Some(rs_sip_state_get_events), get_eventinfo: Some(rs_sip_state_get_event_info), get_eventinfo_byid: Some(rs_sip_state_get_event_info_by_id), localstorage_new: None, localstorage_free: None, get_files: None, get_tx_iterator: None, get_tx_data: rs_sip_get_tx_data, apply_tx_config: None, flags: APP_LAYER_PARSER_OPT_UNIDIR_TXS, truncate: None, }; let ip_proto_str = CString::new("udp").unwrap(); if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); ALPROTO_SIP = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParser(&parser, alproto); } } else { SCLogDebug!("Protocol detecter and parser disabled for SIP/UDP."); } }
export_tx_data_get!(rs_sip_get_tx_data, SIPTransaction); const PARSER_NAME: &'static [u8] = b"sip\0";
random_line_split
sip.rs
/* Copyright (C) 2019-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // written by Giuseppe Longo <[email protected]> extern crate nom; use crate::applayer::{self, *}; use crate::core; use crate::core::{sc_detect_engine_state_free, AppProto, Flow, ALPROTO_UNKNOWN}; use crate::sip::parser::*; use std; use std::ffi::{CStr, CString}; #[repr(u32)] pub enum SIPEvent { IncompleteData = 0, InvalidData, } impl SIPEvent { fn from_i32(value: i32) -> Option<SIPEvent> { match value { 0 => Some(SIPEvent::IncompleteData), 1 => Some(SIPEvent::InvalidData), _ => None, } } } pub struct SIPState { transactions: Vec<SIPTransaction>, tx_id: u64, } pub struct SIPTransaction { id: u64, pub request: Option<Request>, pub response: Option<Response>, pub request_line: Option<String>, pub response_line: Option<String>, de_state: Option<*mut core::DetectEngineState>, events: *mut core::AppLayerDecoderEvents, tx_data: applayer::AppLayerTxData, } impl SIPState { pub fn new() -> SIPState { SIPState { transactions: Vec::new(), tx_id: 0, } } pub fn free(&mut self) { self.transactions.clear(); } fn new_tx(&mut self) -> SIPTransaction { self.tx_id += 1; SIPTransaction::new(self.tx_id) } fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&SIPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64) { let tx = self .transactions .iter() .position(|ref tx| tx.id == tx_id + 1); debug_assert!(tx!= None); if let Some(idx) = tx { let _ = self.transactions.remove(idx); } } fn set_event(&mut self, event: SIPEvent) { if let Some(tx) = self.transactions.last_mut() { let ev = event as u8; core::sc_app_layer_decoder_events_set_event_raw(&mut tx.events, ev); } } fn parse_request(&mut self, input: &[u8]) -> bool { match sip_parse_request(input) { Ok((_, request)) => { let mut tx = self.new_tx(); tx.request = Some(request); if let Ok((_, req_line)) = sip_take_line(input) { tx.request_line = req_line; } self.transactions.push(tx); return true; } Err(nom::Err::Incomplete(_)) => { self.set_event(SIPEvent::IncompleteData); return false; } Err(_) => { self.set_event(SIPEvent::InvalidData); return false; } } } fn parse_response(&mut self, input: &[u8]) -> bool { match sip_parse_response(input) { Ok((_, response)) => { let mut tx = self.new_tx(); tx.response = Some(response); if let Ok((_, resp_line)) = sip_take_line(input) { tx.response_line = resp_line; } self.transactions.push(tx); return true; } Err(nom::Err::Incomplete(_)) => { self.set_event(SIPEvent::IncompleteData); return false; } Err(_) => { self.set_event(SIPEvent::InvalidData); return false; } } } } impl SIPTransaction { pub fn
(id: u64) -> SIPTransaction { SIPTransaction { id: id, de_state: None, request: None, response: None, request_line: None, response_line: None, events: std::ptr::null_mut(), tx_data: applayer::AppLayerTxData::new(), } } } impl Drop for SIPTransaction { fn drop(&mut self) { if self.events!= std::ptr::null_mut() { core::sc_app_layer_decoder_events_free_events(&mut self.events); } if let Some(state) = self.de_state { sc_detect_engine_state_free(state); } } } #[no_mangle] pub extern "C" fn rs_sip_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void { let state = SIPState::new(); let boxed = Box::new(state); return unsafe { std::mem::transmute(boxed) }; } #[no_mangle] pub extern "C" fn rs_sip_state_free(state: *mut std::os::raw::c_void) { let mut state: Box<SIPState> = unsafe { std::mem::transmute(state) }; state.free(); } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx( state: *mut std::os::raw::c_void, tx_id: u64, ) -> *mut std::os::raw::c_void { let state = cast_pointer!(state, SIPState); match state.get_tx_by_id(tx_id) { Some(tx) => unsafe { std::mem::transmute(tx) }, None => std::ptr::null_mut(), } } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 { let state = cast_pointer!(state, SIPState); state.tx_id } #[no_mangle] pub extern "C" fn rs_sip_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) { let state = cast_pointer!(state, SIPState); state.free_tx(tx_id); } #[no_mangle] pub extern "C" fn rs_sip_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int { return 1; } #[no_mangle] pub extern "C" fn rs_sip_tx_get_alstate_progress( _tx: *mut std::os::raw::c_void, _direction: u8, ) -> std::os::raw::c_int { 1 } #[no_mangle] pub extern "C" fn rs_sip_state_set_tx_detect_state( tx: *mut std::os::raw::c_void, de_state: &mut core::DetectEngineState, ) -> std::os::raw::c_int { let tx = cast_pointer!(tx, SIPTransaction); tx.de_state = Some(de_state); 0 } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx_detect_state( tx: *mut std::os::raw::c_void, ) -> *mut core::DetectEngineState { let tx = cast_pointer!(tx, SIPTransaction); match tx.de_state { Some(ds) => ds, None => std::ptr::null_mut(), } } #[no_mangle] pub extern "C" fn rs_sip_state_get_events( tx: *mut std::os::raw::c_void, ) -> *mut core::AppLayerDecoderEvents { let tx = cast_pointer!(tx, SIPTransaction); return tx.events; } #[no_mangle] pub extern "C" fn rs_sip_state_get_event_info( event_name: *const std::os::raw::c_char, event_id: *mut std::os::raw::c_int, event_type: *mut core::AppLayerEventType, ) -> std::os::raw::c_int { if event_name == std::ptr::null() { return -1; } let c_event_name: &CStr = unsafe { CStr::from_ptr(event_name) }; let event = match c_event_name.to_str() { Ok(s) => { match s { "incomplete_data" => SIPEvent::IncompleteData as i32, "invalid_data" => SIPEvent::InvalidData as i32, _ => -1, // unknown event } } Err(_) => -1, // UTF-8 conversion failed }; unsafe { *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION; *event_id = event as std::os::raw::c_int; }; 0 } #[no_mangle] pub extern "C" fn rs_sip_state_get_event_info_by_id( event_id: std::os::raw::c_int, event_name: *mut *const std::os::raw::c_char, event_type: *mut core::AppLayerEventType, ) -> i8 { if let Some(e) = SIPEvent::from_i32(event_id as i32) { let estr = match e { SIPEvent::IncompleteData => "incomplete_data\0", SIPEvent::InvalidData => "invalid_data\0", }; unsafe { *event_name = estr.as_ptr() as *const std::os::raw::c_char; *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION; }; 0 } else { -1 } } static mut ALPROTO_SIP: AppProto = ALPROTO_UNKNOWN; #[no_mangle] pub extern "C" fn rs_sip_probing_parser_ts( _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8, ) -> AppProto { let buf = build_slice!(input, input_len as usize); if sip_parse_request(buf).is_ok() { return unsafe { ALPROTO_SIP }; } return ALPROTO_UNKNOWN; } #[no_mangle] pub extern "C" fn rs_sip_probing_parser_tc( _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8, ) -> AppProto { let buf = build_slice!(input, input_len as usize); if sip_parse_response(buf).is_ok() { return unsafe { ALPROTO_SIP }; } return ALPROTO_UNKNOWN; } #[no_mangle] pub extern "C" fn rs_sip_parse_request( _flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8, ) -> AppLayerResult { let buf = build_slice!(input, input_len as usize); let state = cast_pointer!(state, SIPState); state.parse_request(buf).into() } #[no_mangle] pub extern "C" fn rs_sip_parse_response( _flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8, ) -> AppLayerResult { let buf = build_slice!(input, input_len as usize); let state = cast_pointer!(state, SIPState); state.parse_response(buf).into() } export_tx_data_get!(rs_sip_get_tx_data, SIPTransaction); const PARSER_NAME: &'static [u8] = b"sip\0"; #[no_mangle] pub unsafe extern "C" fn rs_sip_register_parser() { let default_port = CString::new("5060").unwrap(); let parser = RustParser { name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port: default_port.as_ptr(), ipproto: core::IPPROTO_UDP, probe_ts: Some(rs_sip_probing_parser_ts), probe_tc: Some(rs_sip_probing_parser_tc), min_depth: 0, max_depth: 16, state_new: rs_sip_state_new, state_free: rs_sip_state_free, tx_free: rs_sip_state_tx_free, parse_ts: rs_sip_parse_request, parse_tc: rs_sip_parse_response, get_tx_count: rs_sip_state_get_tx_count, get_tx: rs_sip_state_get_tx, tx_get_comp_st: rs_sip_state_progress_completion_status, tx_get_progress: rs_sip_tx_get_alstate_progress, get_de_state: rs_sip_state_get_tx_detect_state, set_de_state: rs_sip_state_set_tx_detect_state, get_events: Some(rs_sip_state_get_events), get_eventinfo: Some(rs_sip_state_get_event_info), get_eventinfo_byid: Some(rs_sip_state_get_event_info_by_id), localstorage_new: None, localstorage_free: None, get_files: None, get_tx_iterator: None, get_tx_data: rs_sip_get_tx_data, apply_tx_config: None, flags: APP_LAYER_PARSER_OPT_UNIDIR_TXS, truncate: None, }; let ip_proto_str = CString::new("udp").unwrap(); if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); ALPROTO_SIP = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParser(&parser, alproto); } } else { SCLogDebug!("Protocol detecter and parser disabled for SIP/UDP."); } }
new
identifier_name
sip.rs
/* Copyright (C) 2019-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // written by Giuseppe Longo <[email protected]> extern crate nom; use crate::applayer::{self, *}; use crate::core; use crate::core::{sc_detect_engine_state_free, AppProto, Flow, ALPROTO_UNKNOWN}; use crate::sip::parser::*; use std; use std::ffi::{CStr, CString}; #[repr(u32)] pub enum SIPEvent { IncompleteData = 0, InvalidData, } impl SIPEvent { fn from_i32(value: i32) -> Option<SIPEvent> { match value { 0 => Some(SIPEvent::IncompleteData), 1 => Some(SIPEvent::InvalidData), _ => None, } } } pub struct SIPState { transactions: Vec<SIPTransaction>, tx_id: u64, } pub struct SIPTransaction { id: u64, pub request: Option<Request>, pub response: Option<Response>, pub request_line: Option<String>, pub response_line: Option<String>, de_state: Option<*mut core::DetectEngineState>, events: *mut core::AppLayerDecoderEvents, tx_data: applayer::AppLayerTxData, } impl SIPState { pub fn new() -> SIPState { SIPState { transactions: Vec::new(), tx_id: 0, } } pub fn free(&mut self)
fn new_tx(&mut self) -> SIPTransaction { self.tx_id += 1; SIPTransaction::new(self.tx_id) } fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&SIPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64) { let tx = self .transactions .iter() .position(|ref tx| tx.id == tx_id + 1); debug_assert!(tx!= None); if let Some(idx) = tx { let _ = self.transactions.remove(idx); } } fn set_event(&mut self, event: SIPEvent) { if let Some(tx) = self.transactions.last_mut() { let ev = event as u8; core::sc_app_layer_decoder_events_set_event_raw(&mut tx.events, ev); } } fn parse_request(&mut self, input: &[u8]) -> bool { match sip_parse_request(input) { Ok((_, request)) => { let mut tx = self.new_tx(); tx.request = Some(request); if let Ok((_, req_line)) = sip_take_line(input) { tx.request_line = req_line; } self.transactions.push(tx); return true; } Err(nom::Err::Incomplete(_)) => { self.set_event(SIPEvent::IncompleteData); return false; } Err(_) => { self.set_event(SIPEvent::InvalidData); return false; } } } fn parse_response(&mut self, input: &[u8]) -> bool { match sip_parse_response(input) { Ok((_, response)) => { let mut tx = self.new_tx(); tx.response = Some(response); if let Ok((_, resp_line)) = sip_take_line(input) { tx.response_line = resp_line; } self.transactions.push(tx); return true; } Err(nom::Err::Incomplete(_)) => { self.set_event(SIPEvent::IncompleteData); return false; } Err(_) => { self.set_event(SIPEvent::InvalidData); return false; } } } } impl SIPTransaction { pub fn new(id: u64) -> SIPTransaction { SIPTransaction { id: id, de_state: None, request: None, response: None, request_line: None, response_line: None, events: std::ptr::null_mut(), tx_data: applayer::AppLayerTxData::new(), } } } impl Drop for SIPTransaction { fn drop(&mut self) { if self.events!= std::ptr::null_mut() { core::sc_app_layer_decoder_events_free_events(&mut self.events); } if let Some(state) = self.de_state { sc_detect_engine_state_free(state); } } } #[no_mangle] pub extern "C" fn rs_sip_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void { let state = SIPState::new(); let boxed = Box::new(state); return unsafe { std::mem::transmute(boxed) }; } #[no_mangle] pub extern "C" fn rs_sip_state_free(state: *mut std::os::raw::c_void) { let mut state: Box<SIPState> = unsafe { std::mem::transmute(state) }; state.free(); } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx( state: *mut std::os::raw::c_void, tx_id: u64, ) -> *mut std::os::raw::c_void { let state = cast_pointer!(state, SIPState); match state.get_tx_by_id(tx_id) { Some(tx) => unsafe { std::mem::transmute(tx) }, None => std::ptr::null_mut(), } } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 { let state = cast_pointer!(state, SIPState); state.tx_id } #[no_mangle] pub extern "C" fn rs_sip_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) { let state = cast_pointer!(state, SIPState); state.free_tx(tx_id); } #[no_mangle] pub extern "C" fn rs_sip_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int { return 1; } #[no_mangle] pub extern "C" fn rs_sip_tx_get_alstate_progress( _tx: *mut std::os::raw::c_void, _direction: u8, ) -> std::os::raw::c_int { 1 } #[no_mangle] pub extern "C" fn rs_sip_state_set_tx_detect_state( tx: *mut std::os::raw::c_void, de_state: &mut core::DetectEngineState, ) -> std::os::raw::c_int { let tx = cast_pointer!(tx, SIPTransaction); tx.de_state = Some(de_state); 0 } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx_detect_state( tx: *mut std::os::raw::c_void, ) -> *mut core::DetectEngineState { let tx = cast_pointer!(tx, SIPTransaction); match tx.de_state { Some(ds) => ds, None => std::ptr::null_mut(), } } #[no_mangle] pub extern "C" fn rs_sip_state_get_events( tx: *mut std::os::raw::c_void, ) -> *mut core::AppLayerDecoderEvents { let tx = cast_pointer!(tx, SIPTransaction); return tx.events; } #[no_mangle] pub extern "C" fn rs_sip_state_get_event_info( event_name: *const std::os::raw::c_char, event_id: *mut std::os::raw::c_int, event_type: *mut core::AppLayerEventType, ) -> std::os::raw::c_int { if event_name == std::ptr::null() { return -1; } let c_event_name: &CStr = unsafe { CStr::from_ptr(event_name) }; let event = match c_event_name.to_str() { Ok(s) => { match s { "incomplete_data" => SIPEvent::IncompleteData as i32, "invalid_data" => SIPEvent::InvalidData as i32, _ => -1, // unknown event } } Err(_) => -1, // UTF-8 conversion failed }; unsafe { *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION; *event_id = event as std::os::raw::c_int; }; 0 } #[no_mangle] pub extern "C" fn rs_sip_state_get_event_info_by_id( event_id: std::os::raw::c_int, event_name: *mut *const std::os::raw::c_char, event_type: *mut core::AppLayerEventType, ) -> i8 { if let Some(e) = SIPEvent::from_i32(event_id as i32) { let estr = match e { SIPEvent::IncompleteData => "incomplete_data\0", SIPEvent::InvalidData => "invalid_data\0", }; unsafe { *event_name = estr.as_ptr() as *const std::os::raw::c_char; *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION; }; 0 } else { -1 } } static mut ALPROTO_SIP: AppProto = ALPROTO_UNKNOWN; #[no_mangle] pub extern "C" fn rs_sip_probing_parser_ts( _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8, ) -> AppProto { let buf = build_slice!(input, input_len as usize); if sip_parse_request(buf).is_ok() { return unsafe { ALPROTO_SIP }; } return ALPROTO_UNKNOWN; } #[no_mangle] pub extern "C" fn rs_sip_probing_parser_tc( _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8, ) -> AppProto { let buf = build_slice!(input, input_len as usize); if sip_parse_response(buf).is_ok() { return unsafe { ALPROTO_SIP }; } return ALPROTO_UNKNOWN; } #[no_mangle] pub extern "C" fn rs_sip_parse_request( _flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8, ) -> AppLayerResult { let buf = build_slice!(input, input_len as usize); let state = cast_pointer!(state, SIPState); state.parse_request(buf).into() } #[no_mangle] pub extern "C" fn rs_sip_parse_response( _flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8, ) -> AppLayerResult { let buf = build_slice!(input, input_len as usize); let state = cast_pointer!(state, SIPState); state.parse_response(buf).into() } export_tx_data_get!(rs_sip_get_tx_data, SIPTransaction); const PARSER_NAME: &'static [u8] = b"sip\0"; #[no_mangle] pub unsafe extern "C" fn rs_sip_register_parser() { let default_port = CString::new("5060").unwrap(); let parser = RustParser { name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port: default_port.as_ptr(), ipproto: core::IPPROTO_UDP, probe_ts: Some(rs_sip_probing_parser_ts), probe_tc: Some(rs_sip_probing_parser_tc), min_depth: 0, max_depth: 16, state_new: rs_sip_state_new, state_free: rs_sip_state_free, tx_free: rs_sip_state_tx_free, parse_ts: rs_sip_parse_request, parse_tc: rs_sip_parse_response, get_tx_count: rs_sip_state_get_tx_count, get_tx: rs_sip_state_get_tx, tx_get_comp_st: rs_sip_state_progress_completion_status, tx_get_progress: rs_sip_tx_get_alstate_progress, get_de_state: rs_sip_state_get_tx_detect_state, set_de_state: rs_sip_state_set_tx_detect_state, get_events: Some(rs_sip_state_get_events), get_eventinfo: Some(rs_sip_state_get_event_info), get_eventinfo_byid: Some(rs_sip_state_get_event_info_by_id), localstorage_new: None, localstorage_free: None, get_files: None, get_tx_iterator: None, get_tx_data: rs_sip_get_tx_data, apply_tx_config: None, flags: APP_LAYER_PARSER_OPT_UNIDIR_TXS, truncate: None, }; let ip_proto_str = CString::new("udp").unwrap(); if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); ALPROTO_SIP = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParser(&parser, alproto); } } else { SCLogDebug!("Protocol detecter and parser disabled for SIP/UDP."); } }
{ self.transactions.clear(); }
identifier_body
sip.rs
/* Copyright (C) 2019-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // written by Giuseppe Longo <[email protected]> extern crate nom; use crate::applayer::{self, *}; use crate::core; use crate::core::{sc_detect_engine_state_free, AppProto, Flow, ALPROTO_UNKNOWN}; use crate::sip::parser::*; use std; use std::ffi::{CStr, CString}; #[repr(u32)] pub enum SIPEvent { IncompleteData = 0, InvalidData, } impl SIPEvent { fn from_i32(value: i32) -> Option<SIPEvent> { match value { 0 => Some(SIPEvent::IncompleteData), 1 => Some(SIPEvent::InvalidData), _ => None, } } } pub struct SIPState { transactions: Vec<SIPTransaction>, tx_id: u64, } pub struct SIPTransaction { id: u64, pub request: Option<Request>, pub response: Option<Response>, pub request_line: Option<String>, pub response_line: Option<String>, de_state: Option<*mut core::DetectEngineState>, events: *mut core::AppLayerDecoderEvents, tx_data: applayer::AppLayerTxData, } impl SIPState { pub fn new() -> SIPState { SIPState { transactions: Vec::new(), tx_id: 0, } } pub fn free(&mut self) { self.transactions.clear(); } fn new_tx(&mut self) -> SIPTransaction { self.tx_id += 1; SIPTransaction::new(self.tx_id) } fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&SIPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64) { let tx = self .transactions .iter() .position(|ref tx| tx.id == tx_id + 1); debug_assert!(tx!= None); if let Some(idx) = tx
} fn set_event(&mut self, event: SIPEvent) { if let Some(tx) = self.transactions.last_mut() { let ev = event as u8; core::sc_app_layer_decoder_events_set_event_raw(&mut tx.events, ev); } } fn parse_request(&mut self, input: &[u8]) -> bool { match sip_parse_request(input) { Ok((_, request)) => { let mut tx = self.new_tx(); tx.request = Some(request); if let Ok((_, req_line)) = sip_take_line(input) { tx.request_line = req_line; } self.transactions.push(tx); return true; } Err(nom::Err::Incomplete(_)) => { self.set_event(SIPEvent::IncompleteData); return false; } Err(_) => { self.set_event(SIPEvent::InvalidData); return false; } } } fn parse_response(&mut self, input: &[u8]) -> bool { match sip_parse_response(input) { Ok((_, response)) => { let mut tx = self.new_tx(); tx.response = Some(response); if let Ok((_, resp_line)) = sip_take_line(input) { tx.response_line = resp_line; } self.transactions.push(tx); return true; } Err(nom::Err::Incomplete(_)) => { self.set_event(SIPEvent::IncompleteData); return false; } Err(_) => { self.set_event(SIPEvent::InvalidData); return false; } } } } impl SIPTransaction { pub fn new(id: u64) -> SIPTransaction { SIPTransaction { id: id, de_state: None, request: None, response: None, request_line: None, response_line: None, events: std::ptr::null_mut(), tx_data: applayer::AppLayerTxData::new(), } } } impl Drop for SIPTransaction { fn drop(&mut self) { if self.events!= std::ptr::null_mut() { core::sc_app_layer_decoder_events_free_events(&mut self.events); } if let Some(state) = self.de_state { sc_detect_engine_state_free(state); } } } #[no_mangle] pub extern "C" fn rs_sip_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void { let state = SIPState::new(); let boxed = Box::new(state); return unsafe { std::mem::transmute(boxed) }; } #[no_mangle] pub extern "C" fn rs_sip_state_free(state: *mut std::os::raw::c_void) { let mut state: Box<SIPState> = unsafe { std::mem::transmute(state) }; state.free(); } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx( state: *mut std::os::raw::c_void, tx_id: u64, ) -> *mut std::os::raw::c_void { let state = cast_pointer!(state, SIPState); match state.get_tx_by_id(tx_id) { Some(tx) => unsafe { std::mem::transmute(tx) }, None => std::ptr::null_mut(), } } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 { let state = cast_pointer!(state, SIPState); state.tx_id } #[no_mangle] pub extern "C" fn rs_sip_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) { let state = cast_pointer!(state, SIPState); state.free_tx(tx_id); } #[no_mangle] pub extern "C" fn rs_sip_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int { return 1; } #[no_mangle] pub extern "C" fn rs_sip_tx_get_alstate_progress( _tx: *mut std::os::raw::c_void, _direction: u8, ) -> std::os::raw::c_int { 1 } #[no_mangle] pub extern "C" fn rs_sip_state_set_tx_detect_state( tx: *mut std::os::raw::c_void, de_state: &mut core::DetectEngineState, ) -> std::os::raw::c_int { let tx = cast_pointer!(tx, SIPTransaction); tx.de_state = Some(de_state); 0 } #[no_mangle] pub extern "C" fn rs_sip_state_get_tx_detect_state( tx: *mut std::os::raw::c_void, ) -> *mut core::DetectEngineState { let tx = cast_pointer!(tx, SIPTransaction); match tx.de_state { Some(ds) => ds, None => std::ptr::null_mut(), } } #[no_mangle] pub extern "C" fn rs_sip_state_get_events( tx: *mut std::os::raw::c_void, ) -> *mut core::AppLayerDecoderEvents { let tx = cast_pointer!(tx, SIPTransaction); return tx.events; } #[no_mangle] pub extern "C" fn rs_sip_state_get_event_info( event_name: *const std::os::raw::c_char, event_id: *mut std::os::raw::c_int, event_type: *mut core::AppLayerEventType, ) -> std::os::raw::c_int { if event_name == std::ptr::null() { return -1; } let c_event_name: &CStr = unsafe { CStr::from_ptr(event_name) }; let event = match c_event_name.to_str() { Ok(s) => { match s { "incomplete_data" => SIPEvent::IncompleteData as i32, "invalid_data" => SIPEvent::InvalidData as i32, _ => -1, // unknown event } } Err(_) => -1, // UTF-8 conversion failed }; unsafe { *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION; *event_id = event as std::os::raw::c_int; }; 0 } #[no_mangle] pub extern "C" fn rs_sip_state_get_event_info_by_id( event_id: std::os::raw::c_int, event_name: *mut *const std::os::raw::c_char, event_type: *mut core::AppLayerEventType, ) -> i8 { if let Some(e) = SIPEvent::from_i32(event_id as i32) { let estr = match e { SIPEvent::IncompleteData => "incomplete_data\0", SIPEvent::InvalidData => "invalid_data\0", }; unsafe { *event_name = estr.as_ptr() as *const std::os::raw::c_char; *event_type = core::APP_LAYER_EVENT_TYPE_TRANSACTION; }; 0 } else { -1 } } static mut ALPROTO_SIP: AppProto = ALPROTO_UNKNOWN; #[no_mangle] pub extern "C" fn rs_sip_probing_parser_ts( _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8, ) -> AppProto { let buf = build_slice!(input, input_len as usize); if sip_parse_request(buf).is_ok() { return unsafe { ALPROTO_SIP }; } return ALPROTO_UNKNOWN; } #[no_mangle] pub extern "C" fn rs_sip_probing_parser_tc( _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8, ) -> AppProto { let buf = build_slice!(input, input_len as usize); if sip_parse_response(buf).is_ok() { return unsafe { ALPROTO_SIP }; } return ALPROTO_UNKNOWN; } #[no_mangle] pub extern "C" fn rs_sip_parse_request( _flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8, ) -> AppLayerResult { let buf = build_slice!(input, input_len as usize); let state = cast_pointer!(state, SIPState); state.parse_request(buf).into() } #[no_mangle] pub extern "C" fn rs_sip_parse_response( _flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, input: *const u8, input_len: u32, _data: *const std::os::raw::c_void, _flags: u8, ) -> AppLayerResult { let buf = build_slice!(input, input_len as usize); let state = cast_pointer!(state, SIPState); state.parse_response(buf).into() } export_tx_data_get!(rs_sip_get_tx_data, SIPTransaction); const PARSER_NAME: &'static [u8] = b"sip\0"; #[no_mangle] pub unsafe extern "C" fn rs_sip_register_parser() { let default_port = CString::new("5060").unwrap(); let parser = RustParser { name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port: default_port.as_ptr(), ipproto: core::IPPROTO_UDP, probe_ts: Some(rs_sip_probing_parser_ts), probe_tc: Some(rs_sip_probing_parser_tc), min_depth: 0, max_depth: 16, state_new: rs_sip_state_new, state_free: rs_sip_state_free, tx_free: rs_sip_state_tx_free, parse_ts: rs_sip_parse_request, parse_tc: rs_sip_parse_response, get_tx_count: rs_sip_state_get_tx_count, get_tx: rs_sip_state_get_tx, tx_get_comp_st: rs_sip_state_progress_completion_status, tx_get_progress: rs_sip_tx_get_alstate_progress, get_de_state: rs_sip_state_get_tx_detect_state, set_de_state: rs_sip_state_set_tx_detect_state, get_events: Some(rs_sip_state_get_events), get_eventinfo: Some(rs_sip_state_get_event_info), get_eventinfo_byid: Some(rs_sip_state_get_event_info_by_id), localstorage_new: None, localstorage_free: None, get_files: None, get_tx_iterator: None, get_tx_data: rs_sip_get_tx_data, apply_tx_config: None, flags: APP_LAYER_PARSER_OPT_UNIDIR_TXS, truncate: None, }; let ip_proto_str = CString::new("udp").unwrap(); if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); ALPROTO_SIP = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParser(&parser, alproto); } } else { SCLogDebug!("Protocol detecter and parser disabled for SIP/UDP."); } }
{ let _ = self.transactions.remove(idx); }
conditional_block
ntp.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // written by Pierre Chifflier <[email protected]> extern crate ntp_parser; use self::ntp_parser::*; use crate::core; use crate::core::{AppProto,Flow,ALPROTO_UNKNOWN,ALPROTO_FAILED}; use crate::applayer::{self, *}; use std; use std::ffi::CString; use nom; #[derive(AppLayerEvent)] pub enum NTPEvent { UnsolicitedResponse, MalformedData, NotRequest, NotResponse, } pub struct NTPState { /// List of transactions for this session transactions: Vec<NTPTransaction>, /// Events counter events: u16, /// tx counter for assigning incrementing id's to tx's tx_id: u64, } #[derive(Debug)] pub struct NTPTransaction { /// The NTP reference ID pub xid: u32, /// The internal transaction id id: u64, tx_data: applayer::AppLayerTxData, } impl Transaction for NTPTransaction { fn id(&self) -> u64 { self.id } } impl NTPState { pub fn new() -> NTPState { NTPState{ transactions: Vec::new(), events: 0, tx_id: 0, } } } impl State<NTPTransaction> for NTPState { fn get_transactions(&self) -> &[NTPTransaction] { &self.transactions } } impl NTPState { /// Parse an NTP request message /// /// Returns 0 if successful, or -1 on error fn
(&mut self, i: &[u8], _direction: u8) -> i32 { match parse_ntp(i) { Ok((_,ref msg)) => { // SCLogDebug!("parse_ntp: {:?}",msg); if msg.mode == NtpMode::SymmetricActive || msg.mode == NtpMode::Client { let mut tx = self.new_tx(); // use the reference id as identifier tx.xid = msg.ref_id; self.transactions.push(tx); } 0 }, Err(nom::Err::Incomplete(_)) => { SCLogDebug!("Insufficient data while parsing NTP data"); self.set_event(NTPEvent::MalformedData); -1 }, Err(_) => { SCLogDebug!("Error while parsing NTP data"); self.set_event(NTPEvent::MalformedData); -1 }, } } fn free(&mut self) { // All transactions are freed when the `transactions` object is freed. // But let's be explicit self.transactions.clear(); } fn new_tx(&mut self) -> NTPTransaction { self.tx_id += 1; NTPTransaction::new(self.tx_id) } pub fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&NTPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64) { let tx = self.transactions.iter().position(|tx| tx.id == tx_id + 1); debug_assert!(tx!= None); if let Some(idx) = tx { let _ = self.transactions.remove(idx); } } /// Set an event. The event is set on the most recent transaction. pub fn set_event(&mut self, event: NTPEvent) { if let Some(tx) = self.transactions.last_mut() { tx.tx_data.set_event(event as u8); self.events += 1; } } } impl NTPTransaction { pub fn new(id: u64) -> NTPTransaction { NTPTransaction { xid: 0, id: id, tx_data: applayer::AppLayerTxData::new(), } } } /// Returns *mut NTPState #[no_mangle] pub extern "C" fn rs_ntp_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void { let state = NTPState::new(); let boxed = Box::new(state); return Box::into_raw(boxed) as *mut _; } /// Params: /// - state: *mut NTPState as void pointer #[no_mangle] pub extern "C" fn rs_ntp_state_free(state: *mut std::os::raw::c_void) { let mut ntp_state = unsafe{ Box::from_raw(state as *mut NTPState) }; ntp_state.free(); } #[no_mangle] pub unsafe extern "C" fn rs_ntp_parse_request(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, stream_slice: StreamSlice, _data: *const std::os::raw::c_void, ) -> AppLayerResult { let state = cast_pointer!(state,NTPState); if state.parse(stream_slice.as_slice(), 0) < 0 { return AppLayerResult::err(); } AppLayerResult::ok() } #[no_mangle] pub unsafe extern "C" fn rs_ntp_parse_response(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, stream_slice: StreamSlice, _data: *const std::os::raw::c_void, ) -> AppLayerResult { let state = cast_pointer!(state,NTPState); if state.parse(stream_slice.as_slice(), 1) < 0 { return AppLayerResult::err(); } AppLayerResult::ok() } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_get_tx(state: *mut std::os::raw::c_void, tx_id: u64) -> *mut std::os::raw::c_void { let state = cast_pointer!(state,NTPState); match state.get_tx_by_id(tx_id) { Some(tx) => tx as *const _ as *mut _, None => std::ptr::null_mut(), } } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 { let state = cast_pointer!(state,NTPState); state.tx_id } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) { let state = cast_pointer!(state,NTPState); state.free_tx(tx_id); } #[no_mangle] pub extern "C" fn rs_ntp_tx_get_alstate_progress(_tx: *mut std::os::raw::c_void, _direction: u8) -> std::os::raw::c_int { 1 } static mut ALPROTO_NTP : AppProto = ALPROTO_UNKNOWN; #[no_mangle] pub extern "C" fn ntp_probing_parser(_flow: *const Flow, _direction: u8, input:*const u8, input_len: u32, _rdir: *mut u8) -> AppProto { let slice: &[u8] = unsafe { std::slice::from_raw_parts(input as *mut u8, input_len as usize) }; let alproto = unsafe{ ALPROTO_NTP }; match parse_ntp(slice) { Ok((_, ref msg)) => { if msg.version == 3 || msg.version == 4 { return alproto; } else { return unsafe{ALPROTO_FAILED}; } }, Err(nom::Err::Incomplete(_)) => { return ALPROTO_UNKNOWN; }, Err(_) => { return unsafe{ALPROTO_FAILED}; }, } } export_tx_data_get!(rs_ntp_get_tx_data, NTPTransaction); const PARSER_NAME : &'static [u8] = b"ntp\0"; #[no_mangle] pub unsafe extern "C" fn rs_register_ntp_parser() { let default_port = CString::new("123").unwrap(); let parser = RustParser { name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port : default_port.as_ptr(), ipproto : core::IPPROTO_UDP, probe_ts : Some(ntp_probing_parser), probe_tc : Some(ntp_probing_parser), min_depth : 0, max_depth : 16, state_new : rs_ntp_state_new, state_free : rs_ntp_state_free, tx_free : rs_ntp_state_tx_free, parse_ts : rs_ntp_parse_request, parse_tc : rs_ntp_parse_response, get_tx_count : rs_ntp_state_get_tx_count, get_tx : rs_ntp_state_get_tx, tx_comp_st_ts : 1, tx_comp_st_tc : 1, tx_get_progress : rs_ntp_tx_get_alstate_progress, get_eventinfo : Some(NTPEvent::get_event_info), get_eventinfo_byid : Some(NTPEvent::get_event_info_by_id), localstorage_new : None, localstorage_free : None, get_files : None, get_tx_iterator : Some(applayer::state_get_tx_iterator::<NTPState, NTPTransaction>), get_tx_data : rs_ntp_get_tx_data, apply_tx_config : None, flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS, truncate : None, get_frame_id_by_name: None, get_frame_name_by_id: None, }; let ip_proto_str = CString::new("udp").unwrap(); if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); // store the allocated ID for the probe function ALPROTO_NTP = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParser(&parser, alproto); } } else { SCLogDebug!("Protocol detector and parser disabled for NTP."); } } #[cfg(test)] mod tests { use super::NTPState; #[test] fn test_ntp_parse_request_valid() { // A UDP NTP v4 request, in client mode const REQ : &[u8] = &[ 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x57, 0xab, 0xc3, 0x4a, 0x5f, 0x2c, 0xfe ]; let mut state = NTPState::new(); assert_eq!(0, state.parse(REQ, 0)); } }
parse
identifier_name
ntp.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // written by Pierre Chifflier <[email protected]> extern crate ntp_parser; use self::ntp_parser::*; use crate::core; use crate::core::{AppProto,Flow,ALPROTO_UNKNOWN,ALPROTO_FAILED}; use crate::applayer::{self, *}; use std; use std::ffi::CString; use nom; #[derive(AppLayerEvent)] pub enum NTPEvent { UnsolicitedResponse, MalformedData, NotRequest, NotResponse, } pub struct NTPState { /// List of transactions for this session transactions: Vec<NTPTransaction>, /// Events counter events: u16, /// tx counter for assigning incrementing id's to tx's tx_id: u64, } #[derive(Debug)] pub struct NTPTransaction { /// The NTP reference ID pub xid: u32, /// The internal transaction id id: u64, tx_data: applayer::AppLayerTxData, } impl Transaction for NTPTransaction { fn id(&self) -> u64 { self.id } } impl NTPState { pub fn new() -> NTPState { NTPState{ transactions: Vec::new(), events: 0, tx_id: 0, } } } impl State<NTPTransaction> for NTPState { fn get_transactions(&self) -> &[NTPTransaction] { &self.transactions } } impl NTPState { /// Parse an NTP request message /// /// Returns 0 if successful, or -1 on error fn parse(&mut self, i: &[u8], _direction: u8) -> i32 { match parse_ntp(i) { Ok((_,ref msg)) => { // SCLogDebug!("parse_ntp: {:?}",msg); if msg.mode == NtpMode::SymmetricActive || msg.mode == NtpMode::Client { let mut tx = self.new_tx(); // use the reference id as identifier tx.xid = msg.ref_id; self.transactions.push(tx); } 0 }, Err(nom::Err::Incomplete(_)) => { SCLogDebug!("Insufficient data while parsing NTP data"); self.set_event(NTPEvent::MalformedData); -1 }, Err(_) => { SCLogDebug!("Error while parsing NTP data"); self.set_event(NTPEvent::MalformedData); -1 }, } } fn free(&mut self) { // All transactions are freed when the `transactions` object is freed. // But let's be explicit self.transactions.clear(); } fn new_tx(&mut self) -> NTPTransaction { self.tx_id += 1; NTPTransaction::new(self.tx_id) } pub fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&NTPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64) { let tx = self.transactions.iter().position(|tx| tx.id == tx_id + 1); debug_assert!(tx!= None); if let Some(idx) = tx { let _ = self.transactions.remove(idx); } } /// Set an event. The event is set on the most recent transaction. pub fn set_event(&mut self, event: NTPEvent) { if let Some(tx) = self.transactions.last_mut() { tx.tx_data.set_event(event as u8); self.events += 1; } } } impl NTPTransaction { pub fn new(id: u64) -> NTPTransaction { NTPTransaction { xid: 0, id: id, tx_data: applayer::AppLayerTxData::new(), } } } /// Returns *mut NTPState #[no_mangle] pub extern "C" fn rs_ntp_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void { let state = NTPState::new(); let boxed = Box::new(state); return Box::into_raw(boxed) as *mut _; } /// Params: /// - state: *mut NTPState as void pointer #[no_mangle] pub extern "C" fn rs_ntp_state_free(state: *mut std::os::raw::c_void) { let mut ntp_state = unsafe{ Box::from_raw(state as *mut NTPState) }; ntp_state.free(); } #[no_mangle] pub unsafe extern "C" fn rs_ntp_parse_request(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, stream_slice: StreamSlice, _data: *const std::os::raw::c_void, ) -> AppLayerResult { let state = cast_pointer!(state,NTPState); if state.parse(stream_slice.as_slice(), 0) < 0 { return AppLayerResult::err(); } AppLayerResult::ok() } #[no_mangle] pub unsafe extern "C" fn rs_ntp_parse_response(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, stream_slice: StreamSlice, _data: *const std::os::raw::c_void, ) -> AppLayerResult { let state = cast_pointer!(state,NTPState); if state.parse(stream_slice.as_slice(), 1) < 0 { return AppLayerResult::err(); } AppLayerResult::ok() } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_get_tx(state: *mut std::os::raw::c_void, tx_id: u64) -> *mut std::os::raw::c_void { let state = cast_pointer!(state,NTPState); match state.get_tx_by_id(tx_id) { Some(tx) => tx as *const _ as *mut _, None => std::ptr::null_mut(), } } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 { let state = cast_pointer!(state,NTPState); state.tx_id } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) { let state = cast_pointer!(state,NTPState); state.free_tx(tx_id); } #[no_mangle] pub extern "C" fn rs_ntp_tx_get_alstate_progress(_tx: *mut std::os::raw::c_void, _direction: u8) -> std::os::raw::c_int { 1 } static mut ALPROTO_NTP : AppProto = ALPROTO_UNKNOWN; #[no_mangle] pub extern "C" fn ntp_probing_parser(_flow: *const Flow, _direction: u8, input:*const u8, input_len: u32, _rdir: *mut u8) -> AppProto { let slice: &[u8] = unsafe { std::slice::from_raw_parts(input as *mut u8, input_len as usize) }; let alproto = unsafe{ ALPROTO_NTP }; match parse_ntp(slice) { Ok((_, ref msg)) => { if msg.version == 3 || msg.version == 4 { return alproto; } else { return unsafe{ALPROTO_FAILED}; } }, Err(nom::Err::Incomplete(_)) => { return ALPROTO_UNKNOWN; }, Err(_) => { return unsafe{ALPROTO_FAILED}; }, } } export_tx_data_get!(rs_ntp_get_tx_data, NTPTransaction); const PARSER_NAME : &'static [u8] = b"ntp\0"; #[no_mangle] pub unsafe extern "C" fn rs_register_ntp_parser() { let default_port = CString::new("123").unwrap(); let parser = RustParser { name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port : default_port.as_ptr(), ipproto : core::IPPROTO_UDP,
max_depth : 16, state_new : rs_ntp_state_new, state_free : rs_ntp_state_free, tx_free : rs_ntp_state_tx_free, parse_ts : rs_ntp_parse_request, parse_tc : rs_ntp_parse_response, get_tx_count : rs_ntp_state_get_tx_count, get_tx : rs_ntp_state_get_tx, tx_comp_st_ts : 1, tx_comp_st_tc : 1, tx_get_progress : rs_ntp_tx_get_alstate_progress, get_eventinfo : Some(NTPEvent::get_event_info), get_eventinfo_byid : Some(NTPEvent::get_event_info_by_id), localstorage_new : None, localstorage_free : None, get_files : None, get_tx_iterator : Some(applayer::state_get_tx_iterator::<NTPState, NTPTransaction>), get_tx_data : rs_ntp_get_tx_data, apply_tx_config : None, flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS, truncate : None, get_frame_id_by_name: None, get_frame_name_by_id: None, }; let ip_proto_str = CString::new("udp").unwrap(); if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); // store the allocated ID for the probe function ALPROTO_NTP = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParser(&parser, alproto); } } else { SCLogDebug!("Protocol detector and parser disabled for NTP."); } } #[cfg(test)] mod tests { use super::NTPState; #[test] fn test_ntp_parse_request_valid() { // A UDP NTP v4 request, in client mode const REQ : &[u8] = &[ 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x57, 0xab, 0xc3, 0x4a, 0x5f, 0x2c, 0xfe ]; let mut state = NTPState::new(); assert_eq!(0, state.parse(REQ, 0)); } }
probe_ts : Some(ntp_probing_parser), probe_tc : Some(ntp_probing_parser), min_depth : 0,
random_line_split
ntp.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // written by Pierre Chifflier <[email protected]> extern crate ntp_parser; use self::ntp_parser::*; use crate::core; use crate::core::{AppProto,Flow,ALPROTO_UNKNOWN,ALPROTO_FAILED}; use crate::applayer::{self, *}; use std; use std::ffi::CString; use nom; #[derive(AppLayerEvent)] pub enum NTPEvent { UnsolicitedResponse, MalformedData, NotRequest, NotResponse, } pub struct NTPState { /// List of transactions for this session transactions: Vec<NTPTransaction>, /// Events counter events: u16, /// tx counter for assigning incrementing id's to tx's tx_id: u64, } #[derive(Debug)] pub struct NTPTransaction { /// The NTP reference ID pub xid: u32, /// The internal transaction id id: u64, tx_data: applayer::AppLayerTxData, } impl Transaction for NTPTransaction { fn id(&self) -> u64 { self.id } } impl NTPState { pub fn new() -> NTPState { NTPState{ transactions: Vec::new(), events: 0, tx_id: 0, } } } impl State<NTPTransaction> for NTPState { fn get_transactions(&self) -> &[NTPTransaction] { &self.transactions } } impl NTPState { /// Parse an NTP request message /// /// Returns 0 if successful, or -1 on error fn parse(&mut self, i: &[u8], _direction: u8) -> i32 { match parse_ntp(i) { Ok((_,ref msg)) => { // SCLogDebug!("parse_ntp: {:?}",msg); if msg.mode == NtpMode::SymmetricActive || msg.mode == NtpMode::Client { let mut tx = self.new_tx(); // use the reference id as identifier tx.xid = msg.ref_id; self.transactions.push(tx); } 0 }, Err(nom::Err::Incomplete(_)) => { SCLogDebug!("Insufficient data while parsing NTP data"); self.set_event(NTPEvent::MalformedData); -1 }, Err(_) => { SCLogDebug!("Error while parsing NTP data"); self.set_event(NTPEvent::MalformedData); -1 }, } } fn free(&mut self) { // All transactions are freed when the `transactions` object is freed. // But let's be explicit self.transactions.clear(); } fn new_tx(&mut self) -> NTPTransaction { self.tx_id += 1; NTPTransaction::new(self.tx_id) } pub fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&NTPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64)
/// Set an event. The event is set on the most recent transaction. pub fn set_event(&mut self, event: NTPEvent) { if let Some(tx) = self.transactions.last_mut() { tx.tx_data.set_event(event as u8); self.events += 1; } } } impl NTPTransaction { pub fn new(id: u64) -> NTPTransaction { NTPTransaction { xid: 0, id: id, tx_data: applayer::AppLayerTxData::new(), } } } /// Returns *mut NTPState #[no_mangle] pub extern "C" fn rs_ntp_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void { let state = NTPState::new(); let boxed = Box::new(state); return Box::into_raw(boxed) as *mut _; } /// Params: /// - state: *mut NTPState as void pointer #[no_mangle] pub extern "C" fn rs_ntp_state_free(state: *mut std::os::raw::c_void) { let mut ntp_state = unsafe{ Box::from_raw(state as *mut NTPState) }; ntp_state.free(); } #[no_mangle] pub unsafe extern "C" fn rs_ntp_parse_request(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, stream_slice: StreamSlice, _data: *const std::os::raw::c_void, ) -> AppLayerResult { let state = cast_pointer!(state,NTPState); if state.parse(stream_slice.as_slice(), 0) < 0 { return AppLayerResult::err(); } AppLayerResult::ok() } #[no_mangle] pub unsafe extern "C" fn rs_ntp_parse_response(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, stream_slice: StreamSlice, _data: *const std::os::raw::c_void, ) -> AppLayerResult { let state = cast_pointer!(state,NTPState); if state.parse(stream_slice.as_slice(), 1) < 0 { return AppLayerResult::err(); } AppLayerResult::ok() } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_get_tx(state: *mut std::os::raw::c_void, tx_id: u64) -> *mut std::os::raw::c_void { let state = cast_pointer!(state,NTPState); match state.get_tx_by_id(tx_id) { Some(tx) => tx as *const _ as *mut _, None => std::ptr::null_mut(), } } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 { let state = cast_pointer!(state,NTPState); state.tx_id } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) { let state = cast_pointer!(state,NTPState); state.free_tx(tx_id); } #[no_mangle] pub extern "C" fn rs_ntp_tx_get_alstate_progress(_tx: *mut std::os::raw::c_void, _direction: u8) -> std::os::raw::c_int { 1 } static mut ALPROTO_NTP : AppProto = ALPROTO_UNKNOWN; #[no_mangle] pub extern "C" fn ntp_probing_parser(_flow: *const Flow, _direction: u8, input:*const u8, input_len: u32, _rdir: *mut u8) -> AppProto { let slice: &[u8] = unsafe { std::slice::from_raw_parts(input as *mut u8, input_len as usize) }; let alproto = unsafe{ ALPROTO_NTP }; match parse_ntp(slice) { Ok((_, ref msg)) => { if msg.version == 3 || msg.version == 4 { return alproto; } else { return unsafe{ALPROTO_FAILED}; } }, Err(nom::Err::Incomplete(_)) => { return ALPROTO_UNKNOWN; }, Err(_) => { return unsafe{ALPROTO_FAILED}; }, } } export_tx_data_get!(rs_ntp_get_tx_data, NTPTransaction); const PARSER_NAME : &'static [u8] = b"ntp\0"; #[no_mangle] pub unsafe extern "C" fn rs_register_ntp_parser() { let default_port = CString::new("123").unwrap(); let parser = RustParser { name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port : default_port.as_ptr(), ipproto : core::IPPROTO_UDP, probe_ts : Some(ntp_probing_parser), probe_tc : Some(ntp_probing_parser), min_depth : 0, max_depth : 16, state_new : rs_ntp_state_new, state_free : rs_ntp_state_free, tx_free : rs_ntp_state_tx_free, parse_ts : rs_ntp_parse_request, parse_tc : rs_ntp_parse_response, get_tx_count : rs_ntp_state_get_tx_count, get_tx : rs_ntp_state_get_tx, tx_comp_st_ts : 1, tx_comp_st_tc : 1, tx_get_progress : rs_ntp_tx_get_alstate_progress, get_eventinfo : Some(NTPEvent::get_event_info), get_eventinfo_byid : Some(NTPEvent::get_event_info_by_id), localstorage_new : None, localstorage_free : None, get_files : None, get_tx_iterator : Some(applayer::state_get_tx_iterator::<NTPState, NTPTransaction>), get_tx_data : rs_ntp_get_tx_data, apply_tx_config : None, flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS, truncate : None, get_frame_id_by_name: None, get_frame_name_by_id: None, }; let ip_proto_str = CString::new("udp").unwrap(); if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); // store the allocated ID for the probe function ALPROTO_NTP = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParser(&parser, alproto); } } else { SCLogDebug!("Protocol detector and parser disabled for NTP."); } } #[cfg(test)] mod tests { use super::NTPState; #[test] fn test_ntp_parse_request_valid() { // A UDP NTP v4 request, in client mode const REQ : &[u8] = &[ 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x57, 0xab, 0xc3, 0x4a, 0x5f, 0x2c, 0xfe ]; let mut state = NTPState::new(); assert_eq!(0, state.parse(REQ, 0)); } }
{ let tx = self.transactions.iter().position(|tx| tx.id == tx_id + 1); debug_assert!(tx != None); if let Some(idx) = tx { let _ = self.transactions.remove(idx); } }
identifier_body
ntp.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ // written by Pierre Chifflier <[email protected]> extern crate ntp_parser; use self::ntp_parser::*; use crate::core; use crate::core::{AppProto,Flow,ALPROTO_UNKNOWN,ALPROTO_FAILED}; use crate::applayer::{self, *}; use std; use std::ffi::CString; use nom; #[derive(AppLayerEvent)] pub enum NTPEvent { UnsolicitedResponse, MalformedData, NotRequest, NotResponse, } pub struct NTPState { /// List of transactions for this session transactions: Vec<NTPTransaction>, /// Events counter events: u16, /// tx counter for assigning incrementing id's to tx's tx_id: u64, } #[derive(Debug)] pub struct NTPTransaction { /// The NTP reference ID pub xid: u32, /// The internal transaction id id: u64, tx_data: applayer::AppLayerTxData, } impl Transaction for NTPTransaction { fn id(&self) -> u64 { self.id } } impl NTPState { pub fn new() -> NTPState { NTPState{ transactions: Vec::new(), events: 0, tx_id: 0, } } } impl State<NTPTransaction> for NTPState { fn get_transactions(&self) -> &[NTPTransaction] { &self.transactions } } impl NTPState { /// Parse an NTP request message /// /// Returns 0 if successful, or -1 on error fn parse(&mut self, i: &[u8], _direction: u8) -> i32 { match parse_ntp(i) { Ok((_,ref msg)) => { // SCLogDebug!("parse_ntp: {:?}",msg); if msg.mode == NtpMode::SymmetricActive || msg.mode == NtpMode::Client { let mut tx = self.new_tx(); // use the reference id as identifier tx.xid = msg.ref_id; self.transactions.push(tx); } 0 }, Err(nom::Err::Incomplete(_)) => { SCLogDebug!("Insufficient data while parsing NTP data"); self.set_event(NTPEvent::MalformedData); -1 }, Err(_) => { SCLogDebug!("Error while parsing NTP data"); self.set_event(NTPEvent::MalformedData); -1 }, } } fn free(&mut self) { // All transactions are freed when the `transactions` object is freed. // But let's be explicit self.transactions.clear(); } fn new_tx(&mut self) -> NTPTransaction { self.tx_id += 1; NTPTransaction::new(self.tx_id) } pub fn get_tx_by_id(&mut self, tx_id: u64) -> Option<&NTPTransaction> { self.transactions.iter().find(|&tx| tx.id == tx_id + 1) } fn free_tx(&mut self, tx_id: u64) { let tx = self.transactions.iter().position(|tx| tx.id == tx_id + 1); debug_assert!(tx!= None); if let Some(idx) = tx { let _ = self.transactions.remove(idx); } } /// Set an event. The event is set on the most recent transaction. pub fn set_event(&mut self, event: NTPEvent) { if let Some(tx) = self.transactions.last_mut() { tx.tx_data.set_event(event as u8); self.events += 1; } } } impl NTPTransaction { pub fn new(id: u64) -> NTPTransaction { NTPTransaction { xid: 0, id: id, tx_data: applayer::AppLayerTxData::new(), } } } /// Returns *mut NTPState #[no_mangle] pub extern "C" fn rs_ntp_state_new(_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto) -> *mut std::os::raw::c_void { let state = NTPState::new(); let boxed = Box::new(state); return Box::into_raw(boxed) as *mut _; } /// Params: /// - state: *mut NTPState as void pointer #[no_mangle] pub extern "C" fn rs_ntp_state_free(state: *mut std::os::raw::c_void) { let mut ntp_state = unsafe{ Box::from_raw(state as *mut NTPState) }; ntp_state.free(); } #[no_mangle] pub unsafe extern "C" fn rs_ntp_parse_request(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, stream_slice: StreamSlice, _data: *const std::os::raw::c_void, ) -> AppLayerResult { let state = cast_pointer!(state,NTPState); if state.parse(stream_slice.as_slice(), 0) < 0 { return AppLayerResult::err(); } AppLayerResult::ok() } #[no_mangle] pub unsafe extern "C" fn rs_ntp_parse_response(_flow: *const core::Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void, stream_slice: StreamSlice, _data: *const std::os::raw::c_void, ) -> AppLayerResult { let state = cast_pointer!(state,NTPState); if state.parse(stream_slice.as_slice(), 1) < 0 { return AppLayerResult::err(); } AppLayerResult::ok() } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_get_tx(state: *mut std::os::raw::c_void, tx_id: u64) -> *mut std::os::raw::c_void { let state = cast_pointer!(state,NTPState); match state.get_tx_by_id(tx_id) { Some(tx) => tx as *const _ as *mut _, None => std::ptr::null_mut(), } } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 { let state = cast_pointer!(state,NTPState); state.tx_id } #[no_mangle] pub unsafe extern "C" fn rs_ntp_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) { let state = cast_pointer!(state,NTPState); state.free_tx(tx_id); } #[no_mangle] pub extern "C" fn rs_ntp_tx_get_alstate_progress(_tx: *mut std::os::raw::c_void, _direction: u8) -> std::os::raw::c_int { 1 } static mut ALPROTO_NTP : AppProto = ALPROTO_UNKNOWN; #[no_mangle] pub extern "C" fn ntp_probing_parser(_flow: *const Flow, _direction: u8, input:*const u8, input_len: u32, _rdir: *mut u8) -> AppProto { let slice: &[u8] = unsafe { std::slice::from_raw_parts(input as *mut u8, input_len as usize) }; let alproto = unsafe{ ALPROTO_NTP }; match parse_ntp(slice) { Ok((_, ref msg)) => { if msg.version == 3 || msg.version == 4 { return alproto; } else { return unsafe{ALPROTO_FAILED}; } }, Err(nom::Err::Incomplete(_)) =>
, Err(_) => { return unsafe{ALPROTO_FAILED}; }, } } export_tx_data_get!(rs_ntp_get_tx_data, NTPTransaction); const PARSER_NAME : &'static [u8] = b"ntp\0"; #[no_mangle] pub unsafe extern "C" fn rs_register_ntp_parser() { let default_port = CString::new("123").unwrap(); let parser = RustParser { name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char, default_port : default_port.as_ptr(), ipproto : core::IPPROTO_UDP, probe_ts : Some(ntp_probing_parser), probe_tc : Some(ntp_probing_parser), min_depth : 0, max_depth : 16, state_new : rs_ntp_state_new, state_free : rs_ntp_state_free, tx_free : rs_ntp_state_tx_free, parse_ts : rs_ntp_parse_request, parse_tc : rs_ntp_parse_response, get_tx_count : rs_ntp_state_get_tx_count, get_tx : rs_ntp_state_get_tx, tx_comp_st_ts : 1, tx_comp_st_tc : 1, tx_get_progress : rs_ntp_tx_get_alstate_progress, get_eventinfo : Some(NTPEvent::get_event_info), get_eventinfo_byid : Some(NTPEvent::get_event_info_by_id), localstorage_new : None, localstorage_free : None, get_files : None, get_tx_iterator : Some(applayer::state_get_tx_iterator::<NTPState, NTPTransaction>), get_tx_data : rs_ntp_get_tx_data, apply_tx_config : None, flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS, truncate : None, get_frame_id_by_name: None, get_frame_name_by_id: None, }; let ip_proto_str = CString::new("udp").unwrap(); if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); // store the allocated ID for the probe function ALPROTO_NTP = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParser(&parser, alproto); } } else { SCLogDebug!("Protocol detector and parser disabled for NTP."); } } #[cfg(test)] mod tests { use super::NTPState; #[test] fn test_ntp_parse_request_valid() { // A UDP NTP v4 request, in client mode const REQ : &[u8] = &[ 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x57, 0xab, 0xc3, 0x4a, 0x5f, 0x2c, 0xfe ]; let mut state = NTPState::new(); assert_eq!(0, state.parse(REQ, 0)); } }
{ return ALPROTO_UNKNOWN; }
conditional_block
task-comm-13.rs
// 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 std::sync::mpsc::{channel, Sender}; use std::thread::Thread; fn start(tx: &Sender<int>, start: int, number_of_messages: int) { let mut i: int = 0; while i< number_of_messages { tx.send(start + i).unwrap(); i += 1; } } pub fn main() { println!("Check that we don't deadlock."); let (tx, rx) = channel(); let _ = Thread::scoped(move|| { start(&tx, 0, 10) }).join(); println!("Joined task"); }
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
random_line_split
task-comm-13.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. use std::sync::mpsc::{channel, Sender}; use std::thread::Thread; fn start(tx: &Sender<int>, start: int, number_of_messages: int) { let mut i: int = 0; while i< number_of_messages { tx.send(start + i).unwrap(); i += 1; } } pub fn main()
{ println!("Check that we don't deadlock."); let (tx, rx) = channel(); let _ = Thread::scoped(move|| { start(&tx, 0, 10) }).join(); println!("Joined task"); }
identifier_body
task-comm-13.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. use std::sync::mpsc::{channel, Sender}; use std::thread::Thread; fn start(tx: &Sender<int>, start: int, number_of_messages: int) { let mut i: int = 0; while i< number_of_messages { tx.send(start + i).unwrap(); i += 1; } } pub fn
() { println!("Check that we don't deadlock."); let (tx, rx) = channel(); let _ = Thread::scoped(move|| { start(&tx, 0, 10) }).join(); println!("Joined task"); }
main
identifier_name
tensor.rs
use std::ops::{Deref, DerefMut}; use enum_map::EnumMap; use crate::features::Layer; use tensorflow::{Tensor, TensorType}; /// Ad-hoc trait for shrinking batches. pub trait ShrinkBatch { fn shrink_batch(&self, n_instances: u64) -> Self; } impl<T> ShrinkBatch for Tensor<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { assert!( n_instances <= self.dims()[0], "Trying to shrink batch of size {} to {}", self.dims()[0], n_instances );
let mut copy = Tensor::new(&new_shape); copy.copy_from_slice(&self[..new_shape.iter().cloned().product::<u64>() as usize]); copy } } impl<T> ShrinkBatch for TensorWrap<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { TensorWrap(self.0.shrink_batch(n_instances)) } } impl<T> ShrinkBatch for LayerTensors<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { let mut copy = LayerTensors::new(); // Note: EnumMap does not support FromIterator. for (layer, tensor) in self.iter() { copy[layer] = tensor.shrink_batch(n_instances); } copy } } /// Ad-hoc trait for converting extracting slices from tensors. pub trait InstanceSlices<T> { /// Extract for each layer the slice corresponding to the `idx`-th /// instance from the batch. fn to_instance_slices(&mut self, idx: usize) -> EnumMap<Layer, &mut [T]>; } impl<T> InstanceSlices<T> for LayerTensors<T> where T: TensorType, { fn to_instance_slices(&mut self, idx: usize) -> EnumMap<Layer, &mut [T]> { let mut slices = EnumMap::new(); for (layer, tensor) in self.iter_mut() { let layer_size = tensor.dims()[1] as usize; let offset = idx * layer_size; slices[layer] = &mut tensor[offset..offset + layer_size]; } slices } } pub type LayerTensors<T> = EnumMap<Layer, TensorWrap<T>>; /// Simple wrapper for `Tensor` that implements the `Default` /// trait. pub struct TensorWrap<T>(pub Tensor<T>) where T: TensorType; impl<T> Default for TensorWrap<T> where T: TensorType, { fn default() -> Self { TensorWrap(Tensor::new(&[])) } } impl<T> From<Tensor<T>> for TensorWrap<T> where T: TensorType, { fn from(tensor: Tensor<T>) -> Self { TensorWrap(tensor) } } impl<T> Deref for TensorWrap<T> where T: TensorType, { type Target = Tensor<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for TensorWrap<T> where T: TensorType, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(test)] mod tests { use tensorflow::Tensor; use super::ShrinkBatch; #[test] fn copy_batches() { let original = Tensor::new(&[4, 2]) .with_values(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]) .expect("Cannot initialize tensor."); let copy = original.shrink_batch(2); assert_eq!(&*copy, &[1.0, 2.0, 3.0, 4.0]); } }
let mut new_shape = self.dims().to_owned(); new_shape[0] = n_instances;
random_line_split
tensor.rs
use std::ops::{Deref, DerefMut}; use enum_map::EnumMap; use crate::features::Layer; use tensorflow::{Tensor, TensorType}; /// Ad-hoc trait for shrinking batches. pub trait ShrinkBatch { fn shrink_batch(&self, n_instances: u64) -> Self; } impl<T> ShrinkBatch for Tensor<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { assert!( n_instances <= self.dims()[0], "Trying to shrink batch of size {} to {}", self.dims()[0], n_instances ); let mut new_shape = self.dims().to_owned(); new_shape[0] = n_instances; let mut copy = Tensor::new(&new_shape); copy.copy_from_slice(&self[..new_shape.iter().cloned().product::<u64>() as usize]); copy } } impl<T> ShrinkBatch for TensorWrap<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { TensorWrap(self.0.shrink_batch(n_instances)) } } impl<T> ShrinkBatch for LayerTensors<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { let mut copy = LayerTensors::new(); // Note: EnumMap does not support FromIterator. for (layer, tensor) in self.iter() { copy[layer] = tensor.shrink_batch(n_instances); } copy } } /// Ad-hoc trait for converting extracting slices from tensors. pub trait InstanceSlices<T> { /// Extract for each layer the slice corresponding to the `idx`-th /// instance from the batch. fn to_instance_slices(&mut self, idx: usize) -> EnumMap<Layer, &mut [T]>; } impl<T> InstanceSlices<T> for LayerTensors<T> where T: TensorType, { fn
(&mut self, idx: usize) -> EnumMap<Layer, &mut [T]> { let mut slices = EnumMap::new(); for (layer, tensor) in self.iter_mut() { let layer_size = tensor.dims()[1] as usize; let offset = idx * layer_size; slices[layer] = &mut tensor[offset..offset + layer_size]; } slices } } pub type LayerTensors<T> = EnumMap<Layer, TensorWrap<T>>; /// Simple wrapper for `Tensor` that implements the `Default` /// trait. pub struct TensorWrap<T>(pub Tensor<T>) where T: TensorType; impl<T> Default for TensorWrap<T> where T: TensorType, { fn default() -> Self { TensorWrap(Tensor::new(&[])) } } impl<T> From<Tensor<T>> for TensorWrap<T> where T: TensorType, { fn from(tensor: Tensor<T>) -> Self { TensorWrap(tensor) } } impl<T> Deref for TensorWrap<T> where T: TensorType, { type Target = Tensor<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for TensorWrap<T> where T: TensorType, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(test)] mod tests { use tensorflow::Tensor; use super::ShrinkBatch; #[test] fn copy_batches() { let original = Tensor::new(&[4, 2]) .with_values(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]) .expect("Cannot initialize tensor."); let copy = original.shrink_batch(2); assert_eq!(&*copy, &[1.0, 2.0, 3.0, 4.0]); } }
to_instance_slices
identifier_name
tensor.rs
use std::ops::{Deref, DerefMut}; use enum_map::EnumMap; use crate::features::Layer; use tensorflow::{Tensor, TensorType}; /// Ad-hoc trait for shrinking batches. pub trait ShrinkBatch { fn shrink_batch(&self, n_instances: u64) -> Self; } impl<T> ShrinkBatch for Tensor<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { assert!( n_instances <= self.dims()[0], "Trying to shrink batch of size {} to {}", self.dims()[0], n_instances ); let mut new_shape = self.dims().to_owned(); new_shape[0] = n_instances; let mut copy = Tensor::new(&new_shape); copy.copy_from_slice(&self[..new_shape.iter().cloned().product::<u64>() as usize]); copy } } impl<T> ShrinkBatch for TensorWrap<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { TensorWrap(self.0.shrink_batch(n_instances)) } } impl<T> ShrinkBatch for LayerTensors<T> where T: Copy + TensorType, { fn shrink_batch(&self, n_instances: u64) -> Self { let mut copy = LayerTensors::new(); // Note: EnumMap does not support FromIterator. for (layer, tensor) in self.iter() { copy[layer] = tensor.shrink_batch(n_instances); } copy } } /// Ad-hoc trait for converting extracting slices from tensors. pub trait InstanceSlices<T> { /// Extract for each layer the slice corresponding to the `idx`-th /// instance from the batch. fn to_instance_slices(&mut self, idx: usize) -> EnumMap<Layer, &mut [T]>; } impl<T> InstanceSlices<T> for LayerTensors<T> where T: TensorType, { fn to_instance_slices(&mut self, idx: usize) -> EnumMap<Layer, &mut [T]> { let mut slices = EnumMap::new(); for (layer, tensor) in self.iter_mut() { let layer_size = tensor.dims()[1] as usize; let offset = idx * layer_size; slices[layer] = &mut tensor[offset..offset + layer_size]; } slices } } pub type LayerTensors<T> = EnumMap<Layer, TensorWrap<T>>; /// Simple wrapper for `Tensor` that implements the `Default` /// trait. pub struct TensorWrap<T>(pub Tensor<T>) where T: TensorType; impl<T> Default for TensorWrap<T> where T: TensorType, { fn default() -> Self { TensorWrap(Tensor::new(&[])) } } impl<T> From<Tensor<T>> for TensorWrap<T> where T: TensorType, { fn from(tensor: Tensor<T>) -> Self
} impl<T> Deref for TensorWrap<T> where T: TensorType, { type Target = Tensor<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for TensorWrap<T> where T: TensorType, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(test)] mod tests { use tensorflow::Tensor; use super::ShrinkBatch; #[test] fn copy_batches() { let original = Tensor::new(&[4, 2]) .with_values(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]) .expect("Cannot initialize tensor."); let copy = original.shrink_batch(2); assert_eq!(&*copy, &[1.0, 2.0, 3.0, 4.0]); } }
{ TensorWrap(tensor) }
identifier_body
coherence_copy_like_err_fundamental_struct_ref.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we are able to introduce a negative constraint that // `MyType:!MyTrait` along with other "fundamental" wrappers. // aux-build:coherence_copy_like_lib.rs // compile-pass // skip-codegen #![allow(dead_code)] extern crate coherence_copy_like_lib as lib; struct MyType { x: i32 } trait MyTrait { fn
() {} } impl<T: lib::MyCopy> MyTrait for T { } // `MyFundamentalStruct` is declared fundamental, so we can test that // // MyFundamentalStruct<&MyTrait>:!MyTrait // // Huzzah. impl<'a> MyTrait for lib::MyFundamentalStruct<&'a MyType> { } fn main() { }
foo
identifier_name
coherence_copy_like_err_fundamental_struct_ref.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we are able to introduce a negative constraint that // `MyType:!MyTrait` along with other "fundamental" wrappers. // aux-build:coherence_copy_like_lib.rs // compile-pass // skip-codegen #![allow(dead_code)]
extern crate coherence_copy_like_lib as lib; struct MyType { x: i32 } trait MyTrait { fn foo() {} } impl<T: lib::MyCopy> MyTrait for T { } // `MyFundamentalStruct` is declared fundamental, so we can test that // // MyFundamentalStruct<&MyTrait>:!MyTrait // // Huzzah. impl<'a> MyTrait for lib::MyFundamentalStruct<&'a MyType> { } fn main() { }
random_line_split
coherence_copy_like_err_fundamental_struct_ref.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we are able to introduce a negative constraint that // `MyType:!MyTrait` along with other "fundamental" wrappers. // aux-build:coherence_copy_like_lib.rs // compile-pass // skip-codegen #![allow(dead_code)] extern crate coherence_copy_like_lib as lib; struct MyType { x: i32 } trait MyTrait { fn foo() {} } impl<T: lib::MyCopy> MyTrait for T { } // `MyFundamentalStruct` is declared fundamental, so we can test that // // MyFundamentalStruct<&MyTrait>:!MyTrait // // Huzzah. impl<'a> MyTrait for lib::MyFundamentalStruct<&'a MyType> { } fn main()
{ }
identifier_body
model.rs
//! Defines the `JsonApiModel` trait. This is primarily used in conjunction with //! the [`jsonapi_model!`](../macro.jsonapi_model.html) macro to allow arbitrary //! structs which implement `Deserialize` to be converted to/from a //! [`JsonApiDocument`](../api/struct.JsonApiDocument.html) or //! [`Resource`](../api/struct.Resource.html) pub use std::collections::HashMap; pub use crate::api::*; use crate::errors::*; use serde::{Deserialize, Serialize}; use serde_json::{from_value, to_value, Value, Map}; /// A trait for any struct that can be converted from/into a /// [`Resource`](api/struct.Resource.tml). The only requirement is that your /// struct has an `id: String` field. /// You shouldn't be implementing JsonApiModel manually, look at the /// `jsonapi_model!` macro instead. pub trait JsonApiModel: Serialize where for<'de> Self: Deserialize<'de>, { #[doc(hidden)] fn jsonapi_type(&self) -> String; #[doc(hidden)] fn jsonapi_id(&self) -> String; #[doc(hidden)] fn relationship_fields() -> Option<&'static [&'static str]>; #[doc(hidden)] fn build_relationships(&self) -> Option<Relationships>; #[doc(hidden)] fn build_included(&self) -> Option<Resources>; fn from_jsonapi_resource(resource: &Resource, included: &Option<Resources>) -> Result<Self> { let visited_relationships: Vec<&str> = Vec::new(); Self::from_serializable(Self::resource_to_attrs(resource, included, &visited_relationships)) } /// Create a single resource object or collection of resource /// objects directly from /// [`DocumentData`](../api/struct.DocumentData.html). This method /// will parse the document (the `data` and `included` resources) in an /// attempt to instantiate the calling struct. fn from_jsonapi_document(doc: &DocumentData) -> Result<Self> { match doc.data.as_ref() { Some(primary_data) => { match *primary_data { PrimaryData::None => bail!("Document had no data"), PrimaryData::Single(ref resource) => { Self::from_jsonapi_resource(resource, &doc.included) } PrimaryData::Multiple(ref resources) => { let visited_relationships: Vec<&str> = Vec::new(); let all: Vec<ResourceAttributes> = resources .iter() .map(|r| Self::resource_to_attrs(r, &doc.included, &visited_relationships)) .collect(); Self::from_serializable(all) } } } None => bail!("Document had no data"), } } /// Converts the instance of the struct into a /// [`Resource`](../api/struct.Resource.html) fn to_jsonapi_resource(&self) -> (Resource, Option<Resources>) { if let Value::Object(mut attrs) = to_value(self).unwrap() { let _ = attrs.remove("id"); let resource = Resource { _type: self.jsonapi_type(), id: self.jsonapi_id(), relationships: self.build_relationships(), attributes: Self::extract_attributes(&attrs), ..Default::default() }; (resource, self.build_included()) } else { panic!(format!("{} is not a Value::Object", self.jsonapi_type())) } } /// Converts the struct into a complete /// [`JsonApiDocument`](../api/struct.JsonApiDocument.html) fn to_jsonapi_document(&self) -> JsonApiDocument { let (resource, included) = self.to_jsonapi_resource(); JsonApiDocument::Data ( DocumentData { data: Some(PrimaryData::Single(Box::new(resource))), included, ..Default::default() } ) } #[doc(hidden)] fn build_has_one<M: JsonApiModel>(model: &M) -> Relationship { Relationship { data: Some(IdentifierData::Single(model.as_resource_identifier())), links: None } } #[doc(hidden)] fn build_has_many<M: JsonApiModel>(models: &[M]) -> Relationship { Relationship { data: Some(IdentifierData::Multiple( models.iter().map(|m| m.as_resource_identifier()).collect() )), links: None } } #[doc(hidden)] fn as_resource_identifier(&self) -> ResourceIdentifier { ResourceIdentifier { _type: self.jsonapi_type(), id: self.jsonapi_id(), } } /* Attribute corresponding to the model is removed from the Map * before calling this, so there's no need to ignore it like we do * with the attributes that correspond with relationships. * */ #[doc(hidden)] fn extract_attributes(attrs: &Map<String, Value>) -> ResourceAttributes { attrs .iter() .filter(|&(key, _)| { if let Some(fields) = Self::relationship_fields() { if fields.contains(&key.as_str()) { return false; } } true }) .map(|(k, v)| (k.clone(), v.clone())) .collect() } #[doc(hidden)] fn to_resources(&self) -> Resources { let (me, maybe_others) = self.to_jsonapi_resource(); let mut flattened = vec![me]; if let Some(mut others) = maybe_others { flattened.append(&mut others); } flattened } /// When passed a `ResourceIdentifier` (which contains a `type` and `id`) /// this will iterate through the collection provided `haystack` in an /// attempt to find and return the `Resource` whose `type` and `id` /// attributes match #[doc(hidden)] fn lookup<'a>(needle: &ResourceIdentifier, haystack: &'a [Resource]) -> Option<&'a Resource> { for resource in haystack { if resource._type == needle._type && resource.id == needle.id { return Some(resource); } } None } /// Return a [`ResourceAttributes`](../api/struct.ResourceAttributes.html) /// object that contains the attributes in this `resource`. This will be /// called recursively for each `relationship` on the resource in an attempt /// to satisfy the properties for the calling struct. /// /// The last parameter in this function call is `visited_relationships` which is used as this /// function is called recursively. This `Vec` contains the JSON:API `relationships` that were /// visited when this function was called last. When operating on the root node of the document /// this is simply started with an empty `Vec`. /// /// Tracking these "visited" relationships is necessary to prevent infinite recursion and stack /// overflows. This situation can arise when the "included" resource object includes the parent /// resource object - it will simply ping pong back and forth unable to acheive a finite /// resolution. /// /// The JSON:API specification doesn't communicate the direction of a relationship. /// Furthermore the current implementation of this crate does not establish an object graph /// that could be used to traverse these relationships effectively. #[doc(hidden)] fn resource_to_attrs(resource: &Resource, included: &Option<Resources>, visited_relationships: &Vec<&str>) -> ResourceAttributes { let mut new_attrs = HashMap::new(); new_attrs.clone_from(&resource.attributes); new_attrs.insert("id".into(), resource.id.clone().into()); // Copy the contents of `visited_relationships` so that we can mutate within the lexical // scope of this function call. This is also important so each edge that we follow (the // relationship) is not polluted by data from traversing sibling relationships let mut this_visited: Vec<&str> = Vec::new(); for rel in visited_relationships.iter() { this_visited.push(rel); } if let Some(relations) = resource.relationships.as_ref() { if let Some(inc) = included.as_ref() { for (name, relation) in relations { // If we have already visited this resource object, exit early and do not // recurse through the relations if this_visited.contains(&name.as_str()) { return new_attrs; } // Track that we have visited this relationship to avoid infinite recursion this_visited.push(name); let value = match relation.data {
Some(IdentifierData::None) => Value::Null, Some(IdentifierData::Single(ref identifier)) => { let found = Self::lookup(identifier, inc) .map(|r| Self::resource_to_attrs(r, included, &this_visited) ); to_value(found) .expect("Casting Single relation to value") }, Some(IdentifierData::Multiple(ref identifiers)) => { let found: Vec<Option<ResourceAttributes>> = identifiers.iter().map(|identifier|{ Self::lookup(identifier, inc).map(|r|{ Self::resource_to_attrs(r, included, &this_visited) }) }).collect(); to_value(found) .expect("Casting Multiple relation to value") }, None => Value::Null, }; new_attrs.insert(name.to_string(), value); } } } new_attrs } #[doc(hidden)] fn from_serializable<S: Serialize>(s: S) -> Result<Self> { from_value(to_value(s)?).map_err(Error::from) } } /// Converts a `vec!` of structs into /// [`Resources`](../api/type.Resources.html) /// pub fn vec_to_jsonapi_resources<T: JsonApiModel>( objects: Vec<T>, ) -> (Resources, Option<Resources>) { let mut included = vec![]; let resources = objects .iter() .map(|obj| { let (res, mut opt_incl) = obj.to_jsonapi_resource(); if let Some(ref mut incl) = opt_incl { included.append(incl); } res }) .collect::<Vec<_>>(); let opt_included = if included.is_empty() { None } else { Some(included) }; (resources, opt_included) } /// Converts a `vec!` of structs into a /// [`JsonApiDocument`](../api/struct.JsonApiDocument.html) /// /// ```rust /// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate jsonapi; /// use jsonapi::api::*; /// use jsonapi::model::*; /// /// #[derive(Debug, PartialEq, Serialize, Deserialize)] /// struct Flea { /// id: String, /// name: String, /// } /// /// jsonapi_model!(Flea; "flea"); /// /// let fleas = vec![ /// Flea { /// id: "2".into(), /// name: "rick".into(), /// }, /// Flea { /// id: "3".into(), /// name: "morty".into(), /// }, /// ]; /// let doc = vec_to_jsonapi_document(fleas); /// assert!(doc.is_valid()); /// ``` pub fn vec_to_jsonapi_document<T: JsonApiModel>(objects: Vec<T>) -> JsonApiDocument { let (resources, included) = vec_to_jsonapi_resources(objects); JsonApiDocument::Data ( DocumentData { data: Some(PrimaryData::Multiple(resources)), included, ..Default::default() } ) } impl<M: JsonApiModel> JsonApiModel for Box<M> { fn jsonapi_type(&self) -> String { self.as_ref().jsonapi_type() } fn jsonapi_id(&self) -> String { self.as_ref().jsonapi_id() } fn relationship_fields() -> Option<&'static [&'static str]> { M::relationship_fields() } fn build_relationships(&self) -> Option<Relationships> { self.as_ref().build_relationships() } fn build_included(&self) -> Option<Resources> { self.as_ref().build_included() } } /// When applied this macro implements the /// [`JsonApiModel`](model/trait.JsonApiModel.html) trait for the provided type /// #[macro_export] macro_rules! jsonapi_model { ($model:ty; $type:expr) => ( impl JsonApiModel for $model { fn jsonapi_type(&self) -> String { $type.to_string() } fn jsonapi_id(&self) -> String { self.id.to_string() } fn relationship_fields() -> Option<&'static [&'static str]> { None } fn build_relationships(&self) -> Option<Relationships> { None } fn build_included(&self) -> Option<Resources> { None } } ); ($model:ty; $type:expr; has one $( $has_one:ident ),* ) => ( jsonapi_model!($model; $type; has one $( $has_one ),*; has many); ); ($model:ty; $type:expr; has many $( $has_many:ident ),* ) => ( jsonapi_model!($model; $type; has one; has many $( $has_many ),*); ); ($model:ty; $type:expr; has one $( $has_one:ident ),*; has many $( $has_many:ident ),* ) => ( impl JsonApiModel for $model { fn jsonapi_type(&self) -> String { $type.to_string() } fn jsonapi_id(&self) -> String { self.id.to_string() } fn relationship_fields() -> Option<&'static [&'static str]> { static FIELDS: &'static [&'static str] = &[ $( stringify!($has_one),)* $( stringify!($has_many),)* ]; Some(FIELDS) } fn build_relationships(&self) -> Option<Relationships> { let mut relationships = HashMap::new(); $( relationships.insert(stringify!($has_one).into(), Self::build_has_one(&self.$has_one) ); )* $( relationships.insert( stringify!($has_many).into(), { let values = &self.$has_many.get_models(); Self::build_has_many(values) } ); )* Some(relationships) } fn build_included(&self) -> Option<Resources> { let mut included:Resources = vec![]; $( included.append(&mut self.$has_one.to_resources()); )* $( for model in self.$has_many.get_models() { included.append(&mut model.to_resources()); } )* Some(included) } } ); }
random_line_split