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
textencoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding::TextEncoderMethods; use dom::bindings::global::GlobalRef; use dom::bindings::error::Fallible; use dom::bindings::error::Error::Range; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::str::USVString; use dom::bindings::utils::{Reflector, reflect_dom_object}; use util::str::DOMString; use std::borrow::ToOwned; use std::ascii::AsciiExt; use std::ptr; use encoding::types::EncodingRef; use encoding::{Encoding, EncoderTrap}; use encoding::label::encoding_from_whatwg_label; use libc::uint8_t; use js::jsapi::{JSContext, JSObject}; use js::jsfriendapi::bindgen::{JS_NewUint8Array, JS_GetUint8ArrayData}; #[dom_struct] pub struct TextEncoder { reflector_: Reflector, encoding: DOMString, encoder: EncodingRef, } impl TextEncoder { fn new_inherited(encoding: DOMString, encoder: EncodingRef) -> TextEncoder { TextEncoder { reflector_: Reflector::new(),
encoder: encoder, } } pub fn new(global: GlobalRef, encoding: DOMString, encoder: EncodingRef) -> Temporary<TextEncoder> { reflect_dom_object(box TextEncoder::new_inherited(encoding, encoder), global, TextEncoderBinding::Wrap) } // https://encoding.spec.whatwg.org/#dom-textencoder pub fn Constructor(global: GlobalRef, label: DOMString) -> Fallible<Temporary<TextEncoder>> { let encoding = match encoding_from_whatwg_label(&label.trim().to_ascii_lowercase()) { Some(enc) => enc, None => { debug!("Encoding Label Not Supported"); return Err(Range("The given encoding is not supported.".to_owned())) } }; match encoding.name() { "utf-8" | "utf-16be" | "utf-16le" => { Ok(TextEncoder::new(global, encoding.name().to_owned(), encoding)) } _ => { debug!("Encoding Not UTF"); return Err(Range("The encoding must be utf-8, utf-16le, or utf-16be.".to_owned())) } } } } impl<'a> TextEncoderMethods for JSRef<'a, TextEncoder> { // https://encoding.spec.whatwg.org/#dom-textencoder-encoding fn Encoding(self) -> DOMString { self.encoding.clone() } // https://encoding.spec.whatwg.org/#dom-textencoder-encode #[allow(unsafe_code)] fn Encode(self, cx: *mut JSContext, input: USVString) -> *mut JSObject { unsafe { let output = self.encoder.encode(&input.0, EncoderTrap::Strict).unwrap(); let length = output.len() as u32; let js_object: *mut JSObject = JS_NewUint8Array(cx, length); let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object, cx); ptr::copy_nonoverlapping(js_object_data, output.as_ptr(), length as usize); return js_object; } } }
encoding: encoding,
random_line_split
textencoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding::TextEncoderMethods; use dom::bindings::global::GlobalRef; use dom::bindings::error::Fallible; use dom::bindings::error::Error::Range; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::str::USVString; use dom::bindings::utils::{Reflector, reflect_dom_object}; use util::str::DOMString; use std::borrow::ToOwned; use std::ascii::AsciiExt; use std::ptr; use encoding::types::EncodingRef; use encoding::{Encoding, EncoderTrap}; use encoding::label::encoding_from_whatwg_label; use libc::uint8_t; use js::jsapi::{JSContext, JSObject}; use js::jsfriendapi::bindgen::{JS_NewUint8Array, JS_GetUint8ArrayData}; #[dom_struct] pub struct TextEncoder { reflector_: Reflector, encoding: DOMString, encoder: EncodingRef, } impl TextEncoder { fn new_inherited(encoding: DOMString, encoder: EncodingRef) -> TextEncoder { TextEncoder { reflector_: Reflector::new(), encoding: encoding, encoder: encoder, } } pub fn new(global: GlobalRef, encoding: DOMString, encoder: EncodingRef) -> Temporary<TextEncoder> { reflect_dom_object(box TextEncoder::new_inherited(encoding, encoder), global, TextEncoderBinding::Wrap) } // https://encoding.spec.whatwg.org/#dom-textencoder pub fn Constructor(global: GlobalRef, label: DOMString) -> Fallible<Temporary<TextEncoder>> { let encoding = match encoding_from_whatwg_label(&label.trim().to_ascii_lowercase()) { Some(enc) => enc, None => { debug!("Encoding Label Not Supported"); return Err(Range("The given encoding is not supported.".to_owned())) } }; match encoding.name() { "utf-8" | "utf-16be" | "utf-16le" => { Ok(TextEncoder::new(global, encoding.name().to_owned(), encoding)) } _ => { debug!("Encoding Not UTF"); return Err(Range("The encoding must be utf-8, utf-16le, or utf-16be.".to_owned())) } } } } impl<'a> TextEncoderMethods for JSRef<'a, TextEncoder> { // https://encoding.spec.whatwg.org/#dom-textencoder-encoding fn Encoding(self) -> DOMString { self.encoding.clone() } // https://encoding.spec.whatwg.org/#dom-textencoder-encode #[allow(unsafe_code)] fn Encode(self, cx: *mut JSContext, input: USVString) -> *mut JSObject
}
{ unsafe { let output = self.encoder.encode(&input.0, EncoderTrap::Strict).unwrap(); let length = output.len() as u32; let js_object: *mut JSObject = JS_NewUint8Array(cx, length); let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object, cx); ptr::copy_nonoverlapping(js_object_data, output.as_ptr(), length as usize); return js_object; } }
identifier_body
textencoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding::TextEncoderMethods; use dom::bindings::global::GlobalRef; use dom::bindings::error::Fallible; use dom::bindings::error::Error::Range; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::str::USVString; use dom::bindings::utils::{Reflector, reflect_dom_object}; use util::str::DOMString; use std::borrow::ToOwned; use std::ascii::AsciiExt; use std::ptr; use encoding::types::EncodingRef; use encoding::{Encoding, EncoderTrap}; use encoding::label::encoding_from_whatwg_label; use libc::uint8_t; use js::jsapi::{JSContext, JSObject}; use js::jsfriendapi::bindgen::{JS_NewUint8Array, JS_GetUint8ArrayData}; #[dom_struct] pub struct TextEncoder { reflector_: Reflector, encoding: DOMString, encoder: EncodingRef, } impl TextEncoder { fn new_inherited(encoding: DOMString, encoder: EncodingRef) -> TextEncoder { TextEncoder { reflector_: Reflector::new(), encoding: encoding, encoder: encoder, } } pub fn
(global: GlobalRef, encoding: DOMString, encoder: EncodingRef) -> Temporary<TextEncoder> { reflect_dom_object(box TextEncoder::new_inherited(encoding, encoder), global, TextEncoderBinding::Wrap) } // https://encoding.spec.whatwg.org/#dom-textencoder pub fn Constructor(global: GlobalRef, label: DOMString) -> Fallible<Temporary<TextEncoder>> { let encoding = match encoding_from_whatwg_label(&label.trim().to_ascii_lowercase()) { Some(enc) => enc, None => { debug!("Encoding Label Not Supported"); return Err(Range("The given encoding is not supported.".to_owned())) } }; match encoding.name() { "utf-8" | "utf-16be" | "utf-16le" => { Ok(TextEncoder::new(global, encoding.name().to_owned(), encoding)) } _ => { debug!("Encoding Not UTF"); return Err(Range("The encoding must be utf-8, utf-16le, or utf-16be.".to_owned())) } } } } impl<'a> TextEncoderMethods for JSRef<'a, TextEncoder> { // https://encoding.spec.whatwg.org/#dom-textencoder-encoding fn Encoding(self) -> DOMString { self.encoding.clone() } // https://encoding.spec.whatwg.org/#dom-textencoder-encode #[allow(unsafe_code)] fn Encode(self, cx: *mut JSContext, input: USVString) -> *mut JSObject { unsafe { let output = self.encoder.encode(&input.0, EncoderTrap::Strict).unwrap(); let length = output.len() as u32; let js_object: *mut JSObject = JS_NewUint8Array(cx, length); let js_object_data: *mut uint8_t = JS_GetUint8ArrayData(js_object, cx); ptr::copy_nonoverlapping(js_object_data, output.as_ptr(), length as usize); return js_object; } } }
new
identifier_name
mir_overflow_off.rs
// Copyright 2016 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. // run-pass // compile-flags: -Z force-overflow-checks=off // Test that with MIR codegen, overflow checks can be // turned off, even when they're from core::ops::*. use std::ops::*; fn
() { assert_eq!(i8::neg(-0x80), -0x80); assert_eq!(u8::add(0xff, 1), 0_u8); assert_eq!(u8::sub(0, 1), 0xff_u8); assert_eq!(u8::mul(0xff, 2), 0xfe_u8); assert_eq!(u8::shl(1, 9), 2_u8); assert_eq!(u8::shr(2, 9), 1_u8); }
main
identifier_name
mir_overflow_off.rs
// // 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. // run-pass // compile-flags: -Z force-overflow-checks=off // Test that with MIR codegen, overflow checks can be // turned off, even when they're from core::ops::*. use std::ops::*; fn main() { assert_eq!(i8::neg(-0x80), -0x80); assert_eq!(u8::add(0xff, 1), 0_u8); assert_eq!(u8::sub(0, 1), 0xff_u8); assert_eq!(u8::mul(0xff, 2), 0xfe_u8); assert_eq!(u8::shl(1, 9), 2_u8); assert_eq!(u8::shr(2, 9), 1_u8); }
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
mir_overflow_off.rs
// Copyright 2016 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. // run-pass // compile-flags: -Z force-overflow-checks=off // Test that with MIR codegen, overflow checks can be // turned off, even when they're from core::ops::*. use std::ops::*; fn main()
{ assert_eq!(i8::neg(-0x80), -0x80); assert_eq!(u8::add(0xff, 1), 0_u8); assert_eq!(u8::sub(0, 1), 0xff_u8); assert_eq!(u8::mul(0xff, 2), 0xfe_u8); assert_eq!(u8::shl(1, 9), 2_u8); assert_eq!(u8::shr(2, 9), 1_u8); }
identifier_body
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// rust_str_free(r_s); /// ``` #[no_mangle] #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] pub unsafe extern "C" fn rust_str_free(_str: RustString) { // Empty body: Just drop _str and we're done (Drop takes care of it). } /// Lends an immutable, NUL-terminated C String. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub unsafe extern "C" fn rust_str_get(str: RustString) -> *const libc::c_char
/// Returns a short string to announce Rust support during startup. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub extern "C" fn rust_welcome_string() -> RustString { let s = CString::new("Tor is running with Rust integration. Please report \ any bugs you encouter.") .unwrap(); RustString::from(s) }
{ let res = str.as_ptr(); forget(str); res }
identifier_body
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// rust_str_free(r_s); /// ``` #[no_mangle] #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] pub unsafe extern "C" fn
(_str: RustString) { // Empty body: Just drop _str and we're done (Drop takes care of it). } /// Lends an immutable, NUL-terminated C String. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub unsafe extern "C" fn rust_str_get(str: RustString) -> *const libc::c_char { let res = str.as_ptr(); forget(str); res } /// Returns a short string to announce Rust support during startup. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub extern "C" fn rust_welcome_string() -> RustString { let s = CString::new("Tor is running with Rust integration. Please report \ any bugs you encouter.") .unwrap(); RustString::from(s) }
rust_str_free
identifier_name
ffi.rs
//! FFI functions, only to be called from C. //! //! Equivalent C versions of these live in `src/common/compat_rust.c` use std::mem::forget; use std::ffi::CString; use libc; use rust_string::RustString; /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of /// `tor_free`(). /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// rust_str_free(r_s); /// ``` #[no_mangle] #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] pub unsafe extern "C" fn rust_str_free(_str: RustString) { // Empty body: Just drop _str and we're done (Drop takes care of it).
/// Lends an immutable, NUL-terminated C String. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub unsafe extern "C" fn rust_str_get(str: RustString) -> *const libc::c_char { let res = str.as_ptr(); forget(str); res } /// Returns a short string to announce Rust support during startup. /// /// # Examples /// ```c /// rust_str_t r_s = rust_welcome_string(); /// const char *s = rust_str_get(r_s); /// printf("%s", s); /// rust_str_free(r_s); /// ``` #[no_mangle] pub extern "C" fn rust_welcome_string() -> RustString { let s = CString::new("Tor is running with Rust integration. Please report \ any bugs you encouter.") .unwrap(); RustString::from(s) }
}
random_line_split
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(rename = "_self")] pub _self: String, #[serde(rename = "_etag")] pub etag: String, #[serde(rename = "_attachments")] pub attachments: String, } impl DocumentAttributes { pub fn rid(&self) -> &str { &self.rid } pub fn ts(&self) -> u64 { self.ts } pub fn _self(&self) -> &str { &self._self } pub fn etag(&self) -> &str { &self.etag } pub fn attachments(&self) -> &str { &self.attachments } pub fn set_rid<T>(&mut self, value: T) where T: Into<String>, { self.rid = value.into(); } pub fn set_ts(&mut self, value: u64) { self.ts = value; } pub fn set_self<T>(&mut self, value: T) where T: Into<String>, { self._self = value.into(); } pub fn set_etag<T>(&mut self, value: T) where T: Into<String>, { self.etag = value.into(); } pub fn set_attachments<T>(&mut self, value: T) where T: Into<String>,
} impl std::convert::TryFrom<(&HeaderMap, &[u8])> for DocumentAttributes { type Error = AzureError; fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> { let body = value.1; Ok(serde_json::from_slice(body)?) } } impl<'a> std::convert::From<&'a DocumentAttributes> for IfMatchCondition<'a> { fn from(document_attributes: &'a DocumentAttributes) -> Self { IfMatchCondition::Match(&document_attributes.etag) } } #[cfg(test)] mod tests { #[test] fn test_mutate() { use super::*; let mut a = DocumentAttributes { rid: "rid".to_owned(), ts: 100, _self: "_self".to_owned(), etag: "etag".to_owned(), attachments: "attachments".to_owned(), }; a.set_attachments("new_attachments".to_owned()); } }
{ self.attachments = value.into(); }
identifier_body
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(rename = "_self")] pub _self: String, #[serde(rename = "_etag")] pub etag: String, #[serde(rename = "_attachments")] pub attachments: String, } impl DocumentAttributes { pub fn rid(&self) -> &str { &self.rid } pub fn ts(&self) -> u64 { self.ts } pub fn _self(&self) -> &str { &self._self } pub fn etag(&self) -> &str { &self.etag } pub fn attachments(&self) -> &str { &self.attachments } pub fn set_rid<T>(&mut self, value: T) where T: Into<String>, { self.rid = value.into(); } pub fn
(&mut self, value: u64) { self.ts = value; } pub fn set_self<T>(&mut self, value: T) where T: Into<String>, { self._self = value.into(); } pub fn set_etag<T>(&mut self, value: T) where T: Into<String>, { self.etag = value.into(); } pub fn set_attachments<T>(&mut self, value: T) where T: Into<String>, { self.attachments = value.into(); } } impl std::convert::TryFrom<(&HeaderMap, &[u8])> for DocumentAttributes { type Error = AzureError; fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> { let body = value.1; Ok(serde_json::from_slice(body)?) } } impl<'a> std::convert::From<&'a DocumentAttributes> for IfMatchCondition<'a> { fn from(document_attributes: &'a DocumentAttributes) -> Self { IfMatchCondition::Match(&document_attributes.etag) } } #[cfg(test)] mod tests { #[test] fn test_mutate() { use super::*; let mut a = DocumentAttributes { rid: "rid".to_owned(), ts: 100, _self: "_self".to_owned(), etag: "etag".to_owned(), attachments: "attachments".to_owned(), }; a.set_attachments("new_attachments".to_owned()); } }
set_ts
identifier_name
document_attributes.rs
use azure_sdk_core::errors::AzureError; use azure_sdk_core::prelude::IfMatchCondition; use http::HeaderMap; #[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct DocumentAttributes { #[serde(rename = "_rid")] pub rid: String, #[serde(rename = "_ts")] pub ts: u64, #[serde(rename = "_self")] pub _self: String, #[serde(rename = "_etag")] pub etag: String, #[serde(rename = "_attachments")] pub attachments: String, } impl DocumentAttributes { pub fn rid(&self) -> &str { &self.rid } pub fn ts(&self) -> u64 { self.ts } pub fn _self(&self) -> &str { &self._self } pub fn etag(&self) -> &str { &self.etag } pub fn attachments(&self) -> &str { &self.attachments } pub fn set_rid<T>(&mut self, value: T) where T: Into<String>, { self.rid = value.into(); } pub fn set_ts(&mut self, value: u64) { self.ts = value; } pub fn set_self<T>(&mut self, value: T) where T: Into<String>, { self._self = value.into(); } pub fn set_etag<T>(&mut self, value: T) where T: Into<String>, { self.etag = value.into(); } pub fn set_attachments<T>(&mut self, value: T) where T: Into<String>, { self.attachments = value.into(); } } impl std::convert::TryFrom<(&HeaderMap, &[u8])> for DocumentAttributes { type Error = AzureError; fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> { let body = value.1; Ok(serde_json::from_slice(body)?) } } impl<'a> std::convert::From<&'a DocumentAttributes> for IfMatchCondition<'a> { fn from(document_attributes: &'a DocumentAttributes) -> Self { IfMatchCondition::Match(&document_attributes.etag) } } #[cfg(test)] mod tests { #[test] fn test_mutate() { use super::*; let mut a = DocumentAttributes { rid: "rid".to_owned(), ts: 100, _self: "_self".to_owned(),
attachments: "attachments".to_owned(), }; a.set_attachments("new_attachments".to_owned()); } }
etag: "etag".to_owned(),
random_line_split
lib.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)] extern crate test; #[macro_use] extern crate slog_global; pub mod encryption; mod kv_generator; mod logging; mod macros; mod runner; mod security; use rand::Rng; use std::sync::atomic::{AtomicU16, Ordering}; use std::{env, thread}; pub use crate::encryption::*; pub use crate::kv_generator::*; pub use crate::logging::*; pub use crate::macros::*; pub use crate::runner::{ clear_failpoints, run_failpoint_tests, run_test_with_hook, run_tests, TestHook, }; pub use crate::security::*; pub fn setup_for_ci()
if env::var("LOG_FILE").is_ok() { logging::init_log_for_test(); } } if env::var("PANIC_ABORT").is_ok() { // Panics as aborts, it's helpful for debugging, // but also stops tests immediately. tikv_util::set_panic_hook(true, "./"); } tikv_util::check_environment_variables(); if let Err(e) = tikv_util::config::check_max_open_fds(4096) { panic!( "To run test, please make sure the maximum number of open file descriptors not \ less than 4096: {:?}", e ); } } static INITIAL_PORT: AtomicU16 = AtomicU16::new(0); /// Linux by default use [32768, 61000] for local port. const MIN_LOCAL_PORT: u16 = 32767; /// Allocates a port for testing purpose. pub fn alloc_port() -> u16 { let p = INITIAL_PORT.load(Ordering::Relaxed); if p == 0 { let _ = INITIAL_PORT.compare_exchange( 0, rand::thread_rng().gen_range(10240..MIN_LOCAL_PORT), Ordering::SeqCst, Ordering::SeqCst, ); } let mut p = INITIAL_PORT.load(Ordering::SeqCst); loop { let next = if p >= MIN_LOCAL_PORT { 10240 } else { p + 1 }; match INITIAL_PORT.compare_exchange_weak(p, next, Ordering::SeqCst, Ordering::SeqCst) { Ok(_) => return next, Err(e) => p = e, } } }
{ // We use backtrace in tests to record suspicious problems. And loading backtrace // the first time can take several seconds. Spawning a thread and load it ahead // of time to avoid causing timeout. thread::Builder::new() .name(tikv_util::thd_name!("backtrace-loader")) .spawn(::backtrace::Backtrace::new) .unwrap(); if env::var("CI").is_ok() { // HACK! Use `epollex` as the polling engine for gRPC when running CI tests on // Linux and it hasn't been set before. // See more: https://github.com/grpc/grpc/blob/v1.17.2/src/core/lib/iomgr/ev_posix.cc#L124 // See more: https://grpc.io/grpc/core/md_doc_core_grpc-polling-engines.html #[cfg(target_os = "linux")] { if env::var("GRPC_POLL_STRATEGY").is_err() { env::set_var("GRPC_POLL_STRATEGY", "epollex"); } }
identifier_body
lib.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)] extern crate test; #[macro_use] extern crate slog_global; pub mod encryption; mod kv_generator; mod logging; mod macros; mod runner; mod security; use rand::Rng; use std::sync::atomic::{AtomicU16, Ordering}; use std::{env, thread}; pub use crate::encryption::*; pub use crate::kv_generator::*; pub use crate::logging::*; pub use crate::macros::*; pub use crate::runner::{ clear_failpoints, run_failpoint_tests, run_test_with_hook, run_tests, TestHook, }; pub use crate::security::*; pub fn
() { // We use backtrace in tests to record suspicious problems. And loading backtrace // the first time can take several seconds. Spawning a thread and load it ahead // of time to avoid causing timeout. thread::Builder::new() .name(tikv_util::thd_name!("backtrace-loader")) .spawn(::backtrace::Backtrace::new) .unwrap(); if env::var("CI").is_ok() { // HACK! Use `epollex` as the polling engine for gRPC when running CI tests on // Linux and it hasn't been set before. // See more: https://github.com/grpc/grpc/blob/v1.17.2/src/core/lib/iomgr/ev_posix.cc#L124 // See more: https://grpc.io/grpc/core/md_doc_core_grpc-polling-engines.html #[cfg(target_os = "linux")] { if env::var("GRPC_POLL_STRATEGY").is_err() { env::set_var("GRPC_POLL_STRATEGY", "epollex"); } } if env::var("LOG_FILE").is_ok() { logging::init_log_for_test(); } } if env::var("PANIC_ABORT").is_ok() { // Panics as aborts, it's helpful for debugging, // but also stops tests immediately. tikv_util::set_panic_hook(true, "./"); } tikv_util::check_environment_variables(); if let Err(e) = tikv_util::config::check_max_open_fds(4096) { panic!( "To run test, please make sure the maximum number of open file descriptors not \ less than 4096: {:?}", e ); } } static INITIAL_PORT: AtomicU16 = AtomicU16::new(0); /// Linux by default use [32768, 61000] for local port. const MIN_LOCAL_PORT: u16 = 32767; /// Allocates a port for testing purpose. pub fn alloc_port() -> u16 { let p = INITIAL_PORT.load(Ordering::Relaxed); if p == 0 { let _ = INITIAL_PORT.compare_exchange( 0, rand::thread_rng().gen_range(10240..MIN_LOCAL_PORT), Ordering::SeqCst, Ordering::SeqCst, ); } let mut p = INITIAL_PORT.load(Ordering::SeqCst); loop { let next = if p >= MIN_LOCAL_PORT { 10240 } else { p + 1 }; match INITIAL_PORT.compare_exchange_weak(p, next, Ordering::SeqCst, Ordering::SeqCst) { Ok(_) => return next, Err(e) => p = e, } } }
setup_for_ci
identifier_name
lib.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. #![feature(test)]
#[macro_use] extern crate slog_global; pub mod encryption; mod kv_generator; mod logging; mod macros; mod runner; mod security; use rand::Rng; use std::sync::atomic::{AtomicU16, Ordering}; use std::{env, thread}; pub use crate::encryption::*; pub use crate::kv_generator::*; pub use crate::logging::*; pub use crate::macros::*; pub use crate::runner::{ clear_failpoints, run_failpoint_tests, run_test_with_hook, run_tests, TestHook, }; pub use crate::security::*; pub fn setup_for_ci() { // We use backtrace in tests to record suspicious problems. And loading backtrace // the first time can take several seconds. Spawning a thread and load it ahead // of time to avoid causing timeout. thread::Builder::new() .name(tikv_util::thd_name!("backtrace-loader")) .spawn(::backtrace::Backtrace::new) .unwrap(); if env::var("CI").is_ok() { // HACK! Use `epollex` as the polling engine for gRPC when running CI tests on // Linux and it hasn't been set before. // See more: https://github.com/grpc/grpc/blob/v1.17.2/src/core/lib/iomgr/ev_posix.cc#L124 // See more: https://grpc.io/grpc/core/md_doc_core_grpc-polling-engines.html #[cfg(target_os = "linux")] { if env::var("GRPC_POLL_STRATEGY").is_err() { env::set_var("GRPC_POLL_STRATEGY", "epollex"); } } if env::var("LOG_FILE").is_ok() { logging::init_log_for_test(); } } if env::var("PANIC_ABORT").is_ok() { // Panics as aborts, it's helpful for debugging, // but also stops tests immediately. tikv_util::set_panic_hook(true, "./"); } tikv_util::check_environment_variables(); if let Err(e) = tikv_util::config::check_max_open_fds(4096) { panic!( "To run test, please make sure the maximum number of open file descriptors not \ less than 4096: {:?}", e ); } } static INITIAL_PORT: AtomicU16 = AtomicU16::new(0); /// Linux by default use [32768, 61000] for local port. const MIN_LOCAL_PORT: u16 = 32767; /// Allocates a port for testing purpose. pub fn alloc_port() -> u16 { let p = INITIAL_PORT.load(Ordering::Relaxed); if p == 0 { let _ = INITIAL_PORT.compare_exchange( 0, rand::thread_rng().gen_range(10240..MIN_LOCAL_PORT), Ordering::SeqCst, Ordering::SeqCst, ); } let mut p = INITIAL_PORT.load(Ordering::SeqCst); loop { let next = if p >= MIN_LOCAL_PORT { 10240 } else { p + 1 }; match INITIAL_PORT.compare_exchange_weak(p, next, Ordering::SeqCst, Ordering::SeqCst) { Ok(_) => return next, Err(e) => p = e, } } }
extern crate test;
random_line_split
to_bytes.rs
use bytes::{Buf, BufMut, Bytes}; use super::HttpBody; /// Concatenate the buffers from a body into a single `Bytes` asynchronously. /// /// This may require copying the data into a single buffer. If you don't need /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate()) /// function. /// /// # Note /// /// Care needs to be taken if the remote is untrusted. The function doesn't implement any length /// checks and an malicious peer might make it consume arbitrary amounts of memory. Checking the /// `Content-Length` is a possibility, but it is not strictly mandated to be present. /// /// # Example /// /// ``` /// # #[cfg(all(feature = "client", any(feature = "http1", feature = "http2")))] /// # async fn doc() -> hyper::Result<()> { /// use hyper::{body::HttpBody}; /// /// # let request = hyper::Request::builder() /// # .method(hyper::Method::POST) /// # .uri("http://httpbin.org/post") /// # .header("content-type", "application/json") /// # .body(hyper::Body::from(r#"{"library":"hyper"}"#)).unwrap(); /// # let client = hyper::Client::new(); /// let response = client.request(request).await?; /// /// const MAX_ALLOWED_RESPONSE_SIZE: u64 = 1024; /// /// let response_content_length = match response.body().size_hint().upper() { /// Some(v) => v, /// None => MAX_ALLOWED_RESPONSE_SIZE + 1 // Just to protect ourselves from a malicious response /// }; /// /// if response_content_length < MAX_ALLOWED_RESPONSE_SIZE { /// let body_bytes = hyper::body::to_bytes(response.into_body()).await?; /// println!("body: {:?}", body_bytes); /// } /// /// # Ok(()) /// # } /// ``` pub async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error> where T: HttpBody,
vec.put(second); while let Some(buf) = body.data().await { vec.put(buf?); } Ok(vec.into()) }
{ futures_util::pin_mut!(body); // If there's only 1 chunk, we can just return Buf::to_bytes() let mut first = if let Some(buf) = body.data().await { buf? } else { return Ok(Bytes::new()); }; let second = if let Some(buf) = body.data().await { buf? } else { return Ok(first.copy_to_bytes(first.remaining())); }; // With more than 1 buf, we gotta flatten into a Vec first. let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize; let mut vec = Vec::with_capacity(cap); vec.put(first);
identifier_body
to_bytes.rs
use bytes::{Buf, BufMut, Bytes}; use super::HttpBody; /// Concatenate the buffers from a body into a single `Bytes` asynchronously. /// /// This may require copying the data into a single buffer. If you don't need /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate()) /// function. /// /// # Note /// /// Care needs to be taken if the remote is untrusted. The function doesn't implement any length /// checks and an malicious peer might make it consume arbitrary amounts of memory. Checking the /// `Content-Length` is a possibility, but it is not strictly mandated to be present. /// /// # Example /// /// ``` /// # #[cfg(all(feature = "client", any(feature = "http1", feature = "http2")))] /// # async fn doc() -> hyper::Result<()> { /// use hyper::{body::HttpBody}; /// /// # let request = hyper::Request::builder() /// # .method(hyper::Method::POST) /// # .uri("http://httpbin.org/post") /// # .header("content-type", "application/json") /// # .body(hyper::Body::from(r#"{"library":"hyper"}"#)).unwrap(); /// # let client = hyper::Client::new(); /// let response = client.request(request).await?; /// /// const MAX_ALLOWED_RESPONSE_SIZE: u64 = 1024; /// /// let response_content_length = match response.body().size_hint().upper() { /// Some(v) => v, /// None => MAX_ALLOWED_RESPONSE_SIZE + 1 // Just to protect ourselves from a malicious response /// };
/// let body_bytes = hyper::body::to_bytes(response.into_body()).await?; /// println!("body: {:?}", body_bytes); /// } /// /// # Ok(()) /// # } /// ``` pub async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error> where T: HttpBody, { futures_util::pin_mut!(body); // If there's only 1 chunk, we can just return Buf::to_bytes() let mut first = if let Some(buf) = body.data().await { buf? } else { return Ok(Bytes::new()); }; let second = if let Some(buf) = body.data().await { buf? } else { return Ok(first.copy_to_bytes(first.remaining())); }; // With more than 1 buf, we gotta flatten into a Vec first. let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize; let mut vec = Vec::with_capacity(cap); vec.put(first); vec.put(second); while let Some(buf) = body.data().await { vec.put(buf?); } Ok(vec.into()) }
/// /// if response_content_length < MAX_ALLOWED_RESPONSE_SIZE {
random_line_split
to_bytes.rs
use bytes::{Buf, BufMut, Bytes}; use super::HttpBody; /// Concatenate the buffers from a body into a single `Bytes` asynchronously. /// /// This may require copying the data into a single buffer. If you don't need /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate()) /// function. /// /// # Note /// /// Care needs to be taken if the remote is untrusted. The function doesn't implement any length /// checks and an malicious peer might make it consume arbitrary amounts of memory. Checking the /// `Content-Length` is a possibility, but it is not strictly mandated to be present. /// /// # Example /// /// ``` /// # #[cfg(all(feature = "client", any(feature = "http1", feature = "http2")))] /// # async fn doc() -> hyper::Result<()> { /// use hyper::{body::HttpBody}; /// /// # let request = hyper::Request::builder() /// # .method(hyper::Method::POST) /// # .uri("http://httpbin.org/post") /// # .header("content-type", "application/json") /// # .body(hyper::Body::from(r#"{"library":"hyper"}"#)).unwrap(); /// # let client = hyper::Client::new(); /// let response = client.request(request).await?; /// /// const MAX_ALLOWED_RESPONSE_SIZE: u64 = 1024; /// /// let response_content_length = match response.body().size_hint().upper() { /// Some(v) => v, /// None => MAX_ALLOWED_RESPONSE_SIZE + 1 // Just to protect ourselves from a malicious response /// }; /// /// if response_content_length < MAX_ALLOWED_RESPONSE_SIZE { /// let body_bytes = hyper::body::to_bytes(response.into_body()).await?; /// println!("body: {:?}", body_bytes); /// } /// /// # Ok(()) /// # } /// ``` pub async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error> where T: HttpBody, { futures_util::pin_mut!(body); // If there's only 1 chunk, we can just return Buf::to_bytes() let mut first = if let Some(buf) = body.data().await
else { return Ok(Bytes::new()); }; let second = if let Some(buf) = body.data().await { buf? } else { return Ok(first.copy_to_bytes(first.remaining())); }; // With more than 1 buf, we gotta flatten into a Vec first. let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize; let mut vec = Vec::with_capacity(cap); vec.put(first); vec.put(second); while let Some(buf) = body.data().await { vec.put(buf?); } Ok(vec.into()) }
{ buf? }
conditional_block
to_bytes.rs
use bytes::{Buf, BufMut, Bytes}; use super::HttpBody; /// Concatenate the buffers from a body into a single `Bytes` asynchronously. /// /// This may require copying the data into a single buffer. If you don't need /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate()) /// function. /// /// # Note /// /// Care needs to be taken if the remote is untrusted. The function doesn't implement any length /// checks and an malicious peer might make it consume arbitrary amounts of memory. Checking the /// `Content-Length` is a possibility, but it is not strictly mandated to be present. /// /// # Example /// /// ``` /// # #[cfg(all(feature = "client", any(feature = "http1", feature = "http2")))] /// # async fn doc() -> hyper::Result<()> { /// use hyper::{body::HttpBody}; /// /// # let request = hyper::Request::builder() /// # .method(hyper::Method::POST) /// # .uri("http://httpbin.org/post") /// # .header("content-type", "application/json") /// # .body(hyper::Body::from(r#"{"library":"hyper"}"#)).unwrap(); /// # let client = hyper::Client::new(); /// let response = client.request(request).await?; /// /// const MAX_ALLOWED_RESPONSE_SIZE: u64 = 1024; /// /// let response_content_length = match response.body().size_hint().upper() { /// Some(v) => v, /// None => MAX_ALLOWED_RESPONSE_SIZE + 1 // Just to protect ourselves from a malicious response /// }; /// /// if response_content_length < MAX_ALLOWED_RESPONSE_SIZE { /// let body_bytes = hyper::body::to_bytes(response.into_body()).await?; /// println!("body: {:?}", body_bytes); /// } /// /// # Ok(()) /// # } /// ``` pub async fn
<T>(body: T) -> Result<Bytes, T::Error> where T: HttpBody, { futures_util::pin_mut!(body); // If there's only 1 chunk, we can just return Buf::to_bytes() let mut first = if let Some(buf) = body.data().await { buf? } else { return Ok(Bytes::new()); }; let second = if let Some(buf) = body.data().await { buf? } else { return Ok(first.copy_to_bytes(first.remaining())); }; // With more than 1 buf, we gotta flatten into a Vec first. let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize; let mut vec = Vec::with_capacity(cap); vec.put(first); vec.put(second); while let Some(buf) = body.data().await { vec.put(buf?); } Ok(vec.into()) }
to_bytes
identifier_name
main.rs
#![feature(associated_consts,collections,custom_derive,ip,lookup_host,optin_builtin_traits,plugin,repr_simd,slice_patterns)] #![allow(dead_code)] #![plugin(docopt_macros)] #![plugin(rand_macros)] #![plugin(serde_macros)] extern crate bincode; extern crate byte_conv; extern crate collections; extern crate core; extern crate docopt; extern crate fixed_circular_buffer; extern crate graphics; extern crate num; extern crate opengl_graphics; extern crate piston; extern crate rand; extern crate rustc_serialize; extern crate serde; extern crate vec_map; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; #[cfg(feature = "include_glfw")] extern crate glfw_window; #[cfg(feature = "include_glutin")]extern crate glutin_window; //Constants macro_rules! PROGRAM_NAME{() => ("tetr")} macro_rules! PROGRAM_NAME_VERSION{() => (concat!(PROGRAM_NAME!()," v",env!("CARGO_PKG_VERSION")))} mod cli; mod controller; mod data; mod game; mod input; mod online; mod render; use core::f64; use piston::window::WindowSettings; use piston::event_loop::Events; use piston::input::{Button,Key,PressEvent,ReleaseEvent,RenderEvent,UpdateEvent,UpdateArgs}; use opengl_graphics::GlGraphics; use std::{net,sync}; use std::collections::hash_map::{self,HashMap}; #[cfg(feature = "include_sdl2")] use sdl2_window::Sdl2Window as Window; #[cfg(feature = "include_glfw")] use glfw_window::GlfwWindow as Window; #[cfg(feature = "include_glutin")]use glutin_window::GlutinWindow as Window; use ::controller::{ai,Controller}; use ::data::{cell,grid,Grid,PairMap}; use ::data::shapes::tetromino::{Shape,RotatedShape}; use ::game::data::world::dynamic::World; use ::game::data::{player,Input,PlayerId,WorldId}; use ::game::{Event,Request}; struct App{ gl: GlGraphics, game_state: game::State<World<cell::ShapeCell>,rand::StdRng>, controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>, request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>, connection: online::ConnectionType, paused: bool, key_map: ::game::data::input::key::KeyMap, key_down: HashMap<Key,f64>, } impl App{ fn update(&mut self,args: &UpdateArgs,request_sender: &sync::mpsc::Sender<Request<PlayerId,WorldId>>){ //Controllers if!self.paused{ for mut controller in self.controllers.iter_mut(){ controller.update(args,&self.game_state.data); } } //Key repeat for (key,time_left) in self.key_down.iter_mut(){ while{ *time_left-= args.dt; *time_left <= 0.0 }{ *time_left = if let Some(mapping) = self.key_map.get(key){ request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); *time_left + mapping.repeat_frequency }else{ f64::NAN//TODO: If the mapping doesn't exist, it will never be removed } } } //Input while let Ok(request) = self.request_receiver.try_recv(){match request{ Request::PlayerInput{input,player: pid} => { if let Some(player) = self.game_state.data.players.get_mut(pid as usize){ if let Some(&mut(ref mut world,false)) = self.game_state.data.worlds.get_mut(player.world as usize){ input::perform(input,player,world); } } if let online::ConnectionType::Client(ref player_ids,Some(connection_id),ref socket,ref address) = self.connection{if let Some(player_network_id) = player_ids.get2(pid){ socket.send_to(&*online::client::packet::Data::Request{ connection: connection_id,//TODO: Maybe this should not send directly to the socket. The connection id is not received until the connection has began request: Request::PlayerInput{ player: player_network_id, input: input } }.into_packet(0).serialize(),address).unwrap(); }} }, Request::PlayerAdd{settings,world: world_id} => { let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.add_player(world_id,settings,&mut |e| for c in cs.iter_mut(){c.event(&e);}); }, Request::WorldRestart{world: world_id} => { let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.reset_world(world_id,&mut |e| for c in cs.iter_mut(){c.event(&e);}); }, _ => () }} //Update if!self.paused{ let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.update(args,&mut |e| for c in cs.iter_mut(){c.event(&e);}); } } fn on_key_press(&mut self,key: Key,request_sender: &sync::mpsc::Sender<Request<PlayerId,WorldId>>){ if self.paused{match key{ Key::Return => {self.paused = false}, _ => {}, }}else{match key{ Key::Return => {self.paused = true}, //Player 0 Tests Key::D1 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::I);};}, Key::D2 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::L);};}, Key::D3 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::O);};}, Key::D4 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::J);};}, Key::D5 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::T);};}, Key::D6 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::S);};}, Key::D7 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::Z);};}, Key::R => { match self.game_state.data.players.get(0 as usize).map(|player| player.world){//TODO: New seed for rng Some(world_id) => {request_sender.send(Request::WorldRestart{world: world_id}).unwrap();}, None => () };
if let hash_map::Entry::Vacant(entry) = self.key_down.entry(key){ entry.insert(mapping.repeat_delay); request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); } } }} } fn on_key_release(&mut self,key: Key){ if let hash_map::Entry::Occupied(entry) = self.key_down.entry(key){ entry.remove(); } } } fn main(){ let args: cli::Args = match cli::Args_docopt().decode(){ Ok(args) => args, Err(docopt::Error::WithProgramUsage(_,usage)) | Err(docopt::Error::Usage(usage)) => { println!("{}",usage); return; }, e => e.unwrap() }; if args.flag_version{ println!(PROGRAM_NAME_VERSION!()); return; } if args.flag_credits{ println!(concat!(PROGRAM_NAME_VERSION!(),": Credits\n\n",include_str!("../CREDITS"))); return; } if args.flag_manual{ println!(concat!(PROGRAM_NAME_VERSION!(),": Instruction manual\n\n",include_str!("../MANUAL"))); return; } //Create a window. let mut window = Window::new( WindowSettings::new( concat!(PROGRAM_NAME!()," v",env!("CARGO_PKG_VERSION")), [args.flag_window_size.0,args.flag_window_size.1] ) .exit_on_esc(true) .opengl(args.flag_gl_version.0) ).unwrap(); let (request_sender,request_receiver) = sync::mpsc::channel(); //Create a new application let mut app = App{ gl: GlGraphics::new(args.flag_gl_version.0), game_state: game::State::new( rand::StdRng::new().unwrap(), {fn f(variant: &RotatedShape) -> cell::ShapeCell{ cell::ShapeCell(Some(variant.shape())) }f}as fn(&_) -> _, {fn f<W: Grid + grid::RectangularBound>(shape: &RotatedShape,world: &W) -> grid::Pos{grid::Pos{ x: world.width() as grid::PosAxis/2 - shape.center_x() as grid::PosAxis, y: 0//TODO: Optionally spawn above: `-(shape.height() as grid::PosAxis);`. Problem is the collision checking. And this is not how it usually is done in other games }}f::<World<cell::ShapeCell>>}as fn(&_,&_) -> _, ), paused: false, controllers: Vec::new(), key_map: HashMap::new(), key_down: HashMap::new(), request_receiver: request_receiver, connection: match args.flag_online{ //No connection cli::OnlineConnection::none => online::ConnectionType::None, //Start to act as a client, connecting to a server cli::OnlineConnection::client => { let server_addr = net::SocketAddr::new( match args.flag_host.0{ net::IpAddr::V4(ip) if ip.is_unspecified() => net::IpAddr::V4(net::Ipv4Addr::new(127,0,0,1)), ip => ip }, args.flag_port ); match online::client::start(server_addr,request_sender.clone()){ Ok(socket) => online::ConnectionType::Client(PairMap::new(),None,socket,server_addr), Err(_) => online::ConnectionType::None } }, //Start to act as a server, listening for clients cli::OnlineConnection::server => { let server_addr = net::SocketAddr::new(args.flag_host.0,args.flag_port); match online::server::start(server_addr,request_sender.clone()){ Ok(_) => online::ConnectionType::Server(PairMap::new()), Err(_) => online::ConnectionType::None } } }, }; //Create world app.game_state.data.worlds.insert(0,(World::new(10,20),false)); app.game_state.data.worlds.insert(1,(World::new(10,20),false)); {let App{game_state: ref mut game,controllers: ref mut cs,..} = app; if let online::ConnectionType::None = app.connection{ //Create player 0 game.rngs.insert_from_global(game::data::mappings::Key::Player(0)); game.add_player(0,player::Settings{ gravityfall_frequency: 1.0, fastfall_shadow : true, },&mut |e| for c in cs.iter_mut(){c.event(&e);}); //Create player 1 game.rngs.insert_from_global(game::data::mappings::Key::Player(1)); cs.push(Box::new(ai::bruteforce::Controller::new(//TODO: Controllers shoulld probably be bound to the individual players request_sender.clone(), 1, ai::bruteforce::Settings::default() ))); game.add_player(1,player::Settings{ gravityfall_frequency: 1.0, fastfall_shadow : true, },&mut |e| for c in cs.iter_mut(){c.event(&e);}); } } {//Key mappings use ::game::data::input::key::Mapping; //Player 0 app.key_map.insert(Key::Left ,Mapping{input: Input::MoveLeft, player: 0,repeat_delay: 0.2,repeat_frequency: 0.125}); app.key_map.insert(Key::Right ,Mapping{input: Input::MoveRight, player: 0,repeat_delay: 0.2,repeat_frequency: 0.125}); app.key_map.insert(Key::Down ,Mapping{input: Input::SlowFall, player: 0,repeat_delay: 0.2,repeat_frequency: 0.07}); app.key_map.insert(Key::End ,Mapping{input: Input::FastFall, player: 0,repeat_delay: f64::NAN,repeat_frequency: f64::NAN}); app.key_map.insert(Key::X ,Mapping{input: Input::RotateAntiClockwise,player: 0,repeat_delay: 0.2,repeat_frequency: 0.2}); app.key_map.insert(Key::Z ,Mapping{input: Input::RotateClockwise, player: 0,repeat_delay: 0.2,repeat_frequency: 0.2}); //Player 1 app.key_map.insert(Key::NumPad4,Mapping{input: Input::MoveLeft, player: 1,repeat_delay: 0.3,repeat_frequency: 0.1}); app.key_map.insert(Key::NumPad6,Mapping{input: Input::MoveRight, player: 1,repeat_delay: 0.3,repeat_frequency: 0.1}); app.key_map.insert(Key::NumPad5,Mapping{input: Input::SlowFall, player: 1,repeat_delay: 0.3,repeat_frequency: 0.07}); app.key_map.insert(Key::NumPad2,Mapping{input: Input::FastFall, player: 1,repeat_delay: f64::NAN,repeat_frequency: f64::NAN}); app.key_map.insert(Key::NumPad1,Mapping{input: Input::RotateAntiClockwise,player: 1,repeat_delay: 0.3,repeat_frequency: 0.2}); app.key_map.insert(Key::NumPad0,Mapping{input: Input::RotateClockwise, player: 1,repeat_delay: 0.3,repeat_frequency: 0.2}); } //Run the created application: Listen for events let mut events = window.events(); while let Some(e) = events.next(&mut window){ //Player inflicted input: Keyboard events if let Some(Button::Keyboard(k)) = e.press_args(){ app.on_key_press(k,&request_sender); } if let Some(Button::Keyboard(k)) = e.release_args(){ app.on_key_release(k); } //Update if let Some(u) = e.update_args(){ app.update(&u,&request_sender); } //Render if let Some(r) = e.render_args(){ if app.paused{ render::default::pause(&mut app.game_state,&mut app.gl,&r); }else{ render::default::gamestate(&mut app.game_state,&mut app.gl,&r); } } } }
}, Key::Home => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.pos.y = 0;};}, //Other keys, check key bindings key => if let Some(mapping) = self.key_map.get(&key){
random_line_split
main.rs
#![feature(associated_consts,collections,custom_derive,ip,lookup_host,optin_builtin_traits,plugin,repr_simd,slice_patterns)] #![allow(dead_code)] #![plugin(docopt_macros)] #![plugin(rand_macros)] #![plugin(serde_macros)] extern crate bincode; extern crate byte_conv; extern crate collections; extern crate core; extern crate docopt; extern crate fixed_circular_buffer; extern crate graphics; extern crate num; extern crate opengl_graphics; extern crate piston; extern crate rand; extern crate rustc_serialize; extern crate serde; extern crate vec_map; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; #[cfg(feature = "include_glfw")] extern crate glfw_window; #[cfg(feature = "include_glutin")]extern crate glutin_window; //Constants macro_rules! PROGRAM_NAME{() => ("tetr")} macro_rules! PROGRAM_NAME_VERSION{() => (concat!(PROGRAM_NAME!()," v",env!("CARGO_PKG_VERSION")))} mod cli; mod controller; mod data; mod game; mod input; mod online; mod render; use core::f64; use piston::window::WindowSettings; use piston::event_loop::Events; use piston::input::{Button,Key,PressEvent,ReleaseEvent,RenderEvent,UpdateEvent,UpdateArgs}; use opengl_graphics::GlGraphics; use std::{net,sync}; use std::collections::hash_map::{self,HashMap}; #[cfg(feature = "include_sdl2")] use sdl2_window::Sdl2Window as Window; #[cfg(feature = "include_glfw")] use glfw_window::GlfwWindow as Window; #[cfg(feature = "include_glutin")]use glutin_window::GlutinWindow as Window; use ::controller::{ai,Controller}; use ::data::{cell,grid,Grid,PairMap}; use ::data::shapes::tetromino::{Shape,RotatedShape}; use ::game::data::world::dynamic::World; use ::game::data::{player,Input,PlayerId,WorldId}; use ::game::{Event,Request}; struct App{ gl: GlGraphics, game_state: game::State<World<cell::ShapeCell>,rand::StdRng>, controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>, request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>, connection: online::ConnectionType, paused: bool, key_map: ::game::data::input::key::KeyMap, key_down: HashMap<Key,f64>, } impl App{ fn update(&mut self,args: &UpdateArgs,request_sender: &sync::mpsc::Sender<Request<PlayerId,WorldId>>){ //Controllers if!self.paused{ for mut controller in self.controllers.iter_mut(){ controller.update(args,&self.game_state.data); } } //Key repeat for (key,time_left) in self.key_down.iter_mut(){ while{ *time_left-= args.dt; *time_left <= 0.0 }{ *time_left = if let Some(mapping) = self.key_map.get(key){ request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); *time_left + mapping.repeat_frequency }else
} } //Input while let Ok(request) = self.request_receiver.try_recv(){match request{ Request::PlayerInput{input,player: pid} => { if let Some(player) = self.game_state.data.players.get_mut(pid as usize){ if let Some(&mut(ref mut world,false)) = self.game_state.data.worlds.get_mut(player.world as usize){ input::perform(input,player,world); } } if let online::ConnectionType::Client(ref player_ids,Some(connection_id),ref socket,ref address) = self.connection{if let Some(player_network_id) = player_ids.get2(pid){ socket.send_to(&*online::client::packet::Data::Request{ connection: connection_id,//TODO: Maybe this should not send directly to the socket. The connection id is not received until the connection has began request: Request::PlayerInput{ player: player_network_id, input: input } }.into_packet(0).serialize(),address).unwrap(); }} }, Request::PlayerAdd{settings,world: world_id} => { let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.add_player(world_id,settings,&mut |e| for c in cs.iter_mut(){c.event(&e);}); }, Request::WorldRestart{world: world_id} => { let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.reset_world(world_id,&mut |e| for c in cs.iter_mut(){c.event(&e);}); }, _ => () }} //Update if!self.paused{ let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.update(args,&mut |e| for c in cs.iter_mut(){c.event(&e);}); } } fn on_key_press(&mut self,key: Key,request_sender: &sync::mpsc::Sender<Request<PlayerId,WorldId>>){ if self.paused{match key{ Key::Return => {self.paused = false}, _ => {}, }}else{match key{ Key::Return => {self.paused = true}, //Player 0 Tests Key::D1 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::I);};}, Key::D2 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::L);};}, Key::D3 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::O);};}, Key::D4 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::J);};}, Key::D5 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::T);};}, Key::D6 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::S);};}, Key::D7 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::Z);};}, Key::R => { match self.game_state.data.players.get(0 as usize).map(|player| player.world){//TODO: New seed for rng Some(world_id) => {request_sender.send(Request::WorldRestart{world: world_id}).unwrap();}, None => () }; }, Key::Home => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.pos.y = 0;};}, //Other keys, check key bindings key => if let Some(mapping) = self.key_map.get(&key){ if let hash_map::Entry::Vacant(entry) = self.key_down.entry(key){ entry.insert(mapping.repeat_delay); request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); } } }} } fn on_key_release(&mut self,key: Key){ if let hash_map::Entry::Occupied(entry) = self.key_down.entry(key){ entry.remove(); } } } fn main(){ let args: cli::Args = match cli::Args_docopt().decode(){ Ok(args) => args, Err(docopt::Error::WithProgramUsage(_,usage)) | Err(docopt::Error::Usage(usage)) => { println!("{}",usage); return; }, e => e.unwrap() }; if args.flag_version{ println!(PROGRAM_NAME_VERSION!()); return; } if args.flag_credits{ println!(concat!(PROGRAM_NAME_VERSION!(),": Credits\n\n",include_str!("../CREDITS"))); return; } if args.flag_manual{ println!(concat!(PROGRAM_NAME_VERSION!(),": Instruction manual\n\n",include_str!("../MANUAL"))); return; } //Create a window. let mut window = Window::new( WindowSettings::new( concat!(PROGRAM_NAME!()," v",env!("CARGO_PKG_VERSION")), [args.flag_window_size.0,args.flag_window_size.1] ) .exit_on_esc(true) .opengl(args.flag_gl_version.0) ).unwrap(); let (request_sender,request_receiver) = sync::mpsc::channel(); //Create a new application let mut app = App{ gl: GlGraphics::new(args.flag_gl_version.0), game_state: game::State::new( rand::StdRng::new().unwrap(), {fn f(variant: &RotatedShape) -> cell::ShapeCell{ cell::ShapeCell(Some(variant.shape())) }f}as fn(&_) -> _, {fn f<W: Grid + grid::RectangularBound>(shape: &RotatedShape,world: &W) -> grid::Pos{grid::Pos{ x: world.width() as grid::PosAxis/2 - shape.center_x() as grid::PosAxis, y: 0//TODO: Optionally spawn above: `-(shape.height() as grid::PosAxis);`. Problem is the collision checking. And this is not how it usually is done in other games }}f::<World<cell::ShapeCell>>}as fn(&_,&_) -> _, ), paused: false, controllers: Vec::new(), key_map: HashMap::new(), key_down: HashMap::new(), request_receiver: request_receiver, connection: match args.flag_online{ //No connection cli::OnlineConnection::none => online::ConnectionType::None, //Start to act as a client, connecting to a server cli::OnlineConnection::client => { let server_addr = net::SocketAddr::new( match args.flag_host.0{ net::IpAddr::V4(ip) if ip.is_unspecified() => net::IpAddr::V4(net::Ipv4Addr::new(127,0,0,1)), ip => ip }, args.flag_port ); match online::client::start(server_addr,request_sender.clone()){ Ok(socket) => online::ConnectionType::Client(PairMap::new(),None,socket,server_addr), Err(_) => online::ConnectionType::None } }, //Start to act as a server, listening for clients cli::OnlineConnection::server => { let server_addr = net::SocketAddr::new(args.flag_host.0,args.flag_port); match online::server::start(server_addr,request_sender.clone()){ Ok(_) => online::ConnectionType::Server(PairMap::new()), Err(_) => online::ConnectionType::None } } }, }; //Create world app.game_state.data.worlds.insert(0,(World::new(10,20),false)); app.game_state.data.worlds.insert(1,(World::new(10,20),false)); {let App{game_state: ref mut game,controllers: ref mut cs,..} = app; if let online::ConnectionType::None = app.connection{ //Create player 0 game.rngs.insert_from_global(game::data::mappings::Key::Player(0)); game.add_player(0,player::Settings{ gravityfall_frequency: 1.0, fastfall_shadow : true, },&mut |e| for c in cs.iter_mut(){c.event(&e);}); //Create player 1 game.rngs.insert_from_global(game::data::mappings::Key::Player(1)); cs.push(Box::new(ai::bruteforce::Controller::new(//TODO: Controllers shoulld probably be bound to the individual players request_sender.clone(), 1, ai::bruteforce::Settings::default() ))); game.add_player(1,player::Settings{ gravityfall_frequency: 1.0, fastfall_shadow : true, },&mut |e| for c in cs.iter_mut(){c.event(&e);}); } } {//Key mappings use ::game::data::input::key::Mapping; //Player 0 app.key_map.insert(Key::Left ,Mapping{input: Input::MoveLeft, player: 0,repeat_delay: 0.2,repeat_frequency: 0.125}); app.key_map.insert(Key::Right ,Mapping{input: Input::MoveRight, player: 0,repeat_delay: 0.2,repeat_frequency: 0.125}); app.key_map.insert(Key::Down ,Mapping{input: Input::SlowFall, player: 0,repeat_delay: 0.2,repeat_frequency: 0.07}); app.key_map.insert(Key::End ,Mapping{input: Input::FastFall, player: 0,repeat_delay: f64::NAN,repeat_frequency: f64::NAN}); app.key_map.insert(Key::X ,Mapping{input: Input::RotateAntiClockwise,player: 0,repeat_delay: 0.2,repeat_frequency: 0.2}); app.key_map.insert(Key::Z ,Mapping{input: Input::RotateClockwise, player: 0,repeat_delay: 0.2,repeat_frequency: 0.2}); //Player 1 app.key_map.insert(Key::NumPad4,Mapping{input: Input::MoveLeft, player: 1,repeat_delay: 0.3,repeat_frequency: 0.1}); app.key_map.insert(Key::NumPad6,Mapping{input: Input::MoveRight, player: 1,repeat_delay: 0.3,repeat_frequency: 0.1}); app.key_map.insert(Key::NumPad5,Mapping{input: Input::SlowFall, player: 1,repeat_delay: 0.3,repeat_frequency: 0.07}); app.key_map.insert(Key::NumPad2,Mapping{input: Input::FastFall, player: 1,repeat_delay: f64::NAN,repeat_frequency: f64::NAN}); app.key_map.insert(Key::NumPad1,Mapping{input: Input::RotateAntiClockwise,player: 1,repeat_delay: 0.3,repeat_frequency: 0.2}); app.key_map.insert(Key::NumPad0,Mapping{input: Input::RotateClockwise, player: 1,repeat_delay: 0.3,repeat_frequency: 0.2}); } //Run the created application: Listen for events let mut events = window.events(); while let Some(e) = events.next(&mut window){ //Player inflicted input: Keyboard events if let Some(Button::Keyboard(k)) = e.press_args(){ app.on_key_press(k,&request_sender); } if let Some(Button::Keyboard(k)) = e.release_args(){ app.on_key_release(k); } //Update if let Some(u) = e.update_args(){ app.update(&u,&request_sender); } //Render if let Some(r) = e.render_args(){ if app.paused{ render::default::pause(&mut app.game_state,&mut app.gl,&r); }else{ render::default::gamestate(&mut app.game_state,&mut app.gl,&r); } } } }
{ f64::NAN//TODO: If the mapping doesn't exist, it will never be removed }
conditional_block
main.rs
#![feature(associated_consts,collections,custom_derive,ip,lookup_host,optin_builtin_traits,plugin,repr_simd,slice_patterns)] #![allow(dead_code)] #![plugin(docopt_macros)] #![plugin(rand_macros)] #![plugin(serde_macros)] extern crate bincode; extern crate byte_conv; extern crate collections; extern crate core; extern crate docopt; extern crate fixed_circular_buffer; extern crate graphics; extern crate num; extern crate opengl_graphics; extern crate piston; extern crate rand; extern crate rustc_serialize; extern crate serde; extern crate vec_map; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; #[cfg(feature = "include_glfw")] extern crate glfw_window; #[cfg(feature = "include_glutin")]extern crate glutin_window; //Constants macro_rules! PROGRAM_NAME{() => ("tetr")} macro_rules! PROGRAM_NAME_VERSION{() => (concat!(PROGRAM_NAME!()," v",env!("CARGO_PKG_VERSION")))} mod cli; mod controller; mod data; mod game; mod input; mod online; mod render; use core::f64; use piston::window::WindowSettings; use piston::event_loop::Events; use piston::input::{Button,Key,PressEvent,ReleaseEvent,RenderEvent,UpdateEvent,UpdateArgs}; use opengl_graphics::GlGraphics; use std::{net,sync}; use std::collections::hash_map::{self,HashMap}; #[cfg(feature = "include_sdl2")] use sdl2_window::Sdl2Window as Window; #[cfg(feature = "include_glfw")] use glfw_window::GlfwWindow as Window; #[cfg(feature = "include_glutin")]use glutin_window::GlutinWindow as Window; use ::controller::{ai,Controller}; use ::data::{cell,grid,Grid,PairMap}; use ::data::shapes::tetromino::{Shape,RotatedShape}; use ::game::data::world::dynamic::World; use ::game::data::{player,Input,PlayerId,WorldId}; use ::game::{Event,Request}; struct
{ gl: GlGraphics, game_state: game::State<World<cell::ShapeCell>,rand::StdRng>, controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>, request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>, connection: online::ConnectionType, paused: bool, key_map: ::game::data::input::key::KeyMap, key_down: HashMap<Key,f64>, } impl App{ fn update(&mut self,args: &UpdateArgs,request_sender: &sync::mpsc::Sender<Request<PlayerId,WorldId>>){ //Controllers if!self.paused{ for mut controller in self.controllers.iter_mut(){ controller.update(args,&self.game_state.data); } } //Key repeat for (key,time_left) in self.key_down.iter_mut(){ while{ *time_left-= args.dt; *time_left <= 0.0 }{ *time_left = if let Some(mapping) = self.key_map.get(key){ request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); *time_left + mapping.repeat_frequency }else{ f64::NAN//TODO: If the mapping doesn't exist, it will never be removed } } } //Input while let Ok(request) = self.request_receiver.try_recv(){match request{ Request::PlayerInput{input,player: pid} => { if let Some(player) = self.game_state.data.players.get_mut(pid as usize){ if let Some(&mut(ref mut world,false)) = self.game_state.data.worlds.get_mut(player.world as usize){ input::perform(input,player,world); } } if let online::ConnectionType::Client(ref player_ids,Some(connection_id),ref socket,ref address) = self.connection{if let Some(player_network_id) = player_ids.get2(pid){ socket.send_to(&*online::client::packet::Data::Request{ connection: connection_id,//TODO: Maybe this should not send directly to the socket. The connection id is not received until the connection has began request: Request::PlayerInput{ player: player_network_id, input: input } }.into_packet(0).serialize(),address).unwrap(); }} }, Request::PlayerAdd{settings,world: world_id} => { let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.add_player(world_id,settings,&mut |e| for c in cs.iter_mut(){c.event(&e);}); }, Request::WorldRestart{world: world_id} => { let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.reset_world(world_id,&mut |e| for c in cs.iter_mut(){c.event(&e);}); }, _ => () }} //Update if!self.paused{ let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.update(args,&mut |e| for c in cs.iter_mut(){c.event(&e);}); } } fn on_key_press(&mut self,key: Key,request_sender: &sync::mpsc::Sender<Request<PlayerId,WorldId>>){ if self.paused{match key{ Key::Return => {self.paused = false}, _ => {}, }}else{match key{ Key::Return => {self.paused = true}, //Player 0 Tests Key::D1 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::I);};}, Key::D2 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::L);};}, Key::D3 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::O);};}, Key::D4 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::J);};}, Key::D5 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::T);};}, Key::D6 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::S);};}, Key::D7 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::Z);};}, Key::R => { match self.game_state.data.players.get(0 as usize).map(|player| player.world){//TODO: New seed for rng Some(world_id) => {request_sender.send(Request::WorldRestart{world: world_id}).unwrap();}, None => () }; }, Key::Home => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.pos.y = 0;};}, //Other keys, check key bindings key => if let Some(mapping) = self.key_map.get(&key){ if let hash_map::Entry::Vacant(entry) = self.key_down.entry(key){ entry.insert(mapping.repeat_delay); request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); } } }} } fn on_key_release(&mut self,key: Key){ if let hash_map::Entry::Occupied(entry) = self.key_down.entry(key){ entry.remove(); } } } fn main(){ let args: cli::Args = match cli::Args_docopt().decode(){ Ok(args) => args, Err(docopt::Error::WithProgramUsage(_,usage)) | Err(docopt::Error::Usage(usage)) => { println!("{}",usage); return; }, e => e.unwrap() }; if args.flag_version{ println!(PROGRAM_NAME_VERSION!()); return; } if args.flag_credits{ println!(concat!(PROGRAM_NAME_VERSION!(),": Credits\n\n",include_str!("../CREDITS"))); return; } if args.flag_manual{ println!(concat!(PROGRAM_NAME_VERSION!(),": Instruction manual\n\n",include_str!("../MANUAL"))); return; } //Create a window. let mut window = Window::new( WindowSettings::new( concat!(PROGRAM_NAME!()," v",env!("CARGO_PKG_VERSION")), [args.flag_window_size.0,args.flag_window_size.1] ) .exit_on_esc(true) .opengl(args.flag_gl_version.0) ).unwrap(); let (request_sender,request_receiver) = sync::mpsc::channel(); //Create a new application let mut app = App{ gl: GlGraphics::new(args.flag_gl_version.0), game_state: game::State::new( rand::StdRng::new().unwrap(), {fn f(variant: &RotatedShape) -> cell::ShapeCell{ cell::ShapeCell(Some(variant.shape())) }f}as fn(&_) -> _, {fn f<W: Grid + grid::RectangularBound>(shape: &RotatedShape,world: &W) -> grid::Pos{grid::Pos{ x: world.width() as grid::PosAxis/2 - shape.center_x() as grid::PosAxis, y: 0//TODO: Optionally spawn above: `-(shape.height() as grid::PosAxis);`. Problem is the collision checking. And this is not how it usually is done in other games }}f::<World<cell::ShapeCell>>}as fn(&_,&_) -> _, ), paused: false, controllers: Vec::new(), key_map: HashMap::new(), key_down: HashMap::new(), request_receiver: request_receiver, connection: match args.flag_online{ //No connection cli::OnlineConnection::none => online::ConnectionType::None, //Start to act as a client, connecting to a server cli::OnlineConnection::client => { let server_addr = net::SocketAddr::new( match args.flag_host.0{ net::IpAddr::V4(ip) if ip.is_unspecified() => net::IpAddr::V4(net::Ipv4Addr::new(127,0,0,1)), ip => ip }, args.flag_port ); match online::client::start(server_addr,request_sender.clone()){ Ok(socket) => online::ConnectionType::Client(PairMap::new(),None,socket,server_addr), Err(_) => online::ConnectionType::None } }, //Start to act as a server, listening for clients cli::OnlineConnection::server => { let server_addr = net::SocketAddr::new(args.flag_host.0,args.flag_port); match online::server::start(server_addr,request_sender.clone()){ Ok(_) => online::ConnectionType::Server(PairMap::new()), Err(_) => online::ConnectionType::None } } }, }; //Create world app.game_state.data.worlds.insert(0,(World::new(10,20),false)); app.game_state.data.worlds.insert(1,(World::new(10,20),false)); {let App{game_state: ref mut game,controllers: ref mut cs,..} = app; if let online::ConnectionType::None = app.connection{ //Create player 0 game.rngs.insert_from_global(game::data::mappings::Key::Player(0)); game.add_player(0,player::Settings{ gravityfall_frequency: 1.0, fastfall_shadow : true, },&mut |e| for c in cs.iter_mut(){c.event(&e);}); //Create player 1 game.rngs.insert_from_global(game::data::mappings::Key::Player(1)); cs.push(Box::new(ai::bruteforce::Controller::new(//TODO: Controllers shoulld probably be bound to the individual players request_sender.clone(), 1, ai::bruteforce::Settings::default() ))); game.add_player(1,player::Settings{ gravityfall_frequency: 1.0, fastfall_shadow : true, },&mut |e| for c in cs.iter_mut(){c.event(&e);}); } } {//Key mappings use ::game::data::input::key::Mapping; //Player 0 app.key_map.insert(Key::Left ,Mapping{input: Input::MoveLeft, player: 0,repeat_delay: 0.2,repeat_frequency: 0.125}); app.key_map.insert(Key::Right ,Mapping{input: Input::MoveRight, player: 0,repeat_delay: 0.2,repeat_frequency: 0.125}); app.key_map.insert(Key::Down ,Mapping{input: Input::SlowFall, player: 0,repeat_delay: 0.2,repeat_frequency: 0.07}); app.key_map.insert(Key::End ,Mapping{input: Input::FastFall, player: 0,repeat_delay: f64::NAN,repeat_frequency: f64::NAN}); app.key_map.insert(Key::X ,Mapping{input: Input::RotateAntiClockwise,player: 0,repeat_delay: 0.2,repeat_frequency: 0.2}); app.key_map.insert(Key::Z ,Mapping{input: Input::RotateClockwise, player: 0,repeat_delay: 0.2,repeat_frequency: 0.2}); //Player 1 app.key_map.insert(Key::NumPad4,Mapping{input: Input::MoveLeft, player: 1,repeat_delay: 0.3,repeat_frequency: 0.1}); app.key_map.insert(Key::NumPad6,Mapping{input: Input::MoveRight, player: 1,repeat_delay: 0.3,repeat_frequency: 0.1}); app.key_map.insert(Key::NumPad5,Mapping{input: Input::SlowFall, player: 1,repeat_delay: 0.3,repeat_frequency: 0.07}); app.key_map.insert(Key::NumPad2,Mapping{input: Input::FastFall, player: 1,repeat_delay: f64::NAN,repeat_frequency: f64::NAN}); app.key_map.insert(Key::NumPad1,Mapping{input: Input::RotateAntiClockwise,player: 1,repeat_delay: 0.3,repeat_frequency: 0.2}); app.key_map.insert(Key::NumPad0,Mapping{input: Input::RotateClockwise, player: 1,repeat_delay: 0.3,repeat_frequency: 0.2}); } //Run the created application: Listen for events let mut events = window.events(); while let Some(e) = events.next(&mut window){ //Player inflicted input: Keyboard events if let Some(Button::Keyboard(k)) = e.press_args(){ app.on_key_press(k,&request_sender); } if let Some(Button::Keyboard(k)) = e.release_args(){ app.on_key_release(k); } //Update if let Some(u) = e.update_args(){ app.update(&u,&request_sender); } //Render if let Some(r) = e.render_args(){ if app.paused{ render::default::pause(&mut app.game_state,&mut app.gl,&r); }else{ render::default::gamestate(&mut app.game_state,&mut app.gl,&r); } } } }
App
identifier_name
main.rs
#![feature(associated_consts,collections,custom_derive,ip,lookup_host,optin_builtin_traits,plugin,repr_simd,slice_patterns)] #![allow(dead_code)] #![plugin(docopt_macros)] #![plugin(rand_macros)] #![plugin(serde_macros)] extern crate bincode; extern crate byte_conv; extern crate collections; extern crate core; extern crate docopt; extern crate fixed_circular_buffer; extern crate graphics; extern crate num; extern crate opengl_graphics; extern crate piston; extern crate rand; extern crate rustc_serialize; extern crate serde; extern crate vec_map; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; #[cfg(feature = "include_glfw")] extern crate glfw_window; #[cfg(feature = "include_glutin")]extern crate glutin_window; //Constants macro_rules! PROGRAM_NAME{() => ("tetr")} macro_rules! PROGRAM_NAME_VERSION{() => (concat!(PROGRAM_NAME!()," v",env!("CARGO_PKG_VERSION")))} mod cli; mod controller; mod data; mod game; mod input; mod online; mod render; use core::f64; use piston::window::WindowSettings; use piston::event_loop::Events; use piston::input::{Button,Key,PressEvent,ReleaseEvent,RenderEvent,UpdateEvent,UpdateArgs}; use opengl_graphics::GlGraphics; use std::{net,sync}; use std::collections::hash_map::{self,HashMap}; #[cfg(feature = "include_sdl2")] use sdl2_window::Sdl2Window as Window; #[cfg(feature = "include_glfw")] use glfw_window::GlfwWindow as Window; #[cfg(feature = "include_glutin")]use glutin_window::GlutinWindow as Window; use ::controller::{ai,Controller}; use ::data::{cell,grid,Grid,PairMap}; use ::data::shapes::tetromino::{Shape,RotatedShape}; use ::game::data::world::dynamic::World; use ::game::data::{player,Input,PlayerId,WorldId}; use ::game::{Event,Request}; struct App{ gl: GlGraphics, game_state: game::State<World<cell::ShapeCell>,rand::StdRng>, controllers: Vec<Box<Controller<World<cell::ShapeCell>,Event<(PlayerId,WorldId),WorldId>>>>, request_receiver: sync::mpsc::Receiver<Request<PlayerId,WorldId>>, connection: online::ConnectionType, paused: bool, key_map: ::game::data::input::key::KeyMap, key_down: HashMap<Key,f64>, } impl App{ fn update(&mut self,args: &UpdateArgs,request_sender: &sync::mpsc::Sender<Request<PlayerId,WorldId>>)
} } //Input while let Ok(request) = self.request_receiver.try_recv(){match request{ Request::PlayerInput{input,player: pid} => { if let Some(player) = self.game_state.data.players.get_mut(pid as usize){ if let Some(&mut(ref mut world,false)) = self.game_state.data.worlds.get_mut(player.world as usize){ input::perform(input,player,world); } } if let online::ConnectionType::Client(ref player_ids,Some(connection_id),ref socket,ref address) = self.connection{if let Some(player_network_id) = player_ids.get2(pid){ socket.send_to(&*online::client::packet::Data::Request{ connection: connection_id,//TODO: Maybe this should not send directly to the socket. The connection id is not received until the connection has began request: Request::PlayerInput{ player: player_network_id, input: input } }.into_packet(0).serialize(),address).unwrap(); }} }, Request::PlayerAdd{settings,world: world_id} => { let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.add_player(world_id,settings,&mut |e| for c in cs.iter_mut(){c.event(&e);}); }, Request::WorldRestart{world: world_id} => { let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.reset_world(world_id,&mut |e| for c in cs.iter_mut(){c.event(&e);}); }, _ => () }} //Update if!self.paused{ let &mut App{game_state: ref mut game,controllers: ref mut cs,..} = self; game.update(args,&mut |e| for c in cs.iter_mut(){c.event(&e);}); } } fn on_key_press(&mut self,key: Key,request_sender: &sync::mpsc::Sender<Request<PlayerId,WorldId>>){ if self.paused{match key{ Key::Return => {self.paused = false}, _ => {}, }}else{match key{ Key::Return => {self.paused = true}, //Player 0 Tests Key::D1 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::I);};}, Key::D2 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::L);};}, Key::D3 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::O);};}, Key::D4 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::J);};}, Key::D5 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::T);};}, Key::D6 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::S);};}, Key::D7 => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.shape = RotatedShape::new(Shape::Z);};}, Key::R => { match self.game_state.data.players.get(0 as usize).map(|player| player.world){//TODO: New seed for rng Some(world_id) => {request_sender.send(Request::WorldRestart{world: world_id}).unwrap();}, None => () }; }, Key::Home => {if let Some(player) = self.game_state.data.players.get_mut(0 as usize){player.pos.y = 0;};}, //Other keys, check key bindings key => if let Some(mapping) = self.key_map.get(&key){ if let hash_map::Entry::Vacant(entry) = self.key_down.entry(key){ entry.insert(mapping.repeat_delay); request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); } } }} } fn on_key_release(&mut self,key: Key){ if let hash_map::Entry::Occupied(entry) = self.key_down.entry(key){ entry.remove(); } } } fn main(){ let args: cli::Args = match cli::Args_docopt().decode(){ Ok(args) => args, Err(docopt::Error::WithProgramUsage(_,usage)) | Err(docopt::Error::Usage(usage)) => { println!("{}",usage); return; }, e => e.unwrap() }; if args.flag_version{ println!(PROGRAM_NAME_VERSION!()); return; } if args.flag_credits{ println!(concat!(PROGRAM_NAME_VERSION!(),": Credits\n\n",include_str!("../CREDITS"))); return; } if args.flag_manual{ println!(concat!(PROGRAM_NAME_VERSION!(),": Instruction manual\n\n",include_str!("../MANUAL"))); return; } //Create a window. let mut window = Window::new( WindowSettings::new( concat!(PROGRAM_NAME!()," v",env!("CARGO_PKG_VERSION")), [args.flag_window_size.0,args.flag_window_size.1] ) .exit_on_esc(true) .opengl(args.flag_gl_version.0) ).unwrap(); let (request_sender,request_receiver) = sync::mpsc::channel(); //Create a new application let mut app = App{ gl: GlGraphics::new(args.flag_gl_version.0), game_state: game::State::new( rand::StdRng::new().unwrap(), {fn f(variant: &RotatedShape) -> cell::ShapeCell{ cell::ShapeCell(Some(variant.shape())) }f}as fn(&_) -> _, {fn f<W: Grid + grid::RectangularBound>(shape: &RotatedShape,world: &W) -> grid::Pos{grid::Pos{ x: world.width() as grid::PosAxis/2 - shape.center_x() as grid::PosAxis, y: 0//TODO: Optionally spawn above: `-(shape.height() as grid::PosAxis);`. Problem is the collision checking. And this is not how it usually is done in other games }}f::<World<cell::ShapeCell>>}as fn(&_,&_) -> _, ), paused: false, controllers: Vec::new(), key_map: HashMap::new(), key_down: HashMap::new(), request_receiver: request_receiver, connection: match args.flag_online{ //No connection cli::OnlineConnection::none => online::ConnectionType::None, //Start to act as a client, connecting to a server cli::OnlineConnection::client => { let server_addr = net::SocketAddr::new( match args.flag_host.0{ net::IpAddr::V4(ip) if ip.is_unspecified() => net::IpAddr::V4(net::Ipv4Addr::new(127,0,0,1)), ip => ip }, args.flag_port ); match online::client::start(server_addr,request_sender.clone()){ Ok(socket) => online::ConnectionType::Client(PairMap::new(),None,socket,server_addr), Err(_) => online::ConnectionType::None } }, //Start to act as a server, listening for clients cli::OnlineConnection::server => { let server_addr = net::SocketAddr::new(args.flag_host.0,args.flag_port); match online::server::start(server_addr,request_sender.clone()){ Ok(_) => online::ConnectionType::Server(PairMap::new()), Err(_) => online::ConnectionType::None } } }, }; //Create world app.game_state.data.worlds.insert(0,(World::new(10,20),false)); app.game_state.data.worlds.insert(1,(World::new(10,20),false)); {let App{game_state: ref mut game,controllers: ref mut cs,..} = app; if let online::ConnectionType::None = app.connection{ //Create player 0 game.rngs.insert_from_global(game::data::mappings::Key::Player(0)); game.add_player(0,player::Settings{ gravityfall_frequency: 1.0, fastfall_shadow : true, },&mut |e| for c in cs.iter_mut(){c.event(&e);}); //Create player 1 game.rngs.insert_from_global(game::data::mappings::Key::Player(1)); cs.push(Box::new(ai::bruteforce::Controller::new(//TODO: Controllers shoulld probably be bound to the individual players request_sender.clone(), 1, ai::bruteforce::Settings::default() ))); game.add_player(1,player::Settings{ gravityfall_frequency: 1.0, fastfall_shadow : true, },&mut |e| for c in cs.iter_mut(){c.event(&e);}); } } {//Key mappings use ::game::data::input::key::Mapping; //Player 0 app.key_map.insert(Key::Left ,Mapping{input: Input::MoveLeft, player: 0,repeat_delay: 0.2,repeat_frequency: 0.125}); app.key_map.insert(Key::Right ,Mapping{input: Input::MoveRight, player: 0,repeat_delay: 0.2,repeat_frequency: 0.125}); app.key_map.insert(Key::Down ,Mapping{input: Input::SlowFall, player: 0,repeat_delay: 0.2,repeat_frequency: 0.07}); app.key_map.insert(Key::End ,Mapping{input: Input::FastFall, player: 0,repeat_delay: f64::NAN,repeat_frequency: f64::NAN}); app.key_map.insert(Key::X ,Mapping{input: Input::RotateAntiClockwise,player: 0,repeat_delay: 0.2,repeat_frequency: 0.2}); app.key_map.insert(Key::Z ,Mapping{input: Input::RotateClockwise, player: 0,repeat_delay: 0.2,repeat_frequency: 0.2}); //Player 1 app.key_map.insert(Key::NumPad4,Mapping{input: Input::MoveLeft, player: 1,repeat_delay: 0.3,repeat_frequency: 0.1}); app.key_map.insert(Key::NumPad6,Mapping{input: Input::MoveRight, player: 1,repeat_delay: 0.3,repeat_frequency: 0.1}); app.key_map.insert(Key::NumPad5,Mapping{input: Input::SlowFall, player: 1,repeat_delay: 0.3,repeat_frequency: 0.07}); app.key_map.insert(Key::NumPad2,Mapping{input: Input::FastFall, player: 1,repeat_delay: f64::NAN,repeat_frequency: f64::NAN}); app.key_map.insert(Key::NumPad1,Mapping{input: Input::RotateAntiClockwise,player: 1,repeat_delay: 0.3,repeat_frequency: 0.2}); app.key_map.insert(Key::NumPad0,Mapping{input: Input::RotateClockwise, player: 1,repeat_delay: 0.3,repeat_frequency: 0.2}); } //Run the created application: Listen for events let mut events = window.events(); while let Some(e) = events.next(&mut window){ //Player inflicted input: Keyboard events if let Some(Button::Keyboard(k)) = e.press_args(){ app.on_key_press(k,&request_sender); } if let Some(Button::Keyboard(k)) = e.release_args(){ app.on_key_release(k); } //Update if let Some(u) = e.update_args(){ app.update(&u,&request_sender); } //Render if let Some(r) = e.render_args(){ if app.paused{ render::default::pause(&mut app.game_state,&mut app.gl,&r); }else{ render::default::gamestate(&mut app.game_state,&mut app.gl,&r); } } } }
{ //Controllers if !self.paused{ for mut controller in self.controllers.iter_mut(){ controller.update(args,&self.game_state.data); } } //Key repeat for (key,time_left) in self.key_down.iter_mut(){ while{ *time_left-= args.dt; *time_left <= 0.0 }{ *time_left = if let Some(mapping) = self.key_map.get(key){ request_sender.send(Request::PlayerInput{input: mapping.input,player: mapping.player}).unwrap(); *time_left + mapping.repeat_frequency }else{ f64::NAN//TODO: If the mapping doesn't exist, it will never be removed }
identifier_body
types.rs
use core::fmt; use core::ops::*; pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv}; #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct PhysAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct MappedAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct VirtAddr(pub usize); enable_unsigned_ops!(PhysAddr); enable_unsigned_ops!(MappedAddr); enable_unsigned_ops!(VirtAddr); const VIRT : VirtAddr = VirtAddr(0xFFFFFF0000000000); const PHYSMAP : MappedAddr = MappedAddr(0xFFFF800000000000); impl PhysAddrConv for PhysAddr { fn to_mapped(&self) -> MappedAddr { if self.0 < PHYSMAP.0 { return MappedAddr(self.0 + PHYSMAP.0); } else { return MappedAddr(self.0); } } fn to_virt(&self) -> VirtAddr { if self.0 < PHYSMAP.0 { return VirtAddr(self.0 + VIRT.0); } else { return VirtAddr(self.0); } } } impl VirtAddrConv for VirtAddr { fn to_phys(&self) -> PhysAddr { if self >= &VIRT
else { PhysAddr(self.0) } } } impl MappedAddrConv for MappedAddr { fn to_phys(&self) -> PhysAddr { if self >= &PHYSMAP { PhysAddr(self.0 - PHYSMAP.0) } else { PhysAddr(self.0) } } }
{ PhysAddr(self.0 - VIRT.0) }
conditional_block
types.rs
use core::fmt; use core::ops::*; pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv}; #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct PhysAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct MappedAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct
(pub usize); enable_unsigned_ops!(PhysAddr); enable_unsigned_ops!(MappedAddr); enable_unsigned_ops!(VirtAddr); const VIRT : VirtAddr = VirtAddr(0xFFFFFF0000000000); const PHYSMAP : MappedAddr = MappedAddr(0xFFFF800000000000); impl PhysAddrConv for PhysAddr { fn to_mapped(&self) -> MappedAddr { if self.0 < PHYSMAP.0 { return MappedAddr(self.0 + PHYSMAP.0); } else { return MappedAddr(self.0); } } fn to_virt(&self) -> VirtAddr { if self.0 < PHYSMAP.0 { return VirtAddr(self.0 + VIRT.0); } else { return VirtAddr(self.0); } } } impl VirtAddrConv for VirtAddr { fn to_phys(&self) -> PhysAddr { if self >= &VIRT { PhysAddr(self.0 - VIRT.0) } else { PhysAddr(self.0) } } } impl MappedAddrConv for MappedAddr { fn to_phys(&self) -> PhysAddr { if self >= &PHYSMAP { PhysAddr(self.0 - PHYSMAP.0) } else { PhysAddr(self.0) } } }
VirtAddr
identifier_name
types.rs
use core::fmt; use core::ops::*; pub use kernel::mm::{PhysAddrConv, MappedAddrConv, VirtAddrConv}; #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct PhysAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct MappedAddr(pub usize); #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] pub struct VirtAddr(pub usize); enable_unsigned_ops!(PhysAddr); enable_unsigned_ops!(MappedAddr); enable_unsigned_ops!(VirtAddr); const VIRT : VirtAddr = VirtAddr(0xFFFFFF0000000000); const PHYSMAP : MappedAddr = MappedAddr(0xFFFF800000000000); impl PhysAddrConv for PhysAddr { fn to_mapped(&self) -> MappedAddr { if self.0 < PHYSMAP.0 { return MappedAddr(self.0 + PHYSMAP.0); } else { return MappedAddr(self.0); } } fn to_virt(&self) -> VirtAddr { if self.0 < PHYSMAP.0 { return VirtAddr(self.0 + VIRT.0); } else { return VirtAddr(self.0); } } } impl VirtAddrConv for VirtAddr { fn to_phys(&self) -> PhysAddr { if self >= &VIRT { PhysAddr(self.0 - VIRT.0) } else { PhysAddr(self.0) }
impl MappedAddrConv for MappedAddr { fn to_phys(&self) -> PhysAddr { if self >= &PHYSMAP { PhysAddr(self.0 - PHYSMAP.0) } else { PhysAddr(self.0) } } }
} }
random_line_split
catalog.rs
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::{io, fs}; use std::io::Read; use std::path::{Path, PathBuf}; use std::collections::HashMap; use toml; use super::{PluginName, PluginDescription}; /// A catalog of all available plugins. pub struct PluginCatalog { items: HashMap<PluginName, PluginDescription>, } /// Errors that can occur while trying to load a plugin. #[derive(Debug)] pub enum PluginLoadError { Io(io::Error), /// Malformed manifest Parse(toml::de::Error), } #[allow(dead_code)] impl <'a>PluginCatalog { /// Loads plugins from the user's search paths pub fn from_paths(paths: Vec<PathBuf>) -> Self { let plugins = paths.iter() .flat_map(|path| { match load_plugins(path) {
path, err); Vec::new() } } }) .collect::<Vec<_>>(); PluginCatalog::new(&plugins) } pub fn new(plugins: &[PluginDescription]) -> Self { let mut items = HashMap::with_capacity(plugins.len()); for plugin in plugins { if items.contains_key(&plugin.name) { eprintln!("Duplicate plugin name.\n 1: {:?}\n 2: {:?}", plugin, items.get(&plugin.name)); continue } items.insert(plugin.name.to_owned(), plugin.to_owned()); } PluginCatalog { items } } /// Returns an iterator over all plugins in the catalog, in arbitrary order. pub fn iter(&'a self) -> Box<Iterator<Item=&'a PluginDescription> + 'a> { Box::new(self.items.values()) } /// Returns an iterator over all plugin names in the catalog, /// in arbitrary order. pub fn iter_names(&'a self) -> Box<Iterator<Item=&'a PluginName> + 'a> { Box::new(self.items.keys()) } /// Returns a reference to the named plugin if it exists in the catalog. pub fn get_named(&self, plugin_name: &str) -> Option<&PluginDescription> { self.items.get(plugin_name) } /// Returns all PluginDescriptions matching some predicate pub fn filter<F>(&self, predicate: F) -> Vec<&PluginDescription> where F: Fn(&PluginDescription) -> bool { self.iter() .filter(|item| predicate(item)) .collect::<Vec<_>>() } } fn load_plugins(plugin_dir: &Path) -> io::Result<Vec<PluginDescription>> { let mut plugins = Vec::new(); for path in plugin_dir.read_dir()? { let path = path?; let path = path.path(); if!path.is_dir() { continue } let manif_path = path.join("manifest.toml"); if!manif_path.exists() { continue } match load_manifest(&manif_path) { Ok(manif) => plugins.push(manif), Err(err) => eprintln!("Error reading manifest {:?}, error:\n{:?}", &manif_path, err), } } Ok(plugins) } fn load_manifest(path: &Path) -> Result<PluginDescription, PluginLoadError> { let mut file = fs::File::open(&path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let mut manifest: PluginDescription = toml::from_str(&contents)?; // normalize relative paths if manifest.exec_path.starts_with("./") { manifest.exec_path = path.parent() .unwrap() .join(manifest.exec_path) .canonicalize()?; } Ok(manifest) } impl From<io::Error> for PluginLoadError { fn from(err: io::Error) -> PluginLoadError { PluginLoadError::Io(err) } } impl From<toml::de::Error> for PluginLoadError { fn from(err: toml::de::Error) -> PluginLoadError { PluginLoadError::Parse(err) } }
Ok(plugins) => plugins, Err(err) => { eprintln!("error loading plugins from {:?}, error:\n{:?}",
random_line_split
catalog.rs
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::{io, fs}; use std::io::Read; use std::path::{Path, PathBuf}; use std::collections::HashMap; use toml; use super::{PluginName, PluginDescription}; /// A catalog of all available plugins. pub struct PluginCatalog { items: HashMap<PluginName, PluginDescription>, } /// Errors that can occur while trying to load a plugin. #[derive(Debug)] pub enum PluginLoadError { Io(io::Error), /// Malformed manifest Parse(toml::de::Error), } #[allow(dead_code)] impl <'a>PluginCatalog { /// Loads plugins from the user's search paths pub fn from_paths(paths: Vec<PathBuf>) -> Self { let plugins = paths.iter() .flat_map(|path| { match load_plugins(path) { Ok(plugins) => plugins, Err(err) => { eprintln!("error loading plugins from {:?}, error:\n{:?}", path, err); Vec::new() } } }) .collect::<Vec<_>>(); PluginCatalog::new(&plugins) } pub fn new(plugins: &[PluginDescription]) -> Self { let mut items = HashMap::with_capacity(plugins.len()); for plugin in plugins { if items.contains_key(&plugin.name) { eprintln!("Duplicate plugin name.\n 1: {:?}\n 2: {:?}", plugin, items.get(&plugin.name)); continue } items.insert(plugin.name.to_owned(), plugin.to_owned()); } PluginCatalog { items } } /// Returns an iterator over all plugins in the catalog, in arbitrary order. pub fn
(&'a self) -> Box<Iterator<Item=&'a PluginDescription> + 'a> { Box::new(self.items.values()) } /// Returns an iterator over all plugin names in the catalog, /// in arbitrary order. pub fn iter_names(&'a self) -> Box<Iterator<Item=&'a PluginName> + 'a> { Box::new(self.items.keys()) } /// Returns a reference to the named plugin if it exists in the catalog. pub fn get_named(&self, plugin_name: &str) -> Option<&PluginDescription> { self.items.get(plugin_name) } /// Returns all PluginDescriptions matching some predicate pub fn filter<F>(&self, predicate: F) -> Vec<&PluginDescription> where F: Fn(&PluginDescription) -> bool { self.iter() .filter(|item| predicate(item)) .collect::<Vec<_>>() } } fn load_plugins(plugin_dir: &Path) -> io::Result<Vec<PluginDescription>> { let mut plugins = Vec::new(); for path in plugin_dir.read_dir()? { let path = path?; let path = path.path(); if!path.is_dir() { continue } let manif_path = path.join("manifest.toml"); if!manif_path.exists() { continue } match load_manifest(&manif_path) { Ok(manif) => plugins.push(manif), Err(err) => eprintln!("Error reading manifest {:?}, error:\n{:?}", &manif_path, err), } } Ok(plugins) } fn load_manifest(path: &Path) -> Result<PluginDescription, PluginLoadError> { let mut file = fs::File::open(&path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let mut manifest: PluginDescription = toml::from_str(&contents)?; // normalize relative paths if manifest.exec_path.starts_with("./") { manifest.exec_path = path.parent() .unwrap() .join(manifest.exec_path) .canonicalize()?; } Ok(manifest) } impl From<io::Error> for PluginLoadError { fn from(err: io::Error) -> PluginLoadError { PluginLoadError::Io(err) } } impl From<toml::de::Error> for PluginLoadError { fn from(err: toml::de::Error) -> PluginLoadError { PluginLoadError::Parse(err) } }
iter
identifier_name
catalog.rs
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::{io, fs}; use std::io::Read; use std::path::{Path, PathBuf}; use std::collections::HashMap; use toml; use super::{PluginName, PluginDescription}; /// A catalog of all available plugins. pub struct PluginCatalog { items: HashMap<PluginName, PluginDescription>, } /// Errors that can occur while trying to load a plugin. #[derive(Debug)] pub enum PluginLoadError { Io(io::Error), /// Malformed manifest Parse(toml::de::Error), } #[allow(dead_code)] impl <'a>PluginCatalog { /// Loads plugins from the user's search paths pub fn from_paths(paths: Vec<PathBuf>) -> Self
pub fn new(plugins: &[PluginDescription]) -> Self { let mut items = HashMap::with_capacity(plugins.len()); for plugin in plugins { if items.contains_key(&plugin.name) { eprintln!("Duplicate plugin name.\n 1: {:?}\n 2: {:?}", plugin, items.get(&plugin.name)); continue } items.insert(plugin.name.to_owned(), plugin.to_owned()); } PluginCatalog { items } } /// Returns an iterator over all plugins in the catalog, in arbitrary order. pub fn iter(&'a self) -> Box<Iterator<Item=&'a PluginDescription> + 'a> { Box::new(self.items.values()) } /// Returns an iterator over all plugin names in the catalog, /// in arbitrary order. pub fn iter_names(&'a self) -> Box<Iterator<Item=&'a PluginName> + 'a> { Box::new(self.items.keys()) } /// Returns a reference to the named plugin if it exists in the catalog. pub fn get_named(&self, plugin_name: &str) -> Option<&PluginDescription> { self.items.get(plugin_name) } /// Returns all PluginDescriptions matching some predicate pub fn filter<F>(&self, predicate: F) -> Vec<&PluginDescription> where F: Fn(&PluginDescription) -> bool { self.iter() .filter(|item| predicate(item)) .collect::<Vec<_>>() } } fn load_plugins(plugin_dir: &Path) -> io::Result<Vec<PluginDescription>> { let mut plugins = Vec::new(); for path in plugin_dir.read_dir()? { let path = path?; let path = path.path(); if!path.is_dir() { continue } let manif_path = path.join("manifest.toml"); if!manif_path.exists() { continue } match load_manifest(&manif_path) { Ok(manif) => plugins.push(manif), Err(err) => eprintln!("Error reading manifest {:?}, error:\n{:?}", &manif_path, err), } } Ok(plugins) } fn load_manifest(path: &Path) -> Result<PluginDescription, PluginLoadError> { let mut file = fs::File::open(&path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let mut manifest: PluginDescription = toml::from_str(&contents)?; // normalize relative paths if manifest.exec_path.starts_with("./") { manifest.exec_path = path.parent() .unwrap() .join(manifest.exec_path) .canonicalize()?; } Ok(manifest) } impl From<io::Error> for PluginLoadError { fn from(err: io::Error) -> PluginLoadError { PluginLoadError::Io(err) } } impl From<toml::de::Error> for PluginLoadError { fn from(err: toml::de::Error) -> PluginLoadError { PluginLoadError::Parse(err) } }
{ let plugins = paths.iter() .flat_map(|path| { match load_plugins(path) { Ok(plugins) => plugins, Err(err) => { eprintln!("error loading plugins from {:?}, error:\n{:?}", path, err); Vec::new() } } }) .collect::<Vec<_>>(); PluginCatalog::new(&plugins) }
identifier_body
catalog.rs
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::{io, fs}; use std::io::Read; use std::path::{Path, PathBuf}; use std::collections::HashMap; use toml; use super::{PluginName, PluginDescription}; /// A catalog of all available plugins. pub struct PluginCatalog { items: HashMap<PluginName, PluginDescription>, } /// Errors that can occur while trying to load a plugin. #[derive(Debug)] pub enum PluginLoadError { Io(io::Error), /// Malformed manifest Parse(toml::de::Error), } #[allow(dead_code)] impl <'a>PluginCatalog { /// Loads plugins from the user's search paths pub fn from_paths(paths: Vec<PathBuf>) -> Self { let plugins = paths.iter() .flat_map(|path| { match load_plugins(path) { Ok(plugins) => plugins, Err(err) => { eprintln!("error loading plugins from {:?}, error:\n{:?}", path, err); Vec::new() } } }) .collect::<Vec<_>>(); PluginCatalog::new(&plugins) } pub fn new(plugins: &[PluginDescription]) -> Self { let mut items = HashMap::with_capacity(plugins.len()); for plugin in plugins { if items.contains_key(&plugin.name)
items.insert(plugin.name.to_owned(), plugin.to_owned()); } PluginCatalog { items } } /// Returns an iterator over all plugins in the catalog, in arbitrary order. pub fn iter(&'a self) -> Box<Iterator<Item=&'a PluginDescription> + 'a> { Box::new(self.items.values()) } /// Returns an iterator over all plugin names in the catalog, /// in arbitrary order. pub fn iter_names(&'a self) -> Box<Iterator<Item=&'a PluginName> + 'a> { Box::new(self.items.keys()) } /// Returns a reference to the named plugin if it exists in the catalog. pub fn get_named(&self, plugin_name: &str) -> Option<&PluginDescription> { self.items.get(plugin_name) } /// Returns all PluginDescriptions matching some predicate pub fn filter<F>(&self, predicate: F) -> Vec<&PluginDescription> where F: Fn(&PluginDescription) -> bool { self.iter() .filter(|item| predicate(item)) .collect::<Vec<_>>() } } fn load_plugins(plugin_dir: &Path) -> io::Result<Vec<PluginDescription>> { let mut plugins = Vec::new(); for path in plugin_dir.read_dir()? { let path = path?; let path = path.path(); if!path.is_dir() { continue } let manif_path = path.join("manifest.toml"); if!manif_path.exists() { continue } match load_manifest(&manif_path) { Ok(manif) => plugins.push(manif), Err(err) => eprintln!("Error reading manifest {:?}, error:\n{:?}", &manif_path, err), } } Ok(plugins) } fn load_manifest(path: &Path) -> Result<PluginDescription, PluginLoadError> { let mut file = fs::File::open(&path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let mut manifest: PluginDescription = toml::from_str(&contents)?; // normalize relative paths if manifest.exec_path.starts_with("./") { manifest.exec_path = path.parent() .unwrap() .join(manifest.exec_path) .canonicalize()?; } Ok(manifest) } impl From<io::Error> for PluginLoadError { fn from(err: io::Error) -> PluginLoadError { PluginLoadError::Io(err) } } impl From<toml::de::Error> for PluginLoadError { fn from(err: toml::de::Error) -> PluginLoadError { PluginLoadError::Parse(err) } }
{ eprintln!("Duplicate plugin name.\n 1: {:?}\n 2: {:?}", plugin, items.get(&plugin.name)); continue }
conditional_block
lib.rs
//! The command-line tool works in the following order:
//! //! 1. [`RemoteMounts::load`](struct.RemoteMounts.html#method.load) is called to load the contents //! of `/etc/mtab` into an internal struct. //! 2. [`RemoteMounts::into_current_dir`](struct.RemoteMounts.html#method.into_current_dir) is //! called to convert the above into a [`Location`](enum.Location.html). //! 3. [`Location::into_env_args`](enum.Location.html#method.into_env_args) is called to convert the //! above into [`ProgramArgs`](struct.ProgramArgs.html). //! 3. [`ProgramArgs::into_command`](struct.ProgramArgs.html#method.into_command) is called to //! convert the above into //! [`std::process::Command`](https://doc.rust-lang.org/nightly/std/process/struct.Command.html). //! //! For `rpwd`, only steps 1 and 2 are run, and the resulting `Location` is printed. mod location; mod program_args; mod remote_location; mod remote_mounts; pub use location::*; pub use program_args::*; pub use remote_location::*; pub use remote_mounts::*;
random_line_split
mod.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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
pub mod frame; pub mod content; pub mod navigation; pub mod menu; pub mod search; pub mod input; pub mod event; pub mod readline; pub mod color; pub mod printer; pub mod highlighter; pub mod rendered_line;
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
random_line_split
associated-const-ambiguity-report.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. trait Foo { const ID: i32; } trait Bar { const ID: i32; } impl Foo for i32 { const ID: i32 = 1; } impl Bar for i32 { const ID: i32 = 3; } const X: i32 = <i32>::ID; //~ ERROR E0034 fn main()
{ assert_eq!(1, X); }
identifier_body
associated-const-ambiguity-report.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. trait Foo { const ID: i32; } trait Bar { const ID: i32; } impl Foo for i32 { const ID: i32 = 1; } impl Bar for i32 { const ID: i32 = 3; } const X: i32 = <i32>::ID; //~ ERROR E0034 fn
() { assert_eq!(1, X); }
main
identifier_name
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct Demon { pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h: i32, }
pub fn new(x: i32, y: i32) -> Demon { Demon { x: x - 12, y: y - 12, vx: 0, vy: 0, moving_to_center: false, w: 24, h: 24, dead: false, active: false, } } pub fn update(&mut self, world: &World, player_x: i32, player_y: i32, player_w: i32, player_h: i32) -> bool { if self.dead { return false; } if world.colliding(self.x, self.y, self.w, self.h) { self.dead = true; return false; } if intersect_rect(self.x, self.y, self.w, self.h, player_x, player_y, player_w, player_h) { return true; } let my_cx = self.x + self.w / 2; let my_cy = self.y + self.h / 2; if self.moving_to_center { let (cx, cy) = world.get_tile_center(self.x, self.y, self.w, self.h); self.vx = if my_cx > cx { -1 } else { 1 }; self.vy = if my_cy > cy { -1 } else { 1 }; if abs(cx - my_cx) < 4 && abs(cy - my_cy) < 4 { self.moving_to_center = false; } } else { let p_cx = player_x + player_w / 2; let p_cy = player_h + player_h / 2; if abs(my_cx - p_cx) < 3 * TILE_SIZE / 2 && abs(my_cy - p_cy) < 3 * TILE_SIZE / 2 { self.vx = if my_cx > p_cx { -1 } else { 1 }; self.vy = if my_cy > p_cy { -1 } else { 1 }; } else { match world.get_demon_policy(self.x + self.w / 2, self.y + self.h / 2) { Some(a) => { let (sx, sy) = a.get_shift(); self.vx = sx; self.vy = sy; self.active = true; }, None => { self.vx = 0; self.vy = 0; } } } } let (nx, ny) = world.checked_move(self.x, self.y, self.w, self.h, self.vx, self.vy, true); if nx == self.x && ny == self.y && (self.vx!= 0 || self.vy!= 0) { // Stuck, move to tile center and try again self.moving_to_center = true; } else { self.x = nx; self.y = ny; } false } pub fn draw(&self, gfx: &Gfx, core: &Core, world: &World, camera: &Camera) { if self.dead { return; } if!self.active { return; } let x = self.x - camera.x; let y = self.y - camera.y; let l = world.get_light(self.x + self.w / 2, self.y + self.h / 2); gfx.fun.draw_tinted(core, x, y, core.map_rgb_f(l, l, l)); gfx.fun_hi.draw(core, x, y); } }
impl Demon {
random_line_split
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct
{ pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h: i32, } impl Demon { pub fn new(x: i32, y: i32) -> Demon { Demon { x: x - 12, y: y - 12, vx: 0, vy: 0, moving_to_center: false, w: 24, h: 24, dead: false, active: false, } } pub fn update(&mut self, world: &World, player_x: i32, player_y: i32, player_w: i32, player_h: i32) -> bool { if self.dead { return false; } if world.colliding(self.x, self.y, self.w, self.h) { self.dead = true; return false; } if intersect_rect(self.x, self.y, self.w, self.h, player_x, player_y, player_w, player_h) { return true; } let my_cx = self.x + self.w / 2; let my_cy = self.y + self.h / 2; if self.moving_to_center { let (cx, cy) = world.get_tile_center(self.x, self.y, self.w, self.h); self.vx = if my_cx > cx { -1 } else { 1 }; self.vy = if my_cy > cy { -1 } else { 1 }; if abs(cx - my_cx) < 4 && abs(cy - my_cy) < 4 { self.moving_to_center = false; } } else { let p_cx = player_x + player_w / 2; let p_cy = player_h + player_h / 2; if abs(my_cx - p_cx) < 3 * TILE_SIZE / 2 && abs(my_cy - p_cy) < 3 * TILE_SIZE / 2 { self.vx = if my_cx > p_cx { -1 } else { 1 }; self.vy = if my_cy > p_cy { -1 } else { 1 }; } else { match world.get_demon_policy(self.x + self.w / 2, self.y + self.h / 2) { Some(a) => { let (sx, sy) = a.get_shift(); self.vx = sx; self.vy = sy; self.active = true; }, None => { self.vx = 0; self.vy = 0; } } } } let (nx, ny) = world.checked_move(self.x, self.y, self.w, self.h, self.vx, self.vy, true); if nx == self.x && ny == self.y && (self.vx!= 0 || self.vy!= 0) { // Stuck, move to tile center and try again self.moving_to_center = true; } else { self.x = nx; self.y = ny; } false } pub fn draw(&self, gfx: &Gfx, core: &Core, world: &World, camera: &Camera) { if self.dead { return; } if!self.active { return; } let x = self.x - camera.x; let y = self.y - camera.y; let l = world.get_light(self.x + self.w / 2, self.y + self.h / 2); gfx.fun.draw_tinted(core, x, y, core.map_rgb_f(l, l, l)); gfx.fun_hi.draw(core, x, y); } }
Demon
identifier_name
fun.rs
use allegro5::*; //~ use std::cmp::{max, min}; use std::num::abs; use world::{World, TILE_SIZE}; use camera::Camera; use util::intersect_rect; use gfx::Gfx; pub struct Demon { pub x: i32, pub y: i32, pub vx: i32, pub vy: i32, pub dead: bool, pub moving_to_center: bool, pub active: bool, pub w: i32, pub h: i32, } impl Demon { pub fn new(x: i32, y: i32) -> Demon { Demon { x: x - 12, y: y - 12, vx: 0, vy: 0, moving_to_center: false, w: 24, h: 24, dead: false, active: false, } } pub fn update(&mut self, world: &World, player_x: i32, player_y: i32, player_w: i32, player_h: i32) -> bool { if self.dead { return false; } if world.colliding(self.x, self.y, self.w, self.h) { self.dead = true; return false; } if intersect_rect(self.x, self.y, self.w, self.h, player_x, player_y, player_w, player_h) { return true; } let my_cx = self.x + self.w / 2; let my_cy = self.y + self.h / 2; if self.moving_to_center { let (cx, cy) = world.get_tile_center(self.x, self.y, self.w, self.h); self.vx = if my_cx > cx { -1 } else { 1 }; self.vy = if my_cy > cy { -1 } else { 1 }; if abs(cx - my_cx) < 4 && abs(cy - my_cy) < 4 { self.moving_to_center = false; } } else { let p_cx = player_x + player_w / 2; let p_cy = player_h + player_h / 2; if abs(my_cx - p_cx) < 3 * TILE_SIZE / 2 && abs(my_cy - p_cy) < 3 * TILE_SIZE / 2 { self.vx = if my_cx > p_cx { -1 } else { 1 }; self.vy = if my_cy > p_cy { -1 } else { 1 }; } else { match world.get_demon_policy(self.x + self.w / 2, self.y + self.h / 2) { Some(a) =>
, None => { self.vx = 0; self.vy = 0; } } } } let (nx, ny) = world.checked_move(self.x, self.y, self.w, self.h, self.vx, self.vy, true); if nx == self.x && ny == self.y && (self.vx!= 0 || self.vy!= 0) { // Stuck, move to tile center and try again self.moving_to_center = true; } else { self.x = nx; self.y = ny; } false } pub fn draw(&self, gfx: &Gfx, core: &Core, world: &World, camera: &Camera) { if self.dead { return; } if!self.active { return; } let x = self.x - camera.x; let y = self.y - camera.y; let l = world.get_light(self.x + self.w / 2, self.y + self.h / 2); gfx.fun.draw_tinted(core, x, y, core.map_rgb_f(l, l, l)); gfx.fun_hi.draw(core, x, y); } }
{ let (sx, sy) = a.get_shift(); self.vx = sx; self.vy = sy; self.active = true; }
conditional_block
variance-cell-is-invariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that Cell is considered invariant with respect to its // type.
use std::cell::Cell; struct Foo<'a> { x: Cell<Option<&'a int>>, } fn use_<'short,'long>(c: Foo<'short>, s: &'short int, l: &'long int, _where:Option<&'short &'long ()>) { let _: Foo<'long> = c; //~ ERROR mismatched types } fn main() { }
random_line_split
variance-cell-is-invariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that Cell is considered invariant with respect to its // type. use std::cell::Cell; struct Foo<'a> { x: Cell<Option<&'a int>>, } fn use_<'short,'long>(c: Foo<'short>, s: &'short int, l: &'long int, _where:Option<&'short &'long ()>) { let _: Foo<'long> = c; //~ ERROR mismatched types } fn
() { }
main
identifier_name
routing_client.rs
// Copyright 2015 MaidSafe.net limited. // // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. use sodiumoxide; use std::sync::mpsc; use std::thread::spawn; use id::Id; use action::Action; use event::Event; use messages::SignedToken; use routing_node::RoutingNode; use NameType; use data::{Data, DataRequest}; use types::Bytes; use error::{RoutingError, ResponseError}; use authority::Authority; use sodiumoxide::crypto; use messages::{ExternalRequest, ExternalResponse, InternalRequest, Content}; type RoutingResult = Result<(), RoutingError>; /// Routing provides an actionable interface to RoutingNode. On constructing a new Routing object a /// RoutingNode will also be started. Routing objects are clonable for multithreading, or a Routing /// object can be cloned with a new set of keys while preserving a single RoutingNode. #[derive(Clone)] pub struct RoutingClient { action_sender: mpsc::Sender<Action>, get_counter: u8, } impl RoutingClient { /// Starts a new RoutingIdentity, which will also start a new RoutingNode. /// The RoutingNode will only bootstrap to the network and not attempt to /// achieve full routing node status. /// If the client is started with a relocated id (ie the name has been reassigned), /// the core will instantely instantiate termination of the client. pub fn new(event_sender: mpsc::Sender<Event>, keys: Option<Id>) -> RoutingClient { sodiumoxide::init(); // enable shared global (i.e. safe to multithread now) let (action_sender, action_receiver) = mpsc::channel::<Action>(); // start the handler for routing with a restriction to become a full node let mut routing_node = RoutingNode::new(action_sender.clone(), action_receiver, event_sender, true, keys); spawn(move || { routing_node.run(); debug!("Routing node terminated running."); }); RoutingClient { action_sender: action_sender, get_counter: 0u8 } } /// Send a Get message with a DataRequest to an Authority, signed with given keys. pub fn get_request(&mut self, location: Authority, data_request: DataRequest) { self.get_counter = self.get_counter.wrapping_add(1); let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest( ExternalRequest::Get(data_request, self.get_counter)))); } /// Add something to the network pub fn put_request(&self, location: Authority, data: Data) { debug!("Received put request from Client for {:?}", data); let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Put(data)))); } /// Change something already on the network pub fn post_request(&self, location: Authority, data: Data) { let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Post(data)))); } /// Remove something from the network pub fn
(&self, location: Authority, data: Data) { let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Delete(data)))); } /// Signal to RoutingNode that it needs to refuse new messages and handle all outstanding /// messages. After handling all messages it will send an Event::Terminated to the user. pub fn stop(&mut self) { let _ = self.action_sender.send(Action::Terminate); } }
delete_request
identifier_name
routing_client.rs
// Copyright 2015 MaidSafe.net limited. // // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. use sodiumoxide; use std::sync::mpsc; use std::thread::spawn; use id::Id; use action::Action; use event::Event; use messages::SignedToken; use routing_node::RoutingNode; use NameType; use data::{Data, DataRequest}; use types::Bytes; use error::{RoutingError, ResponseError}; use authority::Authority; use sodiumoxide::crypto; use messages::{ExternalRequest, ExternalResponse, InternalRequest, Content}; type RoutingResult = Result<(), RoutingError>; /// Routing provides an actionable interface to RoutingNode. On constructing a new Routing object a /// RoutingNode will also be started. Routing objects are clonable for multithreading, or a Routing /// object can be cloned with a new set of keys while preserving a single RoutingNode. #[derive(Clone)] pub struct RoutingClient { action_sender: mpsc::Sender<Action>, get_counter: u8, } impl RoutingClient { /// Starts a new RoutingIdentity, which will also start a new RoutingNode. /// The RoutingNode will only bootstrap to the network and not attempt to /// achieve full routing node status. /// If the client is started with a relocated id (ie the name has been reassigned), /// the core will instantely instantiate termination of the client. pub fn new(event_sender: mpsc::Sender<Event>, keys: Option<Id>) -> RoutingClient { sodiumoxide::init(); // enable shared global (i.e. safe to multithread now) let (action_sender, action_receiver) = mpsc::channel::<Action>(); // start the handler for routing with a restriction to become a full node let mut routing_node = RoutingNode::new(action_sender.clone(), action_receiver, event_sender, true, keys); spawn(move || { routing_node.run(); debug!("Routing node terminated running."); }); RoutingClient { action_sender: action_sender, get_counter: 0u8 } } /// Send a Get message with a DataRequest to an Authority, signed with given keys. pub fn get_request(&mut self, location: Authority, data_request: DataRequest) { self.get_counter = self.get_counter.wrapping_add(1); let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest( ExternalRequest::Get(data_request, self.get_counter)))); } /// Add something to the network pub fn put_request(&self, location: Authority, data: Data) { debug!("Received put request from Client for {:?}", data); let _ = self.action_sender.send(Action::ClientSendContent( location,
let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Post(data)))); } /// Remove something from the network pub fn delete_request(&self, location: Authority, data: Data) { let _ = self.action_sender.send(Action::ClientSendContent( location, Content::ExternalRequest(ExternalRequest::Delete(data)))); } /// Signal to RoutingNode that it needs to refuse new messages and handle all outstanding /// messages. After handling all messages it will send an Event::Terminated to the user. pub fn stop(&mut self) { let _ = self.action_sender.send(Action::Terminate); } }
Content::ExternalRequest(ExternalRequest::Put(data)))); } /// Change something already on the network pub fn post_request(&self, location: Authority, data: Data) {
random_line_split
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used to show current CPU consumptiong pub struct Cpu { attr: Attributes, cpu_data: CpuData, render: Option<Box<dyn Fn(u64) -> String>>, } impl Cpu { /// Creates a new [`Cpu`] widget. /// /// Arguments /// /// * `attr` - Represents `Attributes` which controls properties like /// `Font`, foreground and background color etc. /// /// * `render` - We use the closure to control the way output is /// displayed in the bar. `u64` represents the current CPU usage /// in percentage. /// /// # Examples /// /// ``` /// # #[macro_use] /// # extern crate cnx; /// # /// # use cnx::*; /// # use cnx::text::*; /// # use cnx_contrib::widgets::cpu::*; /// # use anyhow::Result; /// # /// # fn run() -> Result<()> { /// let attr = Attributes { /// font: Font::new("SourceCodePro 21"), /// fg_color: Color::white(), /// bg_color: None, /// padding: Padding::new(8.0, 8.0, 0.0, 0.0), /// }; /// /// let mut cnx = Cnx::new(Position::Top); /// cnx.add_widget(Cpu::new(attr, None)?); /// # Ok(()) /// # } /// # fn main() { run().unwrap(); } /// ``` pub fn new(attr: Attributes, render: Option<Box<dyn Fn(u64) -> String>>) -> Result<Self> { let cpu_data = CpuData::get_values()?; Ok(Cpu { attr, cpu_data, render, }) } fn tick(&mut self) -> Result<Vec<Text>> { let cpu_data = CpuData::get_values()?; // https://github.com/jaor/xmobar/blob/61d075d3c275366c3344d59c058d7dd0baf21ef2/src/Xmobar/Plugins/Monitors/Cpu.hs#L128 let previous = &self.cpu_data; let current = cpu_data; let diff_total = (current.user_time - previous.user_time) + (current.nice_time - previous.nice_time) + (current.system_time - previous.system_time) + (current.idle_time - previous.idle_time) + (current.iowait_time - previous.iowait_time) + (current.total_time - previous.total_time); let percentage = match diff_total { 0 => 0.0, _ => (current.total_time - previous.total_time) as f64 / diff_total as f64, }; let cpu_usage = (percentage * 100.0) as u64; let text = self .render .as_ref() .map_or(format!("{} %", cpu_usage), |x| (x)(cpu_usage)); self.cpu_data = current; let texts = vec![Text { attr: self.attr.clone(), text, stretch: false, markup: true, }]; Ok(texts) } } struct CpuData { user_time: i64, nice_time: i64, system_time: i64, idle_time: i64, total_time: i64, iowait_time: i64, } impl CpuData { fn get_values() -> Result<CpuData> { // https://www.kernel.org/doc/Documentation/filesystems/proc.txt let file = File::open("/proc/stat")?; let mut cpu_line = String::new(); let mut reader = BufReader::new(file); reader.read_line(&mut cpu_line)?; let val: Vec<&str> = cpu_line .split(' ') .filter(|item| item!= &"cpu" &&!item.is_empty()) .collect(); let mut cpu_data = CpuData { user_time: 0, nice_time: 0, system_time: 0, idle_time: 0, total_time: 0, iowait_time: 0, }; match val[..] { [ref user, ref nice, ref system, ref idle, ref iowait,..] =>
_ => return Err(anyhow!("Missing data in /proc/stat")), } Ok(cpu_data) } } impl Widget for Cpu { fn into_stream(mut self: Box<Self>) -> Result<WidgetStream> { let ten_seconds = Duration::from_secs(10); let interval = time::interval(ten_seconds); let stream = IntervalStream::new(interval).map(move |_| self.tick()); Ok(Box::pin(stream)) } }
{ let user_time = user.parse()?; let nice_time = nice.parse()?; let system_time = system.parse()?; let idle_time = idle.parse()?; let iowait_time = iowait.parse()?; cpu_data.user_time = user_time; cpu_data.nice_time = nice_time; cpu_data.system_time = system_time; cpu_data.idle_time = idle_time; cpu_data.iowait_time = iowait_time; cpu_data.total_time = user_time + nice_time + system_time; }
conditional_block
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used to show current CPU consumptiong pub struct Cpu { attr: Attributes, cpu_data: CpuData, render: Option<Box<dyn Fn(u64) -> String>>, } impl Cpu { /// Creates a new [`Cpu`] widget. /// /// Arguments /// /// * `attr` - Represents `Attributes` which controls properties like /// `Font`, foreground and background color etc. /// /// * `render` - We use the closure to control the way output is /// displayed in the bar. `u64` represents the current CPU usage /// in percentage. /// /// # Examples /// /// ``` /// # #[macro_use] /// # extern crate cnx; /// # /// # use cnx::*; /// # use cnx::text::*; /// # use cnx_contrib::widgets::cpu::*; /// # use anyhow::Result; /// # /// # fn run() -> Result<()> { /// let attr = Attributes { /// font: Font::new("SourceCodePro 21"), /// fg_color: Color::white(), /// bg_color: None, /// padding: Padding::new(8.0, 8.0, 0.0, 0.0), /// }; /// /// let mut cnx = Cnx::new(Position::Top); /// cnx.add_widget(Cpu::new(attr, None)?); /// # Ok(()) /// # } /// # fn main() { run().unwrap(); } /// ``` pub fn new(attr: Attributes, render: Option<Box<dyn Fn(u64) -> String>>) -> Result<Self> { let cpu_data = CpuData::get_values()?; Ok(Cpu { attr, cpu_data, render, }) } fn tick(&mut self) -> Result<Vec<Text>> { let cpu_data = CpuData::get_values()?; // https://github.com/jaor/xmobar/blob/61d075d3c275366c3344d59c058d7dd0baf21ef2/src/Xmobar/Plugins/Monitors/Cpu.hs#L128 let previous = &self.cpu_data; let current = cpu_data; let diff_total = (current.user_time - previous.user_time) + (current.nice_time - previous.nice_time) + (current.system_time - previous.system_time) + (current.idle_time - previous.idle_time) + (current.iowait_time - previous.iowait_time) + (current.total_time - previous.total_time); let percentage = match diff_total { 0 => 0.0, _ => (current.total_time - previous.total_time) as f64 / diff_total as f64, }; let cpu_usage = (percentage * 100.0) as u64; let text = self .render .as_ref() .map_or(format!("{} %", cpu_usage), |x| (x)(cpu_usage)); self.cpu_data = current; let texts = vec![Text { attr: self.attr.clone(), text, stretch: false, markup: true, }]; Ok(texts) } } struct CpuData { user_time: i64, nice_time: i64, system_time: i64, idle_time: i64, total_time: i64, iowait_time: i64, } impl CpuData { fn get_values() -> Result<CpuData> { // https://www.kernel.org/doc/Documentation/filesystems/proc.txt let file = File::open("/proc/stat")?; let mut cpu_line = String::new(); let mut reader = BufReader::new(file); reader.read_line(&mut cpu_line)?; let val: Vec<&str> = cpu_line .split(' ') .filter(|item| item!= &"cpu" &&!item.is_empty()) .collect(); let mut cpu_data = CpuData { user_time: 0, nice_time: 0, system_time: 0, idle_time: 0, total_time: 0, iowait_time: 0, }; match val[..] { [ref user, ref nice, ref system, ref idle, ref iowait,..] => { let user_time = user.parse()?; let nice_time = nice.parse()?; let system_time = system.parse()?; let idle_time = idle.parse()?; let iowait_time = iowait.parse()?; cpu_data.user_time = user_time; cpu_data.nice_time = nice_time; cpu_data.system_time = system_time; cpu_data.idle_time = idle_time; cpu_data.iowait_time = iowait_time; cpu_data.total_time = user_time + nice_time + system_time; } _ => return Err(anyhow!("Missing data in /proc/stat")), } Ok(cpu_data) } } impl Widget for Cpu { fn
(mut self: Box<Self>) -> Result<WidgetStream> { let ten_seconds = Duration::from_secs(10); let interval = time::interval(ten_seconds); let stream = IntervalStream::new(interval).map(move |_| self.tick()); Ok(Box::pin(stream)) } }
into_stream
identifier_name
cpu.rs
use anyhow::{anyhow, Result}; use cnx::text::{Attributes, Text}; use cnx::widgets::{Widget, WidgetStream}; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::time::Duration; use tokio::time; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; /// Represents CPU widget used to show current CPU consumptiong pub struct Cpu { attr: Attributes, cpu_data: CpuData, render: Option<Box<dyn Fn(u64) -> String>>, } impl Cpu { /// Creates a new [`Cpu`] widget. /// /// Arguments /// /// * `attr` - Represents `Attributes` which controls properties like /// `Font`, foreground and background color etc. /// /// * `render` - We use the closure to control the way output is /// displayed in the bar. `u64` represents the current CPU usage /// in percentage. /// /// # Examples /// /// ``` /// # #[macro_use] /// # extern crate cnx; /// # /// # use cnx::*; /// # use cnx::text::*; /// # use cnx_contrib::widgets::cpu::*; /// # use anyhow::Result; /// # /// # fn run() -> Result<()> { /// let attr = Attributes { /// font: Font::new("SourceCodePro 21"), /// fg_color: Color::white(), /// bg_color: None, /// padding: Padding::new(8.0, 8.0, 0.0, 0.0), /// }; /// /// let mut cnx = Cnx::new(Position::Top); /// cnx.add_widget(Cpu::new(attr, None)?); /// # Ok(()) /// # } /// # fn main() { run().unwrap(); } /// ``` pub fn new(attr: Attributes, render: Option<Box<dyn Fn(u64) -> String>>) -> Result<Self> { let cpu_data = CpuData::get_values()?; Ok(Cpu { attr, cpu_data, render, }) } fn tick(&mut self) -> Result<Vec<Text>> { let cpu_data = CpuData::get_values()?; // https://github.com/jaor/xmobar/blob/61d075d3c275366c3344d59c058d7dd0baf21ef2/src/Xmobar/Plugins/Monitors/Cpu.hs#L128 let previous = &self.cpu_data; let current = cpu_data; let diff_total = (current.user_time - previous.user_time) + (current.nice_time - previous.nice_time) + (current.system_time - previous.system_time) + (current.idle_time - previous.idle_time) + (current.iowait_time - previous.iowait_time) + (current.total_time - previous.total_time); let percentage = match diff_total { 0 => 0.0, _ => (current.total_time - previous.total_time) as f64 / diff_total as f64, }; let cpu_usage = (percentage * 100.0) as u64; let text = self .render .as_ref() .map_or(format!("{} %", cpu_usage), |x| (x)(cpu_usage)); self.cpu_data = current; let texts = vec![Text { attr: self.attr.clone(), text, stretch: false, markup: true, }]; Ok(texts) } } struct CpuData { user_time: i64, nice_time: i64, system_time: i64, idle_time: i64, total_time: i64, iowait_time: i64, } impl CpuData { fn get_values() -> Result<CpuData> { // https://www.kernel.org/doc/Documentation/filesystems/proc.txt let file = File::open("/proc/stat")?; let mut cpu_line = String::new(); let mut reader = BufReader::new(file); reader.read_line(&mut cpu_line)?; let val: Vec<&str> = cpu_line .split(' ') .filter(|item| item!= &"cpu" &&!item.is_empty()) .collect(); let mut cpu_data = CpuData { user_time: 0, nice_time: 0, system_time: 0, idle_time: 0, total_time: 0, iowait_time: 0, }; match val[..] { [ref user, ref nice, ref system, ref idle, ref iowait,..] => { let user_time = user.parse()?; let nice_time = nice.parse()?; let system_time = system.parse()?;
cpu_data.user_time = user_time; cpu_data.nice_time = nice_time; cpu_data.system_time = system_time; cpu_data.idle_time = idle_time; cpu_data.iowait_time = iowait_time; cpu_data.total_time = user_time + nice_time + system_time; } _ => return Err(anyhow!("Missing data in /proc/stat")), } Ok(cpu_data) } } impl Widget for Cpu { fn into_stream(mut self: Box<Self>) -> Result<WidgetStream> { let ten_seconds = Duration::from_secs(10); let interval = time::interval(ten_seconds); let stream = IntervalStream::new(interval).map(move |_| self.tick()); Ok(Box::pin(stream)) } }
let idle_time = idle.parse()?; let iowait_time = iowait.parse()?;
random_line_split
geometry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel." /// /// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi /// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be /// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals /// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels. /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. #[derive(Debug, Copy, Clone)] pub enum
{} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum PagePx {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => ScreenPx // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)] pub struct Au(pub i32); impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } } pub static ZERO_POINT: Point2D<Au> = Point2D { x: Au(0), y: Au(0), }; pub static ZERO_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(0), y: Au(0), }, size: Size2D { width: Au(0), height: Au(0), } }; pub static MAX_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(i32::MIN / 2), y: Au(i32::MIN / 2), }, size: Size2D { width: MAX_AU, height: MAX_AU, } }; pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); impl Encodable for Au { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(self.to_f64_px()) } } impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}px", self.to_f64_px()) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0.wrapping_sub(other.0)) } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { Au(self.0.wrapping_mul(other)) } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) } #[inline] pub fn from_px(px: i32) -> Au { Au((px * 60) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * 60f32) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32 { self.0 / 60 } /// Rounds this app unit down to the previous (left or top) pixel and returns it. #[inline] pub fn to_prev_px(self) -> i32 { ((self.0 as f64) / 60f64).floor() as i32 } /// Rounds this app unit up to the next (right or bottom) pixel and returns it. #[inline] pub fn to_next_px(self) -> i32 { ((self.0 as f64) / 60f64).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / 60f64).round() as i32 } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / 60f32 } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / 60f64 } #[inline] pub fn to_snapped(self) -> Au { let res = self.0 % 60i32; return if res >= 30i32 { return Au(self.0 - res + 60i32) } else { return Au(self.0 - res) }; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * 60f32) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * 60.) as i32) } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_f32_rect(rect: Rect<Au>) -> Rect<f32> { Rect::new(Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()), Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px())) }
ScreenPx
identifier_name
geometry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel." /// /// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi /// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be /// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals /// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels. /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. #[derive(Debug, Copy, Clone)] pub enum ScreenPx {} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum PagePx {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => ScreenPx // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)] pub struct Au(pub i32); impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } } pub static ZERO_POINT: Point2D<Au> = Point2D { x: Au(0), y: Au(0), }; pub static ZERO_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(0), y: Au(0), }, size: Size2D { width: Au(0), height: Au(0), } }; pub static MAX_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(i32::MIN / 2), y: Au(i32::MIN / 2), }, size: Size2D { width: MAX_AU, height: MAX_AU, } }; pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); impl Encodable for Au { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(self.to_f64_px()) } } impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}px", self.to_f64_px()) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0.wrapping_sub(other.0)) } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { Au(self.0.wrapping_mul(other)) } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline]
#[inline] pub fn from_px(px: i32) -> Au { Au((px * 60) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * 60f32) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32 { self.0 / 60 } /// Rounds this app unit down to the previous (left or top) pixel and returns it. #[inline] pub fn to_prev_px(self) -> i32 { ((self.0 as f64) / 60f64).floor() as i32 } /// Rounds this app unit up to the next (right or bottom) pixel and returns it. #[inline] pub fn to_next_px(self) -> i32 { ((self.0 as f64) / 60f64).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / 60f64).round() as i32 } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / 60f32 } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / 60f64 } #[inline] pub fn to_snapped(self) -> Au { let res = self.0 % 60i32; return if res >= 30i32 { return Au(self.0 - res + 60i32) } else { return Au(self.0 - res) }; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * 60f32) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * 60.) as i32) } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_f32_rect(rect: Rect<Au>) -> Rect<f32> { Rect::new(Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()), Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px())) }
pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) }
random_line_split
geometry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel." /// /// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi /// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be /// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals /// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels. /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. #[derive(Debug, Copy, Clone)] pub enum ScreenPx {} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum PagePx {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => ScreenPx // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)] pub struct Au(pub i32); impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } } pub static ZERO_POINT: Point2D<Au> = Point2D { x: Au(0), y: Au(0), }; pub static ZERO_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(0), y: Au(0), }, size: Size2D { width: Au(0), height: Au(0), } }; pub static MAX_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(i32::MIN / 2), y: Au(i32::MIN / 2), }, size: Size2D { width: MAX_AU, height: MAX_AU, } }; pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); impl Encodable for Au { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(self.to_f64_px()) } } impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0.wrapping_sub(other.0)) } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { Au(self.0.wrapping_mul(other)) } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) } #[inline] pub fn from_px(px: i32) -> Au { Au((px * 60) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * 60f32) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32 { self.0 / 60 } /// Rounds this app unit down to the previous (left or top) pixel and returns it. #[inline] pub fn to_prev_px(self) -> i32 { ((self.0 as f64) / 60f64).floor() as i32 } /// Rounds this app unit up to the next (right or bottom) pixel and returns it. #[inline] pub fn to_next_px(self) -> i32 { ((self.0 as f64) / 60f64).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / 60f64).round() as i32 } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / 60f32 } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / 60f64 } #[inline] pub fn to_snapped(self) -> Au { let res = self.0 % 60i32; return if res >= 30i32 { return Au(self.0 - res + 60i32) } else { return Au(self.0 - res) }; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * 60f32) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * 60.) as i32) } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_f32_rect(rect: Rect<Au>) -> Rect<f32> { Rect::new(Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()), Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px())) }
{ write!(f, "{}px", self.to_f64_px()) }
identifier_body
geometry.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use euclid::length::Length; use euclid::num::Zero; use euclid::point::Point2D; use euclid::rect::Rect; use euclid::size::Size2D; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, Sub, Neg, Mul, Div, Rem}; use rustc_serialize::{Encoder, Encodable}; // Units for use with euclid::length and euclid::scale_factor. /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel." /// /// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi /// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be /// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals /// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels. /// /// The ratio between ScreenPx and DevicePixel for a given display be found by calling /// `servo::windowing::WindowMethods::hidpi_factor`. #[derive(Debug, Copy, Clone)] pub enum ScreenPx {} /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(RustcEncodable, Debug, Copy, Clone)] pub enum PagePx {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => ScreenPx // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx // An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was // originally proposed in 2002 as a standard unit of measure in Gecko. // See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info. // // FIXME: Implement Au using Length and ScaleFactor instead of a custom type. #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord, Deserialize, Serialize)] pub struct Au(pub i32); impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } } pub static ZERO_POINT: Point2D<Au> = Point2D { x: Au(0), y: Au(0), }; pub static ZERO_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(0), y: Au(0), }, size: Size2D { width: Au(0), height: Au(0), } }; pub static MAX_RECT: Rect<Au> = Rect { origin: Point2D { x: Au(i32::MIN / 2), y: Au(i32::MIN / 2), }, size: Size2D { width: MAX_AU, height: MAX_AU, } }; pub const MIN_AU: Au = Au(i32::MIN); pub const MAX_AU: Au = Au(i32::MAX); impl Encodable for Au { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_f64(self.to_f64_px()) } } impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}px", self.to_f64_px()) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0.wrapping_add(other.0)) } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0.wrapping_sub(other.0)) } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { Au(self.0.wrapping_mul(other)) } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value) } #[inline] pub fn scale_by(self, factor: f32) -> Au { Au(((self.0 as f32) * factor) as i32) } #[inline] pub fn from_px(px: i32) -> Au { Au((px * 60) as i32) } #[inline] pub fn from_page_px(px: Length<PagePx, f32>) -> Au { Au((px.get() * 60f32) as i32) } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32 { self.0 / 60 } /// Rounds this app unit down to the previous (left or top) pixel and returns it. #[inline] pub fn to_prev_px(self) -> i32 { ((self.0 as f64) / 60f64).floor() as i32 } /// Rounds this app unit up to the next (right or bottom) pixel and returns it. #[inline] pub fn to_next_px(self) -> i32 { ((self.0 as f64) / 60f64).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / 60f64).round() as i32 } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / 60f32 } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / 60f64 } #[inline] pub fn to_snapped(self) -> Au { let res = self.0 % 60i32; return if res >= 30i32 { return Au(self.0 - res + 60i32) } else
; } #[inline] pub fn from_f32_px(px: f32) -> Au { Au((px * 60f32) as i32) } #[inline] pub fn from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } #[inline] pub fn from_f64_px(px: f64) -> Au { Au((px * 60.) as i32) } } // assumes 72 points per inch, and 96 px per inch pub fn pt_to_px(pt: f64) -> f64 { pt / 72. * 96. } // assumes 72 points per inch, and 96 px per inch pub fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } /// Returns true if the rect contains the given point. Points on the top or left sides of the rect /// are considered inside the rectangle, while points on the right or bottom sides of the rect are /// not considered inside the rectangle. pub fn rect_contains_point<T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool { point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width && point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height } /// A helper function to convert a rect of `f32` pixels to a rect of app units. pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> { Rect::new(Point2D::new(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)), Size2D::new(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height))) } /// A helper function to convert a rect of `Au` pixels to a rect of f32 units. pub fn au_rect_to_f32_rect(rect: Rect<Au>) -> Rect<f32> { Rect::new(Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()), Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px())) }
{ return Au(self.0 - res) }
conditional_block
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v: &T, w: &T) -> Ordering { (*self)(v, w) } } pub fn insertion_sort<T: PartialOrd, C: Comparator<T>>(a: &mut [T], comparator: C) { let n = a.len(); for i in 0.. n { for j in (1.. i + 1).rev() { if comparator.less(&a[j], &a[j-1]) { a.swap(j, j-1); } } } } #[test] fn test_insertion_sort_using_a_comparator()
{ use rand::{thread_rng, Rng}; fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool { for i in 1 .. a.len() { if a[i] > a[i-1] { return false; } } true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME: due to https://github.com/rust-lang/rust/issues/24680 // the Comparator closure's type can't be inferred! insertion_sort(&mut array, |v: &u32, w: &u32| w.cmp(v) ); assert!(is_reverse_sorted(&array)); }
identifier_body
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v: &T, w: &T) -> Ordering { (*self)(v, w) } } pub fn insertion_sort<T: PartialOrd, C: Comparator<T>>(a: &mut [T], comparator: C) { let n = a.len(); for i in 0.. n { for j in (1.. i + 1).rev() { if comparator.less(&a[j], &a[j-1]) { a.swap(j, j-1); } } } }
use rand::{thread_rng, Rng}; fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool { for i in 1.. a.len() { if a[i] > a[i-1] { return false; } } true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME: due to https://github.com/rust-lang/rust/issues/24680 // the Comparator closure's type can't be inferred! insertion_sort(&mut array, |v: &u32, w: &u32| w.cmp(v) ); assert!(is_reverse_sorted(&array)); }
#[test] fn test_insertion_sort_using_a_comparator() {
random_line_split
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v: &T, w: &T) -> Ordering { (*self)(v, w) } } pub fn insertion_sort<T: PartialOrd, C: Comparator<T>>(a: &mut [T], comparator: C) { let n = a.len(); for i in 0.. n { for j in (1.. i + 1).rev() { if comparator.less(&a[j], &a[j-1]) { a.swap(j, j-1); } } } } #[test] fn test_insertion_sort_using_a_comparator() { use rand::{thread_rng, Rng}; fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool { for i in 1.. a.len() { if a[i] > a[i-1]
} true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME: due to https://github.com/rust-lang/rust/issues/24680 // the Comparator closure's type can't be inferred! insertion_sort(&mut array, |v: &u32, w: &u32| w.cmp(v) ); assert!(is_reverse_sorted(&array)); }
{ return false; }
conditional_block
comparator.rs
// rust way of ord use std::cmp::Ordering; pub trait Comparator<T> { fn compare(&self, v: &T, w: &T) -> Ordering; fn less(&self, v: &T, w: &T) -> bool { self.compare(v, w) == Ordering::Less } } impl<T, F> Comparator<T> for F where F: Send + Sync + Fn(&T, &T) -> Ordering { fn compare(&self, v: &T, w: &T) -> Ordering { (*self)(v, w) } } pub fn
<T: PartialOrd, C: Comparator<T>>(a: &mut [T], comparator: C) { let n = a.len(); for i in 0.. n { for j in (1.. i + 1).rev() { if comparator.less(&a[j], &a[j-1]) { a.swap(j, j-1); } } } } #[test] fn test_insertion_sort_using_a_comparator() { use rand::{thread_rng, Rng}; fn is_reverse_sorted<T: PartialOrd>(a: &[T]) -> bool { for i in 1.. a.len() { if a[i] > a[i-1] { return false; } } true } let mut array = thread_rng().gen_iter().take(10).collect::<Vec<u32>>(); // FIXME: due to https://github.com/rust-lang/rust/issues/24680 // the Comparator closure's type can't be inferred! insertion_sort(&mut array, |v: &u32, w: &u32| w.cmp(v) ); assert!(is_reverse_sorted(&array)); }
insertion_sort
identifier_name
flags.rs
mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4))); mat!(match_flag_case_dotnl_toggle_not, "(?is)a.(?-is)a.", "A\na\n", None); mat!(match_flag_case_dotnl_toggle_ok, "(?is)a.(?-is:a.)?", "A\na\n", Some((0, 2)));
mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2)));
mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11)));
random_line_split
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_syntax::parse_executable; use graphql_text_printer::print_full_operation; use relay_test_schema::TEST_SCHEMA; use std::sync::Arc; pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String>
.map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
{ let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&TEST_SCHEMA), ir); build(&TEST_SCHEMA, &ast.definitions) .map(|definitions| { definitions .into_iter() .filter_map(|definition| { if let ExecutableDefinition::Operation(operation) = definition { Some(print_full_operation(&program, &operation)) } else { None } }) .collect::<Vec<String>>() .join("\n\n\n\n") })
identifier_body
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_syntax::parse_executable; use graphql_text_printer::print_full_operation; use relay_test_schema::TEST_SCHEMA; use std::sync::Arc; pub fn
(fixture: &Fixture<'_>) -> Result<String, String> { let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&TEST_SCHEMA), ir); build(&TEST_SCHEMA, &ast.definitions) .map(|definitions| { definitions .into_iter() .filter_map(|definition| { if let ExecutableDefinition::Operation(operation) = definition { Some(print_full_operation(&program, &operation)) } else { None } }) .collect::<Vec<String>>() .join("\n\n\n\n") }) .map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
transform_fixture
identifier_name
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_syntax::parse_executable; use graphql_text_printer::print_full_operation; use relay_test_schema::TEST_SCHEMA; use std::sync::Arc; pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> { let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&TEST_SCHEMA), ir); build(&TEST_SCHEMA, &ast.definitions) .map(|definitions| { definitions .into_iter() .filter_map(|definition| { if let ExecutableDefinition::Operation(operation) = definition { Some(print_full_operation(&program, &operation)) } else { None
.join("\n\n\n\n") }) .map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
} }) .collect::<Vec<String>>()
random_line_split
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, ExecutableDefinition, Program}; use graphql_syntax::parse_executable; use graphql_text_printer::print_full_operation; use relay_test_schema::TEST_SCHEMA; use std::sync::Arc; pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> { let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(fixture.content, source_location).unwrap(); let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap(); let program = Program::from_definitions(Arc::clone(&TEST_SCHEMA), ir); build(&TEST_SCHEMA, &ast.definitions) .map(|definitions| { definitions .into_iter() .filter_map(|definition| { if let ExecutableDefinition::Operation(operation) = definition { Some(print_full_operation(&program, &operation)) } else
}) .collect::<Vec<String>>() .join("\n\n\n\n") }) .map_err(|errors| { errors .into_iter() .map(|error| format!("{:?}", error)) .collect::<Vec<_>>() .join("\n\n") }) }
{ None }
conditional_block
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // srttool 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 // along with srttool. If not, see <http://www.gnu.org/licenses/>. // //! reads and writes srt subtitles #![deny(unsafe_code)] #![deny(trivial_casts, trivial_numeric_casts)] #![deny(missing_docs, missing_debug_implementations, missing_copy_implementations)] #![deny(unused_extern_crates, unused_import_braces, unused_qualifications)] use std::error::Error; use std::fmt::{self, Display}; use std::io::{Lines, BufRead}; use std::str::FromStr; use std::time::Duration; use std::ops::{Add, Sub}; pub use self::error::ParseError; pub use self::time::{Time, StartEnd}; mod error; mod time; /// single subtitle block #[derive(Debug, Clone)] pub struct Block { /// start and end time of the block pub start_end: StartEnd, /// text content pub content: String, } impl Add<StartEnd> for Block { type Output = Block; fn add(self, rhs: StartEnd) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Add<Time> for Block { type Output = Block; fn add(self, rhs: Time) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Add<Duration> for Block { type Output = Block; fn add(self, rhs: Duration) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Sub<StartEnd> for Block { type Output = Block; fn sub(self, rhs: StartEnd) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Sub<Time> for Block { type Output = Block; fn sub(self, rhs: Time) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Sub<Duration> for Block { type Output = Block; fn sub(self, rhs: Duration) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Display for Block { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}\n{}\n", self.start_end, self.content) } } /// a BlockReader pub struct BlockReader<B> { buf: Lines<B>, /// last line read line: u64, } impl<B> BlockReader<B> { /// returns the line number of the last line readed pub fn line(&self) -> u64 { self.line } } impl<B> fmt::Debug for BlockReader<B> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Reader at line {}", self.line) } } impl<B: BufRead> BlockReader<B> { /// Create a BlockReader with `buf` pub fn new(buf: B) -> BlockReader<B> { BlockReader { buf: buf.lines(), line: 0, } } } impl<B: BufRead> Iterator for BlockReader<B> { type Item = Result<Block, ParseError>; /// next returns the next subtitle Block or None at EOF fn next(&mut self) -> Option<Result<Block, ParseError>> { // idx if let Some(Ok(idx)) = self.buf.next() { self.line += 1; if idx == "" { return None; //File ends with final new line } else if!is_idx(&idx) { return Some(Err(ParseError::InvalidIndex)); } } else { return None; // File ends without final newline } let time = if let Some(Ok(tl)) = self.buf.next() { self.line += 1; match StartEnd::from_str(&tl) { Ok(time) => time, Err(e) => return Some(Err(e)), } } else
; let mut content = String::with_capacity(128); while let Some(text) = self.buf.next() { self.line += 1; match text { Ok(text) => { if text == "" { break; } content = content + &text + "\n"; } Err(_) => { return Some(Err(ParseError::InvalidContent)); } } } return Some(Ok(Block { start_end: time, content: content, })); } } fn is_idx(s: &str) -> bool { match s.parse::<u64>() { Ok(_) => true, Err(_) => false, } }
{ return Some(Err(ParseError::InvalidTimeString)); }
conditional_block
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // srttool 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 // along with srttool. If not, see <http://www.gnu.org/licenses/>. // //! reads and writes srt subtitles #![deny(unsafe_code)] #![deny(trivial_casts, trivial_numeric_casts)] #![deny(missing_docs, missing_debug_implementations, missing_copy_implementations)] #![deny(unused_extern_crates, unused_import_braces, unused_qualifications)] use std::error::Error; use std::fmt::{self, Display}; use std::io::{Lines, BufRead}; use std::str::FromStr; use std::time::Duration; use std::ops::{Add, Sub}; pub use self::error::ParseError; pub use self::time::{Time, StartEnd}; mod error; mod time; /// single subtitle block #[derive(Debug, Clone)] pub struct Block { /// start and end time of the block pub start_end: StartEnd, /// text content pub content: String, } impl Add<StartEnd> for Block { type Output = Block; fn add(self, rhs: StartEnd) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Add<Time> for Block { type Output = Block; fn add(self, rhs: Time) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Add<Duration> for Block { type Output = Block; fn add(self, rhs: Duration) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Sub<StartEnd> for Block { type Output = Block; fn sub(self, rhs: StartEnd) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Sub<Time> for Block { type Output = Block; fn sub(self, rhs: Time) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Sub<Duration> for Block { type Output = Block; fn sub(self, rhs: Duration) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Display for Block { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}\n{}\n", self.start_end, self.content) } } /// a BlockReader pub struct BlockReader<B> { buf: Lines<B>, /// last line read line: u64, } impl<B> BlockReader<B> { /// returns the line number of the last line readed pub fn line(&self) -> u64 { self.line } } impl<B> fmt::Debug for BlockReader<B> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Reader at line {}", self.line) } } impl<B: BufRead> BlockReader<B> { /// Create a BlockReader with `buf` pub fn new(buf: B) -> BlockReader<B> { BlockReader { buf: buf.lines(), line: 0, } } } impl<B: BufRead> Iterator for BlockReader<B> { type Item = Result<Block, ParseError>; /// next returns the next subtitle Block or None at EOF fn next(&mut self) -> Option<Result<Block, ParseError>> { // idx if let Some(Ok(idx)) = self.buf.next() { self.line += 1; if idx == "" { return None; //File ends with final new line } else if!is_idx(&idx) { return Some(Err(ParseError::InvalidIndex)); } } else { return None; // File ends without final newline } let time = if let Some(Ok(tl)) = self.buf.next() { self.line += 1; match StartEnd::from_str(&tl) { Ok(time) => time, Err(e) => return Some(Err(e)), } } else { return Some(Err(ParseError::InvalidTimeString)); }; let mut content = String::with_capacity(128); while let Some(text) = self.buf.next() { self.line += 1; match text { Ok(text) => { if text == "" { break; } content = content + &text + "\n"; } Err(_) => { return Some(Err(ParseError::InvalidContent)); } } } return Some(Ok(Block { start_end: time, content: content, })); } } fn is_idx(s: &str) -> bool { match s.parse::<u64>() { Ok(_) => true, Err(_) => false,
} }
random_line_split
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // srttool 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 // along with srttool. If not, see <http://www.gnu.org/licenses/>. // //! reads and writes srt subtitles #![deny(unsafe_code)] #![deny(trivial_casts, trivial_numeric_casts)] #![deny(missing_docs, missing_debug_implementations, missing_copy_implementations)] #![deny(unused_extern_crates, unused_import_braces, unused_qualifications)] use std::error::Error; use std::fmt::{self, Display}; use std::io::{Lines, BufRead}; use std::str::FromStr; use std::time::Duration; use std::ops::{Add, Sub}; pub use self::error::ParseError; pub use self::time::{Time, StartEnd}; mod error; mod time; /// single subtitle block #[derive(Debug, Clone)] pub struct Block { /// start and end time of the block pub start_end: StartEnd, /// text content pub content: String, } impl Add<StartEnd> for Block { type Output = Block; fn add(self, rhs: StartEnd) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Add<Time> for Block { type Output = Block; fn add(self, rhs: Time) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Add<Duration> for Block { type Output = Block; fn add(self, rhs: Duration) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Sub<StartEnd> for Block { type Output = Block; fn sub(self, rhs: StartEnd) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Sub<Time> for Block { type Output = Block; fn sub(self, rhs: Time) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Sub<Duration> for Block { type Output = Block; fn sub(self, rhs: Duration) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Display for Block { fn
(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}\n{}\n", self.start_end, self.content) } } /// a BlockReader pub struct BlockReader<B> { buf: Lines<B>, /// last line read line: u64, } impl<B> BlockReader<B> { /// returns the line number of the last line readed pub fn line(&self) -> u64 { self.line } } impl<B> fmt::Debug for BlockReader<B> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Reader at line {}", self.line) } } impl<B: BufRead> BlockReader<B> { /// Create a BlockReader with `buf` pub fn new(buf: B) -> BlockReader<B> { BlockReader { buf: buf.lines(), line: 0, } } } impl<B: BufRead> Iterator for BlockReader<B> { type Item = Result<Block, ParseError>; /// next returns the next subtitle Block or None at EOF fn next(&mut self) -> Option<Result<Block, ParseError>> { // idx if let Some(Ok(idx)) = self.buf.next() { self.line += 1; if idx == "" { return None; //File ends with final new line } else if!is_idx(&idx) { return Some(Err(ParseError::InvalidIndex)); } } else { return None; // File ends without final newline } let time = if let Some(Ok(tl)) = self.buf.next() { self.line += 1; match StartEnd::from_str(&tl) { Ok(time) => time, Err(e) => return Some(Err(e)), } } else { return Some(Err(ParseError::InvalidTimeString)); }; let mut content = String::with_capacity(128); while let Some(text) = self.buf.next() { self.line += 1; match text { Ok(text) => { if text == "" { break; } content = content + &text + "\n"; } Err(_) => { return Some(Err(ParseError::InvalidContent)); } } } return Some(Ok(Block { start_end: time, content: content, })); } } fn is_idx(s: &str) -> bool { match s.parse::<u64>() { Ok(_) => true, Err(_) => false, } }
fmt
identifier_name
lib.rs
// Copyright 2015 juggle-tux // This file is part of srttool. // // srttool is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // srttool 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 // along with srttool. If not, see <http://www.gnu.org/licenses/>. // //! reads and writes srt subtitles #![deny(unsafe_code)] #![deny(trivial_casts, trivial_numeric_casts)] #![deny(missing_docs, missing_debug_implementations, missing_copy_implementations)] #![deny(unused_extern_crates, unused_import_braces, unused_qualifications)] use std::error::Error; use std::fmt::{self, Display}; use std::io::{Lines, BufRead}; use std::str::FromStr; use std::time::Duration; use std::ops::{Add, Sub}; pub use self::error::ParseError; pub use self::time::{Time, StartEnd}; mod error; mod time; /// single subtitle block #[derive(Debug, Clone)] pub struct Block { /// start and end time of the block pub start_end: StartEnd, /// text content pub content: String, } impl Add<StartEnd> for Block { type Output = Block; fn add(self, rhs: StartEnd) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Add<Time> for Block { type Output = Block; fn add(self, rhs: Time) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Add<Duration> for Block { type Output = Block; fn add(self, rhs: Duration) -> Block { return Block { start_end: self.start_end + rhs, content: self.content, }; } } impl Sub<StartEnd> for Block { type Output = Block; fn sub(self, rhs: StartEnd) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Sub<Time> for Block { type Output = Block; fn sub(self, rhs: Time) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Sub<Duration> for Block { type Output = Block; fn sub(self, rhs: Duration) -> Block { return Block { start_end: self.start_end - rhs, content: self.content, }; } } impl Display for Block { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}\n{}\n", self.start_end, self.content) } } /// a BlockReader pub struct BlockReader<B> { buf: Lines<B>, /// last line read line: u64, } impl<B> BlockReader<B> { /// returns the line number of the last line readed pub fn line(&self) -> u64 { self.line } } impl<B> fmt::Debug for BlockReader<B> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Reader at line {}", self.line) } } impl<B: BufRead> BlockReader<B> { /// Create a BlockReader with `buf` pub fn new(buf: B) -> BlockReader<B> { BlockReader { buf: buf.lines(), line: 0, } } } impl<B: BufRead> Iterator for BlockReader<B> { type Item = Result<Block, ParseError>; /// next returns the next subtitle Block or None at EOF fn next(&mut self) -> Option<Result<Block, ParseError>>
return Some(Err(ParseError::InvalidTimeString)); }; let mut content = String::with_capacity(128); while let Some(text) = self.buf.next() { self.line += 1; match text { Ok(text) => { if text == "" { break; } content = content + &text + "\n"; } Err(_) => { return Some(Err(ParseError::InvalidContent)); } } } return Some(Ok(Block { start_end: time, content: content, })); } } fn is_idx(s: &str) -> bool { match s.parse::<u64>() { Ok(_) => true, Err(_) => false, } }
{ // idx if let Some(Ok(idx)) = self.buf.next() { self.line += 1; if idx == "" { return None; //File ends with final new line } else if !is_idx(&idx) { return Some(Err(ParseError::InvalidIndex)); } } else { return None; // File ends without final newline } let time = if let Some(Ok(tl)) = self.buf.next() { self.line += 1; match StartEnd::from_str(&tl) { Ok(time) => time, Err(e) => return Some(Err(e)), } } else {
identifier_body
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { p4: Unique::new_unchecked(table::P4), } } pub fn p4(&self) -> &Table<Level4> { unsafe { self.p4.as_ref() } } pub fn p4_mut(&mut self) -> &mut Table<Level4> { unsafe { self.p4.as_mut() } } pub fn translate(&self, virtual_address: VirtualAddress) -> Option<PhysicalAddress> { let offset = virtual_address.get() % PAGE_SIZE; self.translate_page(Page::containing_address(virtual_address)) .map(|frame| PhysicalAddress::new(frame.start_address().get() + offset)) } pub fn map_to<A>(&mut self, page: Page, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let p4 = self.p4_mut(); let p3 = p4.next_table_create(page.p4_index(), allocator); let p2 = p3.next_table_create(page.p3_index(), allocator); let p1 = p2.next_table_create(page.p2_index(), allocator); assert!(p1[page.p1_index()].is_unused()); p1[page.p1_index()].set(frame, flags | EntryFlags::PRESENT); } pub fn map<A>(&mut self, page: Page, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let frame = allocator.allocate_frame().expect("Out of Memory"); self.map_to(page, frame, flags, allocator) } pub fn identity_map<A>(&mut self, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let page = Page::containing_address(VirtualAddress::new(frame.start_address().get())); self.map_to(page, frame, flags, allocator) } pub fn unmap<A>(&mut self, page: Page, allocator: &mut A) where A: FrameAllocator { assert!(self.translate(page.start_address()).is_some()); let p1 = self.p4_mut() .next_table_mut(page.p4_index()) .and_then(|p3| p3.next_table_mut(page.p3_index())) .and_then(|p2| p2.next_table_mut(page.p2_index())) .expect("mapping code does not support huge pages"); let frame = p1[page.p1_index()].pointed_frame().unwrap(); p1[page.p1_index()].set_unused(); use x86_64::instructions::tlb; use x86_64::VirtualAddress; tlb::flush(VirtualAddress(page.start_address().get())); // TODO free p(1,2,3) table if empty allocator.deallocate_frame(frame); }
.and_then(|p1| p1[page.p1_index()].pointed_frame()) } }
pub fn translate_page(&self, page: Page) -> Option<Frame> { self.p4().next_table(page.p4_index()) .and_then(|p3| p3.next_table(page.p3_index())) .and_then(|p2| p2.next_table(page.p2_index()))
random_line_split
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { p4: Unique::new_unchecked(table::P4), } } pub fn p4(&self) -> &Table<Level4> { unsafe { self.p4.as_ref() } } pub fn p4_mut(&mut self) -> &mut Table<Level4>
pub fn translate(&self, virtual_address: VirtualAddress) -> Option<PhysicalAddress> { let offset = virtual_address.get() % PAGE_SIZE; self.translate_page(Page::containing_address(virtual_address)) .map(|frame| PhysicalAddress::new(frame.start_address().get() + offset)) } pub fn map_to<A>(&mut self, page: Page, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let p4 = self.p4_mut(); let p3 = p4.next_table_create(page.p4_index(), allocator); let p2 = p3.next_table_create(page.p3_index(), allocator); let p1 = p2.next_table_create(page.p2_index(), allocator); assert!(p1[page.p1_index()].is_unused()); p1[page.p1_index()].set(frame, flags | EntryFlags::PRESENT); } pub fn map<A>(&mut self, page: Page, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let frame = allocator.allocate_frame().expect("Out of Memory"); self.map_to(page, frame, flags, allocator) } pub fn identity_map<A>(&mut self, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let page = Page::containing_address(VirtualAddress::new(frame.start_address().get())); self.map_to(page, frame, flags, allocator) } pub fn unmap<A>(&mut self, page: Page, allocator: &mut A) where A: FrameAllocator { assert!(self.translate(page.start_address()).is_some()); let p1 = self.p4_mut() .next_table_mut(page.p4_index()) .and_then(|p3| p3.next_table_mut(page.p3_index())) .and_then(|p2| p2.next_table_mut(page.p2_index())) .expect("mapping code does not support huge pages"); let frame = p1[page.p1_index()].pointed_frame().unwrap(); p1[page.p1_index()].set_unused(); use x86_64::instructions::tlb; use x86_64::VirtualAddress; tlb::flush(VirtualAddress(page.start_address().get())); // TODO free p(1,2,3) table if empty allocator.deallocate_frame(frame); } pub fn translate_page(&self, page: Page) -> Option<Frame> { self.p4().next_table(page.p4_index()) .and_then(|p3| p3.next_table(page.p3_index())) .and_then(|p2| p2.next_table(page.p2_index())) .and_then(|p1| p1[page.p1_index()].pointed_frame()) } }
{ unsafe { self.p4.as_mut() } }
identifier_body
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { p4: Unique::new_unchecked(table::P4), } } pub fn p4(&self) -> &Table<Level4> { unsafe { self.p4.as_ref() } } pub fn p4_mut(&mut self) -> &mut Table<Level4> { unsafe { self.p4.as_mut() } } pub fn translate(&self, virtual_address: VirtualAddress) -> Option<PhysicalAddress> { let offset = virtual_address.get() % PAGE_SIZE; self.translate_page(Page::containing_address(virtual_address)) .map(|frame| PhysicalAddress::new(frame.start_address().get() + offset)) } pub fn map_to<A>(&mut self, page: Page, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let p4 = self.p4_mut(); let p3 = p4.next_table_create(page.p4_index(), allocator); let p2 = p3.next_table_create(page.p3_index(), allocator); let p1 = p2.next_table_create(page.p2_index(), allocator); assert!(p1[page.p1_index()].is_unused()); p1[page.p1_index()].set(frame, flags | EntryFlags::PRESENT); } pub fn map<A>(&mut self, page: Page, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let frame = allocator.allocate_frame().expect("Out of Memory"); self.map_to(page, frame, flags, allocator) } pub fn
<A>(&mut self, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let page = Page::containing_address(VirtualAddress::new(frame.start_address().get())); self.map_to(page, frame, flags, allocator) } pub fn unmap<A>(&mut self, page: Page, allocator: &mut A) where A: FrameAllocator { assert!(self.translate(page.start_address()).is_some()); let p1 = self.p4_mut() .next_table_mut(page.p4_index()) .and_then(|p3| p3.next_table_mut(page.p3_index())) .and_then(|p2| p2.next_table_mut(page.p2_index())) .expect("mapping code does not support huge pages"); let frame = p1[page.p1_index()].pointed_frame().unwrap(); p1[page.p1_index()].set_unused(); use x86_64::instructions::tlb; use x86_64::VirtualAddress; tlb::flush(VirtualAddress(page.start_address().get())); // TODO free p(1,2,3) table if empty allocator.deallocate_frame(frame); } pub fn translate_page(&self, page: Page) -> Option<Frame> { self.p4().next_table(page.p4_index()) .and_then(|p3| p3.next_table(page.p3_index())) .and_then(|p2| p2.next_table(page.p2_index())) .and_then(|p1| p1[page.p1_index()].pointed_frame()) } }
identity_map
identifier_name
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <[email protected]> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate termion; #[cfg(unix)] use super::libc; use std::env; use std::fs; #[cfg(target_os = "redox")] use std::io; use std::io::{Error, ErrorKind}; use std::io::Result as IOResult; use std::path::{Component, Path, PathBuf}; use std::borrow::Cow; pub fn resolve_relative_path<'a>(path: &'a Path) -> Cow<'a, Path> { if path.components().all(|e| e!= Component::ParentDir) { return path.into(); } let root = Component::RootDir.as_os_str(); let mut result = env::current_dir().unwrap_or(PathBuf::from(root)); for comp in path.components() { match comp { Component::ParentDir => { if let Ok(p) = result.read_link() { result = p; } result.pop(); } Component::CurDir => (), Component::RootDir | Component::Normal(_) | Component::Prefix(_) => { result.push(comp.as_os_str()) } } } result.into() } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CanonicalizeMode { None, Normal, Existing, Missing, } fn resolve<P: AsRef<Path>>(original: P) -> IOResult<PathBuf> { const MAX_LINKS_FOLLOWED: u32 = 255; let mut followed = 0; let mut result = original.as_ref().to_path_buf(); loop { if followed == MAX_LINKS_FOLLOWED { return Err(Error::new( ErrorKind::InvalidInput, "maximum links followed", )); } match fs::symlink_metadata(&result) { Err(e) => return Err(e), Ok(ref m) if!m.file_type().is_symlink() => break, Ok(..) => { followed += 1; match fs::read_link(&result) { Ok(path) => { result.pop(); result.push(path); } Err(e) => { return Err(e); } } } } } Ok(result) } pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) -> IOResult<PathBuf> { // Create an absolute path let original = original.as_ref(); let original = if original.is_absolute() { original.to_path_buf() } else { env::current_dir().unwrap().join(original) }; let mut result = PathBuf::new(); let mut parts = vec![]; // Split path by directory separator; add prefix (Windows-only) and root // directory to final path buffer; add remaining parts to temporary // vector for canonicalization. for part in original.components() { match part { Component::Prefix(_) | Component::RootDir => { result.push(part.as_os_str()); } Component::CurDir => (), Component::ParentDir => { parts.pop(); } Component::Normal(_) => { parts.push(part.as_os_str()); } } } // Resolve the symlinks where possible if!parts.is_empty()
result.push(parts.last().unwrap()); match resolve(&result) { Err(e) => { if can_mode == CanonicalizeMode::Existing { return Err(e); } } Ok(path) => { result.pop(); result.push(path); } } } Ok(result) } #[cfg(unix)] pub fn is_stdin_interactive() -> bool { unsafe { libc::isatty(libc::STDIN_FILENO) == 1 } } #[cfg(windows)] pub fn is_stdin_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stdin_interactive() -> bool { termion::is_tty(&io::stdin()) } #[cfg(unix)] pub fn is_stdout_interactive() -> bool { unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 } } #[cfg(windows)] pub fn is_stdout_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stdout_interactive() -> bool { termion::is_tty(&io::stdout()) } #[cfg(unix)] pub fn is_stderr_interactive() -> bool { unsafe { libc::isatty(libc::STDERR_FILENO) == 1 } } #[cfg(windows)] pub fn is_stderr_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stderr_interactive() -> bool { termion::is_tty(&io::stderr()) }
{ for part in parts[..parts.len() - 1].iter() { result.push(part); if can_mode == CanonicalizeMode::None { continue; } match resolve(&result) { Err(e) => match can_mode { CanonicalizeMode::Missing => continue, _ => return Err(e), }, Ok(path) => { result.pop(); result.push(path); } } }
conditional_block
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <[email protected]> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate termion; #[cfg(unix)] use super::libc; use std::env; use std::fs; #[cfg(target_os = "redox")] use std::io; use std::io::{Error, ErrorKind}; use std::io::Result as IOResult; use std::path::{Component, Path, PathBuf}; use std::borrow::Cow; pub fn resolve_relative_path<'a>(path: &'a Path) -> Cow<'a, Path> { if path.components().all(|e| e!= Component::ParentDir) { return path.into(); } let root = Component::RootDir.as_os_str(); let mut result = env::current_dir().unwrap_or(PathBuf::from(root)); for comp in path.components() { match comp { Component::ParentDir => { if let Ok(p) = result.read_link() {
result = p; } result.pop(); } Component::CurDir => (), Component::RootDir | Component::Normal(_) | Component::Prefix(_) => { result.push(comp.as_os_str()) } } } result.into() } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CanonicalizeMode { None, Normal, Existing, Missing, } fn resolve<P: AsRef<Path>>(original: P) -> IOResult<PathBuf> { const MAX_LINKS_FOLLOWED: u32 = 255; let mut followed = 0; let mut result = original.as_ref().to_path_buf(); loop { if followed == MAX_LINKS_FOLLOWED { return Err(Error::new( ErrorKind::InvalidInput, "maximum links followed", )); } match fs::symlink_metadata(&result) { Err(e) => return Err(e), Ok(ref m) if!m.file_type().is_symlink() => break, Ok(..) => { followed += 1; match fs::read_link(&result) { Ok(path) => { result.pop(); result.push(path); } Err(e) => { return Err(e); } } } } } Ok(result) } pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) -> IOResult<PathBuf> { // Create an absolute path let original = original.as_ref(); let original = if original.is_absolute() { original.to_path_buf() } else { env::current_dir().unwrap().join(original) }; let mut result = PathBuf::new(); let mut parts = vec![]; // Split path by directory separator; add prefix (Windows-only) and root // directory to final path buffer; add remaining parts to temporary // vector for canonicalization. for part in original.components() { match part { Component::Prefix(_) | Component::RootDir => { result.push(part.as_os_str()); } Component::CurDir => (), Component::ParentDir => { parts.pop(); } Component::Normal(_) => { parts.push(part.as_os_str()); } } } // Resolve the symlinks where possible if!parts.is_empty() { for part in parts[..parts.len() - 1].iter() { result.push(part); if can_mode == CanonicalizeMode::None { continue; } match resolve(&result) { Err(e) => match can_mode { CanonicalizeMode::Missing => continue, _ => return Err(e), }, Ok(path) => { result.pop(); result.push(path); } } } result.push(parts.last().unwrap()); match resolve(&result) { Err(e) => { if can_mode == CanonicalizeMode::Existing { return Err(e); } } Ok(path) => { result.pop(); result.push(path); } } } Ok(result) } #[cfg(unix)] pub fn is_stdin_interactive() -> bool { unsafe { libc::isatty(libc::STDIN_FILENO) == 1 } } #[cfg(windows)] pub fn is_stdin_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stdin_interactive() -> bool { termion::is_tty(&io::stdin()) } #[cfg(unix)] pub fn is_stdout_interactive() -> bool { unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 } } #[cfg(windows)] pub fn is_stdout_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stdout_interactive() -> bool { termion::is_tty(&io::stdout()) } #[cfg(unix)] pub fn is_stderr_interactive() -> bool { unsafe { libc::isatty(libc::STDERR_FILENO) == 1 } } #[cfg(windows)] pub fn is_stderr_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stderr_interactive() -> bool { termion::is_tty(&io::stderr()) }
random_line_split
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <[email protected]> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate termion; #[cfg(unix)] use super::libc; use std::env; use std::fs; #[cfg(target_os = "redox")] use std::io; use std::io::{Error, ErrorKind}; use std::io::Result as IOResult; use std::path::{Component, Path, PathBuf}; use std::borrow::Cow; pub fn resolve_relative_path<'a>(path: &'a Path) -> Cow<'a, Path> { if path.components().all(|e| e!= Component::ParentDir) { return path.into(); } let root = Component::RootDir.as_os_str(); let mut result = env::current_dir().unwrap_or(PathBuf::from(root)); for comp in path.components() { match comp { Component::ParentDir => { if let Ok(p) = result.read_link() { result = p; } result.pop(); } Component::CurDir => (), Component::RootDir | Component::Normal(_) | Component::Prefix(_) => { result.push(comp.as_os_str()) } } } result.into() } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CanonicalizeMode { None, Normal, Existing, Missing, } fn resolve<P: AsRef<Path>>(original: P) -> IOResult<PathBuf> { const MAX_LINKS_FOLLOWED: u32 = 255; let mut followed = 0; let mut result = original.as_ref().to_path_buf(); loop { if followed == MAX_LINKS_FOLLOWED { return Err(Error::new( ErrorKind::InvalidInput, "maximum links followed", )); } match fs::symlink_metadata(&result) { Err(e) => return Err(e), Ok(ref m) if!m.file_type().is_symlink() => break, Ok(..) => { followed += 1; match fs::read_link(&result) { Ok(path) => { result.pop(); result.push(path); } Err(e) => { return Err(e); } } } } } Ok(result) } pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) -> IOResult<PathBuf> { // Create an absolute path let original = original.as_ref(); let original = if original.is_absolute() { original.to_path_buf() } else { env::current_dir().unwrap().join(original) }; let mut result = PathBuf::new(); let mut parts = vec![]; // Split path by directory separator; add prefix (Windows-only) and root // directory to final path buffer; add remaining parts to temporary // vector for canonicalization. for part in original.components() { match part { Component::Prefix(_) | Component::RootDir => { result.push(part.as_os_str()); } Component::CurDir => (), Component::ParentDir => { parts.pop(); } Component::Normal(_) => { parts.push(part.as_os_str()); } } } // Resolve the symlinks where possible if!parts.is_empty() { for part in parts[..parts.len() - 1].iter() { result.push(part); if can_mode == CanonicalizeMode::None { continue; } match resolve(&result) { Err(e) => match can_mode { CanonicalizeMode::Missing => continue, _ => return Err(e), }, Ok(path) => { result.pop(); result.push(path); } } } result.push(parts.last().unwrap()); match resolve(&result) { Err(e) => { if can_mode == CanonicalizeMode::Existing { return Err(e); } } Ok(path) => { result.pop(); result.push(path); } } } Ok(result) } #[cfg(unix)] pub fn is_stdin_interactive() -> bool { unsafe { libc::isatty(libc::STDIN_FILENO) == 1 } } #[cfg(windows)] pub fn is_stdin_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stdin_interactive() -> bool { termion::is_tty(&io::stdin()) } #[cfg(unix)] pub fn is_stdout_interactive() -> bool { unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 } } #[cfg(windows)] pub fn is_stdout_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stdout_interactive() -> bool { termion::is_tty(&io::stdout()) } #[cfg(unix)] pub fn is_stderr_interactive() -> bool { unsafe { libc::isatty(libc::STDERR_FILENO) == 1 } } #[cfg(windows)] pub fn is_stderr_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn
() -> bool { termion::is_tty(&io::stderr()) }
is_stderr_interactive
identifier_name
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <[email protected]> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate termion; #[cfg(unix)] use super::libc; use std::env; use std::fs; #[cfg(target_os = "redox")] use std::io; use std::io::{Error, ErrorKind}; use std::io::Result as IOResult; use std::path::{Component, Path, PathBuf}; use std::borrow::Cow; pub fn resolve_relative_path<'a>(path: &'a Path) -> Cow<'a, Path>
result.into() } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CanonicalizeMode { None, Normal, Existing, Missing, } fn resolve<P: AsRef<Path>>(original: P) -> IOResult<PathBuf> { const MAX_LINKS_FOLLOWED: u32 = 255; let mut followed = 0; let mut result = original.as_ref().to_path_buf(); loop { if followed == MAX_LINKS_FOLLOWED { return Err(Error::new( ErrorKind::InvalidInput, "maximum links followed", )); } match fs::symlink_metadata(&result) { Err(e) => return Err(e), Ok(ref m) if!m.file_type().is_symlink() => break, Ok(..) => { followed += 1; match fs::read_link(&result) { Ok(path) => { result.pop(); result.push(path); } Err(e) => { return Err(e); } } } } } Ok(result) } pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) -> IOResult<PathBuf> { // Create an absolute path let original = original.as_ref(); let original = if original.is_absolute() { original.to_path_buf() } else { env::current_dir().unwrap().join(original) }; let mut result = PathBuf::new(); let mut parts = vec![]; // Split path by directory separator; add prefix (Windows-only) and root // directory to final path buffer; add remaining parts to temporary // vector for canonicalization. for part in original.components() { match part { Component::Prefix(_) | Component::RootDir => { result.push(part.as_os_str()); } Component::CurDir => (), Component::ParentDir => { parts.pop(); } Component::Normal(_) => { parts.push(part.as_os_str()); } } } // Resolve the symlinks where possible if!parts.is_empty() { for part in parts[..parts.len() - 1].iter() { result.push(part); if can_mode == CanonicalizeMode::None { continue; } match resolve(&result) { Err(e) => match can_mode { CanonicalizeMode::Missing => continue, _ => return Err(e), }, Ok(path) => { result.pop(); result.push(path); } } } result.push(parts.last().unwrap()); match resolve(&result) { Err(e) => { if can_mode == CanonicalizeMode::Existing { return Err(e); } } Ok(path) => { result.pop(); result.push(path); } } } Ok(result) } #[cfg(unix)] pub fn is_stdin_interactive() -> bool { unsafe { libc::isatty(libc::STDIN_FILENO) == 1 } } #[cfg(windows)] pub fn is_stdin_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stdin_interactive() -> bool { termion::is_tty(&io::stdin()) } #[cfg(unix)] pub fn is_stdout_interactive() -> bool { unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 } } #[cfg(windows)] pub fn is_stdout_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stdout_interactive() -> bool { termion::is_tty(&io::stdout()) } #[cfg(unix)] pub fn is_stderr_interactive() -> bool { unsafe { libc::isatty(libc::STDERR_FILENO) == 1 } } #[cfg(windows)] pub fn is_stderr_interactive() -> bool { false } #[cfg(target_os = "redox")] pub fn is_stderr_interactive() -> bool { termion::is_tty(&io::stderr()) }
{ if path.components().all(|e| e != Component::ParentDir) { return path.into(); } let root = Component::RootDir.as_os_str(); let mut result = env::current_dir().unwrap_or(PathBuf::from(root)); for comp in path.components() { match comp { Component::ParentDir => { if let Ok(p) = result.read_link() { result = p; } result.pop(); } Component::CurDir => (), Component::RootDir | Component::Normal(_) | Component::Prefix(_) => { result.push(comp.as_os_str()) } } }
identifier_body
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } impl Point3D { pub fn from_str(point_str: &str) -> Result<Self, String> { let is_parenthesized = point_str.starts_with('(') && point_str.ends_with(')'); let is_square_bracketed = point_str.starts_with('[') && point_str.ends_with(']'); if!is_parenthesized &&!is_square_bracketed { return Err(format!( "Invalid point -- use parenthesis or square brackets to denote points (received: {})", point_str )); } let parts: Vec<&str> = point_str[1..point_str.len() - 1].split(',').collect(); if parts.len()!= 3
Ok(Self { x: parts[0] .parse() .map_err(|err| format!("Could not parse x coordinate: {:?}", err))?, y: parts[1] .parse() .map_err(|err| format!("Could not parse y coordinate: {:?}", err))?, z: parts[2] .parse() .map_err(|err| format!("Could not parse z coordinate: {:?}", err))?, }) } pub fn is_default(&self) -> bool { self.x == 0 && self.y == 0 && self.z == 0 } pub fn to_vec(&self) -> Vector3D { Vector3D::new(self.x, self.y, self.z) } } impl<T> ops::Sub<T> for Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<T> ops::Sub<T> for &Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<'de> Deserialize<'de> for Point3D { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(Point3DVisitor) } } impl fmt::Display for Point3D { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Point3D({}, {}, {})", self.x, self.y, self.z) } } impl Serialize for Point3D { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_tuple_struct("Point3D", 3)?; state.serialize_field(&self.x)?; state.serialize_field(&self.y)?; state.serialize_field(&self.z)?; state.end() } } struct Point3DVisitor; impl<'de> Visitor<'de> for Point3DVisitor { type Value = Point3D; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an array with three integers") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { let x = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let y = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; let z = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; Ok(Point3D { x, y, z }) } }
{ return Err("Invalid point -- must contain 3 comma-separated coordinates".to_owned()); }
conditional_block
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } impl Point3D { pub fn from_str(point_str: &str) -> Result<Self, String> { let is_parenthesized = point_str.starts_with('(') && point_str.ends_with(')'); let is_square_bracketed = point_str.starts_with('[') && point_str.ends_with(']'); if!is_parenthesized &&!is_square_bracketed { return Err(format!( "Invalid point -- use parenthesis or square brackets to denote points (received: {})", point_str )); } let parts: Vec<&str> = point_str[1..point_str.len() - 1].split(',').collect(); if parts.len()!= 3 { return Err("Invalid point -- must contain 3 comma-separated coordinates".to_owned()); } Ok(Self { x: parts[0] .parse() .map_err(|err| format!("Could not parse x coordinate: {:?}", err))?, y: parts[1] .parse() .map_err(|err| format!("Could not parse y coordinate: {:?}", err))?, z: parts[2] .parse() .map_err(|err| format!("Could not parse z coordinate: {:?}", err))?, }) } pub fn
(&self) -> bool { self.x == 0 && self.y == 0 && self.z == 0 } pub fn to_vec(&self) -> Vector3D { Vector3D::new(self.x, self.y, self.z) } } impl<T> ops::Sub<T> for Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<T> ops::Sub<T> for &Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<'de> Deserialize<'de> for Point3D { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(Point3DVisitor) } } impl fmt::Display for Point3D { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Point3D({}, {}, {})", self.x, self.y, self.z) } } impl Serialize for Point3D { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_tuple_struct("Point3D", 3)?; state.serialize_field(&self.x)?; state.serialize_field(&self.y)?; state.serialize_field(&self.z)?; state.end() } } struct Point3DVisitor; impl<'de> Visitor<'de> for Point3DVisitor { type Value = Point3D; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an array with three integers") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { let x = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let y = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; let z = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; Ok(Point3D { x, y, z }) } }
is_default
identifier_name
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } impl Point3D { pub fn from_str(point_str: &str) -> Result<Self, String> { let is_parenthesized = point_str.starts_with('(') && point_str.ends_with(')'); let is_square_bracketed = point_str.starts_with('[') && point_str.ends_with(']'); if!is_parenthesized &&!is_square_bracketed { return Err(format!( "Invalid point -- use parenthesis or square brackets to denote points (received: {})", point_str )); } let parts: Vec<&str> = point_str[1..point_str.len() - 1].split(',').collect(); if parts.len()!= 3 { return Err("Invalid point -- must contain 3 comma-separated coordinates".to_owned()); } Ok(Self { x: parts[0] .parse() .map_err(|err| format!("Could not parse x coordinate: {:?}", err))?, y: parts[1] .parse() .map_err(|err| format!("Could not parse y coordinate: {:?}", err))?, z: parts[2] .parse() .map_err(|err| format!("Could not parse z coordinate: {:?}", err))?, }) } pub fn is_default(&self) -> bool
pub fn to_vec(&self) -> Vector3D { Vector3D::new(self.x, self.y, self.z) } } impl<T> ops::Sub<T> for Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<T> ops::Sub<T> for &Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<'de> Deserialize<'de> for Point3D { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(Point3DVisitor) } } impl fmt::Display for Point3D { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Point3D({}, {}, {})", self.x, self.y, self.z) } } impl Serialize for Point3D { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_tuple_struct("Point3D", 3)?; state.serialize_field(&self.x)?; state.serialize_field(&self.y)?; state.serialize_field(&self.z)?; state.end() } } struct Point3DVisitor; impl<'de> Visitor<'de> for Point3DVisitor { type Value = Point3D; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an array with three integers") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { let x = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let y = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; let z = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; Ok(Point3D { x, y, z }) } }
{ self.x == 0 && self.y == 0 && self.z == 0 }
identifier_body
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } impl Point3D { pub fn from_str(point_str: &str) -> Result<Self, String> { let is_parenthesized = point_str.starts_with('(') && point_str.ends_with(')'); let is_square_bracketed = point_str.starts_with('[') && point_str.ends_with(']'); if!is_parenthesized &&!is_square_bracketed { return Err(format!( "Invalid point -- use parenthesis or square brackets to denote points (received: {})", point_str )); } let parts: Vec<&str> = point_str[1..point_str.len() - 1].split(',').collect(); if parts.len()!= 3 { return Err("Invalid point -- must contain 3 comma-separated coordinates".to_owned()); } Ok(Self { x: parts[0] .parse() .map_err(|err| format!("Could not parse x coordinate: {:?}", err))?, y: parts[1] .parse() .map_err(|err| format!("Could not parse y coordinate: {:?}", err))?, z: parts[2] .parse() .map_err(|err| format!("Could not parse z coordinate: {:?}", err))?, }) } pub fn is_default(&self) -> bool { self.x == 0 && self.y == 0 && self.z == 0 } pub fn to_vec(&self) -> Vector3D { Vector3D::new(self.x, self.y, self.z) } } impl<T> ops::Sub<T> for Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } }
impl<T> ops::Sub<T> for &Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<'de> Deserialize<'de> for Point3D { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_seq(Point3DVisitor) } } impl fmt::Display for Point3D { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Point3D({}, {}, {})", self.x, self.y, self.z) } } impl Serialize for Point3D { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_tuple_struct("Point3D", 3)?; state.serialize_field(&self.x)?; state.serialize_field(&self.y)?; state.serialize_field(&self.z)?; state.end() } } struct Point3DVisitor; impl<'de> Visitor<'de> for Point3DVisitor { type Value = Point3D; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an array with three integers") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { let x = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let y = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; let z = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; Ok(Point3D { x, y, z }) } }
random_line_split
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer, Session}; use dataflow::channels::Content; use timely_communication::Push; use dataflow::operators::Capability; use dataflow::operators::capability::mint as mint_capability; /// Handle to an operator's input stream. pub struct InputHandle<'a, T: Timestamp, D: 'a> { pull_counter: &'a mut PullCounter<T, D>, internal: Rc<RefCell<CountMap<T>>>, } impl<'a, T: Timestamp, D> InputHandle<'a, T, D> { /// Reads the next input buffer (at some timestamp `t`) and a corresponding capability for `t`. /// The timestamp `t` of the input buffer can be retrieved by invoking `.time()` on the capability. /// Returns `None` when there's no more data available. #[inline] pub fn next(&mut self) -> Option<(Capability<T>, &mut Content<D>)> { let internal = &mut self.internal; self.pull_counter.next().map(|(&time, content)| { (mint_capability(time, internal.clone()), content) }) } /// Repeatedly calls `logic` till exhaustion of the available input data. /// `logic` receives a capability and an input buffer. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Unary}; /// use timely::dataflow::channels::pact::Pipeline; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .unary_stream(Pipeline, "example", |input, output| { /// input.for_each(|cap, data| { /// output.session(&cap).give_content(data); /// }); /// }); /// }); /// ``` #[inline] pub fn for_each<F: FnMut(Capability<T>, &mut Content<D>)>(&mut self, mut logic: F) { while let Some((cap, data)) = self.next() { ::logging::log(&::logging::GUARDED_MESSAGE, true); logic(cap, data); ::logging::log(&::logging::GUARDED_MESSAGE, false); } } } /// Constructs an input handle. /// Declared separately so that it can be kept private when `InputHandle` is re-exported. pub fn new_input_handle<'a, T: Timestamp, D: 'a>(pull_counter: &'a mut PullCounter<T, D>, internal: Rc<RefCell<CountMap<T>>>) -> InputHandle<'a, T, D> { InputHandle { pull_counter: pull_counter, internal: internal, } } /// Handle to an operator's output stream. pub struct OutputHandle<'a, T: Timestamp, D: 'a, P: Push<(T, Content<D>)>+'a> { push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>, } impl<'a, T: Timestamp, D, P: Push<(T, Content<D>)>> OutputHandle<'a, T, D, P> { /// Obtains a session that can send data at the timestamp associated with capability `cap`. /// /// In order to send data at a future timestamp, obtain a capability for the new timestamp /// first, as show in the example. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Unary}; /// use timely::dataflow::channels::pact::Pipeline; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .unary_stream(Pipeline, "example", |input, output| { /// input.for_each(|cap, data| { /// let mut time = cap.time(); /// time.inner += 1; /// output.session(&cap.delayed(&time)).give_content(data); /// }); /// }); /// }); /// ``` pub fn session<'b>(&'b mut self, cap: &'b Capability<T>) -> Session<'b, T, D, PushCounter<T, D, P>> where 'a: 'b { self.push_buffer.session(cap) }
pub fn new_output_handle<'a, T: Timestamp, D, P: Push<(T, Content<D>)>>(push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>) -> OutputHandle<'a, T, D, P> { OutputHandle { push_buffer: push_buffer, } }
} /// Constructs an output handle. /// Declared separately so that it can be kept private when `OutputHandle` is re-exported.
random_line_split
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer, Session}; use dataflow::channels::Content; use timely_communication::Push; use dataflow::operators::Capability; use dataflow::operators::capability::mint as mint_capability; /// Handle to an operator's input stream. pub struct InputHandle<'a, T: Timestamp, D: 'a> { pull_counter: &'a mut PullCounter<T, D>, internal: Rc<RefCell<CountMap<T>>>, } impl<'a, T: Timestamp, D> InputHandle<'a, T, D> { /// Reads the next input buffer (at some timestamp `t`) and a corresponding capability for `t`. /// The timestamp `t` of the input buffer can be retrieved by invoking `.time()` on the capability. /// Returns `None` when there's no more data available. #[inline] pub fn next(&mut self) -> Option<(Capability<T>, &mut Content<D>)> { let internal = &mut self.internal; self.pull_counter.next().map(|(&time, content)| { (mint_capability(time, internal.clone()), content) }) } /// Repeatedly calls `logic` till exhaustion of the available input data. /// `logic` receives a capability and an input buffer. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Unary}; /// use timely::dataflow::channels::pact::Pipeline; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .unary_stream(Pipeline, "example", |input, output| { /// input.for_each(|cap, data| { /// output.session(&cap).give_content(data); /// }); /// }); /// }); /// ``` #[inline] pub fn for_each<F: FnMut(Capability<T>, &mut Content<D>)>(&mut self, mut logic: F) { while let Some((cap, data)) = self.next() { ::logging::log(&::logging::GUARDED_MESSAGE, true); logic(cap, data); ::logging::log(&::logging::GUARDED_MESSAGE, false); } } } /// Constructs an input handle. /// Declared separately so that it can be kept private when `InputHandle` is re-exported. pub fn new_input_handle<'a, T: Timestamp, D: 'a>(pull_counter: &'a mut PullCounter<T, D>, internal: Rc<RefCell<CountMap<T>>>) -> InputHandle<'a, T, D> { InputHandle { pull_counter: pull_counter, internal: internal, } } /// Handle to an operator's output stream. pub struct OutputHandle<'a, T: Timestamp, D: 'a, P: Push<(T, Content<D>)>+'a> { push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>, } impl<'a, T: Timestamp, D, P: Push<(T, Content<D>)>> OutputHandle<'a, T, D, P> { /// Obtains a session that can send data at the timestamp associated with capability `cap`. /// /// In order to send data at a future timestamp, obtain a capability for the new timestamp /// first, as show in the example. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Unary}; /// use timely::dataflow::channels::pact::Pipeline; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .unary_stream(Pipeline, "example", |input, output| { /// input.for_each(|cap, data| { /// let mut time = cap.time(); /// time.inner += 1; /// output.session(&cap.delayed(&time)).give_content(data); /// }); /// }); /// }); /// ``` pub fn session<'b>(&'b mut self, cap: &'b Capability<T>) -> Session<'b, T, D, PushCounter<T, D, P>> where 'a: 'b
} /// Constructs an output handle. /// Declared separately so that it can be kept private when `OutputHandle` is re-exported. pub fn new_output_handle<'a, T: Timestamp, D, P: Push<(T, Content<D>)>>(push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>) -> OutputHandle<'a, T, D, P> { OutputHandle { push_buffer: push_buffer, } }
{ self.push_buffer.session(cap) }
identifier_body
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer, Session}; use dataflow::channels::Content; use timely_communication::Push; use dataflow::operators::Capability; use dataflow::operators::capability::mint as mint_capability; /// Handle to an operator's input stream. pub struct
<'a, T: Timestamp, D: 'a> { pull_counter: &'a mut PullCounter<T, D>, internal: Rc<RefCell<CountMap<T>>>, } impl<'a, T: Timestamp, D> InputHandle<'a, T, D> { /// Reads the next input buffer (at some timestamp `t`) and a corresponding capability for `t`. /// The timestamp `t` of the input buffer can be retrieved by invoking `.time()` on the capability. /// Returns `None` when there's no more data available. #[inline] pub fn next(&mut self) -> Option<(Capability<T>, &mut Content<D>)> { let internal = &mut self.internal; self.pull_counter.next().map(|(&time, content)| { (mint_capability(time, internal.clone()), content) }) } /// Repeatedly calls `logic` till exhaustion of the available input data. /// `logic` receives a capability and an input buffer. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Unary}; /// use timely::dataflow::channels::pact::Pipeline; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .unary_stream(Pipeline, "example", |input, output| { /// input.for_each(|cap, data| { /// output.session(&cap).give_content(data); /// }); /// }); /// }); /// ``` #[inline] pub fn for_each<F: FnMut(Capability<T>, &mut Content<D>)>(&mut self, mut logic: F) { while let Some((cap, data)) = self.next() { ::logging::log(&::logging::GUARDED_MESSAGE, true); logic(cap, data); ::logging::log(&::logging::GUARDED_MESSAGE, false); } } } /// Constructs an input handle. /// Declared separately so that it can be kept private when `InputHandle` is re-exported. pub fn new_input_handle<'a, T: Timestamp, D: 'a>(pull_counter: &'a mut PullCounter<T, D>, internal: Rc<RefCell<CountMap<T>>>) -> InputHandle<'a, T, D> { InputHandle { pull_counter: pull_counter, internal: internal, } } /// Handle to an operator's output stream. pub struct OutputHandle<'a, T: Timestamp, D: 'a, P: Push<(T, Content<D>)>+'a> { push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>, } impl<'a, T: Timestamp, D, P: Push<(T, Content<D>)>> OutputHandle<'a, T, D, P> { /// Obtains a session that can send data at the timestamp associated with capability `cap`. /// /// In order to send data at a future timestamp, obtain a capability for the new timestamp /// first, as show in the example. /// /// #Examples /// ``` /// use timely::dataflow::operators::{ToStream, Unary}; /// use timely::dataflow::channels::pact::Pipeline; /// /// timely::example(|scope| { /// (0..10).to_stream(scope) /// .unary_stream(Pipeline, "example", |input, output| { /// input.for_each(|cap, data| { /// let mut time = cap.time(); /// time.inner += 1; /// output.session(&cap.delayed(&time)).give_content(data); /// }); /// }); /// }); /// ``` pub fn session<'b>(&'b mut self, cap: &'b Capability<T>) -> Session<'b, T, D, PushCounter<T, D, P>> where 'a: 'b { self.push_buffer.session(cap) } } /// Constructs an output handle. /// Declared separately so that it can be kept private when `OutputHandle` is re-exported. pub fn new_output_handle<'a, T: Timestamp, D, P: Push<(T, Content<D>)>>(push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>) -> OutputHandle<'a, T, D, P> { OutputHandle { push_buffer: push_buffer, } }
InputHandle
identifier_name
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches 128 (Timer 0/1) or 16 /// (Timer 2), this is reset and stage2 is incremented. stage1: u8, /// Counted up at the timer's frequency. When this reaches `div`, it is reset and `val` /// (stage3) incremented. Since `div=0` is interpreted as 256, this is a `u16`. stage2: u16, } impl_save_state!(Timer { div, val, enabled, stage1, stage2 } ignore {}); impl Default for Timer { fn default() -> Self { Timer { div: 0, val: 0x0f, enabled: false, stage1: 0, stage2: 0, } } } impl Timer { pub fn new() -> Timer { Timer::default() } /// Update the timer, applying a base-divisor (128 for Timer 0/1, 16 for Timer 2) pub fn update(&mut self, base_div: u8, cy: u8) { self.stage1 += cy; if self.enabled { self.stage2 += self.stage1 as u16 / base_div as u16; } self.stage1 %= base_div; if self.enabled { let real_div: u16 = if self.div == 0 { 256 } else { self.div as u16 }; self.val += (self.stage2 / real_div) as u8; self.stage2 %= real_div; self.val &= 0x0f; // It's a 4-bit counter } }
pub fn set_enable(&mut self, enable: bool) { if!self.enabled && enable { self.stage2 = 0; self.val = 0; } self.enabled = enable; } pub fn enabled(&mut self) -> bool { self.enabled } }
random_line_split
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches 128 (Timer 0/1) or 16 /// (Timer 2), this is reset and stage2 is incremented. stage1: u8, /// Counted up at the timer's frequency. When this reaches `div`, it is reset and `val` /// (stage3) incremented. Since `div=0` is interpreted as 256, this is a `u16`. stage2: u16, } impl_save_state!(Timer { div, val, enabled, stage1, stage2 } ignore {}); impl Default for Timer { fn default() -> Self { Timer { div: 0, val: 0x0f, enabled: false, stage1: 0, stage2: 0, } } } impl Timer { pub fn
() -> Timer { Timer::default() } /// Update the timer, applying a base-divisor (128 for Timer 0/1, 16 for Timer 2) pub fn update(&mut self, base_div: u8, cy: u8) { self.stage1 += cy; if self.enabled { self.stage2 += self.stage1 as u16 / base_div as u16; } self.stage1 %= base_div; if self.enabled { let real_div: u16 = if self.div == 0 { 256 } else { self.div as u16 }; self.val += (self.stage2 / real_div) as u8; self.stage2 %= real_div; self.val &= 0x0f; // It's a 4-bit counter } } pub fn set_enable(&mut self, enable: bool) { if!self.enabled && enable { self.stage2 = 0; self.val = 0; } self.enabled = enable; } pub fn enabled(&mut self) -> bool { self.enabled } }
new
identifier_name
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches 128 (Timer 0/1) or 16 /// (Timer 2), this is reset and stage2 is incremented. stage1: u8, /// Counted up at the timer's frequency. When this reaches `div`, it is reset and `val` /// (stage3) incremented. Since `div=0` is interpreted as 256, this is a `u16`. stage2: u16, } impl_save_state!(Timer { div, val, enabled, stage1, stage2 } ignore {}); impl Default for Timer { fn default() -> Self { Timer { div: 0, val: 0x0f, enabled: false, stage1: 0, stage2: 0, } } } impl Timer { pub fn new() -> Timer { Timer::default() } /// Update the timer, applying a base-divisor (128 for Timer 0/1, 16 for Timer 2) pub fn update(&mut self, base_div: u8, cy: u8) { self.stage1 += cy; if self.enabled { self.stage2 += self.stage1 as u16 / base_div as u16; } self.stage1 %= base_div; if self.enabled
} pub fn set_enable(&mut self, enable: bool) { if!self.enabled && enable { self.stage2 = 0; self.val = 0; } self.enabled = enable; } pub fn enabled(&mut self) -> bool { self.enabled } }
{ let real_div: u16 = if self.div == 0 { 256 } else { self.div as u16 }; self.val += (self.stage2 / real_div) as u8; self.stage2 %= real_div; self.val &= 0x0f; // It's a 4-bit counter }
conditional_block
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches 128 (Timer 0/1) or 16 /// (Timer 2), this is reset and stage2 is incremented. stage1: u8, /// Counted up at the timer's frequency. When this reaches `div`, it is reset and `val` /// (stage3) incremented. Since `div=0` is interpreted as 256, this is a `u16`. stage2: u16, } impl_save_state!(Timer { div, val, enabled, stage1, stage2 } ignore {}); impl Default for Timer { fn default() -> Self { Timer { div: 0, val: 0x0f, enabled: false, stage1: 0, stage2: 0, } } } impl Timer { pub fn new() -> Timer
/// Update the timer, applying a base-divisor (128 for Timer 0/1, 16 for Timer 2) pub fn update(&mut self, base_div: u8, cy: u8) { self.stage1 += cy; if self.enabled { self.stage2 += self.stage1 as u16 / base_div as u16; } self.stage1 %= base_div; if self.enabled { let real_div: u16 = if self.div == 0 { 256 } else { self.div as u16 }; self.val += (self.stage2 / real_div) as u8; self.stage2 %= real_div; self.val &= 0x0f; // It's a 4-bit counter } } pub fn set_enable(&mut self, enable: bool) { if!self.enabled && enable { self.stage2 = 0; self.val = 0; } self.enabled = enable; } pub fn enabled(&mut self) -> bool { self.enabled } }
{ Timer::default() }
identifier_body
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters}; /// Trait implemented by all joints following the reduced-coordinate formation. pub trait Joint<N: RealField>: Downcast + Send + Sync { /// The number of degrees of freedom allowed by the joint. fn ndofs(&self) -> usize; /// The position of the multibody link containing this joint relative to its parent. fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N>; /// Update the jacobians of this joint. fn update_jacobians(&mut self, body_shift: &Vector<N>, vels: &[N]); /// Integrate the position of this joint. fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]); /// Apply a displacement to the joint. fn apply_displacement(&mut self, disp: &[N]); /// Sets in `out` the non-zero entries of the joint jacobian transformed by `transform`. fn jacobian(&self, transform: &Isometry<N>, out: &mut JacobianSliceMut<N>); /// Sets in `out` the non-zero entries of the time-derivative of the joint jacobian transformed by `transform`. fn jacobian_dot(&self, transform: &Isometry<N>, out: &mut JacobianSliceMut<N>); /// Sets in `out` the non-zero entries of the velocity-derivative of the time-derivative of the joint jacobian transformed by `transform`. fn jacobian_dot_veldiff_mul_coordinates( &self, transform: &Isometry<N>, vels: &[N], out: &mut JacobianSliceMut<N>, ); /// Multiply the joint jacobian by generalized velocities to obtain the /// relative velocity of the multibody link containing this joint. fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N>; /// Multiply the joint jacobian by generalized accelerations to obtain the /// relative acceleration of the multibody link containing this joint. fn jacobian_dot_mul_coordinates(&self, vels: &[N]) -> Velocity<N>; /// Fill `out` with the non-zero entries of a damping that can be applied by default to ensure a good stability of the joint. fn default_damping(&self, out: &mut DVectorSliceMut<N>); /// The maximum number of impulses needed by this joints for /// its constraints. fn nimpulses(&self) -> usize { // FIXME: keep this? self.ndofs() * 3 } /// Maximum number of velocity constrains that can be generated by this joint. fn num_velocity_constraints(&self) -> usize { 0 } /// Initialize and generate velocity constraints to enforce, e.g., joint limits and motors. fn velocity_constraints( &self, _params: &IntegrationParameters<N>, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _assembly_id: usize, _dof_id: usize, _ext_vels: &[N], _ground_j_id: &mut usize, _jacobians: &mut [N], _velocity_constraints: &mut ConstraintSet<N, (), (), usize>, ) { } /// The maximum number of non-linear position constraints that can be generated by this joint. fn num_position_constraints(&self) -> usize
/// Initialize and generate the i-th position constraints to enforce, e.g., joint limits. fn position_constraint( &self, _i: usize, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _handle: BodyPartHandle<()>, _dof_id: usize, _jacobians: &mut [N], ) -> Option<GenericNonlinearConstraint<N, ()>> { None } fn clone(&self) -> Box<dyn Joint<N>>; } impl_downcast!(Joint<N> where N: RealField);
{ 0 }
identifier_body
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters}; /// Trait implemented by all joints following the reduced-coordinate formation. pub trait Joint<N: RealField>: Downcast + Send + Sync { /// The number of degrees of freedom allowed by the joint. fn ndofs(&self) -> usize; /// The position of the multibody link containing this joint relative to its parent. fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N>; /// Update the jacobians of this joint. fn update_jacobians(&mut self, body_shift: &Vector<N>, vels: &[N]); /// Integrate the position of this joint. fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]); /// Apply a displacement to the joint. fn apply_displacement(&mut self, disp: &[N]); /// Sets in `out` the non-zero entries of the joint jacobian transformed by `transform`. fn jacobian(&self, transform: &Isometry<N>, out: &mut JacobianSliceMut<N>); /// Sets in `out` the non-zero entries of the time-derivative of the joint jacobian transformed by `transform`. fn jacobian_dot(&self, transform: &Isometry<N>, out: &mut JacobianSliceMut<N>); /// Sets in `out` the non-zero entries of the velocity-derivative of the time-derivative of the joint jacobian transformed by `transform`. fn jacobian_dot_veldiff_mul_coordinates( &self, transform: &Isometry<N>, vels: &[N], out: &mut JacobianSliceMut<N>, ); /// Multiply the joint jacobian by generalized velocities to obtain the /// relative velocity of the multibody link containing this joint. fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N>; /// Multiply the joint jacobian by generalized accelerations to obtain the /// relative acceleration of the multibody link containing this joint. fn jacobian_dot_mul_coordinates(&self, vels: &[N]) -> Velocity<N>; /// Fill `out` with the non-zero entries of a damping that can be applied by default to ensure a good stability of the joint. fn default_damping(&self, out: &mut DVectorSliceMut<N>);
/// The maximum number of impulses needed by this joints for /// its constraints. fn nimpulses(&self) -> usize { // FIXME: keep this? self.ndofs() * 3 } /// Maximum number of velocity constrains that can be generated by this joint. fn num_velocity_constraints(&self) -> usize { 0 } /// Initialize and generate velocity constraints to enforce, e.g., joint limits and motors. fn velocity_constraints( &self, _params: &IntegrationParameters<N>, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _assembly_id: usize, _dof_id: usize, _ext_vels: &[N], _ground_j_id: &mut usize, _jacobians: &mut [N], _velocity_constraints: &mut ConstraintSet<N, (), (), usize>, ) { } /// The maximum number of non-linear position constraints that can be generated by this joint. fn num_position_constraints(&self) -> usize { 0 } /// Initialize and generate the i-th position constraints to enforce, e.g., joint limits. fn position_constraint( &self, _i: usize, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _handle: BodyPartHandle<()>, _dof_id: usize, _jacobians: &mut [N], ) -> Option<GenericNonlinearConstraint<N, ()>> { None } fn clone(&self) -> Box<dyn Joint<N>>; } impl_downcast!(Joint<N> where N: RealField);
random_line_split
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters}; /// Trait implemented by all joints following the reduced-coordinate formation. pub trait Joint<N: RealField>: Downcast + Send + Sync { /// The number of degrees of freedom allowed by the joint. fn ndofs(&self) -> usize; /// The position of the multibody link containing this joint relative to its parent. fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N>; /// Update the jacobians of this joint. fn update_jacobians(&mut self, body_shift: &Vector<N>, vels: &[N]); /// Integrate the position of this joint. fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]); /// Apply a displacement to the joint. fn apply_displacement(&mut self, disp: &[N]); /// Sets in `out` the non-zero entries of the joint jacobian transformed by `transform`. fn jacobian(&self, transform: &Isometry<N>, out: &mut JacobianSliceMut<N>); /// Sets in `out` the non-zero entries of the time-derivative of the joint jacobian transformed by `transform`. fn jacobian_dot(&self, transform: &Isometry<N>, out: &mut JacobianSliceMut<N>); /// Sets in `out` the non-zero entries of the velocity-derivative of the time-derivative of the joint jacobian transformed by `transform`. fn jacobian_dot_veldiff_mul_coordinates( &self, transform: &Isometry<N>, vels: &[N], out: &mut JacobianSliceMut<N>, ); /// Multiply the joint jacobian by generalized velocities to obtain the /// relative velocity of the multibody link containing this joint. fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N>; /// Multiply the joint jacobian by generalized accelerations to obtain the /// relative acceleration of the multibody link containing this joint. fn jacobian_dot_mul_coordinates(&self, vels: &[N]) -> Velocity<N>; /// Fill `out` with the non-zero entries of a damping that can be applied by default to ensure a good stability of the joint. fn default_damping(&self, out: &mut DVectorSliceMut<N>); /// The maximum number of impulses needed by this joints for /// its constraints. fn nimpulses(&self) -> usize { // FIXME: keep this? self.ndofs() * 3 } /// Maximum number of velocity constrains that can be generated by this joint. fn
(&self) -> usize { 0 } /// Initialize and generate velocity constraints to enforce, e.g., joint limits and motors. fn velocity_constraints( &self, _params: &IntegrationParameters<N>, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _assembly_id: usize, _dof_id: usize, _ext_vels: &[N], _ground_j_id: &mut usize, _jacobians: &mut [N], _velocity_constraints: &mut ConstraintSet<N, (), (), usize>, ) { } /// The maximum number of non-linear position constraints that can be generated by this joint. fn num_position_constraints(&self) -> usize { 0 } /// Initialize and generate the i-th position constraints to enforce, e.g., joint limits. fn position_constraint( &self, _i: usize, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _handle: BodyPartHandle<()>, _dof_id: usize, _jacobians: &mut [N], ) -> Option<GenericNonlinearConstraint<N, ()>> { None } fn clone(&self) -> Box<dyn Joint<N>>; } impl_downcast!(Joint<N> where N: RealField);
num_velocity_constraints
identifier_name
type-param-constraints.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. #![allow(non_camel_case_types)] #![allow(dead_code)] // pretty-expanded FIXME #23616 #![feature(box_syntax)] fn p_foo<T>(_pinned: T) { } fn s_foo<T>(_shared: T) { } fn u_foo<T:Send>(_unique: T) { } struct r { i: isize, } impl Drop for r { fn drop(&mut self) {} } fn r(i:isize) -> r
pub fn main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<Box<_>>(box 10); u_foo(10); }
{ r { i: i } }
identifier_body
type-param-constraints.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. #![allow(non_camel_case_types)] #![allow(dead_code)] // pretty-expanded FIXME #23616 #![feature(box_syntax)] fn p_foo<T>(_pinned: T) { } fn s_foo<T>(_shared: T) { } fn
<T:Send>(_unique: T) { } struct r { i: isize, } impl Drop for r { fn drop(&mut self) {} } fn r(i:isize) -> r { r { i: i } } pub fn main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<Box<_>>(box 10); u_foo(10); }
u_foo
identifier_name
type-param-constraints.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. #![allow(non_camel_case_types)] #![allow(dead_code)] // pretty-expanded FIXME #23616 #![feature(box_syntax)] fn p_foo<T>(_pinned: T) { } fn s_foo<T>(_shared: T) { } fn u_foo<T:Send>(_unique: T) { }
i: isize, } impl Drop for r { fn drop(&mut self) {} } fn r(i:isize) -> r { r { i: i } } pub fn main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<Box<_>>(box 10); u_foo(10); }
struct r {
random_line_split
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for -v, --verbose Use verbose output "; pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>>
{ debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>()); config.shell().set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); ops::generate_lockfile(&root, config) .map(|_| None).map_err(|err| CliError::from_boxed(err, 101)) }
identifier_body
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, }
pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for -v, --verbose Use verbose output "; pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> { debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>()); config.shell().set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); ops::generate_lockfile(&root, config) .map(|_| None).map_err(|err| CliError::from_boxed(err, 101)) }
random_line_split
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct
{ flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for -v, --verbose Use verbose output "; pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> { debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>()); config.shell().set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); ops::generate_lockfile(&root, config) .map(|_| None).map_err(|err| CliError::from_boxed(err, 101)) }
Options
identifier_name
structure.rs
KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic algebraic structures use num_traits::{cast, Float}; use std::cmp; use std::iter; use std::ops::*; use approx; use angle::Rad; use num::{BaseFloat, BaseNum}; pub use num_traits::{Bounded, Num, NumCast, One, Zero}; /// An array containing elements of type `Element` pub trait Array where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Index<usize, Output = <Self as Array>::Element>, Self: IndexMut<usize, Output = <Self as Array>::Element>, { type Element: Copy; /// Get the number of elements in the array type /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector3; /// /// assert_eq!(Vector3::<f32>::len(), 3); /// ``` fn len() -> usize; /// Construct a vector from a single value, replicating it. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector3; /// /// assert_eq!(Vector3::from_value(1), /// Vector3::new(1, 1, 1)); /// ``` fn from_value(value: Self::Element) -> Self; /// Get the pointer to the first element of the array. #[inline] fn as_ptr(&self) -> *const Self::Element { &self[0] } /// Get a mutable pointer to the first element of the array. #[inline] fn as_mut_ptr(&mut self) -> *mut Self::Element { &mut self[0] } /// Swap the elements at indices `i` and `j` in-place. #[inline] fn swap_elements(&mut self, i: usize, j: usize) { use std::ptr; // Yeah, ok borrow checker – I know what I'm doing here unsafe { ptr::swap(&mut self[i], &mut self[j]) }; } /// The sum of the elements of the array. fn sum(self) -> Self::Element where Self::Element: Add<Output = <Self as Array>::Element>; /// The product of the elements of the array. fn product(self) -> Self::Element where Self::Element: Mul<Output = <Self as Array>::Element>; /// Whether all elements of the array are finite fn is_finite(&self) -> bool where Self::Element: Float; } /// Element-wise arithmetic operations. These are supplied for pragmatic /// reasons, but will usually fall outside of traditional algebraic properties. pub trait ElementWise<Rhs = Self> { fn add_element_wise(self, rhs: Rhs) -> Self; fn sub_element_wise(self, rhs: Rhs) -> Self; fn mul_element_wise(self, rhs: Rhs) -> Self; fn div_element_wise(self, rhs: Rhs) -> Self; fn rem_element_wise(self, rhs: Rhs) -> Self; fn add_assign_element_wise(&mut self, rhs: Rhs); fn sub_assign_element_wise(&mut self, rhs: Rhs); fn mul_assign_element_wise(&mut self, rhs: Rhs); fn div_assign_element_wise(&mut self, rhs: Rhs); fn rem_assign_element_wise(&mut self, rhs: Rhs); } /// Vectors that can be [added](http://mathworld.wolfram.com/VectorAddition.html) /// together and [multiplied](https://en.wikipedia.org/wiki/Scalar_multiplication) /// by scalars. /// /// Examples include vectors, matrices, and quaternions. /// /// # Required operators /// /// ## Vector addition /// /// Vectors can be added, subtracted, or negated via the following traits: /// /// - `Add<Output = Self>` /// - `Sub<Output = Self>` /// - `Neg<Output = Self>` /// /// ```rust /// use cgmath::Vector3; /// /// let velocity0 = Vector3::new(1, 2, 0); /// let velocity1 = Vector3::new(1, 1, 0); /// /// let total_velocity = velocity0 + velocity1; /// let velocity_diff = velocity1 - velocity0; /// let reversed_velocity0 = -velocity0; /// ``` /// /// Vector spaces are also required to implement the additive identity trait, /// `Zero`. Adding this to another vector should have no effect: /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector2; /// /// let v = Vector2::new(1, 2); /// assert_eq!(v + Vector2::zero(), v); /// ``` /// /// ## Scalar multiplication /// /// Vectors can be multiplied or divided by their associated scalars via the /// following traits: /// /// - `Mul<Self::Scalar, Output = Self>` /// - `Div<Self::Scalar, Output = Self>` /// - `Rem<Self::Scalar, Output = Self>` /// /// ```rust /// use cgmath::Vector2; /// /// let translation = Vector2::new(3.0, 4.0); /// let scale_factor = 2.0; /// /// let upscaled_translation = translation * scale_factor; /// let downscaled_translation = translation / scale_factor; /// ``` pub trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: iter::Sum<Self>, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace>::Scalar, Output = Self>, Self: Rem<<Self as VectorSpace>::Scalar, Output = Self>, { /// The associated scalar. type Scalar: BaseNum; /// Returns the result of linearly interpolating the vector /// towards `other` by the specified amount. #[inline] fn lerp(self, other: Self, amount: Self::Scalar) -> Self { self + ((other - self) * amount) } } /// A type with a distance function between values. /// /// Examples are vectors, points, and quaternions. pub trait MetricSpace: Sized { /// The metric to be returned by the `distance` function. type Metric; /// Returns the squared distance. /// /// This does not perform an expensive square root operation like in /// `MetricSpace::distance` method, and so can be used to compare distances /// more efficiently. fn distance2(self, other: Self) -> Self::Metric; /// The distance between two values. fn distance(self, other: Self) -> Self::Metric where Self::Metric: Float, { Float::sqrt(Self::distance2(self, other)) } } /// Vectors that also have a [dot](https://en.wikipedia.org/wiki/Dot_product) /// (or [inner](https://en.wikipedia.org/wiki/Inner_product_space)) product. /// /// The dot product allows for the definition of other useful operations, like /// finding the magnitude of a vector or normalizing it. /// /// Examples include vectors and quaternions. pub trait InnerSpace: VectorSpace where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: MetricSpace<Metric = <Self as VectorSpace>::Scalar>, { /// Vector dot (or inner) product. fn dot(self, other: Self) -> Self::Scalar; /// Returns `true` if the vector is perpendicular (at right angles) to the /// other vector. fn is_perpendicular(self, other: Self) -> bool where Self::Scalar: approx::UlpsEq, { ulps_eq!(Self::dot(self, other), &Self::Scalar::zero()) } /// Returns the squared magnitude. /// /// This does not perform an expensive square root operation like in /// `InnerSpace::magnitude` method, and so can be used to compare magnitudes /// more efficiently. #[inline] fn magnitude2(self) -> Self::Scalar { Self::dot(self, self) } /// Returns the angle between two vectors in radians. fn angle(self, other: Self) -> Rad<Self::Scalar> where Self::Scalar: BaseFloat, { Rad::acos(Self::dot(self, other) / (self.magnitude() * other.magnitude())) } /// Returns the /// [vector projection](https://en.wikipedia.org/wiki/Vector_projection) /// of the current inner space projected onto the supplied argument. #[inline] fn project_on(self, other: Self) -> Self { other * (self.dot(other) / other.magnitude2()) } /// The distance from the tail to the tip of the vector. #[inline] fn magnitude(self) -> Self::Scalar where Self::Scalar: Float, { Float::sqrt(self.magnitude2()) } /// Returns a vector with the same direction, but with a magnitude of `1`. #[inline] fn normalize(self) -> Self where Self::Scalar: Float, { self.normalize_to(Self::Scalar::one()) } /// Returns a vector with the same direction and a given magnitude. #[inline] fn normalize_to(self, magnitude: Self::Scalar) -> Self where Self::Scalar: Float, { self * (magnitude / self.magnitude()) } } /// Points in a [Euclidean space](https://en.wikipedia.org/wiki/Euclidean_space) /// with an associated space of displacement vectors. /// /// # Point-Vector distinction /// /// `cgmath` distinguishes between points and vectors in the following way: /// /// - Points are _locations_ relative to an origin /// - Vectors are _displacements_ between those points /// /// For example, to find the midpoint between two points, you can write the /// following: /// /// ```rust /// use cgmath::Point3; /// /// let p0 = Point3::new(1.0, 2.0, 3.0); /// let p1 = Point3::new(-3.0, 1.0, 2.0); /// let midpoint: Point3<f32> = p0 + (p1 - p0) * 0.5; /// ``` /// /// Breaking the expression up, and adding explicit types makes it clearer /// to see what is going on: /// /// ```rust /// # use cgmath::{Point3, Vector3}; /// # /// # let p0 = Point3::new(1.0, 2.0, 3.0); /// # let p1 = Point3::new(-3.0, 1.0, 2.0); /// # /// let dv: Vector3<f32> = p1 - p0; /// let half_dv: Vector3<f32> = dv * 0.5; /// let midpoint: Point3<f32> = p0 + half_dv; /// ``` /// /// ## Converting between points and vectors /// /// Points can be converted to and from displacement vectors using the /// `EuclideanSpace::{from_vec, to_vec}` methods. Note that under the hood these /// are implemented as inlined a type conversion, so should not have any /// performance implications. /// /// ## References /// /// - [CGAL 4.7 - 2D and 3D Linear Geometry Kernel: 3.1 Points and Vectors](http://doc.cgal.org/latest/Kernel_23/index.html#Kernel_23PointsandVectors) /// - [What is the difference between a point and a vector](http://math.stackexchange.com/q/645827) /// pub trait EuclideanSpace: Copy + Clone where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Array<Element = <Self as EuclideanSpace>::Scalar>, Self: Add<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<Self, Output = <Self as EuclideanSpace>::Diff>, Self: Mul<<Self as EuclideanSpace>::Scalar, Output = Self>, Self: Div<<Self as EuclideanSpace>::Scalar, Output = Self>, Self: Rem<<Self as EuclideanSpace>::Scalar, Output = Self>, { /// The associated scalar over which the space is defined. /// /// Due to the equality constraints demanded by `Self::Diff`, this is effectively just an /// alias to `Self::Diff::Scalar`. type Scalar: BaseNum; /// The associated space of displacement vectors. type Diff: VectorSpace<Scalar = Self::Scalar>; /// The point at the origin of the Euclidean space. fn origin() -> Self; /// Convert a displacement vector to a point. /// /// This can be considered equivalent to the addition of the displacement /// vector `v` to to `Self::origin()`. fn from_vec(v: Self::Diff) -> Self; /// Convert a point to a displacement vector. /// /// This can be seen as equivalent to the displacement vector from /// `Self::origin()` to `self`. fn to_vec(self) -> Self::Diff; /// Returns the middle point between two other points. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Point3; /// /// let p = Point3::midpoint( /// Point3::new(1.0, 2.0, 3.0), /// Point3::new(3.0, 1.0, 2.0), /// ); /// ``` #[inline] fn midpoint(self, other: Self) -> Self { self + (other - self) / (Self::Scalar::one() + Self::Scalar::one()) } /// Returns the average position of all points in the slice. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Point2; /// /// let triangle = [ /// Point2::new(1.0, 1.0), /// Point2::new(2.0, 3.0), /// Point2::new(3.0, 1.0), /// ]; /// /// let centroid = Point2::centroid(&triangle); /// ``` #[inline] fn centroid(points: &[Self]) -> Self where Self::Scalar: NumCast { let total_displacement = points .iter() .fold(Self::Diff::zero(), |acc, p| acc + p.to_vec()); Self::from_vec(total_displacement / cast(points.len()).unwrap()) } /// This is a weird one, but its useful for plane calculations. fn dot(self, v: Self::Diff) -> Self::Scalar; } /// A column-major matrix of arbitrary dimensions. /// /// Because this is constrained to the `VectorSpace` trait, this means that /// following operators are required to be implemented: /// /// Matrix addition: /// /// - `Add<Output = Self>` /// - `Sub<Output = Self>` /// - `Neg<Output = Self>` /// /// Scalar multiplication: /// /// - `Mul<Self::Scalar, Output = Self>` /// - `Div<Self::Scalar, Output = Self>` /// - `Rem<Self::Scalar, Output = Self>` /// /// Note that matrix multiplication is not required for implementors of this /// trait. This is due to the complexities of implementing these operators with /// Rust's current type system. For the multiplication of square matrices, /// see `SquareMatrix`. pub trait Matrix: VectorSpace where Self::Scalar: Num, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Index<usize, Output = <Self as Matrix>::Column>, Self: IndexMut<usize, Output = <Self as Matrix>::Column>, { /// The row vector of the matrix. type Row: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// The column vector of the matrix. type Column: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// The result of transposing the matrix type Transpose: Matrix<Scalar = Self::Scalar, Row = Self::Column, Column = Self::Row>; /// Get the pointer to the first element of the array. #[inline] fn as_ptr(&self) -> *const Self::Scalar { &self[0][0] } /// Get a mutable pointer to the first element of the array. #[inline] fn as_mut_ptr(&mut self) -> *mut Self::Scalar { &mut self[0][0] } /// Replace a column in the array. #[inline] fn replace_col(&mut self, c: usize, src: Self::Column) -> Self::Column { use std::mem; mem::replace(&mut self[c], src) } /// Get a row from this matrix by-value. fn row(&self, r: usize) -> Self::Row; /// Swap two rows of this array. fn swap_rows(&mut self, a: usize, b: usize); /// Swap two columns of this array. fn swap_columns(&mut self, a: usize, b: usize); /// Swap the values at index `a` and `b` fn swap_elements(&mut self, a: (usize, usize), b: (usize, usize)); /// Transpose this matrix, returning a new matrix. fn transpose(&self) -> Self::Transpose; } /// A column-major major matrix where the rows and column vectors are of the same dimensions. pub trait SquareMatrix where Self::Scalar: Num, Self: One, Self: iter::Product<Self>, Self: Matrix< // FIXME: Can be cleaned up once equality constraints in where clauses are implemented Column = <Self as SquareMatrix>::ColumnRow, Row = <Self as SquareMatrix>::ColumnRow, Transpose = Self, >, Self: Mul<<Self as SquareMatrix>::ColumnRow, Output = <Self as SquareMatrix>::ColumnRow>, Self: Mul<Self, Output = Self>, { // FIXME: Will not be needed once equality constraints in where clauses are implemented /// The row/column vector of the matrix. /// /// This is used to constrain the column and rows to be of the same type in lieu of equality /// constraints being implemented for `where` clauses. Once those are added, this type will /// likely go away. type ColumnRow: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// Create a new diagonal matrix using the supplied value. fn from_value(value: Self::Scalar) -> Self; /// Create a matrix from a non-uniform scale fn from_diagonal(diagonal: Self::ColumnRow) -> Self; /// The [identity matrix]. Multiplying this matrix with another should have /// no effect. /// /// Note that this is exactly the same as `One::one`. The term 'identity /// matrix' is more common though, so we provide this method as an /// alternative. /// /// [identity matrix]: https://en.wikipedia.org/wiki/Identity_matrix #[inline] fn identity() -> Self { Self::one() } /// Transpose this matrix in-place. fn transpose_self(&mut self); /// Take the determinant of this matrix. fn determinant(&self) -> Self::Scalar; /// Return a vector containing the diagonal of this matrix. fn diagonal(&self) -> Self::ColumnRow; /// Return the trace of this matrix. That is, the sum of the diagonal. #[inline] fn trace(&self) -> Self::Scalar {
/// Invert this matrix, returning a new matrix. `m.mul_m(m.invert())` is /// the identity matrix. Returns `None` if this matrix is not invertible /// (has a determinant of zero). fn invert(&self) -> Option<Self>; /// Test if this matrix is invertible. #[inline] fn is_invertible(&self) -> bool where Self::Scalar: approx::UlpsEq, { ulps_ne!(self.determinant(), &Self::Scalar::zero()) } /// Test if this matrix is the identity matrix. That is, it is diagonal /// and every element in the diagonal is one. #[inline] fn is_identity(&self) -> bool where Self: approx::UlpsEq, { ulps_eq!(self, &Self::identity()) } /// Test if this is a diagonal matrix. That is, every element outside of /// the diagonal is 0. fn is_diagonal(&self) -> bool; /// Test if this matrix is symmetric. That is, it is equal to its /// transpose. fn is_symmetric(&self) -> bool; } /// Angles, and their associated trigonometric functions. /// /// Typed angles allow for the writing of self-documenting code that makes it /// clear when semantic violations have occurred - for example, adding degrees to /// radians, or adding a number to an angle. /// pub trait Angle where Self: Copy + Clone, Self: PartialEq + cmp::PartialOrd, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: approx::AbsDiffEq<Epsilon = <Self as Angle>::Unitless>, Self: approx::RelativeEq<Epsilon = <Self as Angle>::Unitless>, Self: approx::UlpsEq<Epsilon = <Self as Angle>::Unitless>, Self: Zero, Self: Neg<Output = Self>, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: Rem<Self, Output = Self>, Self: Mul<<Self as Angle>::Unitless, Output = Self>, Self: Div<Self, Output = <Self as Angle>::Unitless>, Self: Div<<Self as Angle>::Unitless, Output = Self>, Self: iter::Sum, { type Unitless: BaseFloat; /// Return the angle, normalized to the range `[0, full_turn]`. #[inline] fn normalize(self) -> Self { let rem = self % Self::full_turn(); if rem < Self::zero() { rem + Self::full_turn() } else { rem } } /// Return the angle, normalized to the range `[-turn_div_2, turn_div_2]`. #[inline] fn normalize_signed(self) -> Self { let rem = self.normalize(); if Self::turn_div_2() < rem { rem - Self::full_turn() } else { rem } } /// Return the angle rotated by half a turn. #[inline] fn opposite(self) -> Self { Self::normalize(self + Self::turn_div_2()) } /// Returns the interior bisector of the two angles. #[inline] fn bisect(self, other: Self) -> Self { let half = cast(0.5f64).unwrap(); Self::normalize((self - other) * half + self) } /// A full rotation. fn full_turn() -> Self; /// Half of a full rotation. #[inline] fn turn_div_2() -> Self { let factor: Self::Unitless = cast(2).unwrap(); Self::full_turn() / factor } /// A third of a full rotation. #[inline] fn turn_div_3() -> Self { let factor: Self::Unitless = cast(3).unwrap(); Self::full_turn() / factor } /// A quarter of a full rotation. #[inline] fn turn_div_4() -> Self { let factor: Self::Unitless = cast(4).unwrap(); Self::full_turn() / factor } /// A sixth of a full rotation. #[inline] fn turn_div_6() -> Self { let factor: Self::Unitless = cast(6).unwrap(); Self::full_turn() / factor } /// Compute the sine of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::sin(angle); /// ``` fn sin(self) -> Self::Unitless; /// Compute the cosine of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::cos(angle); /// ``` fn cos(self) -> Self::Unitless; /// Compute the tangent of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::tan(angle); /// ``` fn tan(self) -> Self::Unitless; /// Compute the sine and cosine of the angle, returning the result as a /// pair. /// /// This does not have any performance benefits, but calculating both the /// sine and cosine of a single angle is a common operation. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let (s, c) = Rad::sin_cos(angle); /// ``` fn sin_cos(self) -> (Self::Unitless, Self::Unitless); /// Compute the cosecant of the angle. /// /// This is the same as computing the reciprocal of `Self::sin`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::csc(angle); /// ``` #[inline] fn csc(self) -> Self::Unitless { Self::sin(self).recip() } /// Compute the cotangent of the angle. /// /// This is the same as computing the reciprocal of `Self::tan`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::cot(angle); /// ``` #[inline] fn cot(self) -> Self::Unitless { Self::tan(self).recip() } /// Compute the secant of the angle. /// /// This is the same as computing the reciprocal of `Self::cos`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::sec(angle); /// ``` #[inline] fn sec(self) -> Self::Unitless { Self::cos(self).recip() }
self.diagonal().sum() }
identifier_body
structure.rs
, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic algebraic structures use num_traits::{cast, Float}; use std::cmp; use std::iter; use std::ops::*; use approx; use angle::Rad; use num::{BaseFloat, BaseNum}; pub use num_traits::{Bounded, Num, NumCast, One, Zero}; /// An array containing elements of type `Element` pub trait Array where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Index<usize, Output = <Self as Array>::Element>, Self: IndexMut<usize, Output = <Self as Array>::Element>, { type Element: Copy; /// Get the number of elements in the array type /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector3; /// /// assert_eq!(Vector3::<f32>::len(), 3); /// ``` fn len() -> usize; /// Construct a vector from a single value, replicating it. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector3; /// /// assert_eq!(Vector3::from_value(1), /// Vector3::new(1, 1, 1)); /// ``` fn from_value(value: Self::Element) -> Self; /// Get the pointer to the first element of the array. #[inline] fn as_ptr(&self) -> *const Self::Element { &self[0] } /// Get a mutable pointer to the first element of the array. #[inline] fn as_mut_ptr(&mut self) -> *mut Self::Element { &mut self[0] } /// Swap the elements at indices `i` and `j` in-place. #[inline] fn swap_elements(&mut self, i: usize, j: usize) { use std::ptr; // Yeah, ok borrow checker – I know what I'm doing here unsafe { ptr::swap(&mut self[i], &mut self[j]) }; } /// The sum of the elements of the array. fn sum(self) -> Self::Element where Self::Element: Add<Output = <Self as Array>::Element>; /// The product of the elements of the array. fn product(self) -> Self::Element where Self::Element: Mul<Output = <Self as Array>::Element>; /// Whether all elements of the array are finite fn is_finite(&self) -> bool where Self::Element: Float; } /// Element-wise arithmetic operations. These are supplied for pragmatic /// reasons, but will usually fall outside of traditional algebraic properties. pub trait ElementWise<Rhs = Self> { fn add_element_wise(self, rhs: Rhs) -> Self; fn sub_element_wise(self, rhs: Rhs) -> Self; fn mul_element_wise(self, rhs: Rhs) -> Self; fn div_element_wise(self, rhs: Rhs) -> Self; fn rem_element_wise(self, rhs: Rhs) -> Self; fn add_assign_element_wise(&mut self, rhs: Rhs); fn sub_assign_element_wise(&mut self, rhs: Rhs); fn mul_assign_element_wise(&mut self, rhs: Rhs); fn div_assign_element_wise(&mut self, rhs: Rhs); fn rem_assign_element_wise(&mut self, rhs: Rhs); } /// Vectors that can be [added](http://mathworld.wolfram.com/VectorAddition.html) /// together and [multiplied](https://en.wikipedia.org/wiki/Scalar_multiplication) /// by scalars. /// /// Examples include vectors, matrices, and quaternions. /// /// # Required operators /// /// ## Vector addition /// /// Vectors can be added, subtracted, or negated via the following traits: /// /// - `Add<Output = Self>` /// - `Sub<Output = Self>` /// - `Neg<Output = Self>` /// /// ```rust /// use cgmath::Vector3; /// /// let velocity0 = Vector3::new(1, 2, 0); /// let velocity1 = Vector3::new(1, 1, 0); /// /// let total_velocity = velocity0 + velocity1; /// let velocity_diff = velocity1 - velocity0; /// let reversed_velocity0 = -velocity0; /// ``` /// /// Vector spaces are also required to implement the additive identity trait, /// `Zero`. Adding this to another vector should have no effect: /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector2; /// /// let v = Vector2::new(1, 2); /// assert_eq!(v + Vector2::zero(), v); /// ``` /// /// ## Scalar multiplication /// /// Vectors can be multiplied or divided by their associated scalars via the /// following traits: /// /// - `Mul<Self::Scalar, Output = Self>` /// - `Div<Self::Scalar, Output = Self>` /// - `Rem<Self::Scalar, Output = Self>` /// /// ```rust /// use cgmath::Vector2; /// /// let translation = Vector2::new(3.0, 4.0); /// let scale_factor = 2.0; /// /// let upscaled_translation = translation * scale_factor; /// let downscaled_translation = translation / scale_factor; /// ``` pub trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: iter::Sum<Self>, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace>::Scalar, Output = Self>, Self: Rem<<Self as VectorSpace>::Scalar, Output = Self>, { /// The associated scalar. type Scalar: BaseNum; /// Returns the result of linearly interpolating the vector /// towards `other` by the specified amount. #[inline] fn lerp(self, other: Self, amount: Self::Scalar) -> Self { self + ((other - self) * amount) } } /// A type with a distance function between values. /// /// Examples are vectors, points, and quaternions. pub trait MetricSpace: Sized { /// The metric to be returned by the `distance` function. type Metric; /// Returns the squared distance. /// /// This does not perform an expensive square root operation like in /// `MetricSpace::distance` method, and so can be used to compare distances /// more efficiently. fn distance2(self, other: Self) -> Self::Metric; /// The distance between two values. fn distance(self, other: Self) -> Self::Metric where Self::Metric: Float, { Float::sqrt(Self::distance2(self, other)) } } /// Vectors that also have a [dot](https://en.wikipedia.org/wiki/Dot_product) /// (or [inner](https://en.wikipedia.org/wiki/Inner_product_space)) product. /// /// The dot product allows for the definition of other useful operations, like /// finding the magnitude of a vector or normalizing it. /// /// Examples include vectors and quaternions. pub trait InnerSpace: VectorSpace where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: MetricSpace<Metric = <Self as VectorSpace>::Scalar>, { /// Vector dot (or inner) product. fn dot(self, other: Self) -> Self::Scalar; /// Returns `true` if the vector is perpendicular (at right angles) to the /// other vector. fn is_perpendicular(self, other: Self) -> bool where Self::Scalar: approx::UlpsEq, { ulps_eq!(Self::dot(self, other), &Self::Scalar::zero()) } /// Returns the squared magnitude. /// /// This does not perform an expensive square root operation like in /// `InnerSpace::magnitude` method, and so can be used to compare magnitudes /// more efficiently. #[inline] fn magnitude2(self) -> Self::Scalar { Self::dot(self, self) } /// Returns the angle between two vectors in radians. fn angle(self, other: Self) -> Rad<Self::Scalar> where Self::Scalar: BaseFloat, { Rad::acos(Self::dot(self, other) / (self.magnitude() * other.magnitude())) } /// Returns the /// [vector projection](https://en.wikipedia.org/wiki/Vector_projection) /// of the current inner space projected onto the supplied argument. #[inline] fn project_on(self, other: Self) -> Self { other * (self.dot(other) / other.magnitude2()) } /// The distance from the tail to the tip of the vector. #[inline] fn magnitude(self) -> Self::Scalar where Self::Scalar: Float, { Float::sqrt(self.magnitude2()) } /// Returns a vector with the same direction, but with a magnitude of `1`. #[inline] fn normalize(self) -> Self where Self::Scalar: Float, { self.normalize_to(Self::Scalar::one()) } /// Returns a vector with the same direction and a given magnitude. #[inline] fn normalize_to(self, magnitude: Self::Scalar) -> Self where Self::Scalar: Float, { self * (magnitude / self.magnitude()) } } /// Points in a [Euclidean space](https://en.wikipedia.org/wiki/Euclidean_space) /// with an associated space of displacement vectors. /// /// # Point-Vector distinction /// /// `cgmath` distinguishes between points and vectors in the following way: /// /// - Points are _locations_ relative to an origin /// - Vectors are _displacements_ between those points /// /// For example, to find the midpoint between two points, you can write the /// following: /// /// ```rust /// use cgmath::Point3; /// /// let p0 = Point3::new(1.0, 2.0, 3.0); /// let p1 = Point3::new(-3.0, 1.0, 2.0); /// let midpoint: Point3<f32> = p0 + (p1 - p0) * 0.5; /// ``` /// /// Breaking the expression up, and adding explicit types makes it clearer /// to see what is going on: /// /// ```rust /// # use cgmath::{Point3, Vector3}; /// # /// # let p0 = Point3::new(1.0, 2.0, 3.0); /// # let p1 = Point3::new(-3.0, 1.0, 2.0); /// # /// let dv: Vector3<f32> = p1 - p0; /// let half_dv: Vector3<f32> = dv * 0.5; /// let midpoint: Point3<f32> = p0 + half_dv; /// ``` /// /// ## Converting between points and vectors /// /// Points can be converted to and from displacement vectors using the /// `EuclideanSpace::{from_vec, to_vec}` methods. Note that under the hood these /// are implemented as inlined a type conversion, so should not have any /// performance implications. /// /// ## References /// /// - [CGAL 4.7 - 2D and 3D Linear Geometry Kernel: 3.1 Points and Vectors](http://doc.cgal.org/latest/Kernel_23/index.html#Kernel_23PointsandVectors) /// - [What is the difference between a point and a vector](http://math.stackexchange.com/q/645827) /// pub trait EuclideanSpace: Copy + Clone where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Array<Element = <Self as EuclideanSpace>::Scalar>, Self: Add<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<Self, Output = <Self as EuclideanSpace>::Diff>, Self: Mul<<Self as EuclideanSpace>::Scalar, Output = Self>, Self: Div<<Self as EuclideanSpace>::Scalar, Output = Self>, Self: Rem<<Self as EuclideanSpace>::Scalar, Output = Self>, { /// The associated scalar over which the space is defined. /// /// Due to the equality constraints demanded by `Self::Diff`, this is effectively just an /// alias to `Self::Diff::Scalar`. type Scalar: BaseNum; /// The associated space of displacement vectors. type Diff: VectorSpace<Scalar = Self::Scalar>; /// The point at the origin of the Euclidean space. fn origin() -> Self; /// Convert a displacement vector to a point. /// /// This can be considered equivalent to the addition of the displacement /// vector `v` to to `Self::origin()`. fn from_vec(v: Self::Diff) -> Self; /// Convert a point to a displacement vector. /// /// This can be seen as equivalent to the displacement vector from /// `Self::origin()` to `self`. fn to_vec(self) -> Self::Diff; /// Returns the middle point between two other points. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Point3; /// /// let p = Point3::midpoint( /// Point3::new(1.0, 2.0, 3.0), /// Point3::new(3.0, 1.0, 2.0), /// ); /// ``` #[inline] fn midpoint(self, other: Self) -> Self { self + (other - self) / (Self::Scalar::one() + Self::Scalar::one()) } /// Returns the average position of all points in the slice. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Point2; /// /// let triangle = [ /// Point2::new(1.0, 1.0), /// Point2::new(2.0, 3.0), /// Point2::new(3.0, 1.0), /// ]; /// /// let centroid = Point2::centroid(&triangle); /// ``` #[inline] fn centroid(points: &[Self]) -> Self where Self::Scalar: NumCast { let total_displacement = points .iter() .fold(Self::Diff::zero(), |acc, p| acc + p.to_vec()); Self::from_vec(total_displacement / cast(points.len()).unwrap()) } /// This is a weird one, but its useful for plane calculations. fn dot(self, v: Self::Diff) -> Self::Scalar; } /// A column-major matrix of arbitrary dimensions. /// /// Because this is constrained to the `VectorSpace` trait, this means that /// following operators are required to be implemented: /// /// Matrix addition: /// /// - `Add<Output = Self>` /// - `Sub<Output = Self>` /// - `Neg<Output = Self>` /// /// Scalar multiplication: /// /// - `Mul<Self::Scalar, Output = Self>` /// - `Div<Self::Scalar, Output = Self>` /// - `Rem<Self::Scalar, Output = Self>` /// /// Note that matrix multiplication is not required for implementors of this /// trait. This is due to the complexities of implementing these operators with /// Rust's current type system. For the multiplication of square matrices, /// see `SquareMatrix`. pub trait Matrix: VectorSpace where Self::Scalar: Num, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Index<usize, Output = <Self as Matrix>::Column>, Self: IndexMut<usize, Output = <Self as Matrix>::Column>, { /// The row vector of the matrix. type Row: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// The column vector of the matrix. type Column: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// The result of transposing the matrix type Transpose: Matrix<Scalar = Self::Scalar, Row = Self::Column, Column = Self::Row>; /// Get the pointer to the first element of the array. #[inline] fn as_ptr(&self) -> *const Self::Scalar { &self[0][0] } /// Get a mutable pointer to the first element of the array. #[inline] fn as_mut_ptr(&mut self) -> *mut Self::Scalar { &mut self[0][0] } /// Replace a column in the array. #[inline] fn replace_col(&mut self, c: usize, src: Self::Column) -> Self::Column { use std::mem; mem::replace(&mut self[c], src) } /// Get a row from this matrix by-value. fn row(&self, r: usize) -> Self::Row; /// Swap two rows of this array. fn swap_rows(&mut self, a: usize, b: usize); /// Swap two columns of this array. fn swap_columns(&mut self, a: usize, b: usize); /// Swap the values at index `a` and `b` fn swap_elements(&mut self, a: (usize, usize), b: (usize, usize)); /// Transpose this matrix, returning a new matrix. fn transpose(&self) -> Self::Transpose; } /// A column-major major matrix where the rows and column vectors are of the same dimensions. pub trait SquareMatrix where Self::Scalar: Num, Self: One, Self: iter::Product<Self>, Self: Matrix< // FIXME: Can be cleaned up once equality constraints in where clauses are implemented Column = <Self as SquareMatrix>::ColumnRow, Row = <Self as SquareMatrix>::ColumnRow, Transpose = Self, >, Self: Mul<<Self as SquareMatrix>::ColumnRow, Output = <Self as SquareMatrix>::ColumnRow>, Self: Mul<Self, Output = Self>, { // FIXME: Will not be needed once equality constraints in where clauses are implemented /// The row/column vector of the matrix. /// /// This is used to constrain the column and rows to be of the same type in lieu of equality /// constraints being implemented for `where` clauses. Once those are added, this type will /// likely go away. type ColumnRow: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// Create a new diagonal matrix using the supplied value. fn from_value(value: Self::Scalar) -> Self; /// Create a matrix from a non-uniform scale fn from_diagonal(diagonal: Self::ColumnRow) -> Self; /// The [identity matrix]. Multiplying this matrix with another should have /// no effect. /// /// Note that this is exactly the same as `One::one`. The term 'identity /// matrix' is more common though, so we provide this method as an /// alternative. /// /// [identity matrix]: https://en.wikipedia.org/wiki/Identity_matrix #[inline] fn id
-> Self { Self::one() } /// Transpose this matrix in-place. fn transpose_self(&mut self); /// Take the determinant of this matrix. fn determinant(&self) -> Self::Scalar; /// Return a vector containing the diagonal of this matrix. fn diagonal(&self) -> Self::ColumnRow; /// Return the trace of this matrix. That is, the sum of the diagonal. #[inline] fn trace(&self) -> Self::Scalar { self.diagonal().sum() } /// Invert this matrix, returning a new matrix. `m.mul_m(m.invert())` is /// the identity matrix. Returns `None` if this matrix is not invertible /// (has a determinant of zero). fn invert(&self) -> Option<Self>; /// Test if this matrix is invertible. #[inline] fn is_invertible(&self) -> bool where Self::Scalar: approx::UlpsEq, { ulps_ne!(self.determinant(), &Self::Scalar::zero()) } /// Test if this matrix is the identity matrix. That is, it is diagonal /// and every element in the diagonal is one. #[inline] fn is_identity(&self) -> bool where Self: approx::UlpsEq, { ulps_eq!(self, &Self::identity()) } /// Test if this is a diagonal matrix. That is, every element outside of /// the diagonal is 0. fn is_diagonal(&self) -> bool; /// Test if this matrix is symmetric. That is, it is equal to its /// transpose. fn is_symmetric(&self) -> bool; } /// Angles, and their associated trigonometric functions. /// /// Typed angles allow for the writing of self-documenting code that makes it /// clear when semantic violations have occurred - for example, adding degrees to /// radians, or adding a number to an angle. /// pub trait Angle where Self: Copy + Clone, Self: PartialEq + cmp::PartialOrd, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: approx::AbsDiffEq<Epsilon = <Self as Angle>::Unitless>, Self: approx::RelativeEq<Epsilon = <Self as Angle>::Unitless>, Self: approx::UlpsEq<Epsilon = <Self as Angle>::Unitless>, Self: Zero, Self: Neg<Output = Self>, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: Rem<Self, Output = Self>, Self: Mul<<Self as Angle>::Unitless, Output = Self>, Self: Div<Self, Output = <Self as Angle>::Unitless>, Self: Div<<Self as Angle>::Unitless, Output = Self>, Self: iter::Sum, { type Unitless: BaseFloat; /// Return the angle, normalized to the range `[0, full_turn]`. #[inline] fn normalize(self) -> Self { let rem = self % Self::full_turn(); if rem < Self::zero() { rem + Self::full_turn() } else { rem } } /// Return the angle, normalized to the range `[-turn_div_2, turn_div_2]`. #[inline] fn normalize_signed(self) -> Self { let rem = self.normalize(); if Self::turn_div_2() < rem { rem - Self::full_turn() } else { rem } } /// Return the angle rotated by half a turn. #[inline] fn opposite(self) -> Self { Self::normalize(self + Self::turn_div_2()) } /// Returns the interior bisector of the two angles. #[inline] fn bisect(self, other: Self) -> Self { let half = cast(0.5f64).unwrap(); Self::normalize((self - other) * half + self) } /// A full rotation. fn full_turn() -> Self; /// Half of a full rotation. #[inline] fn turn_div_2() -> Self { let factor: Self::Unitless = cast(2).unwrap(); Self::full_turn() / factor } /// A third of a full rotation. #[inline] fn turn_div_3() -> Self { let factor: Self::Unitless = cast(3).unwrap(); Self::full_turn() / factor } /// A quarter of a full rotation. #[inline] fn turn_div_4() -> Self { let factor: Self::Unitless = cast(4).unwrap(); Self::full_turn() / factor } /// A sixth of a full rotation. #[inline] fn turn_div_6() -> Self { let factor: Self::Unitless = cast(6).unwrap(); Self::full_turn() / factor } /// Compute the sine of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::sin(angle); /// ``` fn sin(self) -> Self::Unitless; /// Compute the cosine of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::cos(angle); /// ``` fn cos(self) -> Self::Unitless; /// Compute the tangent of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::tan(angle); /// ``` fn tan(self) -> Self::Unitless; /// Compute the sine and cosine of the angle, returning the result as a /// pair. /// /// This does not have any performance benefits, but calculating both the /// sine and cosine of a single angle is a common operation. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let (s, c) = Rad::sin_cos(angle); /// ``` fn sin_cos(self) -> (Self::Unitless, Self::Unitless); /// Compute the cosecant of the angle. /// /// This is the same as computing the reciprocal of `Self::sin`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::csc(angle); /// ``` #[inline] fn csc(self) -> Self::Unitless { Self::sin(self).recip() } /// Compute the cotangent of the angle. /// /// This is the same as computing the reciprocal of `Self::tan`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::cot(angle); /// ``` #[inline] fn cot(self) -> Self::Unitless { Self::tan(self).recip() } /// Compute the secant of the angle. /// /// This is the same as computing the reciprocal of `Self::cos`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::sec(angle); /// ``` #[inline] fn sec(self) -> Self::Unitless { Self::cos(self).recip() }
entity()
identifier_name
structure.rs
KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic algebraic structures use num_traits::{cast, Float}; use std::cmp; use std::iter; use std::ops::*; use approx; use angle::Rad; use num::{BaseFloat, BaseNum}; pub use num_traits::{Bounded, Num, NumCast, One, Zero}; /// An array containing elements of type `Element` pub trait Array where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Index<usize, Output = <Self as Array>::Element>, Self: IndexMut<usize, Output = <Self as Array>::Element>, { type Element: Copy; /// Get the number of elements in the array type /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector3; /// /// assert_eq!(Vector3::<f32>::len(), 3); /// ``` fn len() -> usize; /// Construct a vector from a single value, replicating it. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector3; /// /// assert_eq!(Vector3::from_value(1), /// Vector3::new(1, 1, 1)); /// ``` fn from_value(value: Self::Element) -> Self; /// Get the pointer to the first element of the array. #[inline] fn as_ptr(&self) -> *const Self::Element { &self[0] } /// Get a mutable pointer to the first element of the array. #[inline] fn as_mut_ptr(&mut self) -> *mut Self::Element { &mut self[0] } /// Swap the elements at indices `i` and `j` in-place. #[inline] fn swap_elements(&mut self, i: usize, j: usize) { use std::ptr; // Yeah, ok borrow checker – I know what I'm doing here unsafe { ptr::swap(&mut self[i], &mut self[j]) }; } /// The sum of the elements of the array. fn sum(self) -> Self::Element where Self::Element: Add<Output = <Self as Array>::Element>; /// The product of the elements of the array. fn product(self) -> Self::Element where Self::Element: Mul<Output = <Self as Array>::Element>; /// Whether all elements of the array are finite fn is_finite(&self) -> bool where Self::Element: Float; } /// Element-wise arithmetic operations. These are supplied for pragmatic /// reasons, but will usually fall outside of traditional algebraic properties. pub trait ElementWise<Rhs = Self> { fn add_element_wise(self, rhs: Rhs) -> Self; fn sub_element_wise(self, rhs: Rhs) -> Self; fn mul_element_wise(self, rhs: Rhs) -> Self; fn div_element_wise(self, rhs: Rhs) -> Self; fn rem_element_wise(self, rhs: Rhs) -> Self; fn add_assign_element_wise(&mut self, rhs: Rhs); fn sub_assign_element_wise(&mut self, rhs: Rhs); fn mul_assign_element_wise(&mut self, rhs: Rhs); fn div_assign_element_wise(&mut self, rhs: Rhs); fn rem_assign_element_wise(&mut self, rhs: Rhs); } /// Vectors that can be [added](http://mathworld.wolfram.com/VectorAddition.html) /// together and [multiplied](https://en.wikipedia.org/wiki/Scalar_multiplication) /// by scalars. /// /// Examples include vectors, matrices, and quaternions. /// /// # Required operators /// /// ## Vector addition /// /// Vectors can be added, subtracted, or negated via the following traits: /// /// - `Add<Output = Self>` /// - `Sub<Output = Self>` /// - `Neg<Output = Self>` /// /// ```rust /// use cgmath::Vector3; /// /// let velocity0 = Vector3::new(1, 2, 0); /// let velocity1 = Vector3::new(1, 1, 0); /// /// let total_velocity = velocity0 + velocity1; /// let velocity_diff = velocity1 - velocity0; /// let reversed_velocity0 = -velocity0; /// ``` /// /// Vector spaces are also required to implement the additive identity trait, /// `Zero`. Adding this to another vector should have no effect: /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector2; /// /// let v = Vector2::new(1, 2); /// assert_eq!(v + Vector2::zero(), v); /// ``` /// /// ## Scalar multiplication /// /// Vectors can be multiplied or divided by their associated scalars via the /// following traits: /// /// - `Mul<Self::Scalar, Output = Self>` /// - `Div<Self::Scalar, Output = Self>` /// - `Rem<Self::Scalar, Output = Self>` /// /// ```rust /// use cgmath::Vector2; /// /// let translation = Vector2::new(3.0, 4.0); /// let scale_factor = 2.0; /// /// let upscaled_translation = translation * scale_factor; /// let downscaled_translation = translation / scale_factor; /// ``` pub trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: iter::Sum<Self>, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace>::Scalar, Output = Self>, Self: Rem<<Self as VectorSpace>::Scalar, Output = Self>, { /// The associated scalar. type Scalar: BaseNum; /// Returns the result of linearly interpolating the vector /// towards `other` by the specified amount. #[inline] fn lerp(self, other: Self, amount: Self::Scalar) -> Self { self + ((other - self) * amount) } } /// A type with a distance function between values. /// /// Examples are vectors, points, and quaternions. pub trait MetricSpace: Sized { /// The metric to be returned by the `distance` function. type Metric; /// Returns the squared distance. /// /// This does not perform an expensive square root operation like in /// `MetricSpace::distance` method, and so can be used to compare distances /// more efficiently. fn distance2(self, other: Self) -> Self::Metric; /// The distance between two values. fn distance(self, other: Self) -> Self::Metric where Self::Metric: Float, { Float::sqrt(Self::distance2(self, other)) } } /// Vectors that also have a [dot](https://en.wikipedia.org/wiki/Dot_product) /// (or [inner](https://en.wikipedia.org/wiki/Inner_product_space)) product. /// /// The dot product allows for the definition of other useful operations, like /// finding the magnitude of a vector or normalizing it. /// /// Examples include vectors and quaternions. pub trait InnerSpace: VectorSpace where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: MetricSpace<Metric = <Self as VectorSpace>::Scalar>, { /// Vector dot (or inner) product. fn dot(self, other: Self) -> Self::Scalar; /// Returns `true` if the vector is perpendicular (at right angles) to the /// other vector. fn is_perpendicular(self, other: Self) -> bool where Self::Scalar: approx::UlpsEq, { ulps_eq!(Self::dot(self, other), &Self::Scalar::zero()) } /// Returns the squared magnitude. /// /// This does not perform an expensive square root operation like in /// `InnerSpace::magnitude` method, and so can be used to compare magnitudes /// more efficiently. #[inline] fn magnitude2(self) -> Self::Scalar { Self::dot(self, self) } /// Returns the angle between two vectors in radians. fn angle(self, other: Self) -> Rad<Self::Scalar> where Self::Scalar: BaseFloat, { Rad::acos(Self::dot(self, other) / (self.magnitude() * other.magnitude())) } /// Returns the /// [vector projection](https://en.wikipedia.org/wiki/Vector_projection) /// of the current inner space projected onto the supplied argument. #[inline] fn project_on(self, other: Self) -> Self { other * (self.dot(other) / other.magnitude2()) } /// The distance from the tail to the tip of the vector. #[inline] fn magnitude(self) -> Self::Scalar where Self::Scalar: Float, { Float::sqrt(self.magnitude2()) } /// Returns a vector with the same direction, but with a magnitude of `1`. #[inline] fn normalize(self) -> Self where Self::Scalar: Float, { self.normalize_to(Self::Scalar::one()) } /// Returns a vector with the same direction and a given magnitude. #[inline] fn normalize_to(self, magnitude: Self::Scalar) -> Self where Self::Scalar: Float, { self * (magnitude / self.magnitude()) } } /// Points in a [Euclidean space](https://en.wikipedia.org/wiki/Euclidean_space) /// with an associated space of displacement vectors. /// /// # Point-Vector distinction /// /// `cgmath` distinguishes between points and vectors in the following way: /// /// - Points are _locations_ relative to an origin /// - Vectors are _displacements_ between those points /// /// For example, to find the midpoint between two points, you can write the /// following: /// /// ```rust /// use cgmath::Point3; /// /// let p0 = Point3::new(1.0, 2.0, 3.0); /// let p1 = Point3::new(-3.0, 1.0, 2.0); /// let midpoint: Point3<f32> = p0 + (p1 - p0) * 0.5; /// ``` /// /// Breaking the expression up, and adding explicit types makes it clearer /// to see what is going on: /// /// ```rust /// # use cgmath::{Point3, Vector3}; /// # /// # let p0 = Point3::new(1.0, 2.0, 3.0); /// # let p1 = Point3::new(-3.0, 1.0, 2.0); /// # /// let dv: Vector3<f32> = p1 - p0; /// let half_dv: Vector3<f32> = dv * 0.5; /// let midpoint: Point3<f32> = p0 + half_dv; /// ``` /// /// ## Converting between points and vectors /// /// Points can be converted to and from displacement vectors using the /// `EuclideanSpace::{from_vec, to_vec}` methods. Note that under the hood these /// are implemented as inlined a type conversion, so should not have any /// performance implications. /// /// ## References /// /// - [CGAL 4.7 - 2D and 3D Linear Geometry Kernel: 3.1 Points and Vectors](http://doc.cgal.org/latest/Kernel_23/index.html#Kernel_23PointsandVectors) /// - [What is the difference between a point and a vector](http://math.stackexchange.com/q/645827) /// pub trait EuclideanSpace: Copy + Clone where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Array<Element = <Self as EuclideanSpace>::Scalar>, Self: Add<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<Self, Output = <Self as EuclideanSpace>::Diff>, Self: Mul<<Self as EuclideanSpace>::Scalar, Output = Self>, Self: Div<<Self as EuclideanSpace>::Scalar, Output = Self>, Self: Rem<<Self as EuclideanSpace>::Scalar, Output = Self>, { /// The associated scalar over which the space is defined. /// /// Due to the equality constraints demanded by `Self::Diff`, this is effectively just an /// alias to `Self::Diff::Scalar`. type Scalar: BaseNum; /// The associated space of displacement vectors. type Diff: VectorSpace<Scalar = Self::Scalar>; /// The point at the origin of the Euclidean space. fn origin() -> Self; /// Convert a displacement vector to a point. /// /// This can be considered equivalent to the addition of the displacement /// vector `v` to to `Self::origin()`. fn from_vec(v: Self::Diff) -> Self; /// Convert a point to a displacement vector. /// /// This can be seen as equivalent to the displacement vector from /// `Self::origin()` to `self`. fn to_vec(self) -> Self::Diff; /// Returns the middle point between two other points. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Point3; /// /// let p = Point3::midpoint( /// Point3::new(1.0, 2.0, 3.0), /// Point3::new(3.0, 1.0, 2.0), /// ); /// ``` #[inline] fn midpoint(self, other: Self) -> Self { self + (other - self) / (Self::Scalar::one() + Self::Scalar::one()) } /// Returns the average position of all points in the slice. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Point2; /// /// let triangle = [ /// Point2::new(1.0, 1.0), /// Point2::new(2.0, 3.0), /// Point2::new(3.0, 1.0), /// ]; /// /// let centroid = Point2::centroid(&triangle); /// ``` #[inline] fn centroid(points: &[Self]) -> Self where Self::Scalar: NumCast { let total_displacement = points .iter() .fold(Self::Diff::zero(), |acc, p| acc + p.to_vec()); Self::from_vec(total_displacement / cast(points.len()).unwrap()) } /// This is a weird one, but its useful for plane calculations. fn dot(self, v: Self::Diff) -> Self::Scalar; } /// A column-major matrix of arbitrary dimensions. /// /// Because this is constrained to the `VectorSpace` trait, this means that /// following operators are required to be implemented: /// /// Matrix addition: /// /// - `Add<Output = Self>` /// - `Sub<Output = Self>` /// - `Neg<Output = Self>` /// /// Scalar multiplication: /// /// - `Mul<Self::Scalar, Output = Self>` /// - `Div<Self::Scalar, Output = Self>` /// - `Rem<Self::Scalar, Output = Self>` /// /// Note that matrix multiplication is not required for implementors of this /// trait. This is due to the complexities of implementing these operators with /// Rust's current type system. For the multiplication of square matrices, /// see `SquareMatrix`. pub trait Matrix: VectorSpace where Self::Scalar: Num, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Index<usize, Output = <Self as Matrix>::Column>, Self: IndexMut<usize, Output = <Self as Matrix>::Column>, { /// The row vector of the matrix. type Row: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// The column vector of the matrix. type Column: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// The result of transposing the matrix type Transpose: Matrix<Scalar = Self::Scalar, Row = Self::Column, Column = Self::Row>; /// Get the pointer to the first element of the array. #[inline] fn as_ptr(&self) -> *const Self::Scalar { &self[0][0] } /// Get a mutable pointer to the first element of the array. #[inline] fn as_mut_ptr(&mut self) -> *mut Self::Scalar { &mut self[0][0] } /// Replace a column in the array. #[inline] fn replace_col(&mut self, c: usize, src: Self::Column) -> Self::Column { use std::mem; mem::replace(&mut self[c], src) } /// Get a row from this matrix by-value. fn row(&self, r: usize) -> Self::Row; /// Swap two rows of this array. fn swap_rows(&mut self, a: usize, b: usize); /// Swap two columns of this array. fn swap_columns(&mut self, a: usize, b: usize); /// Swap the values at index `a` and `b` fn swap_elements(&mut self, a: (usize, usize), b: (usize, usize)); /// Transpose this matrix, returning a new matrix. fn transpose(&self) -> Self::Transpose; } /// A column-major major matrix where the rows and column vectors are of the same dimensions. pub trait SquareMatrix where Self::Scalar: Num, Self: One, Self: iter::Product<Self>, Self: Matrix< // FIXME: Can be cleaned up once equality constraints in where clauses are implemented Column = <Self as SquareMatrix>::ColumnRow, Row = <Self as SquareMatrix>::ColumnRow, Transpose = Self, >, Self: Mul<<Self as SquareMatrix>::ColumnRow, Output = <Self as SquareMatrix>::ColumnRow>, Self: Mul<Self, Output = Self>, { // FIXME: Will not be needed once equality constraints in where clauses are implemented /// The row/column vector of the matrix. /// /// This is used to constrain the column and rows to be of the same type in lieu of equality /// constraints being implemented for `where` clauses. Once those are added, this type will /// likely go away. type ColumnRow: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// Create a new diagonal matrix using the supplied value. fn from_value(value: Self::Scalar) -> Self; /// Create a matrix from a non-uniform scale fn from_diagonal(diagonal: Self::ColumnRow) -> Self; /// The [identity matrix]. Multiplying this matrix with another should have /// no effect. /// /// Note that this is exactly the same as `One::one`. The term 'identity /// matrix' is more common though, so we provide this method as an /// alternative. /// /// [identity matrix]: https://en.wikipedia.org/wiki/Identity_matrix #[inline] fn identity() -> Self { Self::one() } /// Transpose this matrix in-place. fn transpose_self(&mut self); /// Take the determinant of this matrix. fn determinant(&self) -> Self::Scalar; /// Return a vector containing the diagonal of this matrix. fn diagonal(&self) -> Self::ColumnRow; /// Return the trace of this matrix. That is, the sum of the diagonal. #[inline] fn trace(&self) -> Self::Scalar { self.diagonal().sum() } /// Invert this matrix, returning a new matrix. `m.mul_m(m.invert())` is /// the identity matrix. Returns `None` if this matrix is not invertible /// (has a determinant of zero). fn invert(&self) -> Option<Self>; /// Test if this matrix is invertible. #[inline] fn is_invertible(&self) -> bool where Self::Scalar: approx::UlpsEq, { ulps_ne!(self.determinant(), &Self::Scalar::zero()) } /// Test if this matrix is the identity matrix. That is, it is diagonal /// and every element in the diagonal is one. #[inline] fn is_identity(&self) -> bool where Self: approx::UlpsEq, { ulps_eq!(self, &Self::identity()) } /// Test if this is a diagonal matrix. That is, every element outside of /// the diagonal is 0. fn is_diagonal(&self) -> bool; /// Test if this matrix is symmetric. That is, it is equal to its /// transpose. fn is_symmetric(&self) -> bool; } /// Angles, and their associated trigonometric functions. /// /// Typed angles allow for the writing of self-documenting code that makes it /// clear when semantic violations have occurred - for example, adding degrees to /// radians, or adding a number to an angle. /// pub trait Angle where Self: Copy + Clone, Self: PartialEq + cmp::PartialOrd, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: approx::AbsDiffEq<Epsilon = <Self as Angle>::Unitless>, Self: approx::RelativeEq<Epsilon = <Self as Angle>::Unitless>, Self: approx::UlpsEq<Epsilon = <Self as Angle>::Unitless>, Self: Zero, Self: Neg<Output = Self>, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: Rem<Self, Output = Self>, Self: Mul<<Self as Angle>::Unitless, Output = Self>, Self: Div<Self, Output = <Self as Angle>::Unitless>, Self: Div<<Self as Angle>::Unitless, Output = Self>, Self: iter::Sum, { type Unitless: BaseFloat; /// Return the angle, normalized to the range `[0, full_turn]`. #[inline] fn normalize(self) -> Self { let rem = self % Self::full_turn(); if rem < Self::zero() { rem + Self::full_turn() } else { rem } } /// Return the angle, normalized to the range `[-turn_div_2, turn_div_2]`. #[inline] fn normalize_signed(self) -> Self { let rem = self.normalize(); if Self::turn_div_2() < rem { rem - Self::full_turn() } else {
} /// Return the angle rotated by half a turn. #[inline] fn opposite(self) -> Self { Self::normalize(self + Self::turn_div_2()) } /// Returns the interior bisector of the two angles. #[inline] fn bisect(self, other: Self) -> Self { let half = cast(0.5f64).unwrap(); Self::normalize((self - other) * half + self) } /// A full rotation. fn full_turn() -> Self; /// Half of a full rotation. #[inline] fn turn_div_2() -> Self { let factor: Self::Unitless = cast(2).unwrap(); Self::full_turn() / factor } /// A third of a full rotation. #[inline] fn turn_div_3() -> Self { let factor: Self::Unitless = cast(3).unwrap(); Self::full_turn() / factor } /// A quarter of a full rotation. #[inline] fn turn_div_4() -> Self { let factor: Self::Unitless = cast(4).unwrap(); Self::full_turn() / factor } /// A sixth of a full rotation. #[inline] fn turn_div_6() -> Self { let factor: Self::Unitless = cast(6).unwrap(); Self::full_turn() / factor } /// Compute the sine of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::sin(angle); /// ``` fn sin(self) -> Self::Unitless; /// Compute the cosine of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::cos(angle); /// ``` fn cos(self) -> Self::Unitless; /// Compute the tangent of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::tan(angle); /// ``` fn tan(self) -> Self::Unitless; /// Compute the sine and cosine of the angle, returning the result as a /// pair. /// /// This does not have any performance benefits, but calculating both the /// sine and cosine of a single angle is a common operation. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let (s, c) = Rad::sin_cos(angle); /// ``` fn sin_cos(self) -> (Self::Unitless, Self::Unitless); /// Compute the cosecant of the angle. /// /// This is the same as computing the reciprocal of `Self::sin`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::csc(angle); /// ``` #[inline] fn csc(self) -> Self::Unitless { Self::sin(self).recip() } /// Compute the cotangent of the angle. /// /// This is the same as computing the reciprocal of `Self::tan`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::cot(angle); /// ``` #[inline] fn cot(self) -> Self::Unitless { Self::tan(self).recip() } /// Compute the secant of the angle. /// /// This is the same as computing the reciprocal of `Self::cos`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::sec(angle); /// ``` #[inline] fn sec(self) -> Self::Unitless { Self::cos(self).recip() }
rem }
conditional_block
structure.rs
ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Generic algebraic structures use num_traits::{cast, Float}; use std::cmp; use std::iter; use std::ops::*; use approx; use angle::Rad; use num::{BaseFloat, BaseNum}; pub use num_traits::{Bounded, Num, NumCast, One, Zero}; /// An array containing elements of type `Element` pub trait Array where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Index<usize, Output = <Self as Array>::Element>, Self: IndexMut<usize, Output = <Self as Array>::Element>, { type Element: Copy; /// Get the number of elements in the array type /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector3; /// /// assert_eq!(Vector3::<f32>::len(), 3); /// ``` fn len() -> usize; /// Construct a vector from a single value, replicating it. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector3; /// /// assert_eq!(Vector3::from_value(1), /// Vector3::new(1, 1, 1)); /// ``` fn from_value(value: Self::Element) -> Self; /// Get the pointer to the first element of the array. #[inline] fn as_ptr(&self) -> *const Self::Element { &self[0] } /// Get a mutable pointer to the first element of the array. #[inline] fn as_mut_ptr(&mut self) -> *mut Self::Element { &mut self[0] } /// Swap the elements at indices `i` and `j` in-place. #[inline] fn swap_elements(&mut self, i: usize, j: usize) { use std::ptr; // Yeah, ok borrow checker – I know what I'm doing here unsafe { ptr::swap(&mut self[i], &mut self[j]) }; } /// The sum of the elements of the array. fn sum(self) -> Self::Element where Self::Element: Add<Output = <Self as Array>::Element>; /// The product of the elements of the array. fn product(self) -> Self::Element where Self::Element: Mul<Output = <Self as Array>::Element>; /// Whether all elements of the array are finite fn is_finite(&self) -> bool where Self::Element: Float; } /// Element-wise arithmetic operations. These are supplied for pragmatic /// reasons, but will usually fall outside of traditional algebraic properties. pub trait ElementWise<Rhs = Self> { fn add_element_wise(self, rhs: Rhs) -> Self; fn sub_element_wise(self, rhs: Rhs) -> Self; fn mul_element_wise(self, rhs: Rhs) -> Self; fn div_element_wise(self, rhs: Rhs) -> Self; fn rem_element_wise(self, rhs: Rhs) -> Self; fn add_assign_element_wise(&mut self, rhs: Rhs); fn sub_assign_element_wise(&mut self, rhs: Rhs); fn mul_assign_element_wise(&mut self, rhs: Rhs); fn div_assign_element_wise(&mut self, rhs: Rhs); fn rem_assign_element_wise(&mut self, rhs: Rhs); } /// Vectors that can be [added](http://mathworld.wolfram.com/VectorAddition.html) /// together and [multiplied](https://en.wikipedia.org/wiki/Scalar_multiplication) /// by scalars. /// /// Examples include vectors, matrices, and quaternions. /// /// # Required operators /// /// ## Vector addition /// /// Vectors can be added, subtracted, or negated via the following traits: /// /// - `Add<Output = Self>` /// - `Sub<Output = Self>` /// - `Neg<Output = Self>` /// /// ```rust /// use cgmath::Vector3; /// /// let velocity0 = Vector3::new(1, 2, 0); /// let velocity1 = Vector3::new(1, 1, 0); /// /// let total_velocity = velocity0 + velocity1; /// let velocity_diff = velocity1 - velocity0; /// let reversed_velocity0 = -velocity0; /// ``` /// /// Vector spaces are also required to implement the additive identity trait, /// `Zero`. Adding this to another vector should have no effect: /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Vector2; /// /// let v = Vector2::new(1, 2); /// assert_eq!(v + Vector2::zero(), v); /// ``` /// /// ## Scalar multiplication /// /// Vectors can be multiplied or divided by their associated scalars via the /// following traits: /// /// - `Mul<Self::Scalar, Output = Self>` /// - `Div<Self::Scalar, Output = Self>` /// - `Rem<Self::Scalar, Output = Self>` /// /// ```rust /// use cgmath::Vector2; /// /// let translation = Vector2::new(3.0, 4.0); /// let scale_factor = 2.0; /// /// let upscaled_translation = translation * scale_factor; /// let downscaled_translation = translation / scale_factor; /// ``` pub trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: iter::Sum<Self>, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace>::Scalar, Output = Self>, Self: Rem<<Self as VectorSpace>::Scalar, Output = Self>, { /// The associated scalar. type Scalar: BaseNum; /// Returns the result of linearly interpolating the vector /// towards `other` by the specified amount. #[inline] fn lerp(self, other: Self, amount: Self::Scalar) -> Self { self + ((other - self) * amount) } } /// A type with a distance function between values. /// /// Examples are vectors, points, and quaternions. pub trait MetricSpace: Sized { /// The metric to be returned by the `distance` function. type Metric; /// Returns the squared distance. /// /// This does not perform an expensive square root operation like in /// `MetricSpace::distance` method, and so can be used to compare distances /// more efficiently. fn distance2(self, other: Self) -> Self::Metric; /// The distance between two values. fn distance(self, other: Self) -> Self::Metric where Self::Metric: Float, { Float::sqrt(Self::distance2(self, other)) } } /// Vectors that also have a [dot](https://en.wikipedia.org/wiki/Dot_product) /// (or [inner](https://en.wikipedia.org/wiki/Inner_product_space)) product. /// /// The dot product allows for the definition of other useful operations, like /// finding the magnitude of a vector or normalizing it. /// /// Examples include vectors and quaternions. pub trait InnerSpace: VectorSpace where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: MetricSpace<Metric = <Self as VectorSpace>::Scalar>, { /// Vector dot (or inner) product. fn dot(self, other: Self) -> Self::Scalar; /// Returns `true` if the vector is perpendicular (at right angles) to the /// other vector. fn is_perpendicular(self, other: Self) -> bool where Self::Scalar: approx::UlpsEq, { ulps_eq!(Self::dot(self, other), &Self::Scalar::zero()) } /// Returns the squared magnitude. /// /// This does not perform an expensive square root operation like in /// `InnerSpace::magnitude` method, and so can be used to compare magnitudes /// more efficiently. #[inline] fn magnitude2(self) -> Self::Scalar { Self::dot(self, self) } /// Returns the angle between two vectors in radians. fn angle(self, other: Self) -> Rad<Self::Scalar> where Self::Scalar: BaseFloat, { Rad::acos(Self::dot(self, other) / (self.magnitude() * other.magnitude())) } /// Returns the /// [vector projection](https://en.wikipedia.org/wiki/Vector_projection) /// of the current inner space projected onto the supplied argument. #[inline] fn project_on(self, other: Self) -> Self { other * (self.dot(other) / other.magnitude2()) } /// The distance from the tail to the tip of the vector. #[inline] fn magnitude(self) -> Self::Scalar where Self::Scalar: Float, { Float::sqrt(self.magnitude2()) } /// Returns a vector with the same direction, but with a magnitude of `1`. #[inline] fn normalize(self) -> Self where Self::Scalar: Float, { self.normalize_to(Self::Scalar::one()) } /// Returns a vector with the same direction and a given magnitude. #[inline] fn normalize_to(self, magnitude: Self::Scalar) -> Self where Self::Scalar: Float, { self * (magnitude / self.magnitude()) } } /// Points in a [Euclidean space](https://en.wikipedia.org/wiki/Euclidean_space) /// with an associated space of displacement vectors. /// /// # Point-Vector distinction /// /// `cgmath` distinguishes between points and vectors in the following way: /// /// - Points are _locations_ relative to an origin /// - Vectors are _displacements_ between those points /// /// For example, to find the midpoint between two points, you can write the /// following: /// /// ```rust /// use cgmath::Point3; /// /// let p0 = Point3::new(1.0, 2.0, 3.0); /// let p1 = Point3::new(-3.0, 1.0, 2.0); /// let midpoint: Point3<f32> = p0 + (p1 - p0) * 0.5; /// ``` /// /// Breaking the expression up, and adding explicit types makes it clearer /// to see what is going on: /// /// ```rust /// # use cgmath::{Point3, Vector3}; /// # /// # let p0 = Point3::new(1.0, 2.0, 3.0); /// # let p1 = Point3::new(-3.0, 1.0, 2.0); /// # /// let dv: Vector3<f32> = p1 - p0; /// let half_dv: Vector3<f32> = dv * 0.5; /// let midpoint: Point3<f32> = p0 + half_dv; /// ``` /// /// ## Converting between points and vectors /// /// Points can be converted to and from displacement vectors using the /// `EuclideanSpace::{from_vec, to_vec}` methods. Note that under the hood these /// are implemented as inlined a type conversion, so should not have any /// performance implications. /// /// ## References /// /// - [CGAL 4.7 - 2D and 3D Linear Geometry Kernel: 3.1 Points and Vectors](http://doc.cgal.org/latest/Kernel_23/index.html#Kernel_23PointsandVectors)
/// pub trait EuclideanSpace: Copy + Clone where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Array<Element = <Self as EuclideanSpace>::Scalar>, Self: Add<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<Self, Output = <Self as EuclideanSpace>::Diff>, Self: Mul<<Self as EuclideanSpace>::Scalar, Output = Self>, Self: Div<<Self as EuclideanSpace>::Scalar, Output = Self>, Self: Rem<<Self as EuclideanSpace>::Scalar, Output = Self>, { /// The associated scalar over which the space is defined. /// /// Due to the equality constraints demanded by `Self::Diff`, this is effectively just an /// alias to `Self::Diff::Scalar`. type Scalar: BaseNum; /// The associated space of displacement vectors. type Diff: VectorSpace<Scalar = Self::Scalar>; /// The point at the origin of the Euclidean space. fn origin() -> Self; /// Convert a displacement vector to a point. /// /// This can be considered equivalent to the addition of the displacement /// vector `v` to to `Self::origin()`. fn from_vec(v: Self::Diff) -> Self; /// Convert a point to a displacement vector. /// /// This can be seen as equivalent to the displacement vector from /// `Self::origin()` to `self`. fn to_vec(self) -> Self::Diff; /// Returns the middle point between two other points. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Point3; /// /// let p = Point3::midpoint( /// Point3::new(1.0, 2.0, 3.0), /// Point3::new(3.0, 1.0, 2.0), /// ); /// ``` #[inline] fn midpoint(self, other: Self) -> Self { self + (other - self) / (Self::Scalar::one() + Self::Scalar::one()) } /// Returns the average position of all points in the slice. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Point2; /// /// let triangle = [ /// Point2::new(1.0, 1.0), /// Point2::new(2.0, 3.0), /// Point2::new(3.0, 1.0), /// ]; /// /// let centroid = Point2::centroid(&triangle); /// ``` #[inline] fn centroid(points: &[Self]) -> Self where Self::Scalar: NumCast { let total_displacement = points .iter() .fold(Self::Diff::zero(), |acc, p| acc + p.to_vec()); Self::from_vec(total_displacement / cast(points.len()).unwrap()) } /// This is a weird one, but its useful for plane calculations. fn dot(self, v: Self::Diff) -> Self::Scalar; } /// A column-major matrix of arbitrary dimensions. /// /// Because this is constrained to the `VectorSpace` trait, this means that /// following operators are required to be implemented: /// /// Matrix addition: /// /// - `Add<Output = Self>` /// - `Sub<Output = Self>` /// - `Neg<Output = Self>` /// /// Scalar multiplication: /// /// - `Mul<Self::Scalar, Output = Self>` /// - `Div<Self::Scalar, Output = Self>` /// - `Rem<Self::Scalar, Output = Self>` /// /// Note that matrix multiplication is not required for implementors of this /// trait. This is due to the complexities of implementing these operators with /// Rust's current type system. For the multiplication of square matrices, /// see `SquareMatrix`. pub trait Matrix: VectorSpace where Self::Scalar: Num, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Index<usize, Output = <Self as Matrix>::Column>, Self: IndexMut<usize, Output = <Self as Matrix>::Column>, { /// The row vector of the matrix. type Row: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// The column vector of the matrix. type Column: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// The result of transposing the matrix type Transpose: Matrix<Scalar = Self::Scalar, Row = Self::Column, Column = Self::Row>; /// Get the pointer to the first element of the array. #[inline] fn as_ptr(&self) -> *const Self::Scalar { &self[0][0] } /// Get a mutable pointer to the first element of the array. #[inline] fn as_mut_ptr(&mut self) -> *mut Self::Scalar { &mut self[0][0] } /// Replace a column in the array. #[inline] fn replace_col(&mut self, c: usize, src: Self::Column) -> Self::Column { use std::mem; mem::replace(&mut self[c], src) } /// Get a row from this matrix by-value. fn row(&self, r: usize) -> Self::Row; /// Swap two rows of this array. fn swap_rows(&mut self, a: usize, b: usize); /// Swap two columns of this array. fn swap_columns(&mut self, a: usize, b: usize); /// Swap the values at index `a` and `b` fn swap_elements(&mut self, a: (usize, usize), b: (usize, usize)); /// Transpose this matrix, returning a new matrix. fn transpose(&self) -> Self::Transpose; } /// A column-major major matrix where the rows and column vectors are of the same dimensions. pub trait SquareMatrix where Self::Scalar: Num, Self: One, Self: iter::Product<Self>, Self: Matrix< // FIXME: Can be cleaned up once equality constraints in where clauses are implemented Column = <Self as SquareMatrix>::ColumnRow, Row = <Self as SquareMatrix>::ColumnRow, Transpose = Self, >, Self: Mul<<Self as SquareMatrix>::ColumnRow, Output = <Self as SquareMatrix>::ColumnRow>, Self: Mul<Self, Output = Self>, { // FIXME: Will not be needed once equality constraints in where clauses are implemented /// The row/column vector of the matrix. /// /// This is used to constrain the column and rows to be of the same type in lieu of equality /// constraints being implemented for `where` clauses. Once those are added, this type will /// likely go away. type ColumnRow: VectorSpace<Scalar = Self::Scalar> + Array<Element = Self::Scalar>; /// Create a new diagonal matrix using the supplied value. fn from_value(value: Self::Scalar) -> Self; /// Create a matrix from a non-uniform scale fn from_diagonal(diagonal: Self::ColumnRow) -> Self; /// The [identity matrix]. Multiplying this matrix with another should have /// no effect. /// /// Note that this is exactly the same as `One::one`. The term 'identity /// matrix' is more common though, so we provide this method as an /// alternative. /// /// [identity matrix]: https://en.wikipedia.org/wiki/Identity_matrix #[inline] fn identity() -> Self { Self::one() } /// Transpose this matrix in-place. fn transpose_self(&mut self); /// Take the determinant of this matrix. fn determinant(&self) -> Self::Scalar; /// Return a vector containing the diagonal of this matrix. fn diagonal(&self) -> Self::ColumnRow; /// Return the trace of this matrix. That is, the sum of the diagonal. #[inline] fn trace(&self) -> Self::Scalar { self.diagonal().sum() } /// Invert this matrix, returning a new matrix. `m.mul_m(m.invert())` is /// the identity matrix. Returns `None` if this matrix is not invertible /// (has a determinant of zero). fn invert(&self) -> Option<Self>; /// Test if this matrix is invertible. #[inline] fn is_invertible(&self) -> bool where Self::Scalar: approx::UlpsEq, { ulps_ne!(self.determinant(), &Self::Scalar::zero()) } /// Test if this matrix is the identity matrix. That is, it is diagonal /// and every element in the diagonal is one. #[inline] fn is_identity(&self) -> bool where Self: approx::UlpsEq, { ulps_eq!(self, &Self::identity()) } /// Test if this is a diagonal matrix. That is, every element outside of /// the diagonal is 0. fn is_diagonal(&self) -> bool; /// Test if this matrix is symmetric. That is, it is equal to its /// transpose. fn is_symmetric(&self) -> bool; } /// Angles, and their associated trigonometric functions. /// /// Typed angles allow for the writing of self-documenting code that makes it /// clear when semantic violations have occurred - for example, adding degrees to /// radians, or adding a number to an angle. /// pub trait Angle where Self: Copy + Clone, Self: PartialEq + cmp::PartialOrd, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: approx::AbsDiffEq<Epsilon = <Self as Angle>::Unitless>, Self: approx::RelativeEq<Epsilon = <Self as Angle>::Unitless>, Self: approx::UlpsEq<Epsilon = <Self as Angle>::Unitless>, Self: Zero, Self: Neg<Output = Self>, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: Rem<Self, Output = Self>, Self: Mul<<Self as Angle>::Unitless, Output = Self>, Self: Div<Self, Output = <Self as Angle>::Unitless>, Self: Div<<Self as Angle>::Unitless, Output = Self>, Self: iter::Sum, { type Unitless: BaseFloat; /// Return the angle, normalized to the range `[0, full_turn]`. #[inline] fn normalize(self) -> Self { let rem = self % Self::full_turn(); if rem < Self::zero() { rem + Self::full_turn() } else { rem } } /// Return the angle, normalized to the range `[-turn_div_2, turn_div_2]`. #[inline] fn normalize_signed(self) -> Self { let rem = self.normalize(); if Self::turn_div_2() < rem { rem - Self::full_turn() } else { rem } } /// Return the angle rotated by half a turn. #[inline] fn opposite(self) -> Self { Self::normalize(self + Self::turn_div_2()) } /// Returns the interior bisector of the two angles. #[inline] fn bisect(self, other: Self) -> Self { let half = cast(0.5f64).unwrap(); Self::normalize((self - other) * half + self) } /// A full rotation. fn full_turn() -> Self; /// Half of a full rotation. #[inline] fn turn_div_2() -> Self { let factor: Self::Unitless = cast(2).unwrap(); Self::full_turn() / factor } /// A third of a full rotation. #[inline] fn turn_div_3() -> Self { let factor: Self::Unitless = cast(3).unwrap(); Self::full_turn() / factor } /// A quarter of a full rotation. #[inline] fn turn_div_4() -> Self { let factor: Self::Unitless = cast(4).unwrap(); Self::full_turn() / factor } /// A sixth of a full rotation. #[inline] fn turn_div_6() -> Self { let factor: Self::Unitless = cast(6).unwrap(); Self::full_turn() / factor } /// Compute the sine of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::sin(angle); /// ``` fn sin(self) -> Self::Unitless; /// Compute the cosine of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::cos(angle); /// ``` fn cos(self) -> Self::Unitless; /// Compute the tangent of the angle, returning a unitless ratio. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::tan(angle); /// ``` fn tan(self) -> Self::Unitless; /// Compute the sine and cosine of the angle, returning the result as a /// pair. /// /// This does not have any performance benefits, but calculating both the /// sine and cosine of a single angle is a common operation. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let (s, c) = Rad::sin_cos(angle); /// ``` fn sin_cos(self) -> (Self::Unitless, Self::Unitless); /// Compute the cosecant of the angle. /// /// This is the same as computing the reciprocal of `Self::sin`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::csc(angle); /// ``` #[inline] fn csc(self) -> Self::Unitless { Self::sin(self).recip() } /// Compute the cotangent of the angle. /// /// This is the same as computing the reciprocal of `Self::tan`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::cot(angle); /// ``` #[inline] fn cot(self) -> Self::Unitless { Self::tan(self).recip() } /// Compute the secant of the angle. /// /// This is the same as computing the reciprocal of `Self::cos`. /// /// ```rust /// use cgmath::prelude::*; /// use cgmath::Rad; /// /// let angle = Rad(35.0); /// let ratio: f32 = Rad::sec(angle); /// ``` #[inline] fn sec(self) -> Self::Unitless { Self::cos(self).recip() } ///
/// - [What is the difference between a point and a vector](http://math.stackexchange.com/q/645827)
random_line_split
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::UnionTypes::BlobOrString; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use encoding::all::UTF_8; use encoding::types::{EncoderTrap, Encoding}; use num_traits::ToPrimitive; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::cmp::{max, min}; use std::sync::Arc; #[derive(Clone, JSTraceable)] pub struct DataSlice { bytes: Arc<Vec<u8>>, bytes_start: usize, bytes_end: usize } impl DataSlice { /// Construct DataSlice from reference counted bytes pub fn new(bytes: Arc<Vec<u8>>, start: Option<i64>, end: Option<i64>) -> DataSlice { let size = bytes.len() as i64; let relativeStart: i64 = match start { None => 0, Some(start) => { if start < 0 { max(size + start, 0) } else { min(start, size) } } }; let relativeEnd: i64 = match end { None => size, Some(end) => { if end < 0 { max(size + end, 0) } else { min(end, size) } } }; let span: i64 = max(relativeEnd - relativeStart, 0); let start = relativeStart.to_usize().unwrap(); let end = (relativeStart + span).to_usize().unwrap(); DataSlice { bytes: bytes, bytes_start: start, bytes_end: end } } /// Construct an empty data slice pub fn empty() -> DataSlice { DataSlice { bytes: Arc::new(Vec::new()), bytes_start: 0, bytes_end: 0, } } /// Get sliced bytes pub fn
(&self) -> &[u8] { &self.bytes[self.bytes_start..self.bytes_end] } /// Get length of sliced bytes pub fn size(&self) -> u64 { (self.bytes_end as u64) - (self.bytes_start as u64) } } // https://w3c.github.io/FileAPI/#blob #[dom_struct] pub struct Blob { reflector_: Reflector, #[ignore_heap_size_of = "No clear owner"] data: DataSlice, typeString: String, isClosed_: Cell<bool>, } impl Blob { pub fn new(global: GlobalRef, slice: DataSlice, typeString: &str) -> Root<Blob> { let boxed_blob = box Blob::new_inherited(slice, typeString); reflect_dom_object(boxed_blob, global, BlobBinding::Wrap) } pub fn new_inherited(slice: DataSlice, typeString: &str) -> Blob { Blob { reflector_: Reflector::new(), data: slice, typeString: typeString.to_owned(), isClosed_: Cell::new(false), } } // https://w3c.github.io/FileAPI/#constructorBlob pub fn Constructor(global: GlobalRef, blobParts: Option<Vec<BlobOrString>>, blobPropertyBag: &BlobBinding::BlobPropertyBag) -> Fallible<Root<Blob>> { // TODO: accept other blobParts types - ArrayBuffer or ArrayBufferView let bytes: Vec<u8> = match blobParts { None => Vec::new(), Some(blobparts) => blob_parts_to_bytes(blobparts), }; let slice = DataSlice::new(Arc::new(bytes), None, None); Ok(Blob::new(global, slice, &blobPropertyBag.get_typestring())) } pub fn get_data(&self) -> &DataSlice { &self.data } } pub fn blob_parts_to_bytes(blobparts: Vec<BlobOrString>) -> Vec<u8> { blobparts.iter().flat_map(|blobpart| { match blobpart { &BlobOrString::String(ref s) => { UTF_8.encode(s, EncoderTrap::Replace).unwrap() }, &BlobOrString::Blob(ref b) => { b.get_data().get_bytes().to_vec() }, } }).collect::<Vec<u8>>() } impl BlobMethods for Blob { // https://w3c.github.io/FileAPI/#dfn-size fn Size(&self) -> u64 { self.data.size() } // https://w3c.github.io/FileAPI/#dfn-type fn Type(&self) -> DOMString { DOMString::from(self.typeString.clone()) } // https://w3c.github.io/FileAPI/#slice-method-algo fn Slice(&self, start: Option<i64>, end: Option<i64>, contentType: Option<DOMString>) -> Root<Blob> { let relativeContentType = match contentType { None => DOMString::new(), Some(mut str) => { if is_ascii_printable(&str) { str.make_ascii_lowercase(); str } else { DOMString::new() } } }; let global = self.global(); let bytes = self.data.bytes.clone(); Blob::new(global.r(), DataSlice::new(bytes, start, end), &relativeContentType) } // https://w3c.github.io/FileAPI/#dfn-isClosed fn IsClosed(&self) -> bool { self.isClosed_.get() } // https://w3c.github.io/FileAPI/#dfn-close fn Close(&self) { // Step 1 if self.isClosed_.get() { return; } // Step 2 self.isClosed_.set(true); // TODO Step 3 if Blob URL Store is implemented } } impl BlobBinding::BlobPropertyBag { pub fn get_typestring(&self) -> String { if is_ascii_printable(&self.type_) { self.type_.to_lowercase() } else { "".to_string() } } } fn is_ascii_printable(string: &str) -> bool { // Step 5.1 in Sec 5.1 of File API spec // https://w3c.github.io/FileAPI/#constructorBlob string.chars().all(|c| c >= '\x20' && c <= '\x7E') }
get_bytes
identifier_name
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::UnionTypes::BlobOrString; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use encoding::all::UTF_8; use encoding::types::{EncoderTrap, Encoding}; use num_traits::ToPrimitive; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::cmp::{max, min}; use std::sync::Arc; #[derive(Clone, JSTraceable)] pub struct DataSlice { bytes: Arc<Vec<u8>>, bytes_start: usize, bytes_end: usize }
let relativeStart: i64 = match start { None => 0, Some(start) => { if start < 0 { max(size + start, 0) } else { min(start, size) } } }; let relativeEnd: i64 = match end { None => size, Some(end) => { if end < 0 { max(size + end, 0) } else { min(end, size) } } }; let span: i64 = max(relativeEnd - relativeStart, 0); let start = relativeStart.to_usize().unwrap(); let end = (relativeStart + span).to_usize().unwrap(); DataSlice { bytes: bytes, bytes_start: start, bytes_end: end } } /// Construct an empty data slice pub fn empty() -> DataSlice { DataSlice { bytes: Arc::new(Vec::new()), bytes_start: 0, bytes_end: 0, } } /// Get sliced bytes pub fn get_bytes(&self) -> &[u8] { &self.bytes[self.bytes_start..self.bytes_end] } /// Get length of sliced bytes pub fn size(&self) -> u64 { (self.bytes_end as u64) - (self.bytes_start as u64) } } // https://w3c.github.io/FileAPI/#blob #[dom_struct] pub struct Blob { reflector_: Reflector, #[ignore_heap_size_of = "No clear owner"] data: DataSlice, typeString: String, isClosed_: Cell<bool>, } impl Blob { pub fn new(global: GlobalRef, slice: DataSlice, typeString: &str) -> Root<Blob> { let boxed_blob = box Blob::new_inherited(slice, typeString); reflect_dom_object(boxed_blob, global, BlobBinding::Wrap) } pub fn new_inherited(slice: DataSlice, typeString: &str) -> Blob { Blob { reflector_: Reflector::new(), data: slice, typeString: typeString.to_owned(), isClosed_: Cell::new(false), } } // https://w3c.github.io/FileAPI/#constructorBlob pub fn Constructor(global: GlobalRef, blobParts: Option<Vec<BlobOrString>>, blobPropertyBag: &BlobBinding::BlobPropertyBag) -> Fallible<Root<Blob>> { // TODO: accept other blobParts types - ArrayBuffer or ArrayBufferView let bytes: Vec<u8> = match blobParts { None => Vec::new(), Some(blobparts) => blob_parts_to_bytes(blobparts), }; let slice = DataSlice::new(Arc::new(bytes), None, None); Ok(Blob::new(global, slice, &blobPropertyBag.get_typestring())) } pub fn get_data(&self) -> &DataSlice { &self.data } } pub fn blob_parts_to_bytes(blobparts: Vec<BlobOrString>) -> Vec<u8> { blobparts.iter().flat_map(|blobpart| { match blobpart { &BlobOrString::String(ref s) => { UTF_8.encode(s, EncoderTrap::Replace).unwrap() }, &BlobOrString::Blob(ref b) => { b.get_data().get_bytes().to_vec() }, } }).collect::<Vec<u8>>() } impl BlobMethods for Blob { // https://w3c.github.io/FileAPI/#dfn-size fn Size(&self) -> u64 { self.data.size() } // https://w3c.github.io/FileAPI/#dfn-type fn Type(&self) -> DOMString { DOMString::from(self.typeString.clone()) } // https://w3c.github.io/FileAPI/#slice-method-algo fn Slice(&self, start: Option<i64>, end: Option<i64>, contentType: Option<DOMString>) -> Root<Blob> { let relativeContentType = match contentType { None => DOMString::new(), Some(mut str) => { if is_ascii_printable(&str) { str.make_ascii_lowercase(); str } else { DOMString::new() } } }; let global = self.global(); let bytes = self.data.bytes.clone(); Blob::new(global.r(), DataSlice::new(bytes, start, end), &relativeContentType) } // https://w3c.github.io/FileAPI/#dfn-isClosed fn IsClosed(&self) -> bool { self.isClosed_.get() } // https://w3c.github.io/FileAPI/#dfn-close fn Close(&self) { // Step 1 if self.isClosed_.get() { return; } // Step 2 self.isClosed_.set(true); // TODO Step 3 if Blob URL Store is implemented } } impl BlobBinding::BlobPropertyBag { pub fn get_typestring(&self) -> String { if is_ascii_printable(&self.type_) { self.type_.to_lowercase() } else { "".to_string() } } } fn is_ascii_printable(string: &str) -> bool { // Step 5.1 in Sec 5.1 of File API spec // https://w3c.github.io/FileAPI/#constructorBlob string.chars().all(|c| c >= '\x20' && c <= '\x7E') }
impl DataSlice { /// Construct DataSlice from reference counted bytes pub fn new(bytes: Arc<Vec<u8>>, start: Option<i64>, end: Option<i64>) -> DataSlice { let size = bytes.len() as i64;
random_line_split
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::UnionTypes::BlobOrString; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use encoding::all::UTF_8; use encoding::types::{EncoderTrap, Encoding}; use num_traits::ToPrimitive; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::cmp::{max, min}; use std::sync::Arc; #[derive(Clone, JSTraceable)] pub struct DataSlice { bytes: Arc<Vec<u8>>, bytes_start: usize, bytes_end: usize } impl DataSlice { /// Construct DataSlice from reference counted bytes pub fn new(bytes: Arc<Vec<u8>>, start: Option<i64>, end: Option<i64>) -> DataSlice { let size = bytes.len() as i64; let relativeStart: i64 = match start { None => 0, Some(start) => { if start < 0 { max(size + start, 0) } else { min(start, size) } } }; let relativeEnd: i64 = match end { None => size, Some(end) => { if end < 0 { max(size + end, 0) } else { min(end, size) } } }; let span: i64 = max(relativeEnd - relativeStart, 0); let start = relativeStart.to_usize().unwrap(); let end = (relativeStart + span).to_usize().unwrap(); DataSlice { bytes: bytes, bytes_start: start, bytes_end: end } } /// Construct an empty data slice pub fn empty() -> DataSlice { DataSlice { bytes: Arc::new(Vec::new()), bytes_start: 0, bytes_end: 0, } } /// Get sliced bytes pub fn get_bytes(&self) -> &[u8] { &self.bytes[self.bytes_start..self.bytes_end] } /// Get length of sliced bytes pub fn size(&self) -> u64 { (self.bytes_end as u64) - (self.bytes_start as u64) } } // https://w3c.github.io/FileAPI/#blob #[dom_struct] pub struct Blob { reflector_: Reflector, #[ignore_heap_size_of = "No clear owner"] data: DataSlice, typeString: String, isClosed_: Cell<bool>, } impl Blob { pub fn new(global: GlobalRef, slice: DataSlice, typeString: &str) -> Root<Blob> { let boxed_blob = box Blob::new_inherited(slice, typeString); reflect_dom_object(boxed_blob, global, BlobBinding::Wrap) } pub fn new_inherited(slice: DataSlice, typeString: &str) -> Blob { Blob { reflector_: Reflector::new(), data: slice, typeString: typeString.to_owned(), isClosed_: Cell::new(false), } } // https://w3c.github.io/FileAPI/#constructorBlob pub fn Constructor(global: GlobalRef, blobParts: Option<Vec<BlobOrString>>, blobPropertyBag: &BlobBinding::BlobPropertyBag) -> Fallible<Root<Blob>> { // TODO: accept other blobParts types - ArrayBuffer or ArrayBufferView let bytes: Vec<u8> = match blobParts { None => Vec::new(), Some(blobparts) => blob_parts_to_bytes(blobparts), }; let slice = DataSlice::new(Arc::new(bytes), None, None); Ok(Blob::new(global, slice, &blobPropertyBag.get_typestring())) } pub fn get_data(&self) -> &DataSlice { &self.data } } pub fn blob_parts_to_bytes(blobparts: Vec<BlobOrString>) -> Vec<u8> { blobparts.iter().flat_map(|blobpart| { match blobpart { &BlobOrString::String(ref s) => { UTF_8.encode(s, EncoderTrap::Replace).unwrap() }, &BlobOrString::Blob(ref b) =>
, } }).collect::<Vec<u8>>() } impl BlobMethods for Blob { // https://w3c.github.io/FileAPI/#dfn-size fn Size(&self) -> u64 { self.data.size() } // https://w3c.github.io/FileAPI/#dfn-type fn Type(&self) -> DOMString { DOMString::from(self.typeString.clone()) } // https://w3c.github.io/FileAPI/#slice-method-algo fn Slice(&self, start: Option<i64>, end: Option<i64>, contentType: Option<DOMString>) -> Root<Blob> { let relativeContentType = match contentType { None => DOMString::new(), Some(mut str) => { if is_ascii_printable(&str) { str.make_ascii_lowercase(); str } else { DOMString::new() } } }; let global = self.global(); let bytes = self.data.bytes.clone(); Blob::new(global.r(), DataSlice::new(bytes, start, end), &relativeContentType) } // https://w3c.github.io/FileAPI/#dfn-isClosed fn IsClosed(&self) -> bool { self.isClosed_.get() } // https://w3c.github.io/FileAPI/#dfn-close fn Close(&self) { // Step 1 if self.isClosed_.get() { return; } // Step 2 self.isClosed_.set(true); // TODO Step 3 if Blob URL Store is implemented } } impl BlobBinding::BlobPropertyBag { pub fn get_typestring(&self) -> String { if is_ascii_printable(&self.type_) { self.type_.to_lowercase() } else { "".to_string() } } } fn is_ascii_printable(string: &str) -> bool { // Step 5.1 in Sec 5.1 of File API spec // https://w3c.github.io/FileAPI/#constructorBlob string.chars().all(|c| c >= '\x20' && c <= '\x7E') }
{ b.get_data().get_bytes().to_vec() }
conditional_block
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn
(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); for byte in bytes.iter() { while!serial_status.readf(0x20) {} serial_data.write(*byte); if *byte == 8 { while!serial_status.readf(0x20) {} serial_data.write(0x20); while!serial_status.readf(0x20) {} serial_data.write(8); } } } Ok(len) }
do_sys_debug
identifier_name
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); for byte in bytes.iter() { while!serial_status.readf(0x20) {} serial_data.write(*byte); if *byte == 8 { while!serial_status.readf(0x20) {} serial_data.write(0x20); while!serial_status.readf(0x20) {} serial_data.write(8); }
Ok(len) }
} }
random_line_split
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); for byte in bytes.iter() { while!serial_status.readf(0x20) {} serial_data.write(*byte); if *byte == 8
} } Ok(len) }
{ while !serial_status.readf(0x20) {} serial_data.write(0x20); while !serial_status.readf(0x20) {} serial_data.write(8); }
conditional_block
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize>
} } Ok(len) }
{ let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); for byte in bytes.iter() { while !serial_status.readf(0x20) {} serial_data.write(*byte); if *byte == 8 { while !serial_status.readf(0x20) {} serial_data.write(0x20); while !serial_status.readf(0x20) {} serial_data.write(8); }
identifier_body
ascii.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! 7-bit ASCII encoding. use libtww::std::mem; use libtww::std::convert::Into; use types::*; /** * ASCII, also known as ISO/IEC 646:US. * * It is both a basis and a lowest common denominator of many other encodings * including UTF-8, which Rust internally assumes. */
pub struct ASCIIEncoding; impl Encoding for ASCIIEncoding { fn name(&self) -> &'static str { "ascii" } fn raw_encoder(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } } /// An encoder for ASCII. #[derive(Clone, Copy)] pub struct ASCIIEncoder; impl ASCIIEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ASCIIEncoder) } } impl RawEncoder for ASCIIEncoder { fn from_self(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn is_ascii_compatible(&self) -> bool { true } fn raw_feed(&mut self, input: &str, output: &mut ByteWriter) -> (usize, Option<CodecError>) { output.writer_hint(input.len()); match input.as_bytes().iter().position(|&ch| ch >= 0x80) { Some(first_error) => { output.write_bytes(&input.as_bytes()[..first_error]); let len = input[first_error..].chars().next().unwrap().len_utf8(); (first_error, Some(CodecError { upto: (first_error + len) as isize, cause: "unrepresentable character".into(), })) } None => { output.write_bytes(input.as_bytes()); (input.len(), None) } } } fn raw_finish(&mut self, _output: &mut ByteWriter) -> Option<CodecError> { None } } /// A decoder for ASCII. #[derive(Clone, Copy)] pub struct ASCIIDecoder; impl ASCIIDecoder { pub fn new() -> Box<RawDecoder> { Box::new(ASCIIDecoder) } } impl RawDecoder for ASCIIDecoder { fn from_self(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } fn is_ascii_compatible(&self) -> bool { true } fn raw_feed(&mut self, input: &[u8], output: &mut StringWriter) -> (usize, Option<CodecError>) { output.writer_hint(input.len()); fn write_ascii_bytes(output: &mut StringWriter, buf: &[u8]) { output.write_str(unsafe { mem::transmute(buf) }); } match input.iter().position(|&ch| ch >= 0x80) { Some(first_error) => { write_ascii_bytes(output, &input[..first_error]); (first_error, Some(CodecError { upto: first_error as isize + 1, cause: "invalid sequence".into(), })) } None => { write_ascii_bytes(output, input); (input.len(), None) } } } fn raw_finish(&mut self, _output: &mut StringWriter) -> Option<CodecError> { None } } #[cfg(test)] mod tests { extern crate test; use super::ASCIIEncoding; use testutils; use types::*; #[test] fn test_encoder() { let mut e = ASCIIEncoding.raw_encoder(); assert_feed_ok!(e, "A", "", [0x41]); assert_feed_ok!(e, "BC", "", [0x42, 0x43]); assert_feed_ok!(e, "", "", []); assert_feed_err!(e, "", "\u{a0}", "", []); assert_feed_err!(e, "X", "\u{a0}", "Z", [0x58]); assert_finish_ok!(e, []); } #[test] fn test_decoder() { let mut d = ASCIIEncoding.raw_decoder(); assert_feed_ok!(d, [0x41], [], "A"); assert_feed_ok!(d, [0x42, 0x43], [], "BC"); assert_feed_ok!(d, [], [], ""); assert_feed_err!(d, [], [0xa0], [], ""); assert_feed_err!(d, [0x58], [0xa0], [0x5a], "X"); assert_finish_ok!(d, ""); } #[bench] fn bench_encode(bencher: &mut test::Bencher) { let s = testutils::ASCII_TEXT; bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.encode(s, EncoderTrap::Strict) }) }) } #[bench] fn bench_decode(bencher: &mut test::Bencher) { let s = testutils::ASCII_TEXT.as_bytes(); bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.decode(s, DecoderTrap::Strict) }) }) } #[bench] fn bench_encode_replace(bencher: &mut test::Bencher) { let s = testutils::KOREAN_TEXT; bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.encode(s, EncoderTrap::Replace) }) }) } #[bench] fn bench_decode_replace(bencher: &mut test::Bencher) { let s = testutils::KOREAN_TEXT.as_bytes(); bencher.bytes = s.len() as u64; bencher.iter(|| { test::black_box({ ASCIIEncoding.decode(s, DecoderTrap::Replace) }) }) } }
#[derive(Clone, Copy)]
random_line_split