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
local-drop-glue.rs
// // We specify -C incremental here because we want to test the partitioning for // incremental compilation // We specify opt-level=0 because `drop_in_place` is `Internal` when optimizing // compile-flags:-Zprint-mono-items=lazy -Cincremental=tmp/partitioning-tests/local-drop-glue // compile-flags:-Zinline-in-all-cgus -Copt-level=0 #![allow(dead_code)] #![crate_type = "rlib"] //~ MONO_ITEM fn std::ptr::drop_in_place::<Struct> - shim(Some(Struct)) @@ local_drop_glue-fallback.cgu[External] struct Struct { _a: u32, } impl Drop for Struct { //~ MONO_ITEM fn <Struct as std::ops::Drop>::drop @@ local_drop_glue-fallback.cgu[External] fn drop(&mut self)
} //~ MONO_ITEM fn std::ptr::drop_in_place::<Outer> - shim(Some(Outer)) @@ local_drop_glue-fallback.cgu[External] struct Outer { _a: Struct, } //~ MONO_ITEM fn user @@ local_drop_glue[External] pub fn user() { let _ = Outer { _a: Struct { _a: 0 } }; } pub mod mod1 { use super::Struct; //~ MONO_ITEM fn std::ptr::drop_in_place::<mod1::Struct2> - shim(Some(mod1::Struct2)) @@ local_drop_glue-fallback.cgu[External] struct Struct2 { _a: Struct, //~ MONO_ITEM fn std::ptr::drop_in_place::<(u32, Struct)> - shim(Some((u32, Struct))) @@ local_drop_glue-fallback.cgu[Internal] _b: (u32, Struct), } //~ MONO_ITEM fn mod1::user @@ local_drop_glue-mod1[External] pub fn user() { let _ = Struct2 { _a: Struct { _a: 0 }, _b: (0, Struct { _a: 0 }) }; } }
{}
identifier_body
lib.rs
// Copyright 2017 columnar-rs Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! Column is a Rust library to repesent collections of elements //! in a columnar memory layout. pub mod bitmap; pub mod tuple; /// Trait describing associated and generated types for a type /// that can be represented in a columnar layout /// /// # Example /// /// ``` /// # #[macro_use] extern crate column_derive; /// # extern crate column; /// # use column::Column; /// #[derive(Column)] /// struct Data {x: usize}
/// # fn main() { /// let column = <Data as Column>::new(); /// # } /// ``` pub trait Column<'a> { /// The type representing the wrapped data in a columnar data layout. type Output; /// Construct a new `Columar` with default capacity. /// # Example /// /// ``` /// # #[macro_use] extern crate column_derive; /// # extern crate column; /// # use column::Column; /// #[derive(Column)] /// struct Data {x: usize} /// # fn main() { /// let column = <Data as Column>::new(); /// # } /// ``` fn new() -> Self::Output; /// Construct a new `Columar` with the provided capacity. /// # Example /// /// ``` /// # #[macro_use] extern crate column_derive; /// # extern crate column; /// # use column::Column; /// #[derive(Column)] /// struct Data {x: usize} /// # fn main() { /// let column = <Data as Column>::with_capacity(200); /// # } /// ``` fn with_capacity(len: usize) -> Self::Output; }
random_line_split
hold.rs
use std::io::{self, Read, Write}; use crate::BufferRedirect; /// Hold output until dropped. On drop, the held output is sent to the stdout/stderr. /// /// Note: This will ignore IO errors when printing held output. pub struct Hold { buf_redir: Option<BufferRedirect>, is_stdout: bool, } impl Hold { /// Hold stderr output. pub fn stderr() -> io::Result<Hold> { Ok(Hold { buf_redir: Some(BufferRedirect::stderr()?), is_stdout: false, }) } /// Hold stdout output. pub fn stdout() -> io::Result<Hold> { Ok(Hold { buf_redir: Some(BufferRedirect::stdout()?), is_stdout: true, }) } } impl Drop for Hold { fn drop(&mut self)
let from = self.buf_redir.take().unwrap().into_inner(); // Ignore errors. if self.is_stdout { let stdout = io::stdout(); read_into(from, stdout.lock()); } else { let stderr = io::stderr(); read_into(from, stderr.lock()); } } }
{ fn read_into<R: Read, W: Write>(mut from: R, mut to: W) { // TODO: use sendfile? let mut buf = [0u8; 4096]; loop { // Ignore errors match from.read(&mut buf) { Ok(0) => break, Ok(size) => { if to.write_all(&buf[..size]).is_err() { break; } } Err(_) => break, } } // Just in case... let _ = to.flush(); }
identifier_body
hold.rs
use std::io::{self, Read, Write}; use crate::BufferRedirect; /// Hold output until dropped. On drop, the held output is sent to the stdout/stderr. /// /// Note: This will ignore IO errors when printing held output. pub struct Hold { buf_redir: Option<BufferRedirect>, is_stdout: bool, } impl Hold { /// Hold stderr output. pub fn stderr() -> io::Result<Hold> { Ok(Hold { buf_redir: Some(BufferRedirect::stderr()?), is_stdout: false, }) } /// Hold stdout output. pub fn stdout() -> io::Result<Hold> { Ok(Hold { buf_redir: Some(BufferRedirect::stdout()?), is_stdout: true, }) } } impl Drop for Hold {
let mut buf = [0u8; 4096]; loop { // Ignore errors match from.read(&mut buf) { Ok(0) => break, Ok(size) => { if to.write_all(&buf[..size]).is_err() { break; } } Err(_) => break, } } // Just in case... let _ = to.flush(); } let from = self.buf_redir.take().unwrap().into_inner(); // Ignore errors. if self.is_stdout { let stdout = io::stdout(); read_into(from, stdout.lock()); } else { let stderr = io::stderr(); read_into(from, stderr.lock()); } } }
fn drop(&mut self) { fn read_into<R: Read, W: Write>(mut from: R, mut to: W) { // TODO: use sendfile?
random_line_split
hold.rs
use std::io::{self, Read, Write}; use crate::BufferRedirect; /// Hold output until dropped. On drop, the held output is sent to the stdout/stderr. /// /// Note: This will ignore IO errors when printing held output. pub struct Hold { buf_redir: Option<BufferRedirect>, is_stdout: bool, } impl Hold { /// Hold stderr output. pub fn stderr() -> io::Result<Hold> { Ok(Hold { buf_redir: Some(BufferRedirect::stderr()?), is_stdout: false, }) } /// Hold stdout output. pub fn
() -> io::Result<Hold> { Ok(Hold { buf_redir: Some(BufferRedirect::stdout()?), is_stdout: true, }) } } impl Drop for Hold { fn drop(&mut self) { fn read_into<R: Read, W: Write>(mut from: R, mut to: W) { // TODO: use sendfile? let mut buf = [0u8; 4096]; loop { // Ignore errors match from.read(&mut buf) { Ok(0) => break, Ok(size) => { if to.write_all(&buf[..size]).is_err() { break; } } Err(_) => break, } } // Just in case... let _ = to.flush(); } let from = self.buf_redir.take().unwrap().into_inner(); // Ignore errors. if self.is_stdout { let stdout = io::stdout(); read_into(from, stdout.lock()); } else { let stderr = io::stderr(); read_into(from, stderr.lock()); } } }
stdout
identifier_name
reader.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ agent_error::ImlAgentError, daemon_plugins::{get_plugin, DaemonPlugins}, http_comms::{ agent_client::AgentClient, session::{Session, Sessions}, }, }; use futures::{FutureExt, TryFutureExt}; use iml_wire_types::ManagerMessage; use std::time::Duration; use tokio::time::delay_for; use tracing::{error, warn}; async fn get_delivery( sessions: Sessions, agent_client: AgentClient, registry: &DaemonPlugins, ) -> Result<(), ImlAgentError> { let msgs = agent_client.clone().get().map_ok(|x| x.messages).await?; for x in msgs { let sessions2 = sessions.clone(); let agent_client2 = agent_client.clone(); tracing::debug!("--> Delivery from manager {:?}", x); match x { ManagerMessage::SessionCreateResponse { plugin, session_id,.. } => { let plugin_instance = get_plugin(&plugin, &registry)?; let mut s = Session::new(plugin.clone(), session_id.clone(), plugin_instance); let (rx, fut) = s.start(); sessions2.insert_session(plugin.clone(), s, rx).await?; let agent_client3 = agent_client2.clone(); tokio::spawn( async move { if let Some((seq, name, id, output)) = fut.await? { agent_client3.send_data(id, name, seq, output).await?; } Ok(()) } .then(move |r: Result<(), ImlAgentError>| async move { match r { Ok(_) => (), Err(e) => { tracing::warn!("Error during session start {:?}", e); sessions2 .terminate_session(&plugin, &session_id) .await .unwrap_or_else(|e| { tracing::warn!("Error terminating session, {}", e) }); } } }), ); } ManagerMessage::Data { plugin, body,.. } => { tokio::spawn( async move { let r = { sessions2.message(&plugin, body) }; if let Some(x) = r.await { let agent_client3 = agent_client2.clone(); let (seq, name, id, x) = x?; agent_client3.send_data(id, name, seq, x).await?; } Ok(()) } .map_err(|e: ImlAgentError| error!("{}", e)), ); } ManagerMessage::SessionTerminate { plugin, session_id,.. } => sessions.terminate_session(&plugin, &session_id).await?, ManagerMessage::SessionTerminateAll {.. } => sessions.terminate_all_sessions().await?, } } Ok(()) } /// Continually polls the manager for any incoming commands using a loop. pub async fn create_reader( sessions: Sessions, agent_client: AgentClient, registry: DaemonPlugins, ) -> Result<(), ImlAgentError>
{ loop { match get_delivery(sessions.clone(), agent_client.clone(), &registry).await { Ok(_) => continue, Err(ImlAgentError::Reqwest(e)) => { warn!("Got a manager read Error {:?}. Will retry in 5 seconds.", e); sessions.terminate_all_sessions().await?; delay_for(Duration::from_secs(5)).await; } Err(e) => return Err(e), } } }
identifier_body
reader.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ agent_error::ImlAgentError, daemon_plugins::{get_plugin, DaemonPlugins}, http_comms::{ agent_client::AgentClient, session::{Session, Sessions}, }, }; use futures::{FutureExt, TryFutureExt}; use iml_wire_types::ManagerMessage; use std::time::Duration; use tokio::time::delay_for; use tracing::{error, warn}; async fn get_delivery( sessions: Sessions, agent_client: AgentClient, registry: &DaemonPlugins, ) -> Result<(), ImlAgentError> { let msgs = agent_client.clone().get().map_ok(|x| x.messages).await?; for x in msgs { let sessions2 = sessions.clone(); let agent_client2 = agent_client.clone(); tracing::debug!("--> Delivery from manager {:?}", x); match x { ManagerMessage::SessionCreateResponse { plugin, session_id,.. } => { let plugin_instance = get_plugin(&plugin, &registry)?; let mut s = Session::new(plugin.clone(), session_id.clone(), plugin_instance); let (rx, fut) = s.start(); sessions2.insert_session(plugin.clone(), s, rx).await?; let agent_client3 = agent_client2.clone(); tokio::spawn( async move { if let Some((seq, name, id, output)) = fut.await? { agent_client3.send_data(id, name, seq, output).await?; } Ok(()) } .then(move |r: Result<(), ImlAgentError>| async move { match r { Ok(_) => (), Err(e) => { tracing::warn!("Error during session start {:?}", e); sessions2 .terminate_session(&plugin, &session_id) .await .unwrap_or_else(|e| { tracing::warn!("Error terminating session, {}", e) }); } } }), ); } ManagerMessage::Data { plugin, body,.. } => { tokio::spawn( async move { let r = { sessions2.message(&plugin, body) }; if let Some(x) = r.await { let agent_client3 = agent_client2.clone(); let (seq, name, id, x) = x?; agent_client3.send_data(id, name, seq, x).await?; } Ok(()) } .map_err(|e: ImlAgentError| error!("{}", e)), ); } ManagerMessage::SessionTerminate { plugin, session_id,.. } => sessions.terminate_session(&plugin, &session_id).await?, ManagerMessage::SessionTerminateAll {.. } => sessions.terminate_all_sessions().await?, } } Ok(()) } /// Continually polls the manager for any incoming commands using a loop. pub async fn create_reader( sessions: Sessions, agent_client: AgentClient, registry: DaemonPlugins, ) -> Result<(), ImlAgentError> { loop { match get_delivery(sessions.clone(), agent_client.clone(), &registry).await { Ok(_) => continue,
delay_for(Duration::from_secs(5)).await; } Err(e) => return Err(e), } } }
Err(ImlAgentError::Reqwest(e)) => { warn!("Got a manager read Error {:?}. Will retry in 5 seconds.", e); sessions.terminate_all_sessions().await?;
random_line_split
reader.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ agent_error::ImlAgentError, daemon_plugins::{get_plugin, DaemonPlugins}, http_comms::{ agent_client::AgentClient, session::{Session, Sessions}, }, }; use futures::{FutureExt, TryFutureExt}; use iml_wire_types::ManagerMessage; use std::time::Duration; use tokio::time::delay_for; use tracing::{error, warn}; async fn get_delivery( sessions: Sessions, agent_client: AgentClient, registry: &DaemonPlugins, ) -> Result<(), ImlAgentError> { let msgs = agent_client.clone().get().map_ok(|x| x.messages).await?; for x in msgs { let sessions2 = sessions.clone(); let agent_client2 = agent_client.clone(); tracing::debug!("--> Delivery from manager {:?}", x); match x { ManagerMessage::SessionCreateResponse { plugin, session_id,.. } => { let plugin_instance = get_plugin(&plugin, &registry)?; let mut s = Session::new(plugin.clone(), session_id.clone(), plugin_instance); let (rx, fut) = s.start(); sessions2.insert_session(plugin.clone(), s, rx).await?; let agent_client3 = agent_client2.clone(); tokio::spawn( async move { if let Some((seq, name, id, output)) = fut.await? { agent_client3.send_data(id, name, seq, output).await?; } Ok(()) } .then(move |r: Result<(), ImlAgentError>| async move { match r { Ok(_) => (), Err(e) => { tracing::warn!("Error during session start {:?}", e); sessions2 .terminate_session(&plugin, &session_id) .await .unwrap_or_else(|e| { tracing::warn!("Error terminating session, {}", e) }); } } }), ); } ManagerMessage::Data { plugin, body,.. } => { tokio::spawn( async move { let r = { sessions2.message(&plugin, body) }; if let Some(x) = r.await { let agent_client3 = agent_client2.clone(); let (seq, name, id, x) = x?; agent_client3.send_data(id, name, seq, x).await?; } Ok(()) } .map_err(|e: ImlAgentError| error!("{}", e)), ); } ManagerMessage::SessionTerminate { plugin, session_id,.. } => sessions.terminate_session(&plugin, &session_id).await?, ManagerMessage::SessionTerminateAll {.. } => sessions.terminate_all_sessions().await?, } } Ok(()) } /// Continually polls the manager for any incoming commands using a loop. pub async fn
( sessions: Sessions, agent_client: AgentClient, registry: DaemonPlugins, ) -> Result<(), ImlAgentError> { loop { match get_delivery(sessions.clone(), agent_client.clone(), &registry).await { Ok(_) => continue, Err(ImlAgentError::Reqwest(e)) => { warn!("Got a manager read Error {:?}. Will retry in 5 seconds.", e); sessions.terminate_all_sessions().await?; delay_for(Duration::from_secs(5)).await; } Err(e) => return Err(e), } } }
create_reader
identifier_name
errors.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use openssl::error::ErrorStack as CrypterError; use protobuf::ProtobufError; use std::io::{Error as IoError, ErrorKind}; use std::{error, result}; /// The error type for encryption. #[derive(Debug, Fail)] pub enum
{ #[fail(display = "Other error {}", _0)] Other(Box<dyn error::Error + Sync + Send>), #[fail(display = "RocksDB error {}", _0)] Rocks(String), #[fail(display = "IO error {}", _0)] Io(IoError), #[fail(display = "OpenSSL error {}", _0)] Crypter(CrypterError), #[fail(display = "Protobuf error {}", _0)] Proto(ProtobufError), #[fail(display = "Unknown encryption error")] UnknownEncryption, #[fail(display = "Wrong master key error {}", _0)] WrongMasterKey(Box<dyn error::Error + Sync + Send>), #[fail( display = "Both master key failed, current key {}, previous key {}.", _0, _1 )] BothMasterKeyFail( Box<dyn error::Error + Sync + Send>, Box<dyn error::Error + Sync + Send>, ), } macro_rules! impl_from { ($($inner:ty => $container:ident,)+) => { $( impl From<$inner> for Error { fn from(inr: $inner) -> Error { Error::$container(inr) } } )+ }; } impl_from! { Box<dyn error::Error + Sync + Send> => Other, String => Rocks, IoError => Io, CrypterError => Crypter, ProtobufError => Proto, } impl From<Error> for IoError { fn from(err: Error) -> IoError { match err { Error::Io(e) => e, other => IoError::new(ErrorKind::Other, format!("{}", other)), } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn error_code(&self) -> ErrorCode { match self { Error::Rocks(_) => error_code::encryption::ROCKS, Error::Io(_) => error_code::encryption::IO, Error::Crypter(_) => error_code::encryption::CRYPTER, Error::Proto(_) => error_code::encryption::PROTO, Error::UnknownEncryption => error_code::encryption::UNKNOWN_ENCRYPTION, Error::WrongMasterKey(_) => error_code::encryption::WRONG_MASTER_KEY, Error::BothMasterKeyFail(_, _) => error_code::encryption::BOTH_MASTER_KEY_FAIL, Error::Other(_) => error_code::UNKNOWN, } } }
Error
identifier_name
errors.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use openssl::error::ErrorStack as CrypterError; use protobuf::ProtobufError; use std::io::{Error as IoError, ErrorKind}; use std::{error, result}; /// The error type for encryption. #[derive(Debug, Fail)] pub enum Error { #[fail(display = "Other error {}", _0)] Other(Box<dyn error::Error + Sync + Send>), #[fail(display = "RocksDB error {}", _0)] Rocks(String), #[fail(display = "IO error {}", _0)] Io(IoError), #[fail(display = "OpenSSL error {}", _0)]
#[fail(display = "Unknown encryption error")] UnknownEncryption, #[fail(display = "Wrong master key error {}", _0)] WrongMasterKey(Box<dyn error::Error + Sync + Send>), #[fail( display = "Both master key failed, current key {}, previous key {}.", _0, _1 )] BothMasterKeyFail( Box<dyn error::Error + Sync + Send>, Box<dyn error::Error + Sync + Send>, ), } macro_rules! impl_from { ($($inner:ty => $container:ident,)+) => { $( impl From<$inner> for Error { fn from(inr: $inner) -> Error { Error::$container(inr) } } )+ }; } impl_from! { Box<dyn error::Error + Sync + Send> => Other, String => Rocks, IoError => Io, CrypterError => Crypter, ProtobufError => Proto, } impl From<Error> for IoError { fn from(err: Error) -> IoError { match err { Error::Io(e) => e, other => IoError::new(ErrorKind::Other, format!("{}", other)), } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn error_code(&self) -> ErrorCode { match self { Error::Rocks(_) => error_code::encryption::ROCKS, Error::Io(_) => error_code::encryption::IO, Error::Crypter(_) => error_code::encryption::CRYPTER, Error::Proto(_) => error_code::encryption::PROTO, Error::UnknownEncryption => error_code::encryption::UNKNOWN_ENCRYPTION, Error::WrongMasterKey(_) => error_code::encryption::WRONG_MASTER_KEY, Error::BothMasterKeyFail(_, _) => error_code::encryption::BOTH_MASTER_KEY_FAIL, Error::Other(_) => error_code::UNKNOWN, } } }
Crypter(CrypterError), #[fail(display = "Protobuf error {}", _0)] Proto(ProtobufError),
random_line_split
errors.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use openssl::error::ErrorStack as CrypterError; use protobuf::ProtobufError; use std::io::{Error as IoError, ErrorKind}; use std::{error, result}; /// The error type for encryption. #[derive(Debug, Fail)] pub enum Error { #[fail(display = "Other error {}", _0)] Other(Box<dyn error::Error + Sync + Send>), #[fail(display = "RocksDB error {}", _0)] Rocks(String), #[fail(display = "IO error {}", _0)] Io(IoError), #[fail(display = "OpenSSL error {}", _0)] Crypter(CrypterError), #[fail(display = "Protobuf error {}", _0)] Proto(ProtobufError), #[fail(display = "Unknown encryption error")] UnknownEncryption, #[fail(display = "Wrong master key error {}", _0)] WrongMasterKey(Box<dyn error::Error + Sync + Send>), #[fail( display = "Both master key failed, current key {}, previous key {}.", _0, _1 )] BothMasterKeyFail( Box<dyn error::Error + Sync + Send>, Box<dyn error::Error + Sync + Send>, ), } macro_rules! impl_from { ($($inner:ty => $container:ident,)+) => { $( impl From<$inner> for Error { fn from(inr: $inner) -> Error { Error::$container(inr) } } )+ }; } impl_from! { Box<dyn error::Error + Sync + Send> => Other, String => Rocks, IoError => Io, CrypterError => Crypter, ProtobufError => Proto, } impl From<Error> for IoError { fn from(err: Error) -> IoError
} pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn error_code(&self) -> ErrorCode { match self { Error::Rocks(_) => error_code::encryption::ROCKS, Error::Io(_) => error_code::encryption::IO, Error::Crypter(_) => error_code::encryption::CRYPTER, Error::Proto(_) => error_code::encryption::PROTO, Error::UnknownEncryption => error_code::encryption::UNKNOWN_ENCRYPTION, Error::WrongMasterKey(_) => error_code::encryption::WRONG_MASTER_KEY, Error::BothMasterKeyFail(_, _) => error_code::encryption::BOTH_MASTER_KEY_FAIL, Error::Other(_) => error_code::UNKNOWN, } } }
{ match err { Error::Io(e) => e, other => IoError::new(ErrorKind::Other, format!("{}", other)), } }
identifier_body
mem.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/. */ //! APIs for memory profiling. #![deny(missing_docs)] use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; use serde; use std::marker::Send; use std::sync::mpsc::Sender; /// A trait to abstract away the various kinds of message senders we use. pub trait OpaqueSender<T> { /// Send a message. fn send(&self, message: T); } impl<T> OpaqueSender<T> for Sender<T> { fn send(&self, message: T) { if let Err(e) = Sender::send(self, message) { warn!("Error communicating with the target thread from the profiler: {}", e); } } } impl<T> OpaqueSender<T> for IpcSender<T> where T: serde::Serialize { fn send(&self, message: T) { if let Err(e) = IpcSender::send(self, message) { warn!("Error communicating with the target thread from the profiler: {}", e); } } } /// Front-end representation of the profiler used to communicate with the /// profiler. #[derive(Clone, Deserialize, Serialize)] pub struct ProfilerChan(pub IpcSender<ProfilerMsg>); impl ProfilerChan { /// Send `msg` on this `IpcSender`. /// /// Warns if the send fails. pub fn send(&self, msg: ProfilerMsg)
/// Runs `f()` with memory profiling. pub fn run_with_memory_reporting<F, M, T, C>(&self, f: F, reporter_name: String, channel_for_reporter: C, msg: M) where F: FnOnce(), M: Fn(ReportsChan) -> T + Send +'static, T: Send +'static, C: OpaqueSender<T> + Send +'static { // Register the memory reporter. let (reporter_sender, reporter_receiver) = ipc::channel().unwrap(); ROUTER.add_route(reporter_receiver.to_opaque(), Box::new(move |message| { // Just injects an appropriate event into the paint thread's queue. let request: ReporterRequest = message.to().unwrap(); channel_for_reporter.send(msg(request.reports_channel)); })); self.send(ProfilerMsg::RegisterReporter(reporter_name.clone(), Reporter(reporter_sender))); f(); self.send(ProfilerMsg::UnregisterReporter(reporter_name)); } } /// The various kinds of memory measurement. /// /// Here "explicit" means explicit memory allocations done by the application. It includes /// allocations made at the OS level (via functions such as VirtualAlloc, vm_allocate, and mmap), /// allocations made at the heap allocation level (via functions such as malloc, calloc, realloc, /// memalign, operator new, and operator new[]) and where possible, the overhead of the heap /// allocator itself. It excludes memory that is mapped implicitly such as code and data segments, /// and thread stacks. "explicit" is not guaranteed to cover every explicit allocation, but it does /// cover most (including the entire heap), and therefore it is the single best number to focus on /// when trying to reduce memory usage. #[derive(Deserialize, Serialize)] pub enum ReportKind { /// A size measurement for an explicit allocation on the jemalloc heap. This should be used /// for any measurements done via the `MallocSizeOf` trait. ExplicitJemallocHeapSize, /// A size measurement for an explicit allocation on the system heap. Only likely to be used /// for external C or C++ libraries that don't use jemalloc. ExplicitSystemHeapSize, /// A size measurement for an explicit allocation not on the heap, e.g. via mmap(). ExplicitNonHeapSize, /// A size measurement for an explicit allocation whose location is unknown or uncertain. ExplicitUnknownLocationSize, /// A size measurement for a non-explicit allocation. This kind is used for global /// measurements such as "resident" and "vsize", and also for measurements that cross-cut the /// measurements grouped under "explicit", e.g. by grouping those measurements in a way that's /// different to how they are grouped under "explicit". NonExplicitSize, } /// A single memory-related measurement. #[derive(Deserialize, Serialize)] pub struct Report { /// The identifying path for this report. pub path: Vec<String>, /// The report kind. pub kind: ReportKind, /// The size, in bytes. pub size: usize, } /// A channel through which memory reports can be sent. #[derive(Clone, Deserialize, Serialize)] pub struct ReportsChan(pub IpcSender<Vec<Report>>); impl ReportsChan { /// Send `report` on this `IpcSender`. /// /// Panics if the send fails. pub fn send(&self, report: Vec<Report>) { self.0.send(report).unwrap(); } } /// The protocol used to send reporter requests. #[derive(Deserialize, Serialize)] pub struct ReporterRequest { /// The channel on which reports are to be sent. pub reports_channel: ReportsChan, } /// A memory reporter is capable of measuring some data structure of interest. It's structured as /// an IPC sender that a `ReporterRequest` in transmitted over. `ReporterRequest` objects in turn /// encapsulate the channel on which the memory profiling information is to be sent. /// /// In many cases, clients construct `Reporter` objects by creating an IPC sender/receiver pair and /// registering the receiving end with the router so that messages from the memory profiler end up /// injected into the client's event loop. #[derive(Deserialize, Serialize)] pub struct Reporter(pub IpcSender<ReporterRequest>); impl Reporter { /// Collect one or more memory reports. Returns true on success, and false on failure. pub fn collect_reports(&self, reports_chan: ReportsChan) { self.0.send(ReporterRequest { reports_channel: reports_chan, }).unwrap() } } /// An easy way to build a path for a report. #[macro_export] macro_rules! path { ($($x:expr),*) => {{ use std::borrow::ToOwned; vec![$( $x.to_owned() ),*] }} } /// Messages that can be sent to the memory profiler thread. #[derive(Deserialize, Serialize)] pub enum ProfilerMsg { /// Register a Reporter with the memory profiler. The String is only used to identify the /// reporter so it can be unregistered later. The String must be distinct from that used by any /// other registered reporter otherwise a panic will occur. RegisterReporter(String, Reporter), /// Unregister a Reporter with the memory profiler. The String must match the name given when /// the reporter was registered. If the String does not match the name of a registered reporter /// a panic will occur. UnregisterReporter(String), /// Triggers printing of the memory profiling metrics. Print, /// Tells the memory profiler to shut down. Exit, }
{ if let Err(e) = self.0.send(msg) { warn!("Error communicating with the memory profiler thread: {}", e); } }
identifier_body
mem.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/. */ //! APIs for memory profiling. #![deny(missing_docs)] use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; use serde; use std::marker::Send; use std::sync::mpsc::Sender; /// A trait to abstract away the various kinds of message senders we use. pub trait OpaqueSender<T> { /// Send a message. fn send(&self, message: T); } impl<T> OpaqueSender<T> for Sender<T> { fn send(&self, message: T) { if let Err(e) = Sender::send(self, message) { warn!("Error communicating with the target thread from the profiler: {}", e); } } } impl<T> OpaqueSender<T> for IpcSender<T> where T: serde::Serialize { fn send(&self, message: T) { if let Err(e) = IpcSender::send(self, message) { warn!("Error communicating with the target thread from the profiler: {}", e); } } } /// Front-end representation of the profiler used to communicate with the /// profiler. #[derive(Clone, Deserialize, Serialize)] pub struct ProfilerChan(pub IpcSender<ProfilerMsg>); impl ProfilerChan { /// Send `msg` on this `IpcSender`. /// /// Warns if the send fails. pub fn send(&self, msg: ProfilerMsg) { if let Err(e) = self.0.send(msg)
} /// Runs `f()` with memory profiling. pub fn run_with_memory_reporting<F, M, T, C>(&self, f: F, reporter_name: String, channel_for_reporter: C, msg: M) where F: FnOnce(), M: Fn(ReportsChan) -> T + Send +'static, T: Send +'static, C: OpaqueSender<T> + Send +'static { // Register the memory reporter. let (reporter_sender, reporter_receiver) = ipc::channel().unwrap(); ROUTER.add_route(reporter_receiver.to_opaque(), Box::new(move |message| { // Just injects an appropriate event into the paint thread's queue. let request: ReporterRequest = message.to().unwrap(); channel_for_reporter.send(msg(request.reports_channel)); })); self.send(ProfilerMsg::RegisterReporter(reporter_name.clone(), Reporter(reporter_sender))); f(); self.send(ProfilerMsg::UnregisterReporter(reporter_name)); } } /// The various kinds of memory measurement. /// /// Here "explicit" means explicit memory allocations done by the application. It includes /// allocations made at the OS level (via functions such as VirtualAlloc, vm_allocate, and mmap), /// allocations made at the heap allocation level (via functions such as malloc, calloc, realloc, /// memalign, operator new, and operator new[]) and where possible, the overhead of the heap /// allocator itself. It excludes memory that is mapped implicitly such as code and data segments, /// and thread stacks. "explicit" is not guaranteed to cover every explicit allocation, but it does /// cover most (including the entire heap), and therefore it is the single best number to focus on /// when trying to reduce memory usage. #[derive(Deserialize, Serialize)] pub enum ReportKind { /// A size measurement for an explicit allocation on the jemalloc heap. This should be used /// for any measurements done via the `MallocSizeOf` trait. ExplicitJemallocHeapSize, /// A size measurement for an explicit allocation on the system heap. Only likely to be used /// for external C or C++ libraries that don't use jemalloc. ExplicitSystemHeapSize, /// A size measurement for an explicit allocation not on the heap, e.g. via mmap(). ExplicitNonHeapSize, /// A size measurement for an explicit allocation whose location is unknown or uncertain. ExplicitUnknownLocationSize, /// A size measurement for a non-explicit allocation. This kind is used for global /// measurements such as "resident" and "vsize", and also for measurements that cross-cut the /// measurements grouped under "explicit", e.g. by grouping those measurements in a way that's /// different to how they are grouped under "explicit". NonExplicitSize, } /// A single memory-related measurement. #[derive(Deserialize, Serialize)] pub struct Report { /// The identifying path for this report. pub path: Vec<String>, /// The report kind. pub kind: ReportKind, /// The size, in bytes. pub size: usize, } /// A channel through which memory reports can be sent. #[derive(Clone, Deserialize, Serialize)] pub struct ReportsChan(pub IpcSender<Vec<Report>>); impl ReportsChan { /// Send `report` on this `IpcSender`. /// /// Panics if the send fails. pub fn send(&self, report: Vec<Report>) { self.0.send(report).unwrap(); } } /// The protocol used to send reporter requests. #[derive(Deserialize, Serialize)] pub struct ReporterRequest { /// The channel on which reports are to be sent. pub reports_channel: ReportsChan, } /// A memory reporter is capable of measuring some data structure of interest. It's structured as /// an IPC sender that a `ReporterRequest` in transmitted over. `ReporterRequest` objects in turn /// encapsulate the channel on which the memory profiling information is to be sent. /// /// In many cases, clients construct `Reporter` objects by creating an IPC sender/receiver pair and /// registering the receiving end with the router so that messages from the memory profiler end up /// injected into the client's event loop. #[derive(Deserialize, Serialize)] pub struct Reporter(pub IpcSender<ReporterRequest>); impl Reporter { /// Collect one or more memory reports. Returns true on success, and false on failure. pub fn collect_reports(&self, reports_chan: ReportsChan) { self.0.send(ReporterRequest { reports_channel: reports_chan, }).unwrap() } } /// An easy way to build a path for a report. #[macro_export] macro_rules! path { ($($x:expr),*) => {{ use std::borrow::ToOwned; vec![$( $x.to_owned() ),*] }} } /// Messages that can be sent to the memory profiler thread. #[derive(Deserialize, Serialize)] pub enum ProfilerMsg { /// Register a Reporter with the memory profiler. The String is only used to identify the /// reporter so it can be unregistered later. The String must be distinct from that used by any /// other registered reporter otherwise a panic will occur. RegisterReporter(String, Reporter), /// Unregister a Reporter with the memory profiler. The String must match the name given when /// the reporter was registered. If the String does not match the name of a registered reporter /// a panic will occur. UnregisterReporter(String), /// Triggers printing of the memory profiling metrics. Print, /// Tells the memory profiler to shut down. Exit, }
{ warn!("Error communicating with the memory profiler thread: {}", e); }
conditional_block
mem.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/. */ //! APIs for memory profiling. #![deny(missing_docs)] use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; use serde; use std::marker::Send; use std::sync::mpsc::Sender; /// A trait to abstract away the various kinds of message senders we use. pub trait OpaqueSender<T> { /// Send a message. fn send(&self, message: T); } impl<T> OpaqueSender<T> for Sender<T> { fn send(&self, message: T) { if let Err(e) = Sender::send(self, message) { warn!("Error communicating with the target thread from the profiler: {}", e); } } } impl<T> OpaqueSender<T> for IpcSender<T> where T: serde::Serialize { fn send(&self, message: T) { if let Err(e) = IpcSender::send(self, message) { warn!("Error communicating with the target thread from the profiler: {}", e); } } } /// Front-end representation of the profiler used to communicate with the /// profiler. #[derive(Clone, Deserialize, Serialize)] pub struct ProfilerChan(pub IpcSender<ProfilerMsg>); impl ProfilerChan { /// Send `msg` on this `IpcSender`. /// /// Warns if the send fails. pub fn send(&self, msg: ProfilerMsg) { if let Err(e) = self.0.send(msg) { warn!("Error communicating with the memory profiler thread: {}", e); } } /// Runs `f()` with memory profiling. pub fn run_with_memory_reporting<F, M, T, C>(&self, f: F, reporter_name: String, channel_for_reporter: C, msg: M) where F: FnOnce(), M: Fn(ReportsChan) -> T + Send +'static, T: Send +'static, C: OpaqueSender<T> + Send +'static { // Register the memory reporter. let (reporter_sender, reporter_receiver) = ipc::channel().unwrap(); ROUTER.add_route(reporter_receiver.to_opaque(), Box::new(move |message| { // Just injects an appropriate event into the paint thread's queue. let request: ReporterRequest = message.to().unwrap();
self.send(ProfilerMsg::RegisterReporter(reporter_name.clone(), Reporter(reporter_sender))); f(); self.send(ProfilerMsg::UnregisterReporter(reporter_name)); } } /// The various kinds of memory measurement. /// /// Here "explicit" means explicit memory allocations done by the application. It includes /// allocations made at the OS level (via functions such as VirtualAlloc, vm_allocate, and mmap), /// allocations made at the heap allocation level (via functions such as malloc, calloc, realloc, /// memalign, operator new, and operator new[]) and where possible, the overhead of the heap /// allocator itself. It excludes memory that is mapped implicitly such as code and data segments, /// and thread stacks. "explicit" is not guaranteed to cover every explicit allocation, but it does /// cover most (including the entire heap), and therefore it is the single best number to focus on /// when trying to reduce memory usage. #[derive(Deserialize, Serialize)] pub enum ReportKind { /// A size measurement for an explicit allocation on the jemalloc heap. This should be used /// for any measurements done via the `MallocSizeOf` trait. ExplicitJemallocHeapSize, /// A size measurement for an explicit allocation on the system heap. Only likely to be used /// for external C or C++ libraries that don't use jemalloc. ExplicitSystemHeapSize, /// A size measurement for an explicit allocation not on the heap, e.g. via mmap(). ExplicitNonHeapSize, /// A size measurement for an explicit allocation whose location is unknown or uncertain. ExplicitUnknownLocationSize, /// A size measurement for a non-explicit allocation. This kind is used for global /// measurements such as "resident" and "vsize", and also for measurements that cross-cut the /// measurements grouped under "explicit", e.g. by grouping those measurements in a way that's /// different to how they are grouped under "explicit". NonExplicitSize, } /// A single memory-related measurement. #[derive(Deserialize, Serialize)] pub struct Report { /// The identifying path for this report. pub path: Vec<String>, /// The report kind. pub kind: ReportKind, /// The size, in bytes. pub size: usize, } /// A channel through which memory reports can be sent. #[derive(Clone, Deserialize, Serialize)] pub struct ReportsChan(pub IpcSender<Vec<Report>>); impl ReportsChan { /// Send `report` on this `IpcSender`. /// /// Panics if the send fails. pub fn send(&self, report: Vec<Report>) { self.0.send(report).unwrap(); } } /// The protocol used to send reporter requests. #[derive(Deserialize, Serialize)] pub struct ReporterRequest { /// The channel on which reports are to be sent. pub reports_channel: ReportsChan, } /// A memory reporter is capable of measuring some data structure of interest. It's structured as /// an IPC sender that a `ReporterRequest` in transmitted over. `ReporterRequest` objects in turn /// encapsulate the channel on which the memory profiling information is to be sent. /// /// In many cases, clients construct `Reporter` objects by creating an IPC sender/receiver pair and /// registering the receiving end with the router so that messages from the memory profiler end up /// injected into the client's event loop. #[derive(Deserialize, Serialize)] pub struct Reporter(pub IpcSender<ReporterRequest>); impl Reporter { /// Collect one or more memory reports. Returns true on success, and false on failure. pub fn collect_reports(&self, reports_chan: ReportsChan) { self.0.send(ReporterRequest { reports_channel: reports_chan, }).unwrap() } } /// An easy way to build a path for a report. #[macro_export] macro_rules! path { ($($x:expr),*) => {{ use std::borrow::ToOwned; vec![$( $x.to_owned() ),*] }} } /// Messages that can be sent to the memory profiler thread. #[derive(Deserialize, Serialize)] pub enum ProfilerMsg { /// Register a Reporter with the memory profiler. The String is only used to identify the /// reporter so it can be unregistered later. The String must be distinct from that used by any /// other registered reporter otherwise a panic will occur. RegisterReporter(String, Reporter), /// Unregister a Reporter with the memory profiler. The String must match the name given when /// the reporter was registered. If the String does not match the name of a registered reporter /// a panic will occur. UnregisterReporter(String), /// Triggers printing of the memory profiling metrics. Print, /// Tells the memory profiler to shut down. Exit, }
channel_for_reporter.send(msg(request.reports_channel)); }));
random_line_split
mem.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/. */ //! APIs for memory profiling. #![deny(missing_docs)] use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; use serde; use std::marker::Send; use std::sync::mpsc::Sender; /// A trait to abstract away the various kinds of message senders we use. pub trait OpaqueSender<T> { /// Send a message. fn send(&self, message: T); } impl<T> OpaqueSender<T> for Sender<T> { fn send(&self, message: T) { if let Err(e) = Sender::send(self, message) { warn!("Error communicating with the target thread from the profiler: {}", e); } } } impl<T> OpaqueSender<T> for IpcSender<T> where T: serde::Serialize { fn send(&self, message: T) { if let Err(e) = IpcSender::send(self, message) { warn!("Error communicating with the target thread from the profiler: {}", e); } } } /// Front-end representation of the profiler used to communicate with the /// profiler. #[derive(Clone, Deserialize, Serialize)] pub struct ProfilerChan(pub IpcSender<ProfilerMsg>); impl ProfilerChan { /// Send `msg` on this `IpcSender`. /// /// Warns if the send fails. pub fn send(&self, msg: ProfilerMsg) { if let Err(e) = self.0.send(msg) { warn!("Error communicating with the memory profiler thread: {}", e); } } /// Runs `f()` with memory profiling. pub fn
<F, M, T, C>(&self, f: F, reporter_name: String, channel_for_reporter: C, msg: M) where F: FnOnce(), M: Fn(ReportsChan) -> T + Send +'static, T: Send +'static, C: OpaqueSender<T> + Send +'static { // Register the memory reporter. let (reporter_sender, reporter_receiver) = ipc::channel().unwrap(); ROUTER.add_route(reporter_receiver.to_opaque(), Box::new(move |message| { // Just injects an appropriate event into the paint thread's queue. let request: ReporterRequest = message.to().unwrap(); channel_for_reporter.send(msg(request.reports_channel)); })); self.send(ProfilerMsg::RegisterReporter(reporter_name.clone(), Reporter(reporter_sender))); f(); self.send(ProfilerMsg::UnregisterReporter(reporter_name)); } } /// The various kinds of memory measurement. /// /// Here "explicit" means explicit memory allocations done by the application. It includes /// allocations made at the OS level (via functions such as VirtualAlloc, vm_allocate, and mmap), /// allocations made at the heap allocation level (via functions such as malloc, calloc, realloc, /// memalign, operator new, and operator new[]) and where possible, the overhead of the heap /// allocator itself. It excludes memory that is mapped implicitly such as code and data segments, /// and thread stacks. "explicit" is not guaranteed to cover every explicit allocation, but it does /// cover most (including the entire heap), and therefore it is the single best number to focus on /// when trying to reduce memory usage. #[derive(Deserialize, Serialize)] pub enum ReportKind { /// A size measurement for an explicit allocation on the jemalloc heap. This should be used /// for any measurements done via the `MallocSizeOf` trait. ExplicitJemallocHeapSize, /// A size measurement for an explicit allocation on the system heap. Only likely to be used /// for external C or C++ libraries that don't use jemalloc. ExplicitSystemHeapSize, /// A size measurement for an explicit allocation not on the heap, e.g. via mmap(). ExplicitNonHeapSize, /// A size measurement for an explicit allocation whose location is unknown or uncertain. ExplicitUnknownLocationSize, /// A size measurement for a non-explicit allocation. This kind is used for global /// measurements such as "resident" and "vsize", and also for measurements that cross-cut the /// measurements grouped under "explicit", e.g. by grouping those measurements in a way that's /// different to how they are grouped under "explicit". NonExplicitSize, } /// A single memory-related measurement. #[derive(Deserialize, Serialize)] pub struct Report { /// The identifying path for this report. pub path: Vec<String>, /// The report kind. pub kind: ReportKind, /// The size, in bytes. pub size: usize, } /// A channel through which memory reports can be sent. #[derive(Clone, Deserialize, Serialize)] pub struct ReportsChan(pub IpcSender<Vec<Report>>); impl ReportsChan { /// Send `report` on this `IpcSender`. /// /// Panics if the send fails. pub fn send(&self, report: Vec<Report>) { self.0.send(report).unwrap(); } } /// The protocol used to send reporter requests. #[derive(Deserialize, Serialize)] pub struct ReporterRequest { /// The channel on which reports are to be sent. pub reports_channel: ReportsChan, } /// A memory reporter is capable of measuring some data structure of interest. It's structured as /// an IPC sender that a `ReporterRequest` in transmitted over. `ReporterRequest` objects in turn /// encapsulate the channel on which the memory profiling information is to be sent. /// /// In many cases, clients construct `Reporter` objects by creating an IPC sender/receiver pair and /// registering the receiving end with the router so that messages from the memory profiler end up /// injected into the client's event loop. #[derive(Deserialize, Serialize)] pub struct Reporter(pub IpcSender<ReporterRequest>); impl Reporter { /// Collect one or more memory reports. Returns true on success, and false on failure. pub fn collect_reports(&self, reports_chan: ReportsChan) { self.0.send(ReporterRequest { reports_channel: reports_chan, }).unwrap() } } /// An easy way to build a path for a report. #[macro_export] macro_rules! path { ($($x:expr),*) => {{ use std::borrow::ToOwned; vec![$( $x.to_owned() ),*] }} } /// Messages that can be sent to the memory profiler thread. #[derive(Deserialize, Serialize)] pub enum ProfilerMsg { /// Register a Reporter with the memory profiler. The String is only used to identify the /// reporter so it can be unregistered later. The String must be distinct from that used by any /// other registered reporter otherwise a panic will occur. RegisterReporter(String, Reporter), /// Unregister a Reporter with the memory profiler. The String must match the name given when /// the reporter was registered. If the String does not match the name of a registered reporter /// a panic will occur. UnregisterReporter(String), /// Triggers printing of the memory profiling metrics. Print, /// Tells the memory profiler to shut down. Exit, }
run_with_memory_reporting
identifier_name
srgb.rs
pub trait Clamp: std::cmp::PartialOrd + Sized { fn clamp(self, min: Self, max: Self) -> Self { if self.lt(&min) { min } else if self.gt(&max)
else { self } } } impl Clamp for f32 {} pub fn srgb_to_linear(v: f32) -> f32 { if v < 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4).clamp(0.0, 1.0) } } pub fn linear_to_srgb(v: f32) -> f32 { if v < 0.0031308 { v * 12.92 } else { (1.055 * v.powf(1.0 / 2.4) - 0.055).clamp(0.0, 1.0) } }
{ max }
conditional_block
srgb.rs
pub trait Clamp: std::cmp::PartialOrd + Sized { fn clamp(self, min: Self, max: Self) -> Self { if self.lt(&min) { min } else if self.gt(&max) { max } else { self } } } impl Clamp for f32 {} pub fn srgb_to_linear(v: f32) -> f32 {
v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4).clamp(0.0, 1.0) } } pub fn linear_to_srgb(v: f32) -> f32 { if v < 0.0031308 { v * 12.92 } else { (1.055 * v.powf(1.0 / 2.4) - 0.055).clamp(0.0, 1.0) } }
if v < 0.04045 {
random_line_split
srgb.rs
pub trait Clamp: std::cmp::PartialOrd + Sized { fn clamp(self, min: Self, max: Self) -> Self { if self.lt(&min) { min } else if self.gt(&max) { max } else { self } } } impl Clamp for f32 {} pub fn srgb_to_linear(v: f32) -> f32 { if v < 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4).clamp(0.0, 1.0) } } pub fn
(v: f32) -> f32 { if v < 0.0031308 { v * 12.92 } else { (1.055 * v.powf(1.0 / 2.4) - 0.055).clamp(0.0, 1.0) } }
linear_to_srgb
identifier_name
srgb.rs
pub trait Clamp: std::cmp::PartialOrd + Sized { fn clamp(self, min: Self, max: Self) -> Self { if self.lt(&min) { min } else if self.gt(&max) { max } else { self } } } impl Clamp for f32 {} pub fn srgb_to_linear(v: f32) -> f32 { if v < 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4).clamp(0.0, 1.0) } } pub fn linear_to_srgb(v: f32) -> f32
{ if v < 0.0031308 { v * 12.92 } else { (1.055 * v.powf(1.0 / 2.4) - 0.055).clamp(0.0, 1.0) } }
identifier_body
ecdsa_signer_key_manager.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // //////////////////////////////////////////////////////////////////////////////// //! Key manager for ECDSA signing keys. use generic_array::typenum::Unsigned; use p256::elliptic_curve; use tink_core::{utils::wrap_err, TinkError}; use tink_proto::{prost::Message, EllipticCurveType}; /// Maximal version of ECDSA keys. pub const ECDSA_SIGNER_KEY_VERSION: u32 = 0; /// Type URL of ECDSA keys that Tink supports. pub const ECDSA_SIGNER_TYPE_URL: &str = "type.googleapis.com/google.crypto.tink.EcdsaPrivateKey"; /// An implementation of the [`tink_core::registry::KeyManager`] trait. /// It generates new ECDSA private keys and produces new instances of /// [`crate::subtle::EcdsaSigner`]. #[derive(Default)] pub(crate) struct EcdsaSignerKeyManager {} /// Prefix for uncompressed elliptic curve points. pub const ECDSA_UNCOMPRESSED_POINT_PREFIX: u8 = 0x04; impl tink_core::registry::KeyManager for EcdsaSignerKeyManager { fn primitive(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> { if serialized_key.is_empty() { return Err("EcdsaSignerKeyManager: invalid key".into()); } let key = tink_proto::EcdsaPrivateKey::decode(serialized_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid key", e))?; let params = validate_key(&key)?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(&params); match crate::subtle::EcdsaSigner::new(hash, curve, encoding, &key.key_value) { Ok(p) => Ok(tink_core::Primitive::Signer(Box::new(p))), Err(e) => Err(wrap_err("EcdsaSignerKeyManager: invalid key", e)), } } fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> { if serialized_key_format.is_empty() { return Err("EcdsaSignerKeyManager: invalid key format".into()); } let key_format = tink_proto::EcdsaKeyFormat::decode(serialized_key_format) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid key", e))?; let (params, curve) = validate_key_format(&key_format)?; // generate key let mut csprng = signature::rand_core::OsRng {}; let (secret_key_data, pub_x_data, pub_y_data) = match curve { EllipticCurveType::NistP256 => { // Generate a new keypair. let secret_key = p256::ecdsa::SigningKey::random(&mut csprng); let public_key = p256::ecdsa::VerifyingKey::from(&secret_key); let public_key_point = public_key.to_encoded_point(/* compress= */ false); let public_key_data = public_key_point.as_bytes(); // Check that the public key data is in the expected uncompressed format: // - 1 byte uncompressed prefix (0x04) // - P bytes of X coordinate // - P bytes of Y coordinate // where P is the field element size. let point_len = elliptic_curve::FieldSize::<p256::NistP256>::to_usize(); if public_key_data.len()!= 2 * point_len + 1 || public_key_data[0]!= ECDSA_UNCOMPRESSED_POINT_PREFIX { return Err("EcdsaSignerKeyManager: unexpected public key data format".into()); } ( secret_key.to_bytes().to_vec(), public_key_data[1..point_len + 1].to_vec(), public_key_data[point_len + 1..].to_vec(), ) } _ => { return Err(format!("EcdsaSignerKeyManager: unsupported curve {:?}", curve).into()) } }; let pub_key = tink_proto::EcdsaPublicKey { version: ECDSA_SIGNER_KEY_VERSION, params: Some(params), x: pub_x_data, y: pub_y_data, }; let priv_key = tink_proto::EcdsaPrivateKey { version: ECDSA_SIGNER_KEY_VERSION, public_key: Some(pub_key), key_value: secret_key_data, }; let mut sk = Vec::new(); priv_key .encode(&mut sk) .map_err(|e| wrap_err("EcdsaSignerKeyManager: failed to encode new key", e))?; Ok(sk) } fn
(&self) -> &'static str { ECDSA_SIGNER_TYPE_URL } fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType { tink_proto::key_data::KeyMaterialType::AsymmetricPrivate } fn supports_private_keys(&self) -> bool { true } fn public_key_data( &self, serialized_priv_key: &[u8], ) -> Result<tink_proto::KeyData, TinkError> { let priv_key = tink_proto::EcdsaPrivateKey::decode(serialized_priv_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid private key", e))?; let mut serialized_pub_key = Vec::new(); priv_key .public_key .ok_or_else(|| TinkError::new("EcdsaSignerKeyManager: no public key"))? .encode(&mut serialized_pub_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid public key", e))?; Ok(tink_proto::KeyData { type_url: crate::ECDSA_VERIFIER_TYPE_URL.to_string(), value: serialized_pub_key, key_material_type: tink_proto::key_data::KeyMaterialType::AsymmetricPublic as i32, }) } } /// Validate the given [`EcdsaPrivateKey`](tink_proto::EcdsaPrivateKey) and return /// the parameters. fn validate_key(key: &tink_proto::EcdsaPrivateKey) -> Result<tink_proto::EcdsaParams, TinkError> { tink_core::keyset::validate_key_version(key.version, ECDSA_SIGNER_KEY_VERSION) .map_err(|e| wrap_err("EcdsaSignerKeyManager", e))?; let pub_key = key .public_key .as_ref() .ok_or_else(|| TinkError::new("EcdsaSignerKeyManager: no public key"))?; let params = crate::validate_ecdsa_public_key(pub_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager", e))?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(&params); // Check the public key points are on the curve by creating a verifier. crate::subtle::EcdsaVerifier::new(hash, curve, encoding, &pub_key.x, &pub_key.y) .map_err(|e| wrap_err("EcdsaVerifierKeyManager: invalid key", e))?; crate::subtle::validate_ecdsa_params(hash, curve, encoding)?; Ok(params) } /// Validate the given [`EcdsaKeyFormat`](tink_proto::EcdsaKeyFormat) and return /// the parameters. fn validate_key_format( key_format: &tink_proto::EcdsaKeyFormat, ) -> Result<(tink_proto::EcdsaParams, tink_proto::EllipticCurveType), TinkError> { let params = key_format .params .as_ref() .ok_or_else(|| TinkError::new("no public key parameters"))?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(params); crate::subtle::validate_ecdsa_params(hash, curve, encoding)?; Ok((params.clone(), curve)) }
type_url
identifier_name
ecdsa_signer_key_manager.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // //////////////////////////////////////////////////////////////////////////////// //! Key manager for ECDSA signing keys. use generic_array::typenum::Unsigned; use p256::elliptic_curve; use tink_core::{utils::wrap_err, TinkError}; use tink_proto::{prost::Message, EllipticCurveType}; /// Maximal version of ECDSA keys. pub const ECDSA_SIGNER_KEY_VERSION: u32 = 0; /// Type URL of ECDSA keys that Tink supports. pub const ECDSA_SIGNER_TYPE_URL: &str = "type.googleapis.com/google.crypto.tink.EcdsaPrivateKey"; /// An implementation of the [`tink_core::registry::KeyManager`] trait. /// It generates new ECDSA private keys and produces new instances of /// [`crate::subtle::EcdsaSigner`]. #[derive(Default)] pub(crate) struct EcdsaSignerKeyManager {} /// Prefix for uncompressed elliptic curve points. pub const ECDSA_UNCOMPRESSED_POINT_PREFIX: u8 = 0x04; impl tink_core::registry::KeyManager for EcdsaSignerKeyManager { fn primitive(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> { if serialized_key.is_empty() { return Err("EcdsaSignerKeyManager: invalid key".into()); } let key = tink_proto::EcdsaPrivateKey::decode(serialized_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid key", e))?; let params = validate_key(&key)?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(&params); match crate::subtle::EcdsaSigner::new(hash, curve, encoding, &key.key_value) { Ok(p) => Ok(tink_core::Primitive::Signer(Box::new(p))), Err(e) => Err(wrap_err("EcdsaSignerKeyManager: invalid key", e)), } } fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> { if serialized_key_format.is_empty() { return Err("EcdsaSignerKeyManager: invalid key format".into()); } let key_format = tink_proto::EcdsaKeyFormat::decode(serialized_key_format) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid key", e))?; let (params, curve) = validate_key_format(&key_format)?; // generate key let mut csprng = signature::rand_core::OsRng {}; let (secret_key_data, pub_x_data, pub_y_data) = match curve { EllipticCurveType::NistP256 => { // Generate a new keypair. let secret_key = p256::ecdsa::SigningKey::random(&mut csprng); let public_key = p256::ecdsa::VerifyingKey::from(&secret_key); let public_key_point = public_key.to_encoded_point(/* compress= */ false); let public_key_data = public_key_point.as_bytes(); // Check that the public key data is in the expected uncompressed format: // - 1 byte uncompressed prefix (0x04) // - P bytes of X coordinate // - P bytes of Y coordinate // where P is the field element size. let point_len = elliptic_curve::FieldSize::<p256::NistP256>::to_usize(); if public_key_data.len()!= 2 * point_len + 1 || public_key_data[0]!= ECDSA_UNCOMPRESSED_POINT_PREFIX { return Err("EcdsaSignerKeyManager: unexpected public key data format".into()); } ( secret_key.to_bytes().to_vec(), public_key_data[1..point_len + 1].to_vec(), public_key_data[point_len + 1..].to_vec(), ) } _ => { return Err(format!("EcdsaSignerKeyManager: unsupported curve {:?}", curve).into()) } }; let pub_key = tink_proto::EcdsaPublicKey { version: ECDSA_SIGNER_KEY_VERSION, params: Some(params), x: pub_x_data, y: pub_y_data, }; let priv_key = tink_proto::EcdsaPrivateKey { version: ECDSA_SIGNER_KEY_VERSION, public_key: Some(pub_key), key_value: secret_key_data, }; let mut sk = Vec::new(); priv_key .encode(&mut sk) .map_err(|e| wrap_err("EcdsaSignerKeyManager: failed to encode new key", e))?; Ok(sk) } fn type_url(&self) -> &'static str { ECDSA_SIGNER_TYPE_URL } fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType { tink_proto::key_data::KeyMaterialType::AsymmetricPrivate } fn supports_private_keys(&self) -> bool { true } fn public_key_data( &self, serialized_priv_key: &[u8], ) -> Result<tink_proto::KeyData, TinkError> { let priv_key = tink_proto::EcdsaPrivateKey::decode(serialized_priv_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid private key", e))?; let mut serialized_pub_key = Vec::new(); priv_key .public_key .ok_or_else(|| TinkError::new("EcdsaSignerKeyManager: no public key"))? .encode(&mut serialized_pub_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid public key", e))?; Ok(tink_proto::KeyData { type_url: crate::ECDSA_VERIFIER_TYPE_URL.to_string(), value: serialized_pub_key, key_material_type: tink_proto::key_data::KeyMaterialType::AsymmetricPublic as i32, }) } } /// Validate the given [`EcdsaPrivateKey`](tink_proto::EcdsaPrivateKey) and return /// the parameters. fn validate_key(key: &tink_proto::EcdsaPrivateKey) -> Result<tink_proto::EcdsaParams, TinkError> { tink_core::keyset::validate_key_version(key.version, ECDSA_SIGNER_KEY_VERSION) .map_err(|e| wrap_err("EcdsaSignerKeyManager", e))?; let pub_key = key .public_key .as_ref() .ok_or_else(|| TinkError::new("EcdsaSignerKeyManager: no public key"))?; let params = crate::validate_ecdsa_public_key(pub_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager", e))?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(&params);
crate::subtle::validate_ecdsa_params(hash, curve, encoding)?; Ok(params) } /// Validate the given [`EcdsaKeyFormat`](tink_proto::EcdsaKeyFormat) and return /// the parameters. fn validate_key_format( key_format: &tink_proto::EcdsaKeyFormat, ) -> Result<(tink_proto::EcdsaParams, tink_proto::EllipticCurveType), TinkError> { let params = key_format .params .as_ref() .ok_or_else(|| TinkError::new("no public key parameters"))?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(params); crate::subtle::validate_ecdsa_params(hash, curve, encoding)?; Ok((params.clone(), curve)) }
// Check the public key points are on the curve by creating a verifier. crate::subtle::EcdsaVerifier::new(hash, curve, encoding, &pub_key.x, &pub_key.y) .map_err(|e| wrap_err("EcdsaVerifierKeyManager: invalid key", e))?;
random_line_split
ecdsa_signer_key_manager.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // //////////////////////////////////////////////////////////////////////////////// //! Key manager for ECDSA signing keys. use generic_array::typenum::Unsigned; use p256::elliptic_curve; use tink_core::{utils::wrap_err, TinkError}; use tink_proto::{prost::Message, EllipticCurveType}; /// Maximal version of ECDSA keys. pub const ECDSA_SIGNER_KEY_VERSION: u32 = 0; /// Type URL of ECDSA keys that Tink supports. pub const ECDSA_SIGNER_TYPE_URL: &str = "type.googleapis.com/google.crypto.tink.EcdsaPrivateKey"; /// An implementation of the [`tink_core::registry::KeyManager`] trait. /// It generates new ECDSA private keys and produces new instances of /// [`crate::subtle::EcdsaSigner`]. #[derive(Default)] pub(crate) struct EcdsaSignerKeyManager {} /// Prefix for uncompressed elliptic curve points. pub const ECDSA_UNCOMPRESSED_POINT_PREFIX: u8 = 0x04; impl tink_core::registry::KeyManager for EcdsaSignerKeyManager { fn primitive(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> { if serialized_key.is_empty() { return Err("EcdsaSignerKeyManager: invalid key".into()); } let key = tink_proto::EcdsaPrivateKey::decode(serialized_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid key", e))?; let params = validate_key(&key)?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(&params); match crate::subtle::EcdsaSigner::new(hash, curve, encoding, &key.key_value) { Ok(p) => Ok(tink_core::Primitive::Signer(Box::new(p))), Err(e) => Err(wrap_err("EcdsaSignerKeyManager: invalid key", e)), } } fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> { if serialized_key_format.is_empty() { return Err("EcdsaSignerKeyManager: invalid key format".into()); } let key_format = tink_proto::EcdsaKeyFormat::decode(serialized_key_format) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid key", e))?; let (params, curve) = validate_key_format(&key_format)?; // generate key let mut csprng = signature::rand_core::OsRng {}; let (secret_key_data, pub_x_data, pub_y_data) = match curve { EllipticCurveType::NistP256 => { // Generate a new keypair. let secret_key = p256::ecdsa::SigningKey::random(&mut csprng); let public_key = p256::ecdsa::VerifyingKey::from(&secret_key); let public_key_point = public_key.to_encoded_point(/* compress= */ false); let public_key_data = public_key_point.as_bytes(); // Check that the public key data is in the expected uncompressed format: // - 1 byte uncompressed prefix (0x04) // - P bytes of X coordinate // - P bytes of Y coordinate // where P is the field element size. let point_len = elliptic_curve::FieldSize::<p256::NistP256>::to_usize(); if public_key_data.len()!= 2 * point_len + 1 || public_key_data[0]!= ECDSA_UNCOMPRESSED_POINT_PREFIX { return Err("EcdsaSignerKeyManager: unexpected public key data format".into()); } ( secret_key.to_bytes().to_vec(), public_key_data[1..point_len + 1].to_vec(), public_key_data[point_len + 1..].to_vec(), ) } _ =>
}; let pub_key = tink_proto::EcdsaPublicKey { version: ECDSA_SIGNER_KEY_VERSION, params: Some(params), x: pub_x_data, y: pub_y_data, }; let priv_key = tink_proto::EcdsaPrivateKey { version: ECDSA_SIGNER_KEY_VERSION, public_key: Some(pub_key), key_value: secret_key_data, }; let mut sk = Vec::new(); priv_key .encode(&mut sk) .map_err(|e| wrap_err("EcdsaSignerKeyManager: failed to encode new key", e))?; Ok(sk) } fn type_url(&self) -> &'static str { ECDSA_SIGNER_TYPE_URL } fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType { tink_proto::key_data::KeyMaterialType::AsymmetricPrivate } fn supports_private_keys(&self) -> bool { true } fn public_key_data( &self, serialized_priv_key: &[u8], ) -> Result<tink_proto::KeyData, TinkError> { let priv_key = tink_proto::EcdsaPrivateKey::decode(serialized_priv_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid private key", e))?; let mut serialized_pub_key = Vec::new(); priv_key .public_key .ok_or_else(|| TinkError::new("EcdsaSignerKeyManager: no public key"))? .encode(&mut serialized_pub_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid public key", e))?; Ok(tink_proto::KeyData { type_url: crate::ECDSA_VERIFIER_TYPE_URL.to_string(), value: serialized_pub_key, key_material_type: tink_proto::key_data::KeyMaterialType::AsymmetricPublic as i32, }) } } /// Validate the given [`EcdsaPrivateKey`](tink_proto::EcdsaPrivateKey) and return /// the parameters. fn validate_key(key: &tink_proto::EcdsaPrivateKey) -> Result<tink_proto::EcdsaParams, TinkError> { tink_core::keyset::validate_key_version(key.version, ECDSA_SIGNER_KEY_VERSION) .map_err(|e| wrap_err("EcdsaSignerKeyManager", e))?; let pub_key = key .public_key .as_ref() .ok_or_else(|| TinkError::new("EcdsaSignerKeyManager: no public key"))?; let params = crate::validate_ecdsa_public_key(pub_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager", e))?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(&params); // Check the public key points are on the curve by creating a verifier. crate::subtle::EcdsaVerifier::new(hash, curve, encoding, &pub_key.x, &pub_key.y) .map_err(|e| wrap_err("EcdsaVerifierKeyManager: invalid key", e))?; crate::subtle::validate_ecdsa_params(hash, curve, encoding)?; Ok(params) } /// Validate the given [`EcdsaKeyFormat`](tink_proto::EcdsaKeyFormat) and return /// the parameters. fn validate_key_format( key_format: &tink_proto::EcdsaKeyFormat, ) -> Result<(tink_proto::EcdsaParams, tink_proto::EllipticCurveType), TinkError> { let params = key_format .params .as_ref() .ok_or_else(|| TinkError::new("no public key parameters"))?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(params); crate::subtle::validate_ecdsa_params(hash, curve, encoding)?; Ok((params.clone(), curve)) }
{ return Err(format!("EcdsaSignerKeyManager: unsupported curve {:?}", curve).into()) }
conditional_block
ecdsa_signer_key_manager.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // //////////////////////////////////////////////////////////////////////////////// //! Key manager for ECDSA signing keys. use generic_array::typenum::Unsigned; use p256::elliptic_curve; use tink_core::{utils::wrap_err, TinkError}; use tink_proto::{prost::Message, EllipticCurveType}; /// Maximal version of ECDSA keys. pub const ECDSA_SIGNER_KEY_VERSION: u32 = 0; /// Type URL of ECDSA keys that Tink supports. pub const ECDSA_SIGNER_TYPE_URL: &str = "type.googleapis.com/google.crypto.tink.EcdsaPrivateKey"; /// An implementation of the [`tink_core::registry::KeyManager`] trait. /// It generates new ECDSA private keys and produces new instances of /// [`crate::subtle::EcdsaSigner`]. #[derive(Default)] pub(crate) struct EcdsaSignerKeyManager {} /// Prefix for uncompressed elliptic curve points. pub const ECDSA_UNCOMPRESSED_POINT_PREFIX: u8 = 0x04; impl tink_core::registry::KeyManager for EcdsaSignerKeyManager { fn primitive(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> { if serialized_key.is_empty() { return Err("EcdsaSignerKeyManager: invalid key".into()); } let key = tink_proto::EcdsaPrivateKey::decode(serialized_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid key", e))?; let params = validate_key(&key)?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(&params); match crate::subtle::EcdsaSigner::new(hash, curve, encoding, &key.key_value) { Ok(p) => Ok(tink_core::Primitive::Signer(Box::new(p))), Err(e) => Err(wrap_err("EcdsaSignerKeyManager: invalid key", e)), } } fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> { if serialized_key_format.is_empty() { return Err("EcdsaSignerKeyManager: invalid key format".into()); } let key_format = tink_proto::EcdsaKeyFormat::decode(serialized_key_format) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid key", e))?; let (params, curve) = validate_key_format(&key_format)?; // generate key let mut csprng = signature::rand_core::OsRng {}; let (secret_key_data, pub_x_data, pub_y_data) = match curve { EllipticCurveType::NistP256 => { // Generate a new keypair. let secret_key = p256::ecdsa::SigningKey::random(&mut csprng); let public_key = p256::ecdsa::VerifyingKey::from(&secret_key); let public_key_point = public_key.to_encoded_point(/* compress= */ false); let public_key_data = public_key_point.as_bytes(); // Check that the public key data is in the expected uncompressed format: // - 1 byte uncompressed prefix (0x04) // - P bytes of X coordinate // - P bytes of Y coordinate // where P is the field element size. let point_len = elliptic_curve::FieldSize::<p256::NistP256>::to_usize(); if public_key_data.len()!= 2 * point_len + 1 || public_key_data[0]!= ECDSA_UNCOMPRESSED_POINT_PREFIX { return Err("EcdsaSignerKeyManager: unexpected public key data format".into()); } ( secret_key.to_bytes().to_vec(), public_key_data[1..point_len + 1].to_vec(), public_key_data[point_len + 1..].to_vec(), ) } _ => { return Err(format!("EcdsaSignerKeyManager: unsupported curve {:?}", curve).into()) } }; let pub_key = tink_proto::EcdsaPublicKey { version: ECDSA_SIGNER_KEY_VERSION, params: Some(params), x: pub_x_data, y: pub_y_data, }; let priv_key = tink_proto::EcdsaPrivateKey { version: ECDSA_SIGNER_KEY_VERSION, public_key: Some(pub_key), key_value: secret_key_data, }; let mut sk = Vec::new(); priv_key .encode(&mut sk) .map_err(|e| wrap_err("EcdsaSignerKeyManager: failed to encode new key", e))?; Ok(sk) } fn type_url(&self) -> &'static str { ECDSA_SIGNER_TYPE_URL } fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType { tink_proto::key_data::KeyMaterialType::AsymmetricPrivate } fn supports_private_keys(&self) -> bool { true } fn public_key_data( &self, serialized_priv_key: &[u8], ) -> Result<tink_proto::KeyData, TinkError>
} /// Validate the given [`EcdsaPrivateKey`](tink_proto::EcdsaPrivateKey) and return /// the parameters. fn validate_key(key: &tink_proto::EcdsaPrivateKey) -> Result<tink_proto::EcdsaParams, TinkError> { tink_core::keyset::validate_key_version(key.version, ECDSA_SIGNER_KEY_VERSION) .map_err(|e| wrap_err("EcdsaSignerKeyManager", e))?; let pub_key = key .public_key .as_ref() .ok_or_else(|| TinkError::new("EcdsaSignerKeyManager: no public key"))?; let params = crate::validate_ecdsa_public_key(pub_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager", e))?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(&params); // Check the public key points are on the curve by creating a verifier. crate::subtle::EcdsaVerifier::new(hash, curve, encoding, &pub_key.x, &pub_key.y) .map_err(|e| wrap_err("EcdsaVerifierKeyManager: invalid key", e))?; crate::subtle::validate_ecdsa_params(hash, curve, encoding)?; Ok(params) } /// Validate the given [`EcdsaKeyFormat`](tink_proto::EcdsaKeyFormat) and return /// the parameters. fn validate_key_format( key_format: &tink_proto::EcdsaKeyFormat, ) -> Result<(tink_proto::EcdsaParams, tink_proto::EllipticCurveType), TinkError> { let params = key_format .params .as_ref() .ok_or_else(|| TinkError::new("no public key parameters"))?; let (hash, curve, encoding) = crate::get_ecdsa_param_ids(params); crate::subtle::validate_ecdsa_params(hash, curve, encoding)?; Ok((params.clone(), curve)) }
{ let priv_key = tink_proto::EcdsaPrivateKey::decode(serialized_priv_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid private key", e))?; let mut serialized_pub_key = Vec::new(); priv_key .public_key .ok_or_else(|| TinkError::new("EcdsaSignerKeyManager: no public key"))? .encode(&mut serialized_pub_key) .map_err(|e| wrap_err("EcdsaSignerKeyManager: invalid public key", e))?; Ok(tink_proto::KeyData { type_url: crate::ECDSA_VERIFIER_TYPE_URL.to_string(), value: serialized_pub_key, key_material_type: tink_proto::key_data::KeyMaterialType::AsymmetricPublic as i32, }) }
identifier_body
dht22.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // 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. //! Driver for DHT22. use core::iter::range; use core::option::Option::{self, Some, None}; use hal::pin::Gpio; use hal::pin::GpioLevel::Low; use hal::pin::GpioLevel::High; use hal::pin::GpioDirection::In; use hal::pin::GpioDirection::Out; use hal::pin::GpioLevel; use hal::timer::Timer; /// Basic DHT22 driver ported over from Arduino example. pub struct DHT22<'a, T:'a, P:'a> { gpio: &'a P, timer: &'a T, } /// Measurement data from the DHT22. #[allow(missing_docs)] #[derive(Copy)] pub struct Measurements { pub humidity: f32, pub temperature: f32, } impl<'a, T: Timer, P: Gpio> DHT22<'a, T, P> { /// Creates a new DHT22 driver based on I/O GPIO and a timer with 10us resolution. pub fn new(timer: &'a T, gpio: &'a P) -> DHT22<'a, T, P> { DHT22 { gpio: gpio, timer: timer, } } /// Returns previous sensor measurements or None if synchronization failed. pub fn read(&self) -> Option<Measurements> { let buffer: &mut [u8; 5] = &mut [0; 5]; let mut idx: usize = 0; let mut mask: u8 = 128; self.gpio.set_direction(Out); self.gpio.set_low(); self.timer.wait_ms(20); self.gpio.set_high(); self.timer.wait_us(40); self.gpio.set_direction(In); if!self.wait_sync() { return None } for _ in range(0usize, 40) { if!self.wait_while(Low, 80) { return None } let t = self.timer.get_counter(); if!self.wait_while(High, 80) { return None } if self.timer.get_counter() - t > 40 { buffer[idx] |= mask; } mask >>= 1; if mask == 0 { mask = 128; idx += 1; } } let humidity: f32 = (((buffer[0] as u16) << 8) | buffer[1] as u16) as f32 * 0.1; let temperature: f32 = if buffer[2] & 0x80!= 0
else { 0.1 * (((buffer[2] as u16) << 8) | buffer[3] as u16) as f32 }; let checksum: u8 = buffer[0] + buffer[1] + buffer[2] + buffer[3]; if checksum!= buffer[4] { None } else { Some(Measurements { humidity: humidity, temperature: temperature, }) } } fn wait_sync(&self) -> bool { if!self.wait_while(Low, 80) { false } else if!self.wait_while(High, 100) { false } else { true } } fn wait_while(&self, level: GpioLevel, timeout: usize) -> bool { for _ in range(0, timeout / 10) { self.timer.wait_us(10); if self.gpio.level()!= level { return true; } } false } }
{ -0.1 * (((buffer[2] as u16 & 0x7F) << 8) | buffer[3] as u16) as f32 }
conditional_block
dht22.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // 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. //! Driver for DHT22. use core::iter::range; use core::option::Option::{self, Some, None}; use hal::pin::Gpio; use hal::pin::GpioLevel::Low; use hal::pin::GpioLevel::High; use hal::pin::GpioDirection::In; use hal::pin::GpioDirection::Out; use hal::pin::GpioLevel; use hal::timer::Timer; /// Basic DHT22 driver ported over from Arduino example. pub struct DHT22<'a, T:'a, P:'a> { gpio: &'a P, timer: &'a T, } /// Measurement data from the DHT22. #[allow(missing_docs)] #[derive(Copy)] pub struct Measurements { pub humidity: f32, pub temperature: f32, } impl<'a, T: Timer, P: Gpio> DHT22<'a, T, P> { /// Creates a new DHT22 driver based on I/O GPIO and a timer with 10us resolution. pub fn new(timer: &'a T, gpio: &'a P) -> DHT22<'a, T, P> { DHT22 { gpio: gpio, timer: timer, } } /// Returns previous sensor measurements or None if synchronization failed. pub fn read(&self) -> Option<Measurements> { let buffer: &mut [u8; 5] = &mut [0; 5]; let mut idx: usize = 0; let mut mask: u8 = 128; self.gpio.set_direction(Out); self.gpio.set_low(); self.timer.wait_ms(20); self.gpio.set_high(); self.timer.wait_us(40); self.gpio.set_direction(In); if!self.wait_sync() { return None } for _ in range(0usize, 40) { if!self.wait_while(Low, 80) { return None } let t = self.timer.get_counter(); if!self.wait_while(High, 80) { return None } if self.timer.get_counter() - t > 40 { buffer[idx] |= mask; } mask >>= 1; if mask == 0 { mask = 128; idx += 1; } } let humidity: f32 = (((buffer[0] as u16) << 8) | buffer[1] as u16) as f32 * 0.1; let temperature: f32 = if buffer[2] & 0x80!= 0 { -0.1 * (((buffer[2] as u16 & 0x7F) << 8) | buffer[3] as u16) as f32 } else { 0.1 * (((buffer[2] as u16) << 8) | buffer[3] as u16) as f32 }; let checksum: u8 = buffer[0] + buffer[1] + buffer[2] + buffer[3]; if checksum!= buffer[4] { None } else { Some(Measurements { humidity: humidity, temperature: temperature, }) } } fn
(&self) -> bool { if!self.wait_while(Low, 80) { false } else if!self.wait_while(High, 100) { false } else { true } } fn wait_while(&self, level: GpioLevel, timeout: usize) -> bool { for _ in range(0, timeout / 10) { self.timer.wait_us(10); if self.gpio.level()!= level { return true; } } false } }
wait_sync
identifier_name
dht22.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // 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. //! Driver for DHT22. use core::iter::range; use core::option::Option::{self, Some, None}; use hal::pin::Gpio; use hal::pin::GpioLevel::Low; use hal::pin::GpioLevel::High; use hal::pin::GpioDirection::In; use hal::pin::GpioDirection::Out; use hal::pin::GpioLevel; use hal::timer::Timer; /// Basic DHT22 driver ported over from Arduino example. pub struct DHT22<'a, T:'a, P:'a> { gpio: &'a P, timer: &'a T, } /// Measurement data from the DHT22. #[allow(missing_docs)] #[derive(Copy)] pub struct Measurements { pub humidity: f32, pub temperature: f32, } impl<'a, T: Timer, P: Gpio> DHT22<'a, T, P> { /// Creates a new DHT22 driver based on I/O GPIO and a timer with 10us resolution. pub fn new(timer: &'a T, gpio: &'a P) -> DHT22<'a, T, P>
/// Returns previous sensor measurements or None if synchronization failed. pub fn read(&self) -> Option<Measurements> { let buffer: &mut [u8; 5] = &mut [0; 5]; let mut idx: usize = 0; let mut mask: u8 = 128; self.gpio.set_direction(Out); self.gpio.set_low(); self.timer.wait_ms(20); self.gpio.set_high(); self.timer.wait_us(40); self.gpio.set_direction(In); if!self.wait_sync() { return None } for _ in range(0usize, 40) { if!self.wait_while(Low, 80) { return None } let t = self.timer.get_counter(); if!self.wait_while(High, 80) { return None } if self.timer.get_counter() - t > 40 { buffer[idx] |= mask; } mask >>= 1; if mask == 0 { mask = 128; idx += 1; } } let humidity: f32 = (((buffer[0] as u16) << 8) | buffer[1] as u16) as f32 * 0.1; let temperature: f32 = if buffer[2] & 0x80!= 0 { -0.1 * (((buffer[2] as u16 & 0x7F) << 8) | buffer[3] as u16) as f32 } else { 0.1 * (((buffer[2] as u16) << 8) | buffer[3] as u16) as f32 }; let checksum: u8 = buffer[0] + buffer[1] + buffer[2] + buffer[3]; if checksum!= buffer[4] { None } else { Some(Measurements { humidity: humidity, temperature: temperature, }) } } fn wait_sync(&self) -> bool { if!self.wait_while(Low, 80) { false } else if!self.wait_while(High, 100) { false } else { true } } fn wait_while(&self, level: GpioLevel, timeout: usize) -> bool { for _ in range(0, timeout / 10) { self.timer.wait_us(10); if self.gpio.level()!= level { return true; } } false } }
{ DHT22 { gpio: gpio, timer: timer, } }
identifier_body
dht22.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // 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. //! Driver for DHT22. use core::iter::range; use core::option::Option::{self, Some, None}; use hal::pin::Gpio; use hal::pin::GpioLevel::Low; use hal::pin::GpioLevel::High; use hal::pin::GpioDirection::In; use hal::pin::GpioDirection::Out; use hal::pin::GpioLevel; use hal::timer::Timer; /// Basic DHT22 driver ported over from Arduino example. pub struct DHT22<'a, T:'a, P:'a> { gpio: &'a P, timer: &'a T, } /// Measurement data from the DHT22. #[allow(missing_docs)] #[derive(Copy)] pub struct Measurements { pub humidity: f32, pub temperature: f32, } impl<'a, T: Timer, P: Gpio> DHT22<'a, T, P> { /// Creates a new DHT22 driver based on I/O GPIO and a timer with 10us resolution. pub fn new(timer: &'a T, gpio: &'a P) -> DHT22<'a, T, P> { DHT22 { gpio: gpio, timer: timer, } } /// Returns previous sensor measurements or None if synchronization failed. pub fn read(&self) -> Option<Measurements> { let buffer: &mut [u8; 5] = &mut [0; 5]; let mut idx: usize = 0; let mut mask: u8 = 128; self.gpio.set_direction(Out); self.gpio.set_low(); self.timer.wait_ms(20); self.gpio.set_high(); self.timer.wait_us(40); self.gpio.set_direction(In); if!self.wait_sync() { return None } for _ in range(0usize, 40) { if!self.wait_while(Low, 80) { return None } let t = self.timer.get_counter(); if!self.wait_while(High, 80) { return None } if self.timer.get_counter() - t > 40 { buffer[idx] |= mask; } mask >>= 1; if mask == 0 { mask = 128; idx += 1; } } let humidity: f32 = (((buffer[0] as u16) << 8) | buffer[1] as u16) as f32 * 0.1; let temperature: f32 = if buffer[2] & 0x80!= 0 { -0.1 * (((buffer[2] as u16 & 0x7F) << 8) | buffer[3] as u16) as f32 } else { 0.1 * (((buffer[2] as u16) << 8) | buffer[3] as u16) as f32 }; let checksum: u8 = buffer[0] + buffer[1] + buffer[2] + buffer[3]; if checksum!= buffer[4] { None } else { Some(Measurements { humidity: humidity, temperature: temperature, }) } } fn wait_sync(&self) -> bool { if!self.wait_while(Low, 80) { false } else if!self.wait_while(High, 100) { false
} } fn wait_while(&self, level: GpioLevel, timeout: usize) -> bool { for _ in range(0, timeout / 10) { self.timer.wait_us(10); if self.gpio.level()!= level { return true; } } false } }
} else { true
random_line_split
range.rs
use super::Index; /// A range of values in a vector-like object #[derive(Debug, PartialEq, Copy, Clone)] pub(crate) struct Range { /// Starting index start: Index, /// Ending index end: Index, /// Is this range inclusive? If false, this object represents a half-open /// range of [start, end), otherwise [start, end] inclusive: bool, } impl Range { pub(crate) fn to(end: Index) -> Range { Range { start: Index::new(0), end, inclusive: false, } } pub(crate) fn from(start: Index) -> Range { Range { start, end: Index::new(-1), inclusive: true, } } pub(crate) fn inclusive(start: Index, end: Index) -> Range { Range { start, end, inclusive: true, } } pub(crate) fn exclusive(start: Index, end: Index) -> Range { Range { start, end, inclusive: false, } } /// Returns the bounds of this range as a tuple containing: /// - The starting point of the range /// - The length of the range /// ``` /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8]; /// let range = Range::exclusive(Index::new(1), Index::new(5)); /// let (start, size) = range.bounds(vec.len()).unwrap(); /// let expected = vec![1, 2, 3, 4]; /// let selection = vec.iter().skip(start).take(size).collect::<Vec<_>>(); /// assert_eq!(expected, selection); /// ``` pub(crate) fn
(&self, vector_length: usize) -> Option<(usize, usize)> { if let Some(start) = self.start.resolve(vector_length) { if let Some(end) = self.end.resolve(vector_length) { if end < start { None } else if self.inclusive { Some((start, end - start + 1)) } else { Some((start, end - start)) } } else { None } } else { None } } }
bounds
identifier_name
range.rs
use super::Index; /// A range of values in a vector-like object #[derive(Debug, PartialEq, Copy, Clone)] pub(crate) struct Range { /// Starting index start: Index, /// Ending index end: Index, /// Is this range inclusive? If false, this object represents a half-open /// range of [start, end), otherwise [start, end] inclusive: bool, } impl Range { pub(crate) fn to(end: Index) -> Range { Range { start: Index::new(0), end, inclusive: false, } } pub(crate) fn from(start: Index) -> Range { Range { start, end: Index::new(-1), inclusive: true, } } pub(crate) fn inclusive(start: Index, end: Index) -> Range { Range { start,
end, inclusive: true, } } pub(crate) fn exclusive(start: Index, end: Index) -> Range { Range { start, end, inclusive: false, } } /// Returns the bounds of this range as a tuple containing: /// - The starting point of the range /// - The length of the range /// ``` /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8]; /// let range = Range::exclusive(Index::new(1), Index::new(5)); /// let (start, size) = range.bounds(vec.len()).unwrap(); /// let expected = vec![1, 2, 3, 4]; /// let selection = vec.iter().skip(start).take(size).collect::<Vec<_>>(); /// assert_eq!(expected, selection); /// ``` pub(crate) fn bounds(&self, vector_length: usize) -> Option<(usize, usize)> { if let Some(start) = self.start.resolve(vector_length) { if let Some(end) = self.end.resolve(vector_length) { if end < start { None } else if self.inclusive { Some((start, end - start + 1)) } else { Some((start, end - start)) } } else { None } } else { None } } }
random_line_split
range.rs
use super::Index; /// A range of values in a vector-like object #[derive(Debug, PartialEq, Copy, Clone)] pub(crate) struct Range { /// Starting index start: Index, /// Ending index end: Index, /// Is this range inclusive? If false, this object represents a half-open /// range of [start, end), otherwise [start, end] inclusive: bool, } impl Range { pub(crate) fn to(end: Index) -> Range { Range { start: Index::new(0), end, inclusive: false, } } pub(crate) fn from(start: Index) -> Range
pub(crate) fn inclusive(start: Index, end: Index) -> Range { Range { start, end, inclusive: true, } } pub(crate) fn exclusive(start: Index, end: Index) -> Range { Range { start, end, inclusive: false, } } /// Returns the bounds of this range as a tuple containing: /// - The starting point of the range /// - The length of the range /// ``` /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8]; /// let range = Range::exclusive(Index::new(1), Index::new(5)); /// let (start, size) = range.bounds(vec.len()).unwrap(); /// let expected = vec![1, 2, 3, 4]; /// let selection = vec.iter().skip(start).take(size).collect::<Vec<_>>(); /// assert_eq!(expected, selection); /// ``` pub(crate) fn bounds(&self, vector_length: usize) -> Option<(usize, usize)> { if let Some(start) = self.start.resolve(vector_length) { if let Some(end) = self.end.resolve(vector_length) { if end < start { None } else if self.inclusive { Some((start, end - start + 1)) } else { Some((start, end - start)) } } else { None } } else { None } } }
{ Range { start, end: Index::new(-1), inclusive: true, } }
identifier_body
range.rs
use super::Index; /// A range of values in a vector-like object #[derive(Debug, PartialEq, Copy, Clone)] pub(crate) struct Range { /// Starting index start: Index, /// Ending index end: Index, /// Is this range inclusive? If false, this object represents a half-open /// range of [start, end), otherwise [start, end] inclusive: bool, } impl Range { pub(crate) fn to(end: Index) -> Range { Range { start: Index::new(0), end, inclusive: false, } } pub(crate) fn from(start: Index) -> Range { Range { start, end: Index::new(-1), inclusive: true, } } pub(crate) fn inclusive(start: Index, end: Index) -> Range { Range { start, end, inclusive: true, } } pub(crate) fn exclusive(start: Index, end: Index) -> Range { Range { start, end, inclusive: false, } } /// Returns the bounds of this range as a tuple containing: /// - The starting point of the range /// - The length of the range /// ``` /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8]; /// let range = Range::exclusive(Index::new(1), Index::new(5)); /// let (start, size) = range.bounds(vec.len()).unwrap(); /// let expected = vec![1, 2, 3, 4]; /// let selection = vec.iter().skip(start).take(size).collect::<Vec<_>>(); /// assert_eq!(expected, selection); /// ``` pub(crate) fn bounds(&self, vector_length: usize) -> Option<(usize, usize)> { if let Some(start) = self.start.resolve(vector_length) { if let Some(end) = self.end.resolve(vector_length) { if end < start { None } else if self.inclusive
else { Some((start, end - start)) } } else { None } } else { None } } }
{ Some((start, end - start + 1)) }
conditional_block
imagedata.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 core::nonzero::NonZero; use dom::bindings::codegen::Bindings::ImageDataBinding; use dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; use euclid::size::Size2D; use js::jsapi::{Heap, JSContext, JSObject}; use js::rust::Runtime; use js::typedarray::Uint8ClampedArray; use std::default::Default; use std::ptr; use std::vec::Vec; #[dom_struct] pub struct ImageData { reflector_: Reflector, width: u32, height: u32, data: Heap<*mut JSObject>, } impl ImageData { #[allow(unsafe_code)] pub fn new(global: &GlobalScope, width: u32, height: u32, data: Option<Vec<u8>>) -> Root<ImageData> { let imagedata = box ImageData { reflector_: Reflector::new(), width: width, height: height, data: Heap::default(), }; unsafe { let cx = global.get_cx(); rooted!(in (cx) let mut js_object = ptr::null_mut()); let data = data.as_ref().map(|d| &d[..]); Uint8ClampedArray::create(cx, width * height * 4, data, js_object.handle_mut()).unwrap(); (*imagedata).data.set(js_object.get()); } reflect_dom_object(imagedata, global, ImageDataBinding::Wrap) } #[allow(unsafe_code)] pub fn get_data_array(&self) -> Vec<u8> { unsafe { assert!(!self.data.get().is_null()); let cx = Runtime::get(); assert!(!cx.is_null()); typedarray!(in(cx) let array: Uint8ClampedArray = self.data.get()); let vec = array.unwrap().as_slice().to_vec(); vec } } pub fn get_size(&self) -> Size2D<i32> { Size2D::new(self.Width() as i32, self.Height() as i32) } } impl ImageDataMethods for ImageData { // https://html.spec.whatwg.org/multipage/#dom-imagedata-width fn Width(&self) -> u32 { self.width } // https://html.spec.whatwg.org/multipage/#dom-imagedata-height fn Height(&self) -> u32 { self.height } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-imagedata-data unsafe fn
(&self, _: *mut JSContext) -> NonZero<*mut JSObject> { assert!(!self.data.get().is_null()); NonZero::new(self.data.get()) } }
Data
identifier_name
imagedata.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 core::nonzero::NonZero; use dom::bindings::codegen::Bindings::ImageDataBinding; use dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; use euclid::size::Size2D; use js::jsapi::{Heap, JSContext, JSObject}; use js::rust::Runtime; use js::typedarray::Uint8ClampedArray; use std::default::Default; use std::ptr; use std::vec::Vec; #[dom_struct] pub struct ImageData { reflector_: Reflector, width: u32, height: u32, data: Heap<*mut JSObject>, } impl ImageData { #[allow(unsafe_code)] pub fn new(global: &GlobalScope, width: u32, height: u32, data: Option<Vec<u8>>) -> Root<ImageData> { let imagedata = box ImageData { reflector_: Reflector::new(), width: width, height: height, data: Heap::default(), }; unsafe { let cx = global.get_cx(); rooted!(in (cx) let mut js_object = ptr::null_mut()); let data = data.as_ref().map(|d| &d[..]); Uint8ClampedArray::create(cx, width * height * 4, data, js_object.handle_mut()).unwrap(); (*imagedata).data.set(js_object.get()); } reflect_dom_object(imagedata, global, ImageDataBinding::Wrap) } #[allow(unsafe_code)] pub fn get_data_array(&self) -> Vec<u8> { unsafe { assert!(!self.data.get().is_null()); let cx = Runtime::get(); assert!(!cx.is_null()); typedarray!(in(cx) let array: Uint8ClampedArray = self.data.get()); let vec = array.unwrap().as_slice().to_vec(); vec
pub fn get_size(&self) -> Size2D<i32> { Size2D::new(self.Width() as i32, self.Height() as i32) } } impl ImageDataMethods for ImageData { // https://html.spec.whatwg.org/multipage/#dom-imagedata-width fn Width(&self) -> u32 { self.width } // https://html.spec.whatwg.org/multipage/#dom-imagedata-height fn Height(&self) -> u32 { self.height } #[allow(unsafe_code)] // https://html.spec.whatwg.org/multipage/#dom-imagedata-data unsafe fn Data(&self, _: *mut JSContext) -> NonZero<*mut JSObject> { assert!(!self.data.get().is_null()); NonZero::new(self.data.get()) } }
} }
random_line_split
mod.rs
use std; use std::slice; use libc::ptrdiff_t; use md5 as md5_crate; use sha1; use sha2::{Digest, Sha224, Sha256, Sha384, Sha512}; use remacs_macros::lisp_fn; use crate::{ buffers::{LispBufferOrName, LispBufferRef}, lisp::LispObject, multibyte::LispStringRef, remacs_sys::EmacsInt, remacs_sys::{extract_data_from_object, make_uninit_string}, remacs_sys::{Qmd5, Qnil, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512}, symbols::{symbol_name, LispSymbolRef}, threads::ThreadState, }; #[derive(Clone, Copy)] enum HashAlg { MD5, SHA1, SHA224, SHA256, SHA384, SHA512, } static MD5_DIGEST_LEN: usize = 16; static SHA1_DIGEST_LEN: usize = 20; static SHA224_DIGEST_LEN: usize = 224 / 8; static SHA256_DIGEST_LEN: usize = 256 / 8; static SHA384_DIGEST_LEN: usize = 384 / 8; static SHA512_DIGEST_LEN: usize = 512 / 8; fn hash_alg(algorithm: LispSymbolRef) -> HashAlg { match LispObject::from(algorithm) { Qmd5 => HashAlg::MD5, Qsha1 => HashAlg::SHA1, Qsha224 => HashAlg::SHA224, Qsha256 => HashAlg::SHA256, Qsha384 => HashAlg::SHA384, Qsha512 => HashAlg::SHA512, _ => { let name: LispStringRef = symbol_name(algorithm).into(); error!("Invalid algorithm arg: {:?}\0", &name.as_slice()); } } } /// Return MD5 message digest of OBJECT, a buffer or string. /// /// A message digest is a cryptographic checksum of a document, and the /// algorithm to calculate it is defined in RFC 1321. /// /// The two optional arguments START and END are character positions /// specifying for which part of OBJECT the message digest should be /// computed. If nil or omitted, the digest is computed for the whole /// OBJECT. /// /// The MD5 message digest is computed from the result of encoding the /// text in a coding system, not directly from the internal Emacs form of /// the text. The optional fourth argument CODING-SYSTEM specifies which /// coding system to encode the text with. It should be the same coding /// system that you used or will use when actually writing the text into a /// file. /// /// If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If /// OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding /// system would be chosen by default for writing this text into a file. /// /// If OBJECT is a string, the most preferred coding system (see the /// command `prefer-coding-system') is used. /// /// If NOERROR is non-nil, silently assume the `raw-text' coding if the /// guesswork fails. Normally, an error is signaled in such case. #[lisp_fn(min = "1")] pub fn md5( object: LispObject, start: LispObject, end: LispObject, coding_system: LispObject, noerror: LispObject, ) -> LispObject { _secure_hash( HashAlg::MD5, object, start, end, coding_system, noerror, Qnil, ) } /// Return the secure hash of OBJECT, a buffer or string. /// ALGORITHM is a symbol specifying the hash to use: /// md5, sha1, sha224, sha256, sha384 or sha512. /// /// The two optional arguments START and END are positions specifying for /// which part of OBJECT to compute the hash. If nil or omitted, uses the /// whole OBJECT. /// /// The full list of algorithms can be obtained with `secure-hash-algorithms'. /// /// If BINARY is non-nil, returns a string in binary form. #[lisp_fn(min = "2")] pub fn secure_hash( algorithm: LispSymbolRef, object: LispObject, start: LispObject, end: LispObject, binary: LispObject, ) -> LispObject { _secure_hash(hash_alg(algorithm), object, start, end, Qnil, Qnil, binary) } fn _secure_hash( algorithm: HashAlg, object: LispObject, start: LispObject, end: LispObject, coding_system: LispObject, noerror: LispObject, binary: LispObject, ) -> LispObject { type HashFn = fn(&[u8], &mut [u8]); let spec = list!(object, start, end, coding_system, noerror); let mut start_byte: ptrdiff_t = 0; let mut end_byte: ptrdiff_t = 0; let input = unsafe { extract_data_from_object(spec, &mut start_byte, &mut end_byte) }; if input.is_null() { error!("secure_hash: failed to extract data from object, aborting!"); } let input_slice = unsafe { slice::from_raw_parts( input.offset(start_byte) as *mut u8, (end_byte - start_byte) as usize, ) }; let (digest_size, hash_func) = match algorithm { HashAlg::MD5 => (MD5_DIGEST_LEN, md5_buffer as HashFn), HashAlg::SHA1 => (SHA1_DIGEST_LEN, sha1_buffer as HashFn), HashAlg::SHA224 => (SHA224_DIGEST_LEN, sha224_buffer as HashFn), HashAlg::SHA256 => (SHA256_DIGEST_LEN, sha256_buffer as HashFn), HashAlg::SHA384 => (SHA384_DIGEST_LEN, sha384_buffer as HashFn), HashAlg::SHA512 => (SHA512_DIGEST_LEN, sha512_buffer as HashFn), }; let buffer_size = if binary.is_nil() { (digest_size * 2) as EmacsInt } else { digest_size as EmacsInt }; let digest = unsafe { make_uninit_string(buffer_size as EmacsInt) }; let mut digest_str: LispStringRef = digest.into(); hash_func(input_slice, digest_str.as_mut_slice()); if binary.is_nil() { hexify_digest_string(digest_str.as_mut_slice(), digest_size); } digest } /// To avoid a copy, buffer is both the source and the destination of /// this transformation. Buffer must contain len bytes of data and /// 2*len bytes of space for the final hex string. fn hexify_digest_string(buffer: &mut [u8], len: usize) { static hexdigit: [u8; 16] = *b"0123456789abcdef"; debug_assert_eq!( buffer.len(), 2 * len, "buffer must be long enough to hold 2*len hex digits" ); for i in (0..len).rev() { let v = buffer[i]; buffer[2 * i] = hexdigit[(v >> 4) as usize]; buffer[2 * i + 1] = hexdigit[(v & 0xf) as usize]; } } // For the following hash functions, the caller must ensure that the // destination buffer is at least long enough to hold the // digest. Additionally, the caller may have been asked to return a // hex string, in which case dest_buf will be twice as long as the // digest. fn md5_buffer(buffer: &[u8], dest_buf: &mut [u8]) { let output = md5_crate::compute(buffer); dest_buf[..output.len()].copy_from_slice(&*output) } fn sha1_buffer(buffer: &[u8], dest_buf: &mut [u8]) { let mut hasher = sha1::Sha1::new(); hasher.update(buffer); let output = hasher.digest().bytes(); dest_buf[..output.len()].copy_from_slice(&output) } /// Given an instance of `Digest`, and `buffer` write its hash to `dest_buf`. fn sha2_hash_buffer(hasher: impl Digest, buffer: &[u8], dest_buf: &mut [u8]) { let mut hasher = hasher; hasher.input(buffer); let output = hasher.result(); dest_buf[..output.len()].copy_from_slice(&output) } fn sha224_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha224::new(), buffer, dest_buf); } fn sha256_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha256::new(), buffer, dest_buf); } fn sha384_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha384::new(), buffer, dest_buf); } fn sha512_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha512::new(), buffer, dest_buf); } /// Return a hash of the contents of BUFFER-OR-NAME. /// This hash is performed on the raw internal format of the buffer, /// disregarding any coding systems. If nil, use the current buffer. #[lisp_fn(min = "0")] pub fn buffer_hash(buffer_or_name: Option<LispBufferOrName>) -> LispObject
.unwrap() .as_mut_slice() .copy_from_slice(formatted.as_bytes()); digest } include!(concat!(env!("OUT_DIR"), "/crypto_exports.rs"));
{ let b = buffer_or_name.map_or_else(ThreadState::current_buffer_unchecked, LispBufferRef::from); let mut ctx = sha1::Sha1::new(); ctx.update(unsafe { slice::from_raw_parts(b.beg_addr(), (b.gpt_byte() - b.beg_byte()) as usize) }); if b.gpt_byte() < b.z_byte() { ctx.update(unsafe { slice::from_raw_parts( b.gap_end_addr(), b.z_addr() as usize - b.gap_end_addr() as usize, ) }); } let formatted = ctx.digest().to_string(); let digest = unsafe { make_uninit_string(formatted.len() as EmacsInt) }; digest .as_string()
identifier_body
mod.rs
use std; use std::slice; use libc::ptrdiff_t; use md5 as md5_crate; use sha1; use sha2::{Digest, Sha224, Sha256, Sha384, Sha512}; use remacs_macros::lisp_fn; use crate::{ buffers::{LispBufferOrName, LispBufferRef}, lisp::LispObject, multibyte::LispStringRef, remacs_sys::EmacsInt, remacs_sys::{extract_data_from_object, make_uninit_string}, remacs_sys::{Qmd5, Qnil, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512}, symbols::{symbol_name, LispSymbolRef}, threads::ThreadState, }; #[derive(Clone, Copy)] enum HashAlg { MD5, SHA1, SHA224, SHA256, SHA384, SHA512, } static MD5_DIGEST_LEN: usize = 16; static SHA1_DIGEST_LEN: usize = 20; static SHA224_DIGEST_LEN: usize = 224 / 8; static SHA256_DIGEST_LEN: usize = 256 / 8; static SHA384_DIGEST_LEN: usize = 384 / 8; static SHA512_DIGEST_LEN: usize = 512 / 8; fn hash_alg(algorithm: LispSymbolRef) -> HashAlg { match LispObject::from(algorithm) { Qmd5 => HashAlg::MD5, Qsha1 => HashAlg::SHA1, Qsha224 => HashAlg::SHA224, Qsha256 => HashAlg::SHA256, Qsha384 => HashAlg::SHA384, Qsha512 => HashAlg::SHA512, _ => { let name: LispStringRef = symbol_name(algorithm).into(); error!("Invalid algorithm arg: {:?}\0", &name.as_slice()); } } } /// Return MD5 message digest of OBJECT, a buffer or string. /// /// A message digest is a cryptographic checksum of a document, and the /// algorithm to calculate it is defined in RFC 1321. /// /// The two optional arguments START and END are character positions /// specifying for which part of OBJECT the message digest should be /// computed. If nil or omitted, the digest is computed for the whole /// OBJECT. /// /// The MD5 message digest is computed from the result of encoding the /// text in a coding system, not directly from the internal Emacs form of /// the text. The optional fourth argument CODING-SYSTEM specifies which /// coding system to encode the text with. It should be the same coding /// system that you used or will use when actually writing the text into a /// file. /// /// If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If /// OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding /// system would be chosen by default for writing this text into a file. /// /// If OBJECT is a string, the most preferred coding system (see the /// command `prefer-coding-system') is used. /// /// If NOERROR is non-nil, silently assume the `raw-text' coding if the /// guesswork fails. Normally, an error is signaled in such case. #[lisp_fn(min = "1")]
object: LispObject, start: LispObject, end: LispObject, coding_system: LispObject, noerror: LispObject, ) -> LispObject { _secure_hash( HashAlg::MD5, object, start, end, coding_system, noerror, Qnil, ) } /// Return the secure hash of OBJECT, a buffer or string. /// ALGORITHM is a symbol specifying the hash to use: /// md5, sha1, sha224, sha256, sha384 or sha512. /// /// The two optional arguments START and END are positions specifying for /// which part of OBJECT to compute the hash. If nil or omitted, uses the /// whole OBJECT. /// /// The full list of algorithms can be obtained with `secure-hash-algorithms'. /// /// If BINARY is non-nil, returns a string in binary form. #[lisp_fn(min = "2")] pub fn secure_hash( algorithm: LispSymbolRef, object: LispObject, start: LispObject, end: LispObject, binary: LispObject, ) -> LispObject { _secure_hash(hash_alg(algorithm), object, start, end, Qnil, Qnil, binary) } fn _secure_hash( algorithm: HashAlg, object: LispObject, start: LispObject, end: LispObject, coding_system: LispObject, noerror: LispObject, binary: LispObject, ) -> LispObject { type HashFn = fn(&[u8], &mut [u8]); let spec = list!(object, start, end, coding_system, noerror); let mut start_byte: ptrdiff_t = 0; let mut end_byte: ptrdiff_t = 0; let input = unsafe { extract_data_from_object(spec, &mut start_byte, &mut end_byte) }; if input.is_null() { error!("secure_hash: failed to extract data from object, aborting!"); } let input_slice = unsafe { slice::from_raw_parts( input.offset(start_byte) as *mut u8, (end_byte - start_byte) as usize, ) }; let (digest_size, hash_func) = match algorithm { HashAlg::MD5 => (MD5_DIGEST_LEN, md5_buffer as HashFn), HashAlg::SHA1 => (SHA1_DIGEST_LEN, sha1_buffer as HashFn), HashAlg::SHA224 => (SHA224_DIGEST_LEN, sha224_buffer as HashFn), HashAlg::SHA256 => (SHA256_DIGEST_LEN, sha256_buffer as HashFn), HashAlg::SHA384 => (SHA384_DIGEST_LEN, sha384_buffer as HashFn), HashAlg::SHA512 => (SHA512_DIGEST_LEN, sha512_buffer as HashFn), }; let buffer_size = if binary.is_nil() { (digest_size * 2) as EmacsInt } else { digest_size as EmacsInt }; let digest = unsafe { make_uninit_string(buffer_size as EmacsInt) }; let mut digest_str: LispStringRef = digest.into(); hash_func(input_slice, digest_str.as_mut_slice()); if binary.is_nil() { hexify_digest_string(digest_str.as_mut_slice(), digest_size); } digest } /// To avoid a copy, buffer is both the source and the destination of /// this transformation. Buffer must contain len bytes of data and /// 2*len bytes of space for the final hex string. fn hexify_digest_string(buffer: &mut [u8], len: usize) { static hexdigit: [u8; 16] = *b"0123456789abcdef"; debug_assert_eq!( buffer.len(), 2 * len, "buffer must be long enough to hold 2*len hex digits" ); for i in (0..len).rev() { let v = buffer[i]; buffer[2 * i] = hexdigit[(v >> 4) as usize]; buffer[2 * i + 1] = hexdigit[(v & 0xf) as usize]; } } // For the following hash functions, the caller must ensure that the // destination buffer is at least long enough to hold the // digest. Additionally, the caller may have been asked to return a // hex string, in which case dest_buf will be twice as long as the // digest. fn md5_buffer(buffer: &[u8], dest_buf: &mut [u8]) { let output = md5_crate::compute(buffer); dest_buf[..output.len()].copy_from_slice(&*output) } fn sha1_buffer(buffer: &[u8], dest_buf: &mut [u8]) { let mut hasher = sha1::Sha1::new(); hasher.update(buffer); let output = hasher.digest().bytes(); dest_buf[..output.len()].copy_from_slice(&output) } /// Given an instance of `Digest`, and `buffer` write its hash to `dest_buf`. fn sha2_hash_buffer(hasher: impl Digest, buffer: &[u8], dest_buf: &mut [u8]) { let mut hasher = hasher; hasher.input(buffer); let output = hasher.result(); dest_buf[..output.len()].copy_from_slice(&output) } fn sha224_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha224::new(), buffer, dest_buf); } fn sha256_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha256::new(), buffer, dest_buf); } fn sha384_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha384::new(), buffer, dest_buf); } fn sha512_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha512::new(), buffer, dest_buf); } /// Return a hash of the contents of BUFFER-OR-NAME. /// This hash is performed on the raw internal format of the buffer, /// disregarding any coding systems. If nil, use the current buffer. #[lisp_fn(min = "0")] pub fn buffer_hash(buffer_or_name: Option<LispBufferOrName>) -> LispObject { let b = buffer_or_name.map_or_else(ThreadState::current_buffer_unchecked, LispBufferRef::from); let mut ctx = sha1::Sha1::new(); ctx.update(unsafe { slice::from_raw_parts(b.beg_addr(), (b.gpt_byte() - b.beg_byte()) as usize) }); if b.gpt_byte() < b.z_byte() { ctx.update(unsafe { slice::from_raw_parts( b.gap_end_addr(), b.z_addr() as usize - b.gap_end_addr() as usize, ) }); } let formatted = ctx.digest().to_string(); let digest = unsafe { make_uninit_string(formatted.len() as EmacsInt) }; digest .as_string() .unwrap() .as_mut_slice() .copy_from_slice(formatted.as_bytes()); digest } include!(concat!(env!("OUT_DIR"), "/crypto_exports.rs"));
pub fn md5(
random_line_split
mod.rs
use std; use std::slice; use libc::ptrdiff_t; use md5 as md5_crate; use sha1; use sha2::{Digest, Sha224, Sha256, Sha384, Sha512}; use remacs_macros::lisp_fn; use crate::{ buffers::{LispBufferOrName, LispBufferRef}, lisp::LispObject, multibyte::LispStringRef, remacs_sys::EmacsInt, remacs_sys::{extract_data_from_object, make_uninit_string}, remacs_sys::{Qmd5, Qnil, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512}, symbols::{symbol_name, LispSymbolRef}, threads::ThreadState, }; #[derive(Clone, Copy)] enum HashAlg { MD5, SHA1, SHA224, SHA256, SHA384, SHA512, } static MD5_DIGEST_LEN: usize = 16; static SHA1_DIGEST_LEN: usize = 20; static SHA224_DIGEST_LEN: usize = 224 / 8; static SHA256_DIGEST_LEN: usize = 256 / 8; static SHA384_DIGEST_LEN: usize = 384 / 8; static SHA512_DIGEST_LEN: usize = 512 / 8; fn hash_alg(algorithm: LispSymbolRef) -> HashAlg { match LispObject::from(algorithm) { Qmd5 => HashAlg::MD5, Qsha1 => HashAlg::SHA1, Qsha224 => HashAlg::SHA224, Qsha256 => HashAlg::SHA256, Qsha384 => HashAlg::SHA384, Qsha512 => HashAlg::SHA512, _ => { let name: LispStringRef = symbol_name(algorithm).into(); error!("Invalid algorithm arg: {:?}\0", &name.as_slice()); } } } /// Return MD5 message digest of OBJECT, a buffer or string. /// /// A message digest is a cryptographic checksum of a document, and the /// algorithm to calculate it is defined in RFC 1321. /// /// The two optional arguments START and END are character positions /// specifying for which part of OBJECT the message digest should be /// computed. If nil or omitted, the digest is computed for the whole /// OBJECT. /// /// The MD5 message digest is computed from the result of encoding the /// text in a coding system, not directly from the internal Emacs form of /// the text. The optional fourth argument CODING-SYSTEM specifies which /// coding system to encode the text with. It should be the same coding /// system that you used or will use when actually writing the text into a /// file. /// /// If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If /// OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding /// system would be chosen by default for writing this text into a file. /// /// If OBJECT is a string, the most preferred coding system (see the /// command `prefer-coding-system') is used. /// /// If NOERROR is non-nil, silently assume the `raw-text' coding if the /// guesswork fails. Normally, an error is signaled in such case. #[lisp_fn(min = "1")] pub fn md5( object: LispObject, start: LispObject, end: LispObject, coding_system: LispObject, noerror: LispObject, ) -> LispObject { _secure_hash( HashAlg::MD5, object, start, end, coding_system, noerror, Qnil, ) } /// Return the secure hash of OBJECT, a buffer or string. /// ALGORITHM is a symbol specifying the hash to use: /// md5, sha1, sha224, sha256, sha384 or sha512. /// /// The two optional arguments START and END are positions specifying for /// which part of OBJECT to compute the hash. If nil or omitted, uses the /// whole OBJECT. /// /// The full list of algorithms can be obtained with `secure-hash-algorithms'. /// /// If BINARY is non-nil, returns a string in binary form. #[lisp_fn(min = "2")] pub fn secure_hash( algorithm: LispSymbolRef, object: LispObject, start: LispObject, end: LispObject, binary: LispObject, ) -> LispObject { _secure_hash(hash_alg(algorithm), object, start, end, Qnil, Qnil, binary) } fn
( algorithm: HashAlg, object: LispObject, start: LispObject, end: LispObject, coding_system: LispObject, noerror: LispObject, binary: LispObject, ) -> LispObject { type HashFn = fn(&[u8], &mut [u8]); let spec = list!(object, start, end, coding_system, noerror); let mut start_byte: ptrdiff_t = 0; let mut end_byte: ptrdiff_t = 0; let input = unsafe { extract_data_from_object(spec, &mut start_byte, &mut end_byte) }; if input.is_null() { error!("secure_hash: failed to extract data from object, aborting!"); } let input_slice = unsafe { slice::from_raw_parts( input.offset(start_byte) as *mut u8, (end_byte - start_byte) as usize, ) }; let (digest_size, hash_func) = match algorithm { HashAlg::MD5 => (MD5_DIGEST_LEN, md5_buffer as HashFn), HashAlg::SHA1 => (SHA1_DIGEST_LEN, sha1_buffer as HashFn), HashAlg::SHA224 => (SHA224_DIGEST_LEN, sha224_buffer as HashFn), HashAlg::SHA256 => (SHA256_DIGEST_LEN, sha256_buffer as HashFn), HashAlg::SHA384 => (SHA384_DIGEST_LEN, sha384_buffer as HashFn), HashAlg::SHA512 => (SHA512_DIGEST_LEN, sha512_buffer as HashFn), }; let buffer_size = if binary.is_nil() { (digest_size * 2) as EmacsInt } else { digest_size as EmacsInt }; let digest = unsafe { make_uninit_string(buffer_size as EmacsInt) }; let mut digest_str: LispStringRef = digest.into(); hash_func(input_slice, digest_str.as_mut_slice()); if binary.is_nil() { hexify_digest_string(digest_str.as_mut_slice(), digest_size); } digest } /// To avoid a copy, buffer is both the source and the destination of /// this transformation. Buffer must contain len bytes of data and /// 2*len bytes of space for the final hex string. fn hexify_digest_string(buffer: &mut [u8], len: usize) { static hexdigit: [u8; 16] = *b"0123456789abcdef"; debug_assert_eq!( buffer.len(), 2 * len, "buffer must be long enough to hold 2*len hex digits" ); for i in (0..len).rev() { let v = buffer[i]; buffer[2 * i] = hexdigit[(v >> 4) as usize]; buffer[2 * i + 1] = hexdigit[(v & 0xf) as usize]; } } // For the following hash functions, the caller must ensure that the // destination buffer is at least long enough to hold the // digest. Additionally, the caller may have been asked to return a // hex string, in which case dest_buf will be twice as long as the // digest. fn md5_buffer(buffer: &[u8], dest_buf: &mut [u8]) { let output = md5_crate::compute(buffer); dest_buf[..output.len()].copy_from_slice(&*output) } fn sha1_buffer(buffer: &[u8], dest_buf: &mut [u8]) { let mut hasher = sha1::Sha1::new(); hasher.update(buffer); let output = hasher.digest().bytes(); dest_buf[..output.len()].copy_from_slice(&output) } /// Given an instance of `Digest`, and `buffer` write its hash to `dest_buf`. fn sha2_hash_buffer(hasher: impl Digest, buffer: &[u8], dest_buf: &mut [u8]) { let mut hasher = hasher; hasher.input(buffer); let output = hasher.result(); dest_buf[..output.len()].copy_from_slice(&output) } fn sha224_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha224::new(), buffer, dest_buf); } fn sha256_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha256::new(), buffer, dest_buf); } fn sha384_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha384::new(), buffer, dest_buf); } fn sha512_buffer(buffer: &[u8], dest_buf: &mut [u8]) { sha2_hash_buffer(Sha512::new(), buffer, dest_buf); } /// Return a hash of the contents of BUFFER-OR-NAME. /// This hash is performed on the raw internal format of the buffer, /// disregarding any coding systems. If nil, use the current buffer. #[lisp_fn(min = "0")] pub fn buffer_hash(buffer_or_name: Option<LispBufferOrName>) -> LispObject { let b = buffer_or_name.map_or_else(ThreadState::current_buffer_unchecked, LispBufferRef::from); let mut ctx = sha1::Sha1::new(); ctx.update(unsafe { slice::from_raw_parts(b.beg_addr(), (b.gpt_byte() - b.beg_byte()) as usize) }); if b.gpt_byte() < b.z_byte() { ctx.update(unsafe { slice::from_raw_parts( b.gap_end_addr(), b.z_addr() as usize - b.gap_end_addr() as usize, ) }); } let formatted = ctx.digest().to_string(); let digest = unsafe { make_uninit_string(formatted.len() as EmacsInt) }; digest .as_string() .unwrap() .as_mut_slice() .copy_from_slice(formatted.as_bytes()); digest } include!(concat!(env!("OUT_DIR"), "/crypto_exports.rs"));
_secure_hash
identifier_name
implementation.rs
use time::{at_utc, Tm, Timespec}; use json::{FromJsonnable, ToJsonnable}; use serde::de::{Error, Type}; use serde_json::value::Value; use serde_json::error::Error as JsonError; use serde_json::builder::ObjectBuilder; impl FromJsonnable for Tm { // Deserialize via Timespec fn from_json(json: Value) -> Result<Self, JsonError> { match json { Value::Object(map) => { let sec = match map.get("sec") { Some(sec) => match sec { &Value::I64(sec) => sec, &Value::U64(sec) => sec as i64, // The types get weird here _ => return Err(JsonError::invalid_type(Type::I64)), }, None => return Err(JsonError::missing_field("Missing \"sec\"")), }; let nsec = match map.get("nsec") { Some(nsec) => match nsec { &Value::I64(nsec) => nsec as i32, &Value::U64(nsec) => nsec as i32, _ => return Err(JsonError::invalid_type(Type::I32)), }, None => return Err(JsonError::missing_field("Missing \"nsec\"")), }; Ok(at_utc(Timespec::new(sec, nsec))) }, _ => Err(JsonError::invalid_type(Type::Struct)), } } } impl ToJsonnable for Tm { // Serialize via Timespec fn to_json(&self) -> Value { let spec = self.to_timespec(); ObjectBuilder::new().insert("sec", &spec.sec) .insert("nsec", &spec.nsec) .build() } } impl<T: FromJsonnable> FromJsonnable for Vec<T> { fn from_json(json: Value) -> Result<Self, JsonError> { match json { Value::Array(arr) => { let mut elems: Vec<T> = Vec::with_capacity(arr.len()); for elem in arr { match T::from_json(elem) { Ok(elem) => elems.push(elem), Err(e) => return Err(e), } } Ok(elems) }, _ => Err(JsonError::invalid_type(Type::Seq)), } } } impl<T: ToJsonnable> ToJsonnable for Vec<T> { fn to_json(&self) -> Value
} macro_rules! primitive_to_json { ($t:ty, $v:ident, $d:ty) => { impl ToJsonnable for $t { fn to_json(&self) -> Value { Value::$v(self.clone() as $d) } } }; } macro_rules! primitive_from_json { ($t:ty, $expected:ident, $($v:ident)+) => { impl FromJsonnable for $t { fn from_json(json: Value) -> Result<Self, JsonError> { match json { $( Value::$v(value) => Ok(value as $t), )+ _ => Err(JsonError::invalid_type(Type::$expected)), } } } }; } primitive_to_json!(i8, I64, i64); primitive_to_json!(i16, I64, i64); primitive_to_json!(i32, I64, i64); primitive_to_json!(i64, I64, i64); primitive_to_json!(u8, U64, u64); primitive_to_json!(u16, U64, u64); primitive_to_json!(u32, U64, u64); primitive_to_json!(u64, U64, u64); primitive_to_json!(f32, F64, f64); primitive_to_json!(f64, F64, f64); primitive_from_json!(i8, I64, I64 U64); // Non-signed numbers are interpreted as unsigned primitive_from_json!(i16, I64, I64 U64); primitive_from_json!(i32, I64, I64 U64); primitive_from_json!(i64, I64, I64 U64); primitive_from_json!(u8, U64, U64); primitive_from_json!(u16, U64, U64); primitive_from_json!(u32, U64, U64); primitive_from_json!(u64, U64, U64); primitive_from_json!(f32, F64, F64); primitive_from_json!(f64, F64, F64);
{ Value::Array(self.iter().map(|ref elem| elem.to_json()).collect()) }
identifier_body
implementation.rs
use time::{at_utc, Tm, Timespec}; use json::{FromJsonnable, ToJsonnable}; use serde::de::{Error, Type}; use serde_json::value::Value; use serde_json::error::Error as JsonError; use serde_json::builder::ObjectBuilder; impl FromJsonnable for Tm { // Deserialize via Timespec fn from_json(json: Value) -> Result<Self, JsonError> { match json { Value::Object(map) => { let sec = match map.get("sec") { Some(sec) => match sec { &Value::I64(sec) => sec, &Value::U64(sec) => sec as i64, // The types get weird here _ => return Err(JsonError::invalid_type(Type::I64)), }, None => return Err(JsonError::missing_field("Missing \"sec\"")), }; let nsec = match map.get("nsec") { Some(nsec) => match nsec { &Value::I64(nsec) => nsec as i32, &Value::U64(nsec) => nsec as i32, _ => return Err(JsonError::invalid_type(Type::I32)), }, None => return Err(JsonError::missing_field("Missing \"nsec\"")), }; Ok(at_utc(Timespec::new(sec, nsec))) }, _ => Err(JsonError::invalid_type(Type::Struct)), } } } impl ToJsonnable for Tm { // Serialize via Timespec fn to_json(&self) -> Value { let spec = self.to_timespec(); ObjectBuilder::new().insert("sec", &spec.sec) .insert("nsec", &spec.nsec) .build() } } impl<T: FromJsonnable> FromJsonnable for Vec<T> { fn from_json(json: Value) -> Result<Self, JsonError> { match json { Value::Array(arr) => { let mut elems: Vec<T> = Vec::with_capacity(arr.len()); for elem in arr { match T::from_json(elem) { Ok(elem) => elems.push(elem), Err(e) => return Err(e), } } Ok(elems) }, _ => Err(JsonError::invalid_type(Type::Seq)), } } } impl<T: ToJsonnable> ToJsonnable for Vec<T> { fn to_json(&self) -> Value { Value::Array(self.iter().map(|ref elem| elem.to_json()).collect()) } } macro_rules! primitive_to_json { ($t:ty, $v:ident, $d:ty) => { impl ToJsonnable for $t { fn to_json(&self) -> Value { Value::$v(self.clone() as $d) } } }; } macro_rules! primitive_from_json { ($t:ty, $expected:ident, $($v:ident)+) => { impl FromJsonnable for $t { fn from_json(json: Value) -> Result<Self, JsonError> { match json { $( Value::$v(value) => Ok(value as $t), )+ _ => Err(JsonError::invalid_type(Type::$expected)), } }
primitive_to_json!(i16, I64, i64); primitive_to_json!(i32, I64, i64); primitive_to_json!(i64, I64, i64); primitive_to_json!(u8, U64, u64); primitive_to_json!(u16, U64, u64); primitive_to_json!(u32, U64, u64); primitive_to_json!(u64, U64, u64); primitive_to_json!(f32, F64, f64); primitive_to_json!(f64, F64, f64); primitive_from_json!(i8, I64, I64 U64); // Non-signed numbers are interpreted as unsigned primitive_from_json!(i16, I64, I64 U64); primitive_from_json!(i32, I64, I64 U64); primitive_from_json!(i64, I64, I64 U64); primitive_from_json!(u8, U64, U64); primitive_from_json!(u16, U64, U64); primitive_from_json!(u32, U64, U64); primitive_from_json!(u64, U64, U64); primitive_from_json!(f32, F64, F64); primitive_from_json!(f64, F64, F64);
} }; } primitive_to_json!(i8, I64, i64);
random_line_split
implementation.rs
use time::{at_utc, Tm, Timespec}; use json::{FromJsonnable, ToJsonnable}; use serde::de::{Error, Type}; use serde_json::value::Value; use serde_json::error::Error as JsonError; use serde_json::builder::ObjectBuilder; impl FromJsonnable for Tm { // Deserialize via Timespec fn from_json(json: Value) -> Result<Self, JsonError> { match json { Value::Object(map) => { let sec = match map.get("sec") { Some(sec) => match sec { &Value::I64(sec) => sec, &Value::U64(sec) => sec as i64, // The types get weird here _ => return Err(JsonError::invalid_type(Type::I64)), }, None => return Err(JsonError::missing_field("Missing \"sec\"")), }; let nsec = match map.get("nsec") { Some(nsec) => match nsec { &Value::I64(nsec) => nsec as i32, &Value::U64(nsec) => nsec as i32, _ => return Err(JsonError::invalid_type(Type::I32)), }, None => return Err(JsonError::missing_field("Missing \"nsec\"")), }; Ok(at_utc(Timespec::new(sec, nsec))) }, _ => Err(JsonError::invalid_type(Type::Struct)), } } } impl ToJsonnable for Tm { // Serialize via Timespec fn
(&self) -> Value { let spec = self.to_timespec(); ObjectBuilder::new().insert("sec", &spec.sec) .insert("nsec", &spec.nsec) .build() } } impl<T: FromJsonnable> FromJsonnable for Vec<T> { fn from_json(json: Value) -> Result<Self, JsonError> { match json { Value::Array(arr) => { let mut elems: Vec<T> = Vec::with_capacity(arr.len()); for elem in arr { match T::from_json(elem) { Ok(elem) => elems.push(elem), Err(e) => return Err(e), } } Ok(elems) }, _ => Err(JsonError::invalid_type(Type::Seq)), } } } impl<T: ToJsonnable> ToJsonnable for Vec<T> { fn to_json(&self) -> Value { Value::Array(self.iter().map(|ref elem| elem.to_json()).collect()) } } macro_rules! primitive_to_json { ($t:ty, $v:ident, $d:ty) => { impl ToJsonnable for $t { fn to_json(&self) -> Value { Value::$v(self.clone() as $d) } } }; } macro_rules! primitive_from_json { ($t:ty, $expected:ident, $($v:ident)+) => { impl FromJsonnable for $t { fn from_json(json: Value) -> Result<Self, JsonError> { match json { $( Value::$v(value) => Ok(value as $t), )+ _ => Err(JsonError::invalid_type(Type::$expected)), } } } }; } primitive_to_json!(i8, I64, i64); primitive_to_json!(i16, I64, i64); primitive_to_json!(i32, I64, i64); primitive_to_json!(i64, I64, i64); primitive_to_json!(u8, U64, u64); primitive_to_json!(u16, U64, u64); primitive_to_json!(u32, U64, u64); primitive_to_json!(u64, U64, u64); primitive_to_json!(f32, F64, f64); primitive_to_json!(f64, F64, f64); primitive_from_json!(i8, I64, I64 U64); // Non-signed numbers are interpreted as unsigned primitive_from_json!(i16, I64, I64 U64); primitive_from_json!(i32, I64, I64 U64); primitive_from_json!(i64, I64, I64 U64); primitive_from_json!(u8, U64, U64); primitive_from_json!(u16, U64, U64); primitive_from_json!(u32, U64, U64); primitive_from_json!(u64, U64, U64); primitive_from_json!(f32, F64, F64); primitive_from_json!(f64, F64, F64);
to_json
identifier_name
media_queries.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 std::ascii::AsciiExt; use cssparser::{Token, Parser, Delimiter}; use geom::size::{Size2D, TypedSize2D}; use properties::longhands; use util::geometry::{Au, ViewportPx}; use values::specified; #[derive(Debug, PartialEq)] pub struct MediaQueryList { pub media_queries: Vec<MediaQuery> } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum Range<T> { Min(T), Max(T), //Eq(T), // FIXME: Implement parsing support for equality then re-enable this. } impl Range<specified::Length> { fn to_computed_range(&self, viewport_size: Size2D<Au>) -> Range<Au> { let compute_width = |width| { match width { &specified::Length::Absolute(value) => value, &specified::Length::FontRelative(value) => { // http://dev.w3.org/csswg/mediaqueries3/#units // em units are relative to the initial font-size. let initial_font_size = longhands::font_size::get_initial_value(); value.to_computed_value(initial_font_size, initial_font_size) } &specified::Length::ViewportPercentage(value) => value.to_computed_value(viewport_size), _ => unreachable!() } }; match *self { Range::Min(ref width) => Range::Min(compute_width(width)), Range::Max(ref width) => Range::Max(compute_width(width)), //Range::Eq(ref width) => Range::Eq(compute_width(width)) } } } impl<T: Ord> Range<T> { fn evaluate(&self, value: T) -> bool { match *self { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, //Range::Eq(ref width) => { value == *width }, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media1 #[derive(PartialEq, Copy, Clone, Debug)] pub enum Expression { /// http://dev.w3.org/csswg/mediaqueries-3/#width Width(Range<specified::Length>), } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum Qualifier { Only, Not, } #[derive(Debug, PartialEq)] pub struct MediaQuery { pub qualifier: Option<Qualifier>, pub media_type: MediaQueryType, pub expressions: Vec<Expression>, } impl MediaQuery { pub fn new(qualifier: Option<Qualifier>, media_type: MediaQueryType, expressions: Vec<Expression>) -> MediaQuery { MediaQuery { qualifier: qualifier, media_type: media_type, expressions: expressions, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum
{ All, // Always true MediaType(MediaType), } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum MediaType { Screen, Print, Unknown, } #[derive(Debug)] pub struct Device { pub media_type: MediaType, pub viewport_size: TypedSize2D<ViewportPx, f32>, } impl Device { pub fn new(media_type: MediaType, viewport_size: TypedSize2D<ViewportPx, f32>) -> Device { Device { media_type: media_type, viewport_size: viewport_size, } } } impl Expression { fn parse(input: &mut Parser) -> Result<Expression, ()> { try!(input.expect_parenthesis_block()); input.parse_nested_block(|input| { let name = try!(input.expect_ident()); try!(input.expect_colon()); // TODO: Handle other media features match_ignore_ascii_case! { name, "min-width" => { Ok(Expression::Width(Range::Min(try!(specified::Length::parse_non_negative(input))))) }, "max-width" => { Ok(Expression::Width(Range::Max(try!(specified::Length::parse_non_negative(input))))) } _ => Err(()) } }) } } impl MediaQuery { fn parse(input: &mut Parser) -> Result<MediaQuery, ()> { let mut expressions = vec![]; let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() { Some(Qualifier::Only) } else if input.try(|input| input.expect_ident_matching("not")).is_ok() { Some(Qualifier::Not) } else { None }; let media_type; if let Ok(ident) = input.try(|input| input.expect_ident()) { media_type = match_ignore_ascii_case! { ident, "screen" => MediaQueryType::MediaType(MediaType::Screen), "print" => MediaQueryType::MediaType(MediaType::Print), "all" => MediaQueryType::All _ => MediaQueryType::MediaType(MediaType::Unknown) } } else { // Media type is only optional if qualifier is not specified. if qualifier.is_some() { return Err(()) } media_type = MediaQueryType::All; // Without a media type, require at least one expression expressions.push(try!(Expression::parse(input))); } // Parse any subsequent expressions loop { if input.try(|input| input.expect_ident_matching("and")).is_err() { return Ok(MediaQuery::new(qualifier, media_type, expressions)) } expressions.push(try!(Expression::parse(input))) } } } pub fn parse_media_query_list(input: &mut Parser) -> MediaQueryList { let queries = if input.is_exhausted() { vec![MediaQuery::new(None, MediaQueryType::All, vec!())] } else { let mut media_queries = vec![]; loop { media_queries.push( input.parse_until_before(Delimiter::Comma, MediaQuery::parse) .unwrap_or(MediaQuery::new(Some(Qualifier::Not), MediaQueryType::All, vec!()))); match input.next() { Ok(Token::Comma) => continue, Ok(_) => unreachable!(), Err(()) => break, } } media_queries }; MediaQueryList { media_queries: queries } } impl MediaQueryList { pub fn evaluate(&self, device: &Device) -> bool { let viewport_size = Size2D(Au::from_frac32_px(device.viewport_size.width.get()), Au::from_frac32_px(device.viewport_size.height.get())); // Check if any queries match (OR condition) self.media_queries.iter().any(|mq| { // Check if media matches. Unknown media never matches. let media_match = match mq.media_type { MediaQueryType::MediaType(MediaType::Unknown) => false, MediaQueryType::MediaType(media_type) => media_type == device.media_type, MediaQueryType::All => true, }; // Check if all conditions match (AND condition) let query_match = media_match && mq.expressions.iter().all(|expression| { match expression { &Expression::Width(value) => value.to_computed_range(viewport_size).evaluate(viewport_size.width), } }); // Apply the logical NOT qualifier to the result match mq.qualifier { Some(Qualifier::Not) =>!query_match, _ => query_match, } }) } }
MediaQueryType
identifier_name
media_queries.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 std::ascii::AsciiExt; use cssparser::{Token, Parser, Delimiter}; use geom::size::{Size2D, TypedSize2D}; use properties::longhands; use util::geometry::{Au, ViewportPx}; use values::specified; #[derive(Debug, PartialEq)] pub struct MediaQueryList { pub media_queries: Vec<MediaQuery> } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum Range<T> { Min(T), Max(T), //Eq(T), // FIXME: Implement parsing support for equality then re-enable this. } impl Range<specified::Length> { fn to_computed_range(&self, viewport_size: Size2D<Au>) -> Range<Au> { let compute_width = |width| { match width { &specified::Length::Absolute(value) => value, &specified::Length::FontRelative(value) => { // http://dev.w3.org/csswg/mediaqueries3/#units // em units are relative to the initial font-size. let initial_font_size = longhands::font_size::get_initial_value(); value.to_computed_value(initial_font_size, initial_font_size) } &specified::Length::ViewportPercentage(value) => value.to_computed_value(viewport_size), _ => unreachable!() } }; match *self { Range::Min(ref width) => Range::Min(compute_width(width)), Range::Max(ref width) => Range::Max(compute_width(width)), //Range::Eq(ref width) => Range::Eq(compute_width(width)) } } } impl<T: Ord> Range<T> { fn evaluate(&self, value: T) -> bool { match *self { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, //Range::Eq(ref width) => { value == *width }, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media1 #[derive(PartialEq, Copy, Clone, Debug)] pub enum Expression { /// http://dev.w3.org/csswg/mediaqueries-3/#width Width(Range<specified::Length>), } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum Qualifier { Only, Not, } #[derive(Debug, PartialEq)] pub struct MediaQuery { pub qualifier: Option<Qualifier>, pub media_type: MediaQueryType, pub expressions: Vec<Expression>, } impl MediaQuery { pub fn new(qualifier: Option<Qualifier>, media_type: MediaQueryType, expressions: Vec<Expression>) -> MediaQuery { MediaQuery { qualifier: qualifier, media_type: media_type, expressions: expressions, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum MediaQueryType { All, // Always true MediaType(MediaType), } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum MediaType { Screen, Print, Unknown, } #[derive(Debug)] pub struct Device { pub media_type: MediaType, pub viewport_size: TypedSize2D<ViewportPx, f32>, } impl Device { pub fn new(media_type: MediaType, viewport_size: TypedSize2D<ViewportPx, f32>) -> Device { Device { media_type: media_type, viewport_size: viewport_size, } } } impl Expression { fn parse(input: &mut Parser) -> Result<Expression, ()> { try!(input.expect_parenthesis_block()); input.parse_nested_block(|input| { let name = try!(input.expect_ident()); try!(input.expect_colon()); // TODO: Handle other media features match_ignore_ascii_case! { name,
"max-width" => { Ok(Expression::Width(Range::Max(try!(specified::Length::parse_non_negative(input))))) } _ => Err(()) } }) } } impl MediaQuery { fn parse(input: &mut Parser) -> Result<MediaQuery, ()> { let mut expressions = vec![]; let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() { Some(Qualifier::Only) } else if input.try(|input| input.expect_ident_matching("not")).is_ok() { Some(Qualifier::Not) } else { None }; let media_type; if let Ok(ident) = input.try(|input| input.expect_ident()) { media_type = match_ignore_ascii_case! { ident, "screen" => MediaQueryType::MediaType(MediaType::Screen), "print" => MediaQueryType::MediaType(MediaType::Print), "all" => MediaQueryType::All _ => MediaQueryType::MediaType(MediaType::Unknown) } } else { // Media type is only optional if qualifier is not specified. if qualifier.is_some() { return Err(()) } media_type = MediaQueryType::All; // Without a media type, require at least one expression expressions.push(try!(Expression::parse(input))); } // Parse any subsequent expressions loop { if input.try(|input| input.expect_ident_matching("and")).is_err() { return Ok(MediaQuery::new(qualifier, media_type, expressions)) } expressions.push(try!(Expression::parse(input))) } } } pub fn parse_media_query_list(input: &mut Parser) -> MediaQueryList { let queries = if input.is_exhausted() { vec![MediaQuery::new(None, MediaQueryType::All, vec!())] } else { let mut media_queries = vec![]; loop { media_queries.push( input.parse_until_before(Delimiter::Comma, MediaQuery::parse) .unwrap_or(MediaQuery::new(Some(Qualifier::Not), MediaQueryType::All, vec!()))); match input.next() { Ok(Token::Comma) => continue, Ok(_) => unreachable!(), Err(()) => break, } } media_queries }; MediaQueryList { media_queries: queries } } impl MediaQueryList { pub fn evaluate(&self, device: &Device) -> bool { let viewport_size = Size2D(Au::from_frac32_px(device.viewport_size.width.get()), Au::from_frac32_px(device.viewport_size.height.get())); // Check if any queries match (OR condition) self.media_queries.iter().any(|mq| { // Check if media matches. Unknown media never matches. let media_match = match mq.media_type { MediaQueryType::MediaType(MediaType::Unknown) => false, MediaQueryType::MediaType(media_type) => media_type == device.media_type, MediaQueryType::All => true, }; // Check if all conditions match (AND condition) let query_match = media_match && mq.expressions.iter().all(|expression| { match expression { &Expression::Width(value) => value.to_computed_range(viewport_size).evaluate(viewport_size.width), } }); // Apply the logical NOT qualifier to the result match mq.qualifier { Some(Qualifier::Not) =>!query_match, _ => query_match, } }) } }
"min-width" => { Ok(Expression::Width(Range::Min(try!(specified::Length::parse_non_negative(input))))) },
random_line_split
media_queries.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 std::ascii::AsciiExt; use cssparser::{Token, Parser, Delimiter}; use geom::size::{Size2D, TypedSize2D}; use properties::longhands; use util::geometry::{Au, ViewportPx}; use values::specified; #[derive(Debug, PartialEq)] pub struct MediaQueryList { pub media_queries: Vec<MediaQuery> } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum Range<T> { Min(T), Max(T), //Eq(T), // FIXME: Implement parsing support for equality then re-enable this. } impl Range<specified::Length> { fn to_computed_range(&self, viewport_size: Size2D<Au>) -> Range<Au>
} } } impl<T: Ord> Range<T> { fn evaluate(&self, value: T) -> bool { match *self { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, //Range::Eq(ref width) => { value == *width }, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media1 #[derive(PartialEq, Copy, Clone, Debug)] pub enum Expression { /// http://dev.w3.org/csswg/mediaqueries-3/#width Width(Range<specified::Length>), } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum Qualifier { Only, Not, } #[derive(Debug, PartialEq)] pub struct MediaQuery { pub qualifier: Option<Qualifier>, pub media_type: MediaQueryType, pub expressions: Vec<Expression>, } impl MediaQuery { pub fn new(qualifier: Option<Qualifier>, media_type: MediaQueryType, expressions: Vec<Expression>) -> MediaQuery { MediaQuery { qualifier: qualifier, media_type: media_type, expressions: expressions, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum MediaQueryType { All, // Always true MediaType(MediaType), } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum MediaType { Screen, Print, Unknown, } #[derive(Debug)] pub struct Device { pub media_type: MediaType, pub viewport_size: TypedSize2D<ViewportPx, f32>, } impl Device { pub fn new(media_type: MediaType, viewport_size: TypedSize2D<ViewportPx, f32>) -> Device { Device { media_type: media_type, viewport_size: viewport_size, } } } impl Expression { fn parse(input: &mut Parser) -> Result<Expression, ()> { try!(input.expect_parenthesis_block()); input.parse_nested_block(|input| { let name = try!(input.expect_ident()); try!(input.expect_colon()); // TODO: Handle other media features match_ignore_ascii_case! { name, "min-width" => { Ok(Expression::Width(Range::Min(try!(specified::Length::parse_non_negative(input))))) }, "max-width" => { Ok(Expression::Width(Range::Max(try!(specified::Length::parse_non_negative(input))))) } _ => Err(()) } }) } } impl MediaQuery { fn parse(input: &mut Parser) -> Result<MediaQuery, ()> { let mut expressions = vec![]; let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() { Some(Qualifier::Only) } else if input.try(|input| input.expect_ident_matching("not")).is_ok() { Some(Qualifier::Not) } else { None }; let media_type; if let Ok(ident) = input.try(|input| input.expect_ident()) { media_type = match_ignore_ascii_case! { ident, "screen" => MediaQueryType::MediaType(MediaType::Screen), "print" => MediaQueryType::MediaType(MediaType::Print), "all" => MediaQueryType::All _ => MediaQueryType::MediaType(MediaType::Unknown) } } else { // Media type is only optional if qualifier is not specified. if qualifier.is_some() { return Err(()) } media_type = MediaQueryType::All; // Without a media type, require at least one expression expressions.push(try!(Expression::parse(input))); } // Parse any subsequent expressions loop { if input.try(|input| input.expect_ident_matching("and")).is_err() { return Ok(MediaQuery::new(qualifier, media_type, expressions)) } expressions.push(try!(Expression::parse(input))) } } } pub fn parse_media_query_list(input: &mut Parser) -> MediaQueryList { let queries = if input.is_exhausted() { vec![MediaQuery::new(None, MediaQueryType::All, vec!())] } else { let mut media_queries = vec![]; loop { media_queries.push( input.parse_until_before(Delimiter::Comma, MediaQuery::parse) .unwrap_or(MediaQuery::new(Some(Qualifier::Not), MediaQueryType::All, vec!()))); match input.next() { Ok(Token::Comma) => continue, Ok(_) => unreachable!(), Err(()) => break, } } media_queries }; MediaQueryList { media_queries: queries } } impl MediaQueryList { pub fn evaluate(&self, device: &Device) -> bool { let viewport_size = Size2D(Au::from_frac32_px(device.viewport_size.width.get()), Au::from_frac32_px(device.viewport_size.height.get())); // Check if any queries match (OR condition) self.media_queries.iter().any(|mq| { // Check if media matches. Unknown media never matches. let media_match = match mq.media_type { MediaQueryType::MediaType(MediaType::Unknown) => false, MediaQueryType::MediaType(media_type) => media_type == device.media_type, MediaQueryType::All => true, }; // Check if all conditions match (AND condition) let query_match = media_match && mq.expressions.iter().all(|expression| { match expression { &Expression::Width(value) => value.to_computed_range(viewport_size).evaluate(viewport_size.width), } }); // Apply the logical NOT qualifier to the result match mq.qualifier { Some(Qualifier::Not) =>!query_match, _ => query_match, } }) } }
{ let compute_width = |width| { match width { &specified::Length::Absolute(value) => value, &specified::Length::FontRelative(value) => { // http://dev.w3.org/csswg/mediaqueries3/#units // em units are relative to the initial font-size. let initial_font_size = longhands::font_size::get_initial_value(); value.to_computed_value(initial_font_size, initial_font_size) } &specified::Length::ViewportPercentage(value) => value.to_computed_value(viewport_size), _ => unreachable!() } }; match *self { Range::Min(ref width) => Range::Min(compute_width(width)), Range::Max(ref width) => Range::Max(compute_width(width)), //Range::Eq(ref width) => Range::Eq(compute_width(width))
identifier_body
new.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, Config}; #[derive(Deserialize)] pub struct Options { flag_verbose: u32, flag_quiet: Option<bool>, flag_color: Option<String>, flag_bin: bool, flag_lib: bool, arg_path: String, flag_name: Option<String>, flag_vcs: Option<ops::VersionControl>, flag_frozen: bool, flag_locked: bool, #[serde(rename = "flag_Z")] flag_z: Vec<String>, } pub const USAGE: &'static str = " Create a new cargo package at <path> Usage: cargo new [options] <path> cargo new -h | --help Options: -h, --help Print this message --vcs VCS Initialize a new repository for the given version control system (git, hg, pijul, or fossil) or do not initialize any version control at all (none), overriding a global configuration. --bin Use a binary (application) template --lib Use a library template [default] --name NAME Set the resulting package name, defaults to the value of <path> -v, --verbose... Use verbose output (-vv very verbose/build.rs output) -q, --quiet No output printed to stdout --color WHEN Coloring: auto, always, never --frozen Require Cargo.lock and cache are up to date --locked Require Cargo.lock is up to date -Z FLAG... Unstable (nightly-only) flags to Cargo "; pub fn execute(options: Options, config: &mut Config) -> CliResult
config.shell().status("Created", format!("{} `{}` project", if opts_lib { "library" } else {"binary (application)"}, arg_path))?; Ok(()) }
{ debug!("executing; cmd=cargo-new; args={:?}", env::args().collect::<Vec<_>>()); config.configure(options.flag_verbose, options.flag_quiet, &options.flag_color, options.flag_frozen, options.flag_locked, &options.flag_z)?; let Options { flag_bin, flag_lib, arg_path, flag_name, flag_vcs, .. } = options; let opts = ops::NewOptions::new(flag_vcs, flag_bin, flag_lib, &arg_path, flag_name.as_ref().map(|s| s.as_ref())); let opts_lib = opts.lib; ops::new(&opts, config)?;
identifier_body
new.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, Config}; #[derive(Deserialize)] pub struct
{ flag_verbose: u32, flag_quiet: Option<bool>, flag_color: Option<String>, flag_bin: bool, flag_lib: bool, arg_path: String, flag_name: Option<String>, flag_vcs: Option<ops::VersionControl>, flag_frozen: bool, flag_locked: bool, #[serde(rename = "flag_Z")] flag_z: Vec<String>, } pub const USAGE: &'static str = " Create a new cargo package at <path> Usage: cargo new [options] <path> cargo new -h | --help Options: -h, --help Print this message --vcs VCS Initialize a new repository for the given version control system (git, hg, pijul, or fossil) or do not initialize any version control at all (none), overriding a global configuration. --bin Use a binary (application) template --lib Use a library template [default] --name NAME Set the resulting package name, defaults to the value of <path> -v, --verbose... Use verbose output (-vv very verbose/build.rs output) -q, --quiet No output printed to stdout --color WHEN Coloring: auto, always, never --frozen Require Cargo.lock and cache are up to date --locked Require Cargo.lock is up to date -Z FLAG... Unstable (nightly-only) flags to Cargo "; pub fn execute(options: Options, config: &mut Config) -> CliResult { debug!("executing; cmd=cargo-new; args={:?}", env::args().collect::<Vec<_>>()); config.configure(options.flag_verbose, options.flag_quiet, &options.flag_color, options.flag_frozen, options.flag_locked, &options.flag_z)?; let Options { flag_bin, flag_lib, arg_path, flag_name, flag_vcs,.. } = options; let opts = ops::NewOptions::new(flag_vcs, flag_bin, flag_lib, &arg_path, flag_name.as_ref().map(|s| s.as_ref())); let opts_lib = opts.lib; ops::new(&opts, config)?; config.shell().status("Created", format!("{} `{}` project", if opts_lib { "library" } else {"binary (application)"}, arg_path))?; Ok(()) }
Options
identifier_name
new.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, Config}; #[derive(Deserialize)] pub struct Options { flag_verbose: u32, flag_quiet: Option<bool>, flag_color: Option<String>, flag_bin: bool, flag_lib: bool, arg_path: String, flag_name: Option<String>, flag_vcs: Option<ops::VersionControl>, flag_frozen: bool, flag_locked: bool, #[serde(rename = "flag_Z")] flag_z: Vec<String>, } pub const USAGE: &'static str = " Create a new cargo package at <path> Usage: cargo new [options] <path> cargo new -h | --help Options: -h, --help Print this message --vcs VCS Initialize a new repository for the given version control system (git, hg, pijul, or fossil) or do not initialize any version control at all (none), overriding a global configuration.
--color WHEN Coloring: auto, always, never --frozen Require Cargo.lock and cache are up to date --locked Require Cargo.lock is up to date -Z FLAG... Unstable (nightly-only) flags to Cargo "; pub fn execute(options: Options, config: &mut Config) -> CliResult { debug!("executing; cmd=cargo-new; args={:?}", env::args().collect::<Vec<_>>()); config.configure(options.flag_verbose, options.flag_quiet, &options.flag_color, options.flag_frozen, options.flag_locked, &options.flag_z)?; let Options { flag_bin, flag_lib, arg_path, flag_name, flag_vcs,.. } = options; let opts = ops::NewOptions::new(flag_vcs, flag_bin, flag_lib, &arg_path, flag_name.as_ref().map(|s| s.as_ref())); let opts_lib = opts.lib; ops::new(&opts, config)?; config.shell().status("Created", format!("{} `{}` project", if opts_lib { "library" } else {"binary (application)"}, arg_path))?; Ok(()) }
--bin Use a binary (application) template --lib Use a library template [default] --name NAME Set the resulting package name, defaults to the value of <path> -v, --verbose ... Use verbose output (-vv very verbose/build.rs output) -q, --quiet No output printed to stdout
random_line_split
asset.rs
use std::sync::Arc; use std::borrow::Cow; use asset::{Mesh, Image}; use entity::{EntityTemplate, Entity, ComponentTemplate}; use client::render::Material; /// Holds AssetData and the path it was loaded from #[derive(Debug)] pub struct Asset { pub asset_data: AssetData, pub path: Cow<'static, str> } /// The data for the various types of asset, wrapped in Arcs for thread safe sharing #[derive(Debug)] pub enum AssetData { Mesh(Arc<Mesh>), Image(Arc<Image>), EntityTemplate(Arc<EntityTemplate>), ComponentTemplate(Arc<ComponentTemplate>), StaticEntity(Arc<Entity>), Material(Arc<Material>) } /// The various types of asset #[derive(Debug)] pub enum
{ Mesh, Image, EntityTemplate, StaticEntity, ComponentTemplate, Material } impl Asset { /// Create a new asset from its AssetData and its path pub fn new(path: Cow<'static, str>, asset_data: AssetData) -> Asset { Asset { path: path, asset_data: asset_data } } } impl AssetType { /// Attempt to infer an Asset's type from its path. Returns None if it cannot infer a type pub fn from_path(path: &str) -> Option<AssetType> { let path_parts: Vec<&str> = path.split(".").collect(); let extension = if path_parts.len() > 1 { path_parts[path_parts.len() - 1] } else { return None; }; match extension { "obj" => Some(AssetType::Mesh), "png" | "jpeg" | "jpg" => Some(AssetType::Image), _ => None } } }
AssetType
identifier_name
asset.rs
use std::sync::Arc; use std::borrow::Cow; use asset::{Mesh, Image}; use entity::{EntityTemplate, Entity, ComponentTemplate}; use client::render::Material; /// Holds AssetData and the path it was loaded from #[derive(Debug)] pub struct Asset { pub asset_data: AssetData, pub path: Cow<'static, str> } /// The data for the various types of asset, wrapped in Arcs for thread safe sharing #[derive(Debug)] pub enum AssetData { Mesh(Arc<Mesh>), Image(Arc<Image>), EntityTemplate(Arc<EntityTemplate>), ComponentTemplate(Arc<ComponentTemplate>), StaticEntity(Arc<Entity>), Material(Arc<Material>) } /// The various types of asset #[derive(Debug)] pub enum AssetType { Mesh, Image, EntityTemplate, StaticEntity, ComponentTemplate, Material } impl Asset { /// Create a new asset from its AssetData and its path pub fn new(path: Cow<'static, str>, asset_data: AssetData) -> Asset { Asset { path: path, asset_data: asset_data } } } impl AssetType { /// Attempt to infer an Asset's type from its path. Returns None if it cannot infer a type pub fn from_path(path: &str) -> Option<AssetType>
}
{ let path_parts: Vec<&str> = path.split(".").collect(); let extension = if path_parts.len() > 1 { path_parts[path_parts.len() - 1] } else { return None; }; match extension { "obj" => Some(AssetType::Mesh), "png" | "jpeg" | "jpg" => Some(AssetType::Image), _ => None } }
identifier_body
asset.rs
use std::sync::Arc;
use std::borrow::Cow; use asset::{Mesh, Image}; use entity::{EntityTemplate, Entity, ComponentTemplate}; use client::render::Material; /// Holds AssetData and the path it was loaded from #[derive(Debug)] pub struct Asset { pub asset_data: AssetData, pub path: Cow<'static, str> } /// The data for the various types of asset, wrapped in Arcs for thread safe sharing #[derive(Debug)] pub enum AssetData { Mesh(Arc<Mesh>), Image(Arc<Image>), EntityTemplate(Arc<EntityTemplate>), ComponentTemplate(Arc<ComponentTemplate>), StaticEntity(Arc<Entity>), Material(Arc<Material>) } /// The various types of asset #[derive(Debug)] pub enum AssetType { Mesh, Image, EntityTemplate, StaticEntity, ComponentTemplate, Material } impl Asset { /// Create a new asset from its AssetData and its path pub fn new(path: Cow<'static, str>, asset_data: AssetData) -> Asset { Asset { path: path, asset_data: asset_data } } } impl AssetType { /// Attempt to infer an Asset's type from its path. Returns None if it cannot infer a type pub fn from_path(path: &str) -> Option<AssetType> { let path_parts: Vec<&str> = path.split(".").collect(); let extension = if path_parts.len() > 1 { path_parts[path_parts.len() - 1] } else { return None; }; match extension { "obj" => Some(AssetType::Mesh), "png" | "jpeg" | "jpg" => Some(AssetType::Image), _ => None } } }
random_line_split
timer.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 base::prelude::*; use core::{mem}; use cty::{c_int, itimerspec, TFD_TIMER_ABSTIME}; use syscall::{close, timerfd_settime, timerfd_gettime, read}; use fd::{FdContainer}; use rv::{retry}; use super::{Time, time_to_timespec, time_from_timespec}; /// A timer. pub struct Timer { fd: c_int, owned: bool, } impl Timer { /// Disables the timer. pub fn disable(&self) -> Result { let arg = mem::zeroed(); rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire every `iv` time units. pub fn interval(&self, iv: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(iv), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire every `iv` time units, starting at the absolute `start`. pub fn interval_from(&self, iv: Time, start: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(start), }; rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None)) } /// Sets the timer to expire every `iv` time units, starting in `when` units. pub fn interval_in(&self, iv: Time, when: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire once at the absolute `when`. pub fn once_at(&self, when: Time) -> Result { let arg = itimerspec { it_interval: mem::zeroed(), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None)) } /// Sets the timer to expire in `when` time units. pub fn once_in(&self, when: Time) -> Result { let arg = itimerspec { it_interval: mem::zeroed(), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Returns the status of the timer. /// /// TODO: Document this. pub fn status(&self) -> Result<(Time, Time)> { let mut arg = mem::zeroed(); try!(rv!(timerfd_gettime(self.fd, &mut arg))); Ok((time_from_timespec(arg.it_interval), time_from_timespec(arg.it_value))) } /// Returns the number of times the timer expired since this function was last called. pub fn ticks(&self) -> Result<u64> { let mut buf = 0; try!(retry(|| read(self.fd, buf.as_mut()))); Ok(buf) } } impl Drop for Timer { fn
(&mut self) { if self.owned { close(self.fd); } } } impl Into<c_int> for Timer { fn into(self) -> c_int { let fd = self.fd; mem::forget(self); fd } } impl FdContainer for Timer { fn is_owned(&self) -> bool { self.owned } fn borrow(&self) -> c_int { self.fd } fn from_owned(fd: c_int) -> Timer { Timer { fd: fd, owned: true } } fn from_borrowed(fd: c_int) -> Timer { Timer { fd: fd, owned: false } } }
drop
identifier_name
timer.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 base::prelude::*; use core::{mem}; use cty::{c_int, itimerspec, TFD_TIMER_ABSTIME}; use syscall::{close, timerfd_settime, timerfd_gettime, read}; use fd::{FdContainer}; use rv::{retry}; use super::{Time, time_to_timespec, time_from_timespec}; /// A timer. pub struct Timer { fd: c_int, owned: bool, } impl Timer { /// Disables the timer. pub fn disable(&self) -> Result { let arg = mem::zeroed(); rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire every `iv` time units. pub fn interval(&self, iv: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(iv), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire every `iv` time units, starting at the absolute `start`. pub fn interval_from(&self, iv: Time, start: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(start), }; rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None)) } /// Sets the timer to expire every `iv` time units, starting in `when` units. pub fn interval_in(&self, iv: Time, when: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire once at the absolute `when`. pub fn once_at(&self, when: Time) -> Result { let arg = itimerspec { it_interval: mem::zeroed(), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None)) } /// Sets the timer to expire in `when` time units. pub fn once_in(&self, when: Time) -> Result { let arg = itimerspec { it_interval: mem::zeroed(), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Returns the status of the timer. /// /// TODO: Document this. pub fn status(&self) -> Result<(Time, Time)> { let mut arg = mem::zeroed(); try!(rv!(timerfd_gettime(self.fd, &mut arg))); Ok((time_from_timespec(arg.it_interval), time_from_timespec(arg.it_value))) } /// Returns the number of times the timer expired since this function was last called. pub fn ticks(&self) -> Result<u64> { let mut buf = 0; try!(retry(|| read(self.fd, buf.as_mut()))); Ok(buf) } } impl Drop for Timer { fn drop(&mut self) { if self.owned
} } impl Into<c_int> for Timer { fn into(self) -> c_int { let fd = self.fd; mem::forget(self); fd } } impl FdContainer for Timer { fn is_owned(&self) -> bool { self.owned } fn borrow(&self) -> c_int { self.fd } fn from_owned(fd: c_int) -> Timer { Timer { fd: fd, owned: true } } fn from_borrowed(fd: c_int) -> Timer { Timer { fd: fd, owned: false } } }
{ close(self.fd); }
conditional_block
timer.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 base::prelude::*; use core::{mem}; use cty::{c_int, itimerspec, TFD_TIMER_ABSTIME}; use syscall::{close, timerfd_settime, timerfd_gettime, read}; use fd::{FdContainer}; use rv::{retry}; use super::{Time, time_to_timespec, time_from_timespec}; /// A timer. pub struct Timer { fd: c_int, owned: bool, } impl Timer { /// Disables the timer. pub fn disable(&self) -> Result { let arg = mem::zeroed(); rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire every `iv` time units. pub fn interval(&self, iv: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(iv), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire every `iv` time units, starting at the absolute `start`. pub fn interval_from(&self, iv: Time, start: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(start), }; rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None)) } /// Sets the timer to expire every `iv` time units, starting in `when` units. pub fn interval_in(&self, iv: Time, when: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire once at the absolute `when`. pub fn once_at(&self, when: Time) -> Result { let arg = itimerspec { it_interval: mem::zeroed(), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None)) } /// Sets the timer to expire in `when` time units. pub fn once_in(&self, when: Time) -> Result { let arg = itimerspec { it_interval: mem::zeroed(), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Returns the status of the timer. /// /// TODO: Document this. pub fn status(&self) -> Result<(Time, Time)> { let mut arg = mem::zeroed(); try!(rv!(timerfd_gettime(self.fd, &mut arg))); Ok((time_from_timespec(arg.it_interval), time_from_timespec(arg.it_value))) } /// Returns the number of times the timer expired since this function was last called. pub fn ticks(&self) -> Result<u64> { let mut buf = 0; try!(retry(|| read(self.fd, buf.as_mut()))); Ok(buf) } } impl Drop for Timer { fn drop(&mut self) { if self.owned { close(self.fd); } } } impl Into<c_int> for Timer { fn into(self) -> c_int { let fd = self.fd; mem::forget(self); fd } } impl FdContainer for Timer { fn is_owned(&self) -> bool { self.owned } fn borrow(&self) -> c_int { self.fd } fn from_owned(fd: c_int) -> Timer { Timer { fd: fd, owned: true } }
}
fn from_borrowed(fd: c_int) -> Timer { Timer { fd: fd, owned: false } }
random_line_split
timer.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 base::prelude::*; use core::{mem}; use cty::{c_int, itimerspec, TFD_TIMER_ABSTIME}; use syscall::{close, timerfd_settime, timerfd_gettime, read}; use fd::{FdContainer}; use rv::{retry}; use super::{Time, time_to_timespec, time_from_timespec}; /// A timer. pub struct Timer { fd: c_int, owned: bool, } impl Timer { /// Disables the timer. pub fn disable(&self) -> Result
/// Sets the timer to expire every `iv` time units. pub fn interval(&self, iv: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(iv), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire every `iv` time units, starting at the absolute `start`. pub fn interval_from(&self, iv: Time, start: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(start), }; rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None)) } /// Sets the timer to expire every `iv` time units, starting in `when` units. pub fn interval_in(&self, iv: Time, when: Time) -> Result { let arg = itimerspec { it_interval: time_to_timespec(iv), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Sets the timer to expire once at the absolute `when`. pub fn once_at(&self, when: Time) -> Result { let arg = itimerspec { it_interval: mem::zeroed(), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None)) } /// Sets the timer to expire in `when` time units. pub fn once_in(&self, when: Time) -> Result { let arg = itimerspec { it_interval: mem::zeroed(), it_value: time_to_timespec(when), }; rv!(timerfd_settime(self.fd, 0, &arg, None)) } /// Returns the status of the timer. /// /// TODO: Document this. pub fn status(&self) -> Result<(Time, Time)> { let mut arg = mem::zeroed(); try!(rv!(timerfd_gettime(self.fd, &mut arg))); Ok((time_from_timespec(arg.it_interval), time_from_timespec(arg.it_value))) } /// Returns the number of times the timer expired since this function was last called. pub fn ticks(&self) -> Result<u64> { let mut buf = 0; try!(retry(|| read(self.fd, buf.as_mut()))); Ok(buf) } } impl Drop for Timer { fn drop(&mut self) { if self.owned { close(self.fd); } } } impl Into<c_int> for Timer { fn into(self) -> c_int { let fd = self.fd; mem::forget(self); fd } } impl FdContainer for Timer { fn is_owned(&self) -> bool { self.owned } fn borrow(&self) -> c_int { self.fd } fn from_owned(fd: c_int) -> Timer { Timer { fd: fd, owned: true } } fn from_borrowed(fd: c_int) -> Timer { Timer { fd: fd, owned: false } } }
{ let arg = mem::zeroed(); rv!(timerfd_settime(self.fd, 0, &arg, None)) }
identifier_body
rect.rs
// Copyright 2014 The sdl2-rs Developers. // // 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 ffi::stdinc::{SDL_bool, SDL_TRUE, SDL_FALSE}; use libc::c_int; // SDL_rect.h #[deriving(Eq)] pub struct SDL_Point { pub x: c_int, pub y: c_int, } #[deriving(Eq)] pub struct SDL_Rect { pub x: c_int, pub y: c_int, pub w: c_int, pub h: c_int, } #[inline] pub fn SDL_RectEmpty(r: &SDL_Rect) -> SDL_bool { if (r.w <= 0) || (r.h <= 0) { SDL_TRUE } else { SDL_FALSE } } #[inline] pub fn
(a: &SDL_Rect, b: &SDL_Rect) -> SDL_bool { if *a == *b { SDL_TRUE } else { SDL_FALSE } } extern "C" { pub fn SDL_HasIntersection(A: *SDL_Rect, B: *SDL_Rect) -> SDL_bool; pub fn SDL_IntersectRect(A: *SDL_Rect, B: *SDL_Rect, result: *mut SDL_Rect) -> SDL_bool; pub fn SDL_UnionRect(A: *SDL_Rect, B: *SDL_Rect, result: *mut SDL_Rect); pub fn SDL_EnclosePoints(points: *SDL_Point, count: c_int, clip: *SDL_Rect, result: *mut SDL_Rect) -> SDL_bool; pub fn SDL_IntersectRectAndLine(r: *SDL_Rect, X1: *mut c_int, Y1: *mut c_int, X2: *mut c_int, Y2: *mut c_int) -> SDL_bool; }
SDL_RectEquals
identifier_name
rect.rs
// Copyright 2014 The sdl2-rs Developers. // // 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.
use libc::c_int; // SDL_rect.h #[deriving(Eq)] pub struct SDL_Point { pub x: c_int, pub y: c_int, } #[deriving(Eq)] pub struct SDL_Rect { pub x: c_int, pub y: c_int, pub w: c_int, pub h: c_int, } #[inline] pub fn SDL_RectEmpty(r: &SDL_Rect) -> SDL_bool { if (r.w <= 0) || (r.h <= 0) { SDL_TRUE } else { SDL_FALSE } } #[inline] pub fn SDL_RectEquals(a: &SDL_Rect, b: &SDL_Rect) -> SDL_bool { if *a == *b { SDL_TRUE } else { SDL_FALSE } } extern "C" { pub fn SDL_HasIntersection(A: *SDL_Rect, B: *SDL_Rect) -> SDL_bool; pub fn SDL_IntersectRect(A: *SDL_Rect, B: *SDL_Rect, result: *mut SDL_Rect) -> SDL_bool; pub fn SDL_UnionRect(A: *SDL_Rect, B: *SDL_Rect, result: *mut SDL_Rect); pub fn SDL_EnclosePoints(points: *SDL_Point, count: c_int, clip: *SDL_Rect, result: *mut SDL_Rect) -> SDL_bool; pub fn SDL_IntersectRectAndLine(r: *SDL_Rect, X1: *mut c_int, Y1: *mut c_int, X2: *mut c_int, Y2: *mut c_int) -> SDL_bool; }
// See the License for the specific language governing permissions and // limitations under the License. use ffi::stdinc::{SDL_bool, SDL_TRUE, SDL_FALSE};
random_line_split
rect.rs
// Copyright 2014 The sdl2-rs Developers. // // 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 ffi::stdinc::{SDL_bool, SDL_TRUE, SDL_FALSE}; use libc::c_int; // SDL_rect.h #[deriving(Eq)] pub struct SDL_Point { pub x: c_int, pub y: c_int, } #[deriving(Eq)] pub struct SDL_Rect { pub x: c_int, pub y: c_int, pub w: c_int, pub h: c_int, } #[inline] pub fn SDL_RectEmpty(r: &SDL_Rect) -> SDL_bool { if (r.w <= 0) || (r.h <= 0) { SDL_TRUE } else { SDL_FALSE } } #[inline] pub fn SDL_RectEquals(a: &SDL_Rect, b: &SDL_Rect) -> SDL_bool { if *a == *b { SDL_TRUE } else
} extern "C" { pub fn SDL_HasIntersection(A: *SDL_Rect, B: *SDL_Rect) -> SDL_bool; pub fn SDL_IntersectRect(A: *SDL_Rect, B: *SDL_Rect, result: *mut SDL_Rect) -> SDL_bool; pub fn SDL_UnionRect(A: *SDL_Rect, B: *SDL_Rect, result: *mut SDL_Rect); pub fn SDL_EnclosePoints(points: *SDL_Point, count: c_int, clip: *SDL_Rect, result: *mut SDL_Rect) -> SDL_bool; pub fn SDL_IntersectRectAndLine(r: *SDL_Rect, X1: *mut c_int, Y1: *mut c_int, X2: *mut c_int, Y2: *mut c_int) -> SDL_bool; }
{ SDL_FALSE }
conditional_block
comm.rs
#![crate_name = "comm"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use getopts::Options; use std::cmp::Ordering; use std::fs::File; use std::io::{self, BufRead, BufReader, Read, stdin, Stdin}; use std::path::Path; static NAME: &'static str = "comm"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn mkdelim(col: usize, opts: &getopts::Matches) -> String
fn ensure_nl(line: &mut String) { match line.chars().last() { Some('\n') => (), _ => line.push_str("\n") } } enum LineReader { Stdin(Stdin), FileIn(BufReader<File>) } impl LineReader { fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { match self { &mut LineReader::Stdin(ref mut r) => r.read_line(buf), &mut LineReader::FileIn(ref mut r) => r.read_line(buf), } } } fn comm(a: &mut LineReader, b: &mut LineReader, opts: &getopts::Matches) { let delim : Vec<String> = (0.. 4).map(|col| mkdelim(col, opts)).collect(); let mut ra = &mut String::new(); let mut na = a.read_line(ra); let mut rb = &mut String::new(); let mut nb = b.read_line(rb); while na.is_ok() || nb.is_ok() { let ord = match (na.is_ok(), nb.is_ok()) { (false, true) => Ordering::Greater, (true, false) => Ordering::Less, (true, true) => match(&na, &nb) { (&Ok(0), _) => Ordering::Greater, (_, &Ok(0)) => Ordering::Less, _ => ra.cmp(&rb), }, _ => unreachable!(), }; match ord { Ordering::Less => { if!opts.opt_present("1") { ensure_nl(ra); print!("{}{}", delim[1], ra); } na = a.read_line(ra); }, Ordering::Greater => { if!opts.opt_present("2") { ensure_nl(rb); print!("{}{}", delim[2], rb); } nb = b.read_line(rb); }, Ordering::Equal => { if!opts.opt_present("3") { ensure_nl(ra); print!("{}{}", delim[3], ra); } na = a.read_line(ra); nb = b.read_line(rb); } } } } fn open_file(name: &str) -> io::Result<LineReader> { match name { "-" => Ok(LineReader::Stdin(stdin())), _ => { let f = try!(File::open(&Path::new(name))); Ok(LineReader::FileIn(BufReader::new(f))) } } } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("1", "", "suppress column 1 (lines uniq to FILE1)"); opts.optflag("2", "", "suppress column 2 (lines uniq to FILE2)"); opts.optflag("3", "", "suppress column 3 (lines that appear in both files)"); opts.optopt("", "output-delimiter", "separate columns with STR", "STR"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => panic!("{}", err), }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("help") || matches.free.len()!= 2 { let msg = format!("{0} {1} Usage: {0} [OPTIONS] FILE1 FILE2 Compare sorted files line by line.", NAME, VERSION); print!("{}", opts.usage(&msg)); if matches.free.len()!= 2 { return 1; } return 0; } let mut f1 = open_file(matches.free[0].as_ref()).unwrap(); let mut f2 = open_file(matches.free[1].as_ref()).unwrap(); comm(&mut f1, &mut f2, &matches); 0 } #[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
{ let mut s = String::new(); let delim = match opts.opt_str("output-delimiter") { Some(d) => d.clone(), None => "\t".to_string(), }; if col > 1 && !opts.opt_present("1") { s.push_str(delim.as_ref()); } if col > 2 && !opts.opt_present("2") { s.push_str(delim.as_ref()); } s }
identifier_body
comm.rs
#![crate_name = "comm"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use getopts::Options; use std::cmp::Ordering; use std::fs::File; use std::io::{self, BufRead, BufReader, Read, stdin, Stdin}; use std::path::Path; static NAME: &'static str = "comm"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn mkdelim(col: usize, opts: &getopts::Matches) -> String { let mut s = String::new(); let delim = match opts.opt_str("output-delimiter") { Some(d) => d.clone(), None => "\t".to_string(), }; if col > 1 &&!opts.opt_present("1") { s.push_str(delim.as_ref()); } if col > 2 &&!opts.opt_present("2") { s.push_str(delim.as_ref()); } s } fn ensure_nl(line: &mut String) { match line.chars().last() { Some('\n') => (), _ => line.push_str("\n") } } enum LineReader { Stdin(Stdin), FileIn(BufReader<File>) } impl LineReader { fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { match self { &mut LineReader::Stdin(ref mut r) => r.read_line(buf), &mut LineReader::FileIn(ref mut r) => r.read_line(buf), } } } fn comm(a: &mut LineReader, b: &mut LineReader, opts: &getopts::Matches) { let delim : Vec<String> = (0.. 4).map(|col| mkdelim(col, opts)).collect(); let mut ra = &mut String::new(); let mut na = a.read_line(ra); let mut rb = &mut String::new(); let mut nb = b.read_line(rb); while na.is_ok() || nb.is_ok() { let ord = match (na.is_ok(), nb.is_ok()) { (false, true) => Ordering::Greater, (true, false) => Ordering::Less, (true, true) => match(&na, &nb) { (&Ok(0), _) => Ordering::Greater, (_, &Ok(0)) => Ordering::Less, _ => ra.cmp(&rb), }, _ => unreachable!(), }; match ord { Ordering::Less => { if!opts.opt_present("1") { ensure_nl(ra); print!("{}{}", delim[1], ra); } na = a.read_line(ra); }, Ordering::Greater => { if!opts.opt_present("2") { ensure_nl(rb); print!("{}{}", delim[2], rb); } nb = b.read_line(rb); }, Ordering::Equal => { if!opts.opt_present("3") { ensure_nl(ra); print!("{}{}", delim[3], ra); } na = a.read_line(ra); nb = b.read_line(rb); } } } } fn open_file(name: &str) -> io::Result<LineReader> { match name { "-" => Ok(LineReader::Stdin(stdin())), _ => { let f = try!(File::open(&Path::new(name))); Ok(LineReader::FileIn(BufReader::new(f))) } } } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("1", "", "suppress column 1 (lines uniq to FILE1)"); opts.optflag("2", "", "suppress column 2 (lines uniq to FILE2)"); opts.optflag("3", "", "suppress column 3 (lines that appear in both files)"); opts.optopt("", "output-delimiter", "separate columns with STR", "STR"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => panic!("{}", err), }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("help") || matches.free.len()!= 2 { let msg = format!("{0} {1} Usage: {0} [OPTIONS] FILE1 FILE2 Compare sorted files line by line.", NAME, VERSION); print!("{}", opts.usage(&msg)); if matches.free.len()!= 2 { return 1; } return 0; }
0 } #[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
let mut f1 = open_file(matches.free[0].as_ref()).unwrap(); let mut f2 = open_file(matches.free[1].as_ref()).unwrap(); comm(&mut f1, &mut f2, &matches);
random_line_split
comm.rs
#![crate_name = "comm"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; use getopts::Options; use std::cmp::Ordering; use std::fs::File; use std::io::{self, BufRead, BufReader, Read, stdin, Stdin}; use std::path::Path; static NAME: &'static str = "comm"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn
(col: usize, opts: &getopts::Matches) -> String { let mut s = String::new(); let delim = match opts.opt_str("output-delimiter") { Some(d) => d.clone(), None => "\t".to_string(), }; if col > 1 &&!opts.opt_present("1") { s.push_str(delim.as_ref()); } if col > 2 &&!opts.opt_present("2") { s.push_str(delim.as_ref()); } s } fn ensure_nl(line: &mut String) { match line.chars().last() { Some('\n') => (), _ => line.push_str("\n") } } enum LineReader { Stdin(Stdin), FileIn(BufReader<File>) } impl LineReader { fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { match self { &mut LineReader::Stdin(ref mut r) => r.read_line(buf), &mut LineReader::FileIn(ref mut r) => r.read_line(buf), } } } fn comm(a: &mut LineReader, b: &mut LineReader, opts: &getopts::Matches) { let delim : Vec<String> = (0.. 4).map(|col| mkdelim(col, opts)).collect(); let mut ra = &mut String::new(); let mut na = a.read_line(ra); let mut rb = &mut String::new(); let mut nb = b.read_line(rb); while na.is_ok() || nb.is_ok() { let ord = match (na.is_ok(), nb.is_ok()) { (false, true) => Ordering::Greater, (true, false) => Ordering::Less, (true, true) => match(&na, &nb) { (&Ok(0), _) => Ordering::Greater, (_, &Ok(0)) => Ordering::Less, _ => ra.cmp(&rb), }, _ => unreachable!(), }; match ord { Ordering::Less => { if!opts.opt_present("1") { ensure_nl(ra); print!("{}{}", delim[1], ra); } na = a.read_line(ra); }, Ordering::Greater => { if!opts.opt_present("2") { ensure_nl(rb); print!("{}{}", delim[2], rb); } nb = b.read_line(rb); }, Ordering::Equal => { if!opts.opt_present("3") { ensure_nl(ra); print!("{}{}", delim[3], ra); } na = a.read_line(ra); nb = b.read_line(rb); } } } } fn open_file(name: &str) -> io::Result<LineReader> { match name { "-" => Ok(LineReader::Stdin(stdin())), _ => { let f = try!(File::open(&Path::new(name))); Ok(LineReader::FileIn(BufReader::new(f))) } } } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = Options::new(); opts.optflag("1", "", "suppress column 1 (lines uniq to FILE1)"); opts.optflag("2", "", "suppress column 2 (lines uniq to FILE2)"); opts.optflag("3", "", "suppress column 3 (lines that appear in both files)"); opts.optopt("", "output-delimiter", "separate columns with STR", "STR"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => panic!("{}", err), }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("help") || matches.free.len()!= 2 { let msg = format!("{0} {1} Usage: {0} [OPTIONS] FILE1 FILE2 Compare sorted files line by line.", NAME, VERSION); print!("{}", opts.usage(&msg)); if matches.free.len()!= 2 { return 1; } return 0; } let mut f1 = open_file(matches.free[0].as_ref()).unwrap(); let mut f2 = open_file(matches.free[1].as_ref()).unwrap(); comm(&mut f1, &mut f2, &matches); 0 } #[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
mkdelim
identifier_name
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use geom::point::TypedPoint2D; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use layers::geometry::DevicePixel; use servo_msg::compositor_msg::{ReadyState, RenderState}; use servo_util::geometry::ScreenPx; pub enum MouseWindowEvent { MouseWindowClickEvent(uint, TypedPoint2D<DevicePixel, f32>), MouseWindowMouseDownEvent(uint, TypedPoint2D<DevicePixel, f32>), MouseWindowMouseUpEvent(uint, TypedPoint2D<DevicePixel, f32>),
pub enum WindowNavigateMsg { Forward, Back, } /// Events that the windowing system sends to Servo. pub enum WindowEvent { /// Sent when no message has arrived. /// /// FIXME: This is a bogus event and is only used because we don't have the new /// scheduler integrated with the platform event loop. IdleWindowEvent, /// Sent when part of the window is marked dirty and needs to be redrawn. RefreshWindowEvent, /// Sent when the window is resized. ResizeWindowEvent(TypedSize2D<DevicePixel, uint>), /// Sent when a new URL is to be loaded. LoadUrlWindowEvent(String), /// Sent when a mouse hit test is to be performed. MouseWindowEventClass(MouseWindowEvent), /// Sent when a mouse move. MouseWindowMoveEventClass(TypedPoint2D<DevicePixel, f32>), /// Sent when the user scrolls. Includes the current cursor position. ScrollWindowEvent(TypedPoint2D<DevicePixel, f32>, TypedPoint2D<DevicePixel, i32>), /// Sent when the user zooms. ZoomWindowEvent(f32), /// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel). PinchZoomWindowEvent(f32), /// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace). NavigationWindowEvent(WindowNavigateMsg), /// Sent when rendering is finished. FinishedWindowEvent, /// Sent when the user quits the application QuitWindowEvent, } pub trait WindowMethods { /// Returns the size of the window in hardware pixels. fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, uint>; /// Returns the size of the window in density-independent "px" units. fn size(&self) -> TypedSize2D<ScreenPx, f32>; /// Presents the window to the screen (perhaps by page flipping). fn present(&self); /// Spins the event loop and returns the next event. fn recv(&self) -> WindowEvent; /// Sets the ready state of the current page. fn set_ready_state(&self, ready_state: ReadyState); /// Sets the render state of the current page. fn set_render_state(&self, render_state: RenderState); /// Returns the hidpi factor of the monitor. fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32>; }
}
random_line_split
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use geom::point::TypedPoint2D; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use layers::geometry::DevicePixel; use servo_msg::compositor_msg::{ReadyState, RenderState}; use servo_util::geometry::ScreenPx; pub enum MouseWindowEvent { MouseWindowClickEvent(uint, TypedPoint2D<DevicePixel, f32>), MouseWindowMouseDownEvent(uint, TypedPoint2D<DevicePixel, f32>), MouseWindowMouseUpEvent(uint, TypedPoint2D<DevicePixel, f32>), } pub enum
{ Forward, Back, } /// Events that the windowing system sends to Servo. pub enum WindowEvent { /// Sent when no message has arrived. /// /// FIXME: This is a bogus event and is only used because we don't have the new /// scheduler integrated with the platform event loop. IdleWindowEvent, /// Sent when part of the window is marked dirty and needs to be redrawn. RefreshWindowEvent, /// Sent when the window is resized. ResizeWindowEvent(TypedSize2D<DevicePixel, uint>), /// Sent when a new URL is to be loaded. LoadUrlWindowEvent(String), /// Sent when a mouse hit test is to be performed. MouseWindowEventClass(MouseWindowEvent), /// Sent when a mouse move. MouseWindowMoveEventClass(TypedPoint2D<DevicePixel, f32>), /// Sent when the user scrolls. Includes the current cursor position. ScrollWindowEvent(TypedPoint2D<DevicePixel, f32>, TypedPoint2D<DevicePixel, i32>), /// Sent when the user zooms. ZoomWindowEvent(f32), /// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel). PinchZoomWindowEvent(f32), /// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace). NavigationWindowEvent(WindowNavigateMsg), /// Sent when rendering is finished. FinishedWindowEvent, /// Sent when the user quits the application QuitWindowEvent, } pub trait WindowMethods { /// Returns the size of the window in hardware pixels. fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, uint>; /// Returns the size of the window in density-independent "px" units. fn size(&self) -> TypedSize2D<ScreenPx, f32>; /// Presents the window to the screen (perhaps by page flipping). fn present(&self); /// Spins the event loop and returns the next event. fn recv(&self) -> WindowEvent; /// Sets the ready state of the current page. fn set_ready_state(&self, ready_state: ReadyState); /// Sets the render state of the current page. fn set_render_state(&self, render_state: RenderState); /// Returns the hidpi factor of the monitor. fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32>; }
WindowNavigateMsg
identifier_name
macros.rs
#[macro_use] extern crate gfx; pub use gfx::format as fm; #[derive(Clone, Debug)] pub struct Rg16; gfx_format!(Rg16: R16_G16 = Vec2<Float>); gfx_defines!{ #[derive(PartialEq)] vertex Vertex { _x: i8 = "x", _y: f32 = "y", } vertex Instance { pos: [f32; 2] = "pos", color: [f32; 3] = "color", } constant Local { pos: [u32; 4] = "pos", } #[derive(PartialEq)] #[derive(PartialOrd)] constant LocalMeta { pos: [u32; 4] = "pos_meta", } pipeline testpipe { vertex: gfx::VertexBuffer<Vertex> = (), instance: gfx::InstanceBuffer<Instance> = (), const_locals: gfx::ConstantBuffer<Local> = "Locals", global: gfx::Global<[f32; 4]> = "Global", tex_diffuse: gfx::ShaderResource<[f32; 4]> = "Diffuse", sampler_linear: gfx::Sampler = "Linear", buf_frequency: gfx::UnorderedAccess<[f32; 4]> = "Frequency", pixel_color: gfx::RenderTarget<fm::Rgba8> = "Color", blend_target: gfx::BlendTarget<Rg16> = ("o_Color1", gfx::state::MASK_ALL, gfx::preset::blend::ADD), depth: gfx::DepthTarget<gfx::format::DepthStencil> = gfx::preset::depth::LESS_EQUAL_TEST, blend_ref: gfx::BlendRef = (), scissor: gfx::Scissor = (), } } fn _test_pso<R, F>(factory: &mut F) -> gfx::PipelineState<R, testpipe::Meta> where R: gfx::Resources, F: gfx::traits::FactoryExt<R>, { factory.create_pipeline_simple(&[], &[], testpipe::new()).unwrap() } gfx_pipeline_base!( testraw { vertex: gfx::RawVertexBuffer,
cbuf: gfx::RawConstantBuffer, tex: gfx::RawShaderResource, target: gfx::RawRenderTarget, }); fn _test_raw<R, F>(factory: &mut F) -> gfx::PipelineState<R, testraw::Meta> where R: gfx::Resources, F: gfx::traits::FactoryExt<R>, { let special = gfx::pso::buffer::Element { format: fm::Format(fm::SurfaceType::R32, fm::ChannelType::Float), offset: 0, }; let init = testraw::Init { vertex: (&[("a_Special", special)], 12, 0), cbuf: "Locals", tex: "Specular", target: ("o_Color2", fm::Format(fm::SurfaceType::R8_G8_B8_A8, fm::ChannelType::Unorm), gfx::state::MASK_ALL, None), }; factory.create_pipeline_simple(&[], &[], init).unwrap() }
random_line_split
macros.rs
#[macro_use] extern crate gfx; pub use gfx::format as fm; #[derive(Clone, Debug)] pub struct Rg16; gfx_format!(Rg16: R16_G16 = Vec2<Float>); gfx_defines!{ #[derive(PartialEq)] vertex Vertex { _x: i8 = "x", _y: f32 = "y", } vertex Instance { pos: [f32; 2] = "pos", color: [f32; 3] = "color", } constant Local { pos: [u32; 4] = "pos", } #[derive(PartialEq)] #[derive(PartialOrd)] constant LocalMeta { pos: [u32; 4] = "pos_meta", } pipeline testpipe { vertex: gfx::VertexBuffer<Vertex> = (), instance: gfx::InstanceBuffer<Instance> = (), const_locals: gfx::ConstantBuffer<Local> = "Locals", global: gfx::Global<[f32; 4]> = "Global", tex_diffuse: gfx::ShaderResource<[f32; 4]> = "Diffuse", sampler_linear: gfx::Sampler = "Linear", buf_frequency: gfx::UnorderedAccess<[f32; 4]> = "Frequency", pixel_color: gfx::RenderTarget<fm::Rgba8> = "Color", blend_target: gfx::BlendTarget<Rg16> = ("o_Color1", gfx::state::MASK_ALL, gfx::preset::blend::ADD), depth: gfx::DepthTarget<gfx::format::DepthStencil> = gfx::preset::depth::LESS_EQUAL_TEST, blend_ref: gfx::BlendRef = (), scissor: gfx::Scissor = (), } } fn _test_pso<R, F>(factory: &mut F) -> gfx::PipelineState<R, testpipe::Meta> where R: gfx::Resources, F: gfx::traits::FactoryExt<R>, { factory.create_pipeline_simple(&[], &[], testpipe::new()).unwrap() } gfx_pipeline_base!( testraw { vertex: gfx::RawVertexBuffer, cbuf: gfx::RawConstantBuffer, tex: gfx::RawShaderResource, target: gfx::RawRenderTarget, }); fn
<R, F>(factory: &mut F) -> gfx::PipelineState<R, testraw::Meta> where R: gfx::Resources, F: gfx::traits::FactoryExt<R>, { let special = gfx::pso::buffer::Element { format: fm::Format(fm::SurfaceType::R32, fm::ChannelType::Float), offset: 0, }; let init = testraw::Init { vertex: (&[("a_Special", special)], 12, 0), cbuf: "Locals", tex: "Specular", target: ("o_Color2", fm::Format(fm::SurfaceType::R8_G8_B8_A8, fm::ChannelType::Unorm), gfx::state::MASK_ALL, None), }; factory.create_pipeline_simple(&[], &[], init).unwrap() }
_test_raw
identifier_name
message.rs
use libc::{c_int, size_t, c_void}; use std::mem; use std::marker::PhantomData; #[repr(C)] pub struct nl_msg { _unused: [u8; 0], } #[repr(C)] pub struct nlmsghdr { _unused: [u8; 0], } #[link(name="nl-3")] extern "C" { // Exposed msg functions fn nlmsg_alloc() -> *const nl_msg; fn nlmsg_free(msg: *const nl_msg); fn nlmsg_append(msg: *const nl_msg, data: *const c_void, len: size_t, pad: c_int) -> i32; fn nlmsg_put(msg: *const nl_msg, pid: u32, seq: u32, mtype: c_int, payload: c_int, flags: c_int) -> *const nlmsghdr; fn nlmsg_datalen(nlh: *const nlmsghdr) -> i32; fn nlmsg_next(nlh: *const nlmsghdr, remaining: *const i32) -> *const nlmsghdr; fn nlmsg_inherit(nlh: *const nlmsghdr) -> *const nl_msg; fn nlmsg_hdr(msg: *const nl_msg) -> *const nlmsghdr; fn nlmsg_ok(msg: *const nl_msg) -> u32; fn nlmsg_data(msg: *const nlmsghdr) -> *const c_void; } pub struct NetlinkMessage { ptr: *const nl_msg, hdr: *const nlmsghdr, } pub struct NetlinkData <T> { ptr: Option<*const c_void>, phantom: PhantomData<T> } impl <T> NetlinkData <T> { pub fn new() -> NetlinkData<T> { NetlinkData { ptr: None, phantom: PhantomData } } pub fn with_data<D>(data: &D) -> NetlinkData<T> { NetlinkData { ptr: Some(unsafe{ mem::transmute(data) }), phantom: PhantomData } } pub fn with_vptr(data: *const c_void) -> NetlinkData<T> { NetlinkData { ptr: Some(data), phantom: PhantomData } } pub fn get(&self) -> Option<&T> { match self.ptr { None => None, Some(vptr) => { Some( unsafe { mem::transmute(vptr) } ) } } } pub fn set(&mut self, data: &T) { match self.ptr { None => { let p: *const c_void = unsafe{ mem::transmute(data) }; self.ptr = Some( p ); }, _ => return } } pub fn from_vptr(&mut self, data: *const c_void) { match self.ptr { None => self.ptr = Some(data), _ => return } } pub fn to_vptr(&self) -> Option<*const c_void> { self.ptr } } pub fn contain(ptr: *const nl_msg) -> Option<NetlinkMessage> { match ptr as isize { 0x0 => None, _ => Some ( NetlinkMessage { ptr: ptr, hdr: unsafe { nlmsg_hdr(ptr) } }) } } pub fn alloc() -> Option<NetlinkMessage> { let mptr = unsafe { nlmsg_alloc() }; contain(mptr) } pub fn free(msg: NetlinkMessage) { unsafe { nlmsg_free(msg.ptr) } } pub fn append<T>(msg: &mut NetlinkMessage, data: &T, len: u32, pad: i32) -> i32 { unsafe { let vptr: *const c_void = mem::transmute(data); nlmsg_append(msg.ptr, vptr, len as size_t, pad as c_int) as i32 } } pub fn put(msg: &mut NetlinkMessage, pid: u32, seq: u32, mtype: i32, payload: i32, flags: i32) -> bool { let hdr = unsafe { nlmsg_put(msg.ptr, pid, seq, mtype as c_int, payload as c_int, flags as c_int) }; match hdr as i32 { 0x0 => false, _ =>
} } pub fn data_len(msg: &NetlinkMessage) -> i32 { unsafe { nlmsg_datalen(msg.hdr) } } pub fn inherit(msg: &NetlinkMessage) -> NetlinkMessage { let mptr = unsafe { nlmsg_inherit(msg.hdr) }; NetlinkMessage { ptr: mptr, hdr: unsafe { nlmsg_hdr(mptr) } } } pub fn data<T>(msg: &NetlinkMessage, container: &mut NetlinkData<T>) { unsafe { let vptr = nlmsg_data(msg.hdr); container.from_vptr(vptr); } } pub mod expose { pub fn nl_msg_ptr(msg: &::message::NetlinkMessage) -> *const ::message::nl_msg { msg.ptr } pub fn nlmsghdr_ptr(msg: &::message::NetlinkMessage) -> *const ::message::nlmsghdr { msg.hdr } }
{ true }
conditional_block
message.rs
use libc::{c_int, size_t, c_void}; use std::mem; use std::marker::PhantomData; #[repr(C)] pub struct nl_msg { _unused: [u8; 0], } #[repr(C)] pub struct nlmsghdr { _unused: [u8; 0], } #[link(name="nl-3")] extern "C" { // Exposed msg functions fn nlmsg_alloc() -> *const nl_msg; fn nlmsg_free(msg: *const nl_msg); fn nlmsg_append(msg: *const nl_msg, data: *const c_void, len: size_t, pad: c_int) -> i32; fn nlmsg_put(msg: *const nl_msg, pid: u32, seq: u32, mtype: c_int, payload: c_int, flags: c_int) -> *const nlmsghdr; fn nlmsg_datalen(nlh: *const nlmsghdr) -> i32; fn nlmsg_next(nlh: *const nlmsghdr, remaining: *const i32) -> *const nlmsghdr; fn nlmsg_inherit(nlh: *const nlmsghdr) -> *const nl_msg; fn nlmsg_hdr(msg: *const nl_msg) -> *const nlmsghdr; fn nlmsg_ok(msg: *const nl_msg) -> u32; fn nlmsg_data(msg: *const nlmsghdr) -> *const c_void; } pub struct NetlinkMessage { ptr: *const nl_msg, hdr: *const nlmsghdr, } pub struct NetlinkData <T> { ptr: Option<*const c_void>, phantom: PhantomData<T> } impl <T> NetlinkData <T> { pub fn new() -> NetlinkData<T> { NetlinkData { ptr: None, phantom: PhantomData } } pub fn with_data<D>(data: &D) -> NetlinkData<T> { NetlinkData { ptr: Some(unsafe{ mem::transmute(data) }), phantom: PhantomData } } pub fn with_vptr(data: *const c_void) -> NetlinkData<T> { NetlinkData { ptr: Some(data), phantom: PhantomData } } pub fn get(&self) -> Option<&T>
pub fn set(&mut self, data: &T) { match self.ptr { None => { let p: *const c_void = unsafe{ mem::transmute(data) }; self.ptr = Some( p ); }, _ => return } } pub fn from_vptr(&mut self, data: *const c_void) { match self.ptr { None => self.ptr = Some(data), _ => return } } pub fn to_vptr(&self) -> Option<*const c_void> { self.ptr } } pub fn contain(ptr: *const nl_msg) -> Option<NetlinkMessage> { match ptr as isize { 0x0 => None, _ => Some ( NetlinkMessage { ptr: ptr, hdr: unsafe { nlmsg_hdr(ptr) } }) } } pub fn alloc() -> Option<NetlinkMessage> { let mptr = unsafe { nlmsg_alloc() }; contain(mptr) } pub fn free(msg: NetlinkMessage) { unsafe { nlmsg_free(msg.ptr) } } pub fn append<T>(msg: &mut NetlinkMessage, data: &T, len: u32, pad: i32) -> i32 { unsafe { let vptr: *const c_void = mem::transmute(data); nlmsg_append(msg.ptr, vptr, len as size_t, pad as c_int) as i32 } } pub fn put(msg: &mut NetlinkMessage, pid: u32, seq: u32, mtype: i32, payload: i32, flags: i32) -> bool { let hdr = unsafe { nlmsg_put(msg.ptr, pid, seq, mtype as c_int, payload as c_int, flags as c_int) }; match hdr as i32 { 0x0 => false, _ => { true } } } pub fn data_len(msg: &NetlinkMessage) -> i32 { unsafe { nlmsg_datalen(msg.hdr) } } pub fn inherit(msg: &NetlinkMessage) -> NetlinkMessage { let mptr = unsafe { nlmsg_inherit(msg.hdr) }; NetlinkMessage { ptr: mptr, hdr: unsafe { nlmsg_hdr(mptr) } } } pub fn data<T>(msg: &NetlinkMessage, container: &mut NetlinkData<T>) { unsafe { let vptr = nlmsg_data(msg.hdr); container.from_vptr(vptr); } } pub mod expose { pub fn nl_msg_ptr(msg: &::message::NetlinkMessage) -> *const ::message::nl_msg { msg.ptr } pub fn nlmsghdr_ptr(msg: &::message::NetlinkMessage) -> *const ::message::nlmsghdr { msg.hdr } }
{ match self.ptr { None => None, Some(vptr) => { Some( unsafe { mem::transmute(vptr) } ) } } }
identifier_body
message.rs
use libc::{c_int, size_t, c_void}; use std::mem; use std::marker::PhantomData; #[repr(C)] pub struct nl_msg { _unused: [u8; 0],
} #[link(name="nl-3")] extern "C" { // Exposed msg functions fn nlmsg_alloc() -> *const nl_msg; fn nlmsg_free(msg: *const nl_msg); fn nlmsg_append(msg: *const nl_msg, data: *const c_void, len: size_t, pad: c_int) -> i32; fn nlmsg_put(msg: *const nl_msg, pid: u32, seq: u32, mtype: c_int, payload: c_int, flags: c_int) -> *const nlmsghdr; fn nlmsg_datalen(nlh: *const nlmsghdr) -> i32; fn nlmsg_next(nlh: *const nlmsghdr, remaining: *const i32) -> *const nlmsghdr; fn nlmsg_inherit(nlh: *const nlmsghdr) -> *const nl_msg; fn nlmsg_hdr(msg: *const nl_msg) -> *const nlmsghdr; fn nlmsg_ok(msg: *const nl_msg) -> u32; fn nlmsg_data(msg: *const nlmsghdr) -> *const c_void; } pub struct NetlinkMessage { ptr: *const nl_msg, hdr: *const nlmsghdr, } pub struct NetlinkData <T> { ptr: Option<*const c_void>, phantom: PhantomData<T> } impl <T> NetlinkData <T> { pub fn new() -> NetlinkData<T> { NetlinkData { ptr: None, phantom: PhantomData } } pub fn with_data<D>(data: &D) -> NetlinkData<T> { NetlinkData { ptr: Some(unsafe{ mem::transmute(data) }), phantom: PhantomData } } pub fn with_vptr(data: *const c_void) -> NetlinkData<T> { NetlinkData { ptr: Some(data), phantom: PhantomData } } pub fn get(&self) -> Option<&T> { match self.ptr { None => None, Some(vptr) => { Some( unsafe { mem::transmute(vptr) } ) } } } pub fn set(&mut self, data: &T) { match self.ptr { None => { let p: *const c_void = unsafe{ mem::transmute(data) }; self.ptr = Some( p ); }, _ => return } } pub fn from_vptr(&mut self, data: *const c_void) { match self.ptr { None => self.ptr = Some(data), _ => return } } pub fn to_vptr(&self) -> Option<*const c_void> { self.ptr } } pub fn contain(ptr: *const nl_msg) -> Option<NetlinkMessage> { match ptr as isize { 0x0 => None, _ => Some ( NetlinkMessage { ptr: ptr, hdr: unsafe { nlmsg_hdr(ptr) } }) } } pub fn alloc() -> Option<NetlinkMessage> { let mptr = unsafe { nlmsg_alloc() }; contain(mptr) } pub fn free(msg: NetlinkMessage) { unsafe { nlmsg_free(msg.ptr) } } pub fn append<T>(msg: &mut NetlinkMessage, data: &T, len: u32, pad: i32) -> i32 { unsafe { let vptr: *const c_void = mem::transmute(data); nlmsg_append(msg.ptr, vptr, len as size_t, pad as c_int) as i32 } } pub fn put(msg: &mut NetlinkMessage, pid: u32, seq: u32, mtype: i32, payload: i32, flags: i32) -> bool { let hdr = unsafe { nlmsg_put(msg.ptr, pid, seq, mtype as c_int, payload as c_int, flags as c_int) }; match hdr as i32 { 0x0 => false, _ => { true } } } pub fn data_len(msg: &NetlinkMessage) -> i32 { unsafe { nlmsg_datalen(msg.hdr) } } pub fn inherit(msg: &NetlinkMessage) -> NetlinkMessage { let mptr = unsafe { nlmsg_inherit(msg.hdr) }; NetlinkMessage { ptr: mptr, hdr: unsafe { nlmsg_hdr(mptr) } } } pub fn data<T>(msg: &NetlinkMessage, container: &mut NetlinkData<T>) { unsafe { let vptr = nlmsg_data(msg.hdr); container.from_vptr(vptr); } } pub mod expose { pub fn nl_msg_ptr(msg: &::message::NetlinkMessage) -> *const ::message::nl_msg { msg.ptr } pub fn nlmsghdr_ptr(msg: &::message::NetlinkMessage) -> *const ::message::nlmsghdr { msg.hdr } }
} #[repr(C)] pub struct nlmsghdr { _unused: [u8; 0],
random_line_split
message.rs
use libc::{c_int, size_t, c_void}; use std::mem; use std::marker::PhantomData; #[repr(C)] pub struct nl_msg { _unused: [u8; 0], } #[repr(C)] pub struct nlmsghdr { _unused: [u8; 0], } #[link(name="nl-3")] extern "C" { // Exposed msg functions fn nlmsg_alloc() -> *const nl_msg; fn nlmsg_free(msg: *const nl_msg); fn nlmsg_append(msg: *const nl_msg, data: *const c_void, len: size_t, pad: c_int) -> i32; fn nlmsg_put(msg: *const nl_msg, pid: u32, seq: u32, mtype: c_int, payload: c_int, flags: c_int) -> *const nlmsghdr; fn nlmsg_datalen(nlh: *const nlmsghdr) -> i32; fn nlmsg_next(nlh: *const nlmsghdr, remaining: *const i32) -> *const nlmsghdr; fn nlmsg_inherit(nlh: *const nlmsghdr) -> *const nl_msg; fn nlmsg_hdr(msg: *const nl_msg) -> *const nlmsghdr; fn nlmsg_ok(msg: *const nl_msg) -> u32; fn nlmsg_data(msg: *const nlmsghdr) -> *const c_void; } pub struct NetlinkMessage { ptr: *const nl_msg, hdr: *const nlmsghdr, } pub struct NetlinkData <T> { ptr: Option<*const c_void>, phantom: PhantomData<T> } impl <T> NetlinkData <T> { pub fn new() -> NetlinkData<T> { NetlinkData { ptr: None, phantom: PhantomData } } pub fn with_data<D>(data: &D) -> NetlinkData<T> { NetlinkData { ptr: Some(unsafe{ mem::transmute(data) }), phantom: PhantomData } } pub fn with_vptr(data: *const c_void) -> NetlinkData<T> { NetlinkData { ptr: Some(data), phantom: PhantomData } } pub fn get(&self) -> Option<&T> { match self.ptr { None => None, Some(vptr) => { Some( unsafe { mem::transmute(vptr) } ) } } } pub fn set(&mut self, data: &T) { match self.ptr { None => { let p: *const c_void = unsafe{ mem::transmute(data) }; self.ptr = Some( p ); }, _ => return } } pub fn from_vptr(&mut self, data: *const c_void) { match self.ptr { None => self.ptr = Some(data), _ => return } } pub fn to_vptr(&self) -> Option<*const c_void> { self.ptr } } pub fn contain(ptr: *const nl_msg) -> Option<NetlinkMessage> { match ptr as isize { 0x0 => None, _ => Some ( NetlinkMessage { ptr: ptr, hdr: unsafe { nlmsg_hdr(ptr) } }) } } pub fn alloc() -> Option<NetlinkMessage> { let mptr = unsafe { nlmsg_alloc() }; contain(mptr) } pub fn free(msg: NetlinkMessage) { unsafe { nlmsg_free(msg.ptr) } } pub fn
<T>(msg: &mut NetlinkMessage, data: &T, len: u32, pad: i32) -> i32 { unsafe { let vptr: *const c_void = mem::transmute(data); nlmsg_append(msg.ptr, vptr, len as size_t, pad as c_int) as i32 } } pub fn put(msg: &mut NetlinkMessage, pid: u32, seq: u32, mtype: i32, payload: i32, flags: i32) -> bool { let hdr = unsafe { nlmsg_put(msg.ptr, pid, seq, mtype as c_int, payload as c_int, flags as c_int) }; match hdr as i32 { 0x0 => false, _ => { true } } } pub fn data_len(msg: &NetlinkMessage) -> i32 { unsafe { nlmsg_datalen(msg.hdr) } } pub fn inherit(msg: &NetlinkMessage) -> NetlinkMessage { let mptr = unsafe { nlmsg_inherit(msg.hdr) }; NetlinkMessage { ptr: mptr, hdr: unsafe { nlmsg_hdr(mptr) } } } pub fn data<T>(msg: &NetlinkMessage, container: &mut NetlinkData<T>) { unsafe { let vptr = nlmsg_data(msg.hdr); container.from_vptr(vptr); } } pub mod expose { pub fn nl_msg_ptr(msg: &::message::NetlinkMessage) -> *const ::message::nl_msg { msg.ptr } pub fn nlmsghdr_ptr(msg: &::message::NetlinkMessage) -> *const ::message::nlmsghdr { msg.hdr } }
append
identifier_name
server.rs
use std::io::IoResult; use crypto::sha1::Sha1; use crypto::digest::Digest; use serialize::base64::{ToBase64, STANDARD}; use std::ascii::AsciiExt; use time; use std::io::{Listener, Acceptor}; use std::io::net::tcp::TcpListener; use std::io::net::tcp::TcpStream; use http::buffer::BufferedStream; use std::thread::Thread; use std::sync::mpsc::{channel, Sender, Receiver}; use http::server::{Server, Request, ResponseWriter}; use http::status::SwitchingProtocols; use http::headers::HeaderEnum; use http::headers::response::Header::ExtensionHeader; use http::headers::connection::Connection::Token; use http::method::Method::Get; pub use message::Payload::{Text, Binary, Empty}; pub use message::Opcode::{ContinuationOp, TextOp, BinaryOp, CloseOp, PingOp, PongOp}; use message::Message; static WEBSOCKET_SALT: &'static str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; pub trait WebSocketServer: Server { // called when a web socket connection is successfully established. // // this can't block! leaving implementation to trait user, in case they // want to custom scheduling, tracking clients, reconnect logic, etc. // // TODO: may want to send more info in, such as the connecting IP address? fn handle_ws_connect(&self, receiver: Receiver<Box<Message>>, sender: Sender<Box<Message>>) -> (); // XXX: this is mostly a copy of the serve_forever fn in the Server trait. // rust-http needs some changes in order to avoid this duplication fn ws_serve_forever(self) { let config = self.get_config(); debug!("About to bind to {}", config.bind_address); let mut acceptor = match TcpListener::bind((config.bind_address.ip.to_string().as_slice(), config.bind_address.port)).listen() { Err(err) => { error!("bind or listen failed :-(: {}", err); return; }, Ok(acceptor) => acceptor, }; debug!("listening"); loop { let stream = match acceptor.accept() { Err(error) => { debug!("accept failed: {}", error); // Question: is this the correct thing to do? We should probably be more // intelligent, for there are some accept failures that are likely to be // permanent, such that continuing would be a very bad idea, such as // ENOBUFS/ENOMEM; and some where it should just be ignored, e.g. // ECONNABORTED. TODO. continue; }, Ok(socket) => socket, }; let child_self = self.clone(); Thread::spawn(move || { let mut stream = BufferedStream::new(stream); debug!("accepted connection"); let mut successful_handshake = false; loop { // A keep-alive loop, condition at end let (request, err_status) = Request::load(&mut stream); let close_connection = request.close_connection; let mut response = ResponseWriter::new(&mut stream); match err_status { Ok(()) => { successful_handshake = child_self.handle_possible_ws_request(request, &mut response); // Ensure that we actually do send a response: match response.try_write_headers() { Err(err) => { error!("Writing headers failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } }, Err(status) => { // Uh oh, it's a response that I as a server cannot cope with. // No good user-agent should have caused this, so for the moment // at least I am content to send no body in the response. response.status = status; response.headers.content_length = Some(0); match response.write_headers() { Err(err) => { error!("Writing headers failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } }, } // Ensure the request is flushed, any Transfer-Encoding completed, etc. match response.finish_response() { Err(err) => { error!("finishing response failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } if successful_handshake || close_connection { break; } } if successful_handshake { child_self.serve_websockets(stream).unwrap(); } }).detach(); } } fn serve_websockets(&self, stream: BufferedStream<TcpStream>) -> IoResult<()> { let mut stream = stream.wrapped; let write_stream = stream.clone(); let (in_sender, in_receiver) = channel(); let (out_sender, out_receiver) = channel(); self.handle_ws_connect(in_receiver, out_sender); // write task Thread::spawn(move || { // ugh: https://github.com/mozilla/rust/blob/3dbc1c34e694f38daeef741cfffc558606443c15/src/test/run-pass/kindck-implicit-close-over-mut-var.rs#L40-L44 // work to fix this is ongoing here: https://github.com/mozilla/rust/issues/11958 let mut write_stream = write_stream; loop { let message = out_receiver.recv().unwrap(); message.send(&mut write_stream).unwrap(); // fails this task in case of an error; FIXME make sure this fails the read (parent) task } }).detach(); // read task, effectively the parent of the write task loop { let message = Message::load(&mut stream).unwrap(); // fails the task if there's an error. debug!("message: {}", message); match message.opcode { CloseOp => { try!(stream.close_read()); try!(message.send(&mut stream)); // complete close handeshake - send the same message right back at the client try!(stream.close_write());
payload: message.payload, opcode: PongOp }; try!(pong.send(&mut stream)); }, PongOp => (), _ => in_sender.send(message).unwrap() } } Ok(()) } fn sec_websocket_accept(&self, sec_websocket_key: &str) -> String { // NOTE from RFC 6455 // // To prove that the handshake was received, the server has to take two // pieces of information and combine them to form a response. The first // piece of information comes from the |Sec-WebSocket-Key| header field // in the client handshake: // // Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== // // For this header field, the server has to take the value (as present // in the header field, e.g., the base64-encoded [RFC4648] version minus // any leading and trailing whitespace) and concatenate this with the // Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA- // 95CA-C5AB0DC85B11" in string form, which is unlikely to be used by // network endpoints that do not understand the WebSocket Protocol. A // SHA-1 hash (160 bits) [FIPS.180-3], base64-encoded (see Section 4 of // [RFC4648]), of this concatenation is then returned in the server's // handshake. let mut sh = Sha1::new(); let mut out = [0u8; 20]; sh.input_str((String::from_str(sec_websocket_key) + WEBSOCKET_SALT).as_slice()); sh.result(out.as_mut_slice()); return out.to_base64(STANDARD); } // check if the http request is a web socket upgrade request, and return true if so. // otherwise, fall back on the regular http request handler fn handle_possible_ws_request(&self, r: Request, w: &mut ResponseWriter) -> bool { // TODO allow configuration of endpoint for websocket match (r.method.clone(), r.headers.upgrade.clone()){ // (&Get, &Some("websocket"), &Some(box [Token(box "Upgrade")])) => //\{ FIXME this doesn't work. but client must have the header "Connection: Upgrade" (Get, Some(ref upgrade)) => { if!upgrade.as_slice().eq_ignore_ascii_case("websocket"){ self.handle_request(r, w); return false; } // TODO client must have the header "Connection: Upgrade" // // TODO The request MUST include a header field with the name // |Sec-WebSocket-Version|. The value of this header field MUST be 13. // WebSocket Opening Handshake w.status = SwitchingProtocols; w.headers.upgrade = Some(String::from_str("websocket")); // w.headers.transfer_encoding = None; w.headers.content_length = Some(0); w.headers.connection = Some(vec!(Token(String::from_str("Upgrade")))); w.headers.date = Some(time::now_utc()); w.headers.server = Some(String::from_str("rust-ws/0.1-pre")); for header in r.headers.iter() { debug!("Header {}: {}", header.header_name(), header.header_value()); } // NOTE: think this is actually Sec-WebSocket-Key (capital Web[S]ocket), but rust-http normalizes header names match r.headers.extensions.get(&String::from_str("Sec-Websocket-Key")) { Some(val) => { let sec_websocket_accept = self.sec_websocket_accept((*val).as_slice()); w.headers.insert(ExtensionHeader(String::from_str("Sec-WebSocket-Accept"), sec_websocket_accept)); }, None => panic!() } return true; // successful_handshake }, (_, _) => self.handle_request(r, w) } return false; } }
break; // as this task dies, this should release the write task above, as well as the task set up in handle_ws_connection, if any }, PingOp => { let pong = Message {
random_line_split
server.rs
use std::io::IoResult; use crypto::sha1::Sha1; use crypto::digest::Digest; use serialize::base64::{ToBase64, STANDARD}; use std::ascii::AsciiExt; use time; use std::io::{Listener, Acceptor}; use std::io::net::tcp::TcpListener; use std::io::net::tcp::TcpStream; use http::buffer::BufferedStream; use std::thread::Thread; use std::sync::mpsc::{channel, Sender, Receiver}; use http::server::{Server, Request, ResponseWriter}; use http::status::SwitchingProtocols; use http::headers::HeaderEnum; use http::headers::response::Header::ExtensionHeader; use http::headers::connection::Connection::Token; use http::method::Method::Get; pub use message::Payload::{Text, Binary, Empty}; pub use message::Opcode::{ContinuationOp, TextOp, BinaryOp, CloseOp, PingOp, PongOp}; use message::Message; static WEBSOCKET_SALT: &'static str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; pub trait WebSocketServer: Server { // called when a web socket connection is successfully established. // // this can't block! leaving implementation to trait user, in case they // want to custom scheduling, tracking clients, reconnect logic, etc. // // TODO: may want to send more info in, such as the connecting IP address? fn handle_ws_connect(&self, receiver: Receiver<Box<Message>>, sender: Sender<Box<Message>>) -> (); // XXX: this is mostly a copy of the serve_forever fn in the Server trait. // rust-http needs some changes in order to avoid this duplication fn ws_serve_forever(self)
continue; }, Ok(socket) => socket, }; let child_self = self.clone(); Thread::spawn(move || { let mut stream = BufferedStream::new(stream); debug!("accepted connection"); let mut successful_handshake = false; loop { // A keep-alive loop, condition at end let (request, err_status) = Request::load(&mut stream); let close_connection = request.close_connection; let mut response = ResponseWriter::new(&mut stream); match err_status { Ok(()) => { successful_handshake = child_self.handle_possible_ws_request(request, &mut response); // Ensure that we actually do send a response: match response.try_write_headers() { Err(err) => { error!("Writing headers failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } }, Err(status) => { // Uh oh, it's a response that I as a server cannot cope with. // No good user-agent should have caused this, so for the moment // at least I am content to send no body in the response. response.status = status; response.headers.content_length = Some(0); match response.write_headers() { Err(err) => { error!("Writing headers failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } }, } // Ensure the request is flushed, any Transfer-Encoding completed, etc. match response.finish_response() { Err(err) => { error!("finishing response failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } if successful_handshake || close_connection { break; } } if successful_handshake { child_self.serve_websockets(stream).unwrap(); } }).detach(); } } fn serve_websockets(&self, stream: BufferedStream<TcpStream>) -> IoResult<()> { let mut stream = stream.wrapped; let write_stream = stream.clone(); let (in_sender, in_receiver) = channel(); let (out_sender, out_receiver) = channel(); self.handle_ws_connect(in_receiver, out_sender); // write task Thread::spawn(move || { // ugh: https://github.com/mozilla/rust/blob/3dbc1c34e694f38daeef741cfffc558606443c15/src/test/run-pass/kindck-implicit-close-over-mut-var.rs#L40-L44 // work to fix this is ongoing here: https://github.com/mozilla/rust/issues/11958 let mut write_stream = write_stream; loop { let message = out_receiver.recv().unwrap(); message.send(&mut write_stream).unwrap(); // fails this task in case of an error; FIXME make sure this fails the read (parent) task } }).detach(); // read task, effectively the parent of the write task loop { let message = Message::load(&mut stream).unwrap(); // fails the task if there's an error. debug!("message: {}", message); match message.opcode { CloseOp => { try!(stream.close_read()); try!(message.send(&mut stream)); // complete close handeshake - send the same message right back at the client try!(stream.close_write()); break; // as this task dies, this should release the write task above, as well as the task set up in handle_ws_connection, if any }, PingOp => { let pong = Message { payload: message.payload, opcode: PongOp }; try!(pong.send(&mut stream)); }, PongOp => (), _ => in_sender.send(message).unwrap() } } Ok(()) } fn sec_websocket_accept(&self, sec_websocket_key: &str) -> String { // NOTE from RFC 6455 // // To prove that the handshake was received, the server has to take two // pieces of information and combine them to form a response. The first // piece of information comes from the |Sec-WebSocket-Key| header field // in the client handshake: // // Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== // // For this header field, the server has to take the value (as present // in the header field, e.g., the base64-encoded [RFC4648] version minus // any leading and trailing whitespace) and concatenate this with the // Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA- // 95CA-C5AB0DC85B11" in string form, which is unlikely to be used by // network endpoints that do not understand the WebSocket Protocol. A // SHA-1 hash (160 bits) [FIPS.180-3], base64-encoded (see Section 4 of // [RFC4648]), of this concatenation is then returned in the server's // handshake. let mut sh = Sha1::new(); let mut out = [0u8; 20]; sh.input_str((String::from_str(sec_websocket_key) + WEBSOCKET_SALT).as_slice()); sh.result(out.as_mut_slice()); return out.to_base64(STANDARD); } // check if the http request is a web socket upgrade request, and return true if so. // otherwise, fall back on the regular http request handler fn handle_possible_ws_request(&self, r: Request, w: &mut ResponseWriter) -> bool { // TODO allow configuration of endpoint for websocket match (r.method.clone(), r.headers.upgrade.clone()){ // (&Get, &Some("websocket"), &Some(box [Token(box "Upgrade")])) => //\{ FIXME this doesn't work. but client must have the header "Connection: Upgrade" (Get, Some(ref upgrade)) => { if!upgrade.as_slice().eq_ignore_ascii_case("websocket"){ self.handle_request(r, w); return false; } // TODO client must have the header "Connection: Upgrade" // // TODO The request MUST include a header field with the name // |Sec-WebSocket-Version|. The value of this header field MUST be 13. // WebSocket Opening Handshake w.status = SwitchingProtocols; w.headers.upgrade = Some(String::from_str("websocket")); // w.headers.transfer_encoding = None; w.headers.content_length = Some(0); w.headers.connection = Some(vec!(Token(String::from_str("Upgrade")))); w.headers.date = Some(time::now_utc()); w.headers.server = Some(String::from_str("rust-ws/0.1-pre")); for header in r.headers.iter() { debug!("Header {}: {}", header.header_name(), header.header_value()); } // NOTE: think this is actually Sec-WebSocket-Key (capital Web[S]ocket), but rust-http normalizes header names match r.headers.extensions.get(&String::from_str("Sec-Websocket-Key")) { Some(val) => { let sec_websocket_accept = self.sec_websocket_accept((*val).as_slice()); w.headers.insert(ExtensionHeader(String::from_str("Sec-WebSocket-Accept"), sec_websocket_accept)); }, None => panic!() } return true; // successful_handshake }, (_, _) => self.handle_request(r, w) } return false; } }
{ let config = self.get_config(); debug!("About to bind to {}", config.bind_address); let mut acceptor = match TcpListener::bind((config.bind_address.ip.to_string().as_slice(), config.bind_address.port)).listen() { Err(err) => { error!("bind or listen failed :-(: {}", err); return; }, Ok(acceptor) => acceptor, }; debug!("listening"); loop { let stream = match acceptor.accept() { Err(error) => { debug!("accept failed: {}", error); // Question: is this the correct thing to do? We should probably be more // intelligent, for there are some accept failures that are likely to be // permanent, such that continuing would be a very bad idea, such as // ENOBUFS/ENOMEM; and some where it should just be ignored, e.g. // ECONNABORTED. TODO.
identifier_body
server.rs
use std::io::IoResult; use crypto::sha1::Sha1; use crypto::digest::Digest; use serialize::base64::{ToBase64, STANDARD}; use std::ascii::AsciiExt; use time; use std::io::{Listener, Acceptor}; use std::io::net::tcp::TcpListener; use std::io::net::tcp::TcpStream; use http::buffer::BufferedStream; use std::thread::Thread; use std::sync::mpsc::{channel, Sender, Receiver}; use http::server::{Server, Request, ResponseWriter}; use http::status::SwitchingProtocols; use http::headers::HeaderEnum; use http::headers::response::Header::ExtensionHeader; use http::headers::connection::Connection::Token; use http::method::Method::Get; pub use message::Payload::{Text, Binary, Empty}; pub use message::Opcode::{ContinuationOp, TextOp, BinaryOp, CloseOp, PingOp, PongOp}; use message::Message; static WEBSOCKET_SALT: &'static str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; pub trait WebSocketServer: Server { // called when a web socket connection is successfully established. // // this can't block! leaving implementation to trait user, in case they // want to custom scheduling, tracking clients, reconnect logic, etc. // // TODO: may want to send more info in, such as the connecting IP address? fn handle_ws_connect(&self, receiver: Receiver<Box<Message>>, sender: Sender<Box<Message>>) -> (); // XXX: this is mostly a copy of the serve_forever fn in the Server trait. // rust-http needs some changes in order to avoid this duplication fn ws_serve_forever(self) { let config = self.get_config(); debug!("About to bind to {}", config.bind_address); let mut acceptor = match TcpListener::bind((config.bind_address.ip.to_string().as_slice(), config.bind_address.port)).listen() { Err(err) => { error!("bind or listen failed :-(: {}", err); return; }, Ok(acceptor) => acceptor, }; debug!("listening"); loop { let stream = match acceptor.accept() { Err(error) => { debug!("accept failed: {}", error); // Question: is this the correct thing to do? We should probably be more // intelligent, for there are some accept failures that are likely to be // permanent, such that continuing would be a very bad idea, such as // ENOBUFS/ENOMEM; and some where it should just be ignored, e.g. // ECONNABORTED. TODO. continue; }, Ok(socket) => socket, }; let child_self = self.clone(); Thread::spawn(move || { let mut stream = BufferedStream::new(stream); debug!("accepted connection"); let mut successful_handshake = false; loop { // A keep-alive loop, condition at end let (request, err_status) = Request::load(&mut stream); let close_connection = request.close_connection; let mut response = ResponseWriter::new(&mut stream); match err_status { Ok(()) => { successful_handshake = child_self.handle_possible_ws_request(request, &mut response); // Ensure that we actually do send a response: match response.try_write_headers() { Err(err) => { error!("Writing headers failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } }, Err(status) => { // Uh oh, it's a response that I as a server cannot cope with. // No good user-agent should have caused this, so for the moment // at least I am content to send no body in the response. response.status = status; response.headers.content_length = Some(0); match response.write_headers() { Err(err) => { error!("Writing headers failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } }, } // Ensure the request is flushed, any Transfer-Encoding completed, etc. match response.finish_response() { Err(err) => { error!("finishing response failed: {}", err); return; // Presumably bad connection, so give up. }, Ok(_) => (), } if successful_handshake || close_connection { break; } } if successful_handshake { child_self.serve_websockets(stream).unwrap(); } }).detach(); } } fn serve_websockets(&self, stream: BufferedStream<TcpStream>) -> IoResult<()> { let mut stream = stream.wrapped; let write_stream = stream.clone(); let (in_sender, in_receiver) = channel(); let (out_sender, out_receiver) = channel(); self.handle_ws_connect(in_receiver, out_sender); // write task Thread::spawn(move || { // ugh: https://github.com/mozilla/rust/blob/3dbc1c34e694f38daeef741cfffc558606443c15/src/test/run-pass/kindck-implicit-close-over-mut-var.rs#L40-L44 // work to fix this is ongoing here: https://github.com/mozilla/rust/issues/11958 let mut write_stream = write_stream; loop { let message = out_receiver.recv().unwrap(); message.send(&mut write_stream).unwrap(); // fails this task in case of an error; FIXME make sure this fails the read (parent) task } }).detach(); // read task, effectively the parent of the write task loop { let message = Message::load(&mut stream).unwrap(); // fails the task if there's an error. debug!("message: {}", message); match message.opcode { CloseOp => { try!(stream.close_read()); try!(message.send(&mut stream)); // complete close handeshake - send the same message right back at the client try!(stream.close_write()); break; // as this task dies, this should release the write task above, as well as the task set up in handle_ws_connection, if any }, PingOp => { let pong = Message { payload: message.payload, opcode: PongOp }; try!(pong.send(&mut stream)); }, PongOp => (), _ => in_sender.send(message).unwrap() } } Ok(()) } fn
(&self, sec_websocket_key: &str) -> String { // NOTE from RFC 6455 // // To prove that the handshake was received, the server has to take two // pieces of information and combine them to form a response. The first // piece of information comes from the |Sec-WebSocket-Key| header field // in the client handshake: // // Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== // // For this header field, the server has to take the value (as present // in the header field, e.g., the base64-encoded [RFC4648] version minus // any leading and trailing whitespace) and concatenate this with the // Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA- // 95CA-C5AB0DC85B11" in string form, which is unlikely to be used by // network endpoints that do not understand the WebSocket Protocol. A // SHA-1 hash (160 bits) [FIPS.180-3], base64-encoded (see Section 4 of // [RFC4648]), of this concatenation is then returned in the server's // handshake. let mut sh = Sha1::new(); let mut out = [0u8; 20]; sh.input_str((String::from_str(sec_websocket_key) + WEBSOCKET_SALT).as_slice()); sh.result(out.as_mut_slice()); return out.to_base64(STANDARD); } // check if the http request is a web socket upgrade request, and return true if so. // otherwise, fall back on the regular http request handler fn handle_possible_ws_request(&self, r: Request, w: &mut ResponseWriter) -> bool { // TODO allow configuration of endpoint for websocket match (r.method.clone(), r.headers.upgrade.clone()){ // (&Get, &Some("websocket"), &Some(box [Token(box "Upgrade")])) => //\{ FIXME this doesn't work. but client must have the header "Connection: Upgrade" (Get, Some(ref upgrade)) => { if!upgrade.as_slice().eq_ignore_ascii_case("websocket"){ self.handle_request(r, w); return false; } // TODO client must have the header "Connection: Upgrade" // // TODO The request MUST include a header field with the name // |Sec-WebSocket-Version|. The value of this header field MUST be 13. // WebSocket Opening Handshake w.status = SwitchingProtocols; w.headers.upgrade = Some(String::from_str("websocket")); // w.headers.transfer_encoding = None; w.headers.content_length = Some(0); w.headers.connection = Some(vec!(Token(String::from_str("Upgrade")))); w.headers.date = Some(time::now_utc()); w.headers.server = Some(String::from_str("rust-ws/0.1-pre")); for header in r.headers.iter() { debug!("Header {}: {}", header.header_name(), header.header_value()); } // NOTE: think this is actually Sec-WebSocket-Key (capital Web[S]ocket), but rust-http normalizes header names match r.headers.extensions.get(&String::from_str("Sec-Websocket-Key")) { Some(val) => { let sec_websocket_accept = self.sec_websocket_accept((*val).as_slice()); w.headers.insert(ExtensionHeader(String::from_str("Sec-WebSocket-Accept"), sec_websocket_accept)); }, None => panic!() } return true; // successful_handshake }, (_, _) => self.handle_request(r, w) } return false; } }
sec_websocket_accept
identifier_name
gametime.rs
extern crate time;
#[allow(dead_code)] impl GameTime { pub fn new() -> GameTime { let now = time::get_time(); GameTime { prev_frame_time: now, curr_frame_time: now, } } pub fn reset(&mut self) { let now = time::get_time(); self.prev_frame_time = now; self.curr_frame_time = now; } pub fn update(&mut self) { self.prev_frame_time = self.curr_frame_time; self.curr_frame_time = time::get_time(); } pub fn delta(self) -> time::Duration { self.curr_frame_time - self.prev_frame_time } pub fn dt(self) -> f32 { (self.delta().num_nanoseconds().unwrap() as f32) / 1_000_000_000_f32 } }
#[derive(Debug, Clone, Copy)] pub struct GameTime { prev_frame_time: time::Timespec, curr_frame_time: time::Timespec, }
random_line_split
gametime.rs
extern crate time; #[derive(Debug, Clone, Copy)] pub struct GameTime { prev_frame_time: time::Timespec, curr_frame_time: time::Timespec, } #[allow(dead_code)] impl GameTime { pub fn new() -> GameTime { let now = time::get_time(); GameTime { prev_frame_time: now, curr_frame_time: now, } } pub fn reset(&mut self) { let now = time::get_time(); self.prev_frame_time = now; self.curr_frame_time = now; } pub fn update(&mut self) { self.prev_frame_time = self.curr_frame_time; self.curr_frame_time = time::get_time(); } pub fn
(self) -> time::Duration { self.curr_frame_time - self.prev_frame_time } pub fn dt(self) -> f32 { (self.delta().num_nanoseconds().unwrap() as f32) / 1_000_000_000_f32 } }
delta
identifier_name
gametime.rs
extern crate time; #[derive(Debug, Clone, Copy)] pub struct GameTime { prev_frame_time: time::Timespec, curr_frame_time: time::Timespec, } #[allow(dead_code)] impl GameTime { pub fn new() -> GameTime { let now = time::get_time(); GameTime { prev_frame_time: now, curr_frame_time: now, } } pub fn reset(&mut self) { let now = time::get_time(); self.prev_frame_time = now; self.curr_frame_time = now; } pub fn update(&mut self)
pub fn delta(self) -> time::Duration { self.curr_frame_time - self.prev_frame_time } pub fn dt(self) -> f32 { (self.delta().num_nanoseconds().unwrap() as f32) / 1_000_000_000_f32 } }
{ self.prev_frame_time = self.curr_frame_time; self.curr_frame_time = time::get_time(); }
identifier_body
capabilities.rs
use caps::*; use oci::{LinuxCapabilities, LinuxCapabilityType}; fn to_cap(cap: LinuxCapabilityType) -> Capability { unsafe { ::std::mem::transmute(cap) } } fn to_set(caps: &[LinuxCapabilityType]) -> CapsHashSet { let mut capabilities = CapsHashSet::new(); for c in caps { capabilities.insert(to_cap(*c)); }
pub fn reset_effective() -> ::Result<()> { let mut all = CapsHashSet::new(); for c in Capability::iter_variants() { all.insert(c); } set(None, CapSet::Effective, all)?; Ok(()) } pub fn drop_privileges(cs: &LinuxCapabilities) -> ::Result<()> { let mut all = CapsHashSet::new(); for c in Capability::iter_variants() { all.insert(c); } debug!("dropping bounding capabilities to {:?}", cs.bounding); // drop excluded caps from the bounding set for c in all.difference(&to_set(&cs.bounding)) { drop(None, CapSet::Bounding, *c)?; } // set other sets for current process set(None, CapSet::Effective, to_set(&cs.effective))?; set(None, CapSet::Permitted, to_set(&cs.permitted))?; set(None, CapSet::Inheritable, to_set(&cs.inheritable))?; set(None, CapSet::Ambient, to_set(&cs.ambient))?; Ok(()) }
capabilities }
random_line_split
capabilities.rs
use caps::*; use oci::{LinuxCapabilities, LinuxCapabilityType}; fn to_cap(cap: LinuxCapabilityType) -> Capability { unsafe { ::std::mem::transmute(cap) } } fn to_set(caps: &[LinuxCapabilityType]) -> CapsHashSet { let mut capabilities = CapsHashSet::new(); for c in caps { capabilities.insert(to_cap(*c)); } capabilities } pub fn
() -> ::Result<()> { let mut all = CapsHashSet::new(); for c in Capability::iter_variants() { all.insert(c); } set(None, CapSet::Effective, all)?; Ok(()) } pub fn drop_privileges(cs: &LinuxCapabilities) -> ::Result<()> { let mut all = CapsHashSet::new(); for c in Capability::iter_variants() { all.insert(c); } debug!("dropping bounding capabilities to {:?}", cs.bounding); // drop excluded caps from the bounding set for c in all.difference(&to_set(&cs.bounding)) { drop(None, CapSet::Bounding, *c)?; } // set other sets for current process set(None, CapSet::Effective, to_set(&cs.effective))?; set(None, CapSet::Permitted, to_set(&cs.permitted))?; set(None, CapSet::Inheritable, to_set(&cs.inheritable))?; set(None, CapSet::Ambient, to_set(&cs.ambient))?; Ok(()) }
reset_effective
identifier_name
capabilities.rs
use caps::*; use oci::{LinuxCapabilities, LinuxCapabilityType}; fn to_cap(cap: LinuxCapabilityType) -> Capability { unsafe { ::std::mem::transmute(cap) } } fn to_set(caps: &[LinuxCapabilityType]) -> CapsHashSet { let mut capabilities = CapsHashSet::new(); for c in caps { capabilities.insert(to_cap(*c)); } capabilities } pub fn reset_effective() -> ::Result<()> { let mut all = CapsHashSet::new(); for c in Capability::iter_variants() { all.insert(c); } set(None, CapSet::Effective, all)?; Ok(()) } pub fn drop_privileges(cs: &LinuxCapabilities) -> ::Result<()>
{ let mut all = CapsHashSet::new(); for c in Capability::iter_variants() { all.insert(c); } debug!("dropping bounding capabilities to {:?}", cs.bounding); // drop excluded caps from the bounding set for c in all.difference(&to_set(&cs.bounding)) { drop(None, CapSet::Bounding, *c)?; } // set other sets for current process set(None, CapSet::Effective, to_set(&cs.effective))?; set(None, CapSet::Permitted, to_set(&cs.permitted))?; set(None, CapSet::Inheritable, to_set(&cs.inheritable))?; set(None, CapSet::Ambient, to_set(&cs.ambient))?; Ok(()) }
identifier_body
issue-15149.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::{TempDir, Command, fs}; use std::os; fn main() { // If we're the child, make sure we were invoked correctly let args = os::args(); if args.len() > 1 && args[1].as_slice() == "child" { return assert_eq!(args[0].as_slice(), "mytest"); } test(); } fn test() { // If we're the parent, copy our own binary to a tempr directory, and then // make it executable. let dir = TempDir::new("mytest").unwrap();
fs::copy(&me, &dest).unwrap(); // Append the temp directory to our own PATH. let mut path = os::split_paths(os::getenv("PATH").unwrap_or(String::new())); path.push(dir.path().clone()); let path = os::join_paths(path.as_slice()).unwrap(); Command::new("mytest").env("PATH", path.as_slice()) .arg("child") .spawn().unwrap(); }
let me = os::self_exe_name().unwrap(); let dest = dir.path().join(format!("mytest{}", os::consts::EXE_SUFFIX));
random_line_split
issue-15149.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::{TempDir, Command, fs}; use std::os; fn main() { // If we're the child, make sure we were invoked correctly let args = os::args(); if args.len() > 1 && args[1].as_slice() == "child" { return assert_eq!(args[0].as_slice(), "mytest"); } test(); } fn test()
{ // If we're the parent, copy our own binary to a tempr directory, and then // make it executable. let dir = TempDir::new("mytest").unwrap(); let me = os::self_exe_name().unwrap(); let dest = dir.path().join(format!("mytest{}", os::consts::EXE_SUFFIX)); fs::copy(&me, &dest).unwrap(); // Append the temp directory to our own PATH. let mut path = os::split_paths(os::getenv("PATH").unwrap_or(String::new())); path.push(dir.path().clone()); let path = os::join_paths(path.as_slice()).unwrap(); Command::new("mytest").env("PATH", path.as_slice()) .arg("child") .spawn().unwrap(); }
identifier_body
issue-15149.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::{TempDir, Command, fs}; use std::os; fn main() { // If we're the child, make sure we were invoked correctly let args = os::args(); if args.len() > 1 && args[1].as_slice() == "child"
test(); } fn test() { // If we're the parent, copy our own binary to a tempr directory, and then // make it executable. let dir = TempDir::new("mytest").unwrap(); let me = os::self_exe_name().unwrap(); let dest = dir.path().join(format!("mytest{}", os::consts::EXE_SUFFIX)); fs::copy(&me, &dest).unwrap(); // Append the temp directory to our own PATH. let mut path = os::split_paths(os::getenv("PATH").unwrap_or(String::new())); path.push(dir.path().clone()); let path = os::join_paths(path.as_slice()).unwrap(); Command::new("mytest").env("PATH", path.as_slice()) .arg("child") .spawn().unwrap(); }
{ return assert_eq!(args[0].as_slice(), "mytest"); }
conditional_block
issue-15149.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::{TempDir, Command, fs}; use std::os; fn
() { // If we're the child, make sure we were invoked correctly let args = os::args(); if args.len() > 1 && args[1].as_slice() == "child" { return assert_eq!(args[0].as_slice(), "mytest"); } test(); } fn test() { // If we're the parent, copy our own binary to a tempr directory, and then // make it executable. let dir = TempDir::new("mytest").unwrap(); let me = os::self_exe_name().unwrap(); let dest = dir.path().join(format!("mytest{}", os::consts::EXE_SUFFIX)); fs::copy(&me, &dest).unwrap(); // Append the temp directory to our own PATH. let mut path = os::split_paths(os::getenv("PATH").unwrap_or(String::new())); path.push(dir.path().clone()); let path = os::join_paths(path.as_slice()).unwrap(); Command::new("mytest").env("PATH", path.as_slice()) .arg("child") .spawn().unwrap(); }
main
identifier_name
main.rs
{ version: String, name: String, // path to the extracted sources that clippy can check path: PathBuf, options: Option<Vec<String>>, } /// A single warning that clippy issued while checking a `Crate` #[derive(Debug)] struct ClippyWarning { crate_name: String, crate_version: String, file: String, line: String, column: String, linttype: String, message: String, is_ice: bool, } impl std::fmt::Display for ClippyWarning { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, r#"target/lintcheck/sources/{}-{}/{}:{}:{} {} "{}""#, &self.crate_name, &self.crate_version, &self.file, &self.line, &self.column, &self.linttype, &self.message ) } } impl CrateSource { /// Makes the sources available on the disk for clippy to check. /// Clones a git repo and checks out the specified commit or downloads a crate from crates.io or /// copies a local folder fn download_and_extract(&self) -> Crate { match self { CrateSource::CratesIo { name, version, options } => { let extract_dir = PathBuf::from(LINTCHECK_SOURCES); let krate_download_dir = PathBuf::from(LINTCHECK_DOWNLOADS); // url to download the crate from crates.io let url = format!("https://crates.io/api/v1/crates/{}/{}/download", name, version); println!("Downloading and extracting {} {} from {}", name, version, url); create_dirs(&krate_download_dir, &extract_dir); let krate_file_path = krate_download_dir.join(format!("{}-{}.crate.tar.gz", name, version)); // don't download/extract if we already have done so if!krate_file_path.is_file() { // create a file path to download and write the crate data into let mut krate_dest = std::fs::File::create(&krate_file_path).unwrap(); let mut krate_req = ureq::get(&url).call().unwrap().into_reader(); // copy the crate into the file std::io::copy(&mut krate_req, &mut krate_dest).unwrap(); // unzip the tarball let ungz_tar = flate2::read::GzDecoder::new(std::fs::File::open(&krate_file_path).unwrap()); // extract the tar archive let mut archive = tar::Archive::new(ungz_tar); archive.unpack(&extract_dir).expect("Failed to extract!"); } // crate is extracted, return a new Krate object which contains the path to the extracted // sources that clippy can check Crate { version: version.clone(), name: name.clone(), path: extract_dir.join(format!("{}-{}/", name, version)), options: options.clone(), } }, CrateSource::Git { name, url, commit, options, } => { let repo_path = { let mut repo_path = PathBuf::from(LINTCHECK_SOURCES); // add a -git suffix in case we have the same crate from crates.io and a git repo repo_path.push(format!("{}-git", name)); repo_path }; // clone the repo if we have not done so if!repo_path.is_dir() { println!("Cloning {} and checking out {}", url, commit); if!Command::new("git") .arg("clone") .arg(url) .arg(&repo_path) .status() .expect("Failed to clone git repo!") .success() { eprintln!("Failed to clone {} into {}", url, repo_path.display()) } } // check out the commit/branch/whatever if!Command::new("git") .arg("checkout") .arg(commit) .current_dir(&repo_path) .status() .expect("Failed to check out commit") .success() { eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display()) } Crate { version: commit.clone(), name: name.clone(), path: repo_path, options: options.clone(), } }, CrateSource::Path { name, path, options } => { use fs_extra::dir; // simply copy the entire directory into our target dir let copy_dest = PathBuf::from(format!("{}/", LINTCHECK_SOURCES)); // the source path of the crate we copied, ${copy_dest}/crate_name let crate_root = copy_dest.join(name); //.../crates/local_crate if crate_root.exists() { println!( "Not copying {} to {}, destination already exists", path.display(), crate_root.display() ); } else { println!("Copying {} to {}", path.display(), copy_dest.display()); dir::copy(path, &copy_dest, &dir::CopyOptions::new()).unwrap_or_else(|_| { panic!("Failed to copy from {}, to {}", path.display(), crate_root.display()) }); } Crate { version: String::from("local"), name: name.clone(), path: crate_root, options: options.clone(), } }, } } } impl Crate { /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy /// issued fn run_clippy_lints( &self, cargo_clippy_path: &Path, target_dir_index: &AtomicUsize, thread_limit: usize, total_crates_to_lint: usize, fix: bool, ) -> Vec<ClippyWarning> { // advance the atomic index by one let index = target_dir_index.fetch_add(1, Ordering::SeqCst); // "loop" the index within 0..thread_limit let thread_index = index % thread_limit; let perc = (index * 100) / total_crates_to_lint; if thread_limit == 1 { println!( "{}/{} {}% Linting {} {}", index, total_crates_to_lint, perc, &self.name, &self.version ); } else { println!( "{}/{} {}% Linting {} {} in target dir {:?}", index, total_crates_to_lint, perc, &self.name, &self.version, thread_index ); } let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap(); let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir"); let mut args = if fix { vec!["--fix", "--allow-no-vcs", "--", "--cap-lints=warn"] } else { vec!["--", "--message-format=json", "--", "--cap-lints=warn"] }; if let Some(options) = &self.options { for opt in options { args.push(opt); } } else { args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"]) } let all_output = std::process::Command::new(&cargo_clippy_path) // use the looping index to create individual target dirs .env( "CARGO_TARGET_DIR", shared_target_dir.join(format!("_{:?}", thread_index)), ) // lint warnings will look like this: // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter` .args(&args) .current_dir(&self.path) .output() .unwrap_or_else(|error| { panic!( "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n", error, &cargo_clippy_path.display(), &self.path.display() ); }); let stdout = String::from_utf8_lossy(&all_output.stdout); let stderr = String::from_utf8_lossy(&all_output.stderr); let status = &all_output.status; if!status.success() { eprintln!( "\nWARNING: bad exit status after checking {} {} \n", self.name, self.version ); } if fix { if let Some(stderr) = stderr .lines() .find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate")) { let subcrate = &stderr[63..]; println!( "ERROR: failed to apply some suggetion to {} / to (sub)crate {}", self.name, subcrate ); } // fast path, we don't need the warnings anyway return Vec::new(); } let output_lines = stdout.lines(); let warnings: Vec<ClippyWarning> = output_lines .into_iter() // get all clippy warnings and ICEs .filter(|line| filter_clippy_warnings(&line)) .map(|json_msg| parse_json_message(json_msg, &self)) .collect(); warnings } } #[derive(Debug)] struct LintcheckConfig { // max number of jobs to spawn (default 1) max_jobs: usize, // we read the sources to check from here sources_toml_path: PathBuf, // we save the clippy lint results here lintcheck_results_path: PathBuf, // whether to just run --fix and not collect all the warnings fix: bool, } impl LintcheckConfig { fn from_clap(clap_config: &ArgMatches) -> Self { // first, check if we got anything passed via the LINTCHECK_TOML env var, // if not, ask clap if we got any value for --crates-toml <foo> // if not, use the default "lintcheck/lintcheck_crates.toml" let sources_toml = env::var("LINTCHECK_TOML").unwrap_or_else(|_| { clap_config .value_of("crates-toml") .clone() .unwrap_or("lintcheck/lintcheck_crates.toml") .to_string() }); let sources_toml_path = PathBuf::from(sources_toml); // for the path where we save the lint results, get the filename without extension (so for // wasd.toml, use "wasd"...) let filename: PathBuf = sources_toml_path.file_stem().unwrap().into(); let lintcheck_results_path = PathBuf::from(format!("lintcheck-logs/{}_logs.txt", filename.display())); // look at the --threads arg, if 0 is passed, ask rayon rayon how many threads it would spawn and // use half of that for the physical core count // by default use a single thread let max_jobs = match clap_config.value_of("threads") { Some(threads) => { let threads: usize = threads .parse() .unwrap_or_else(|_| panic!("Failed to parse '{}' to a digit", threads)); if threads == 0 { // automatic choice // Rayon seems to return thread count so half that for core count (rayon::current_num_threads() / 2) as usize } else { threads } }, // no -j passed, use a single thread None => 1, }; let fix: bool = clap_config.is_present("fix"); LintcheckConfig { max_jobs, sources_toml_path, lintcheck_results_path, fix, } } } /// takes a single json-formatted clippy warnings and returns true (we are interested in that line) /// or false (we aren't) fn filter_clippy_warnings(line: &str) -> bool { // we want to collect ICEs because clippy might have crashed. // these are summarized later if line.contains("internal compiler error: ") { return true; } // in general, we want all clippy warnings // however due to some kind of bug, sometimes there are absolute paths // to libcore files inside the message // or we end up with cargo-metadata output (https://github.com/rust-lang/rust-clippy/issues/6508) // filter out these message to avoid unnecessary noise in the logs if line.contains("clippy::") &&!(line.contains("could not read cargo metadata") || (line.contains(".rustup") && line.contains("toolchains"))) { return true; } false } /// Builds clippy inside the repo to make sure we have a clippy executable we can use. fn build_clippy() { let status = Command::new("cargo") .arg("build") .status() .expect("Failed to build clippy!"); if!status.success() { eprintln!("Error: Failed to compile Clippy!"); std::process::exit(1); } } /// Read a `toml` file and return a list of `CrateSources` that we want to check with clippy fn read_crates(toml_path: &Path) -> Vec<CrateSource> { let toml_content: String = std::fs::read_to_string(&toml_path).unwrap_or_else(|_| panic!("Failed to read {}", toml_path.display())); let crate_list: SourceList = toml::from_str(&toml_content).unwrap_or_else(|e| panic!("Failed to parse {}: \n{}", toml_path.display(), e)); // parse the hashmap of the toml file into a list of crates let tomlcrates: Vec<TomlCrate> = crate_list .crates .into_iter() .map(|(_cratename, tomlcrate)| tomlcrate) .collect(); // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate => // multiple Cratesources) let mut crate_sources = Vec::new(); tomlcrates.into_iter().for_each(|tk| { if let Some(ref path) = tk.path { crate_sources.push(CrateSource::Path { name: tk.name.clone(), path: PathBuf::from(path), options: tk.options.clone(), }); } // if we have multiple versions, save each one if let Some(ref versions) = tk.versions { versions.iter().for_each(|ver| { crate_sources.push(CrateSource::CratesIo { name: tk.name.clone(), version: ver.to_string(), options: tk.options.clone(), }); }) } // otherwise, we should have a git source if tk.git_url.is_some() && tk.git_hash.is_some() { crate_sources.push(CrateSource::Git { name: tk.name.clone(), url: tk.git_url.clone().unwrap(), commit: tk.git_hash.clone().unwrap(), options: tk.options.clone(), }); } // if we have a version as well as a git data OR only one git data, something is funky if tk.versions.is_some() && (tk.git_url.is_some() || tk.git_hash.is_some()) || tk.git_hash.is_some()!= tk.git_url.is_some() { eprintln!("tomlkrate: {:?}", tk); if tk.git_hash.is_some()!= tk.git_url.is_some() { panic!("Error: Encountered TomlCrate with only one of git_hash and git_url!"); } if tk.path.is_some() && (tk.git_hash.is_some() || tk.versions.is_some()) { panic!("Error: TomlCrate can only have one of 'git_.*','version' or 'path' fields"); } unreachable!("Failed to translate TomlCrate into CrateSource!"); } }); // sort the crates crate_sources.sort(); crate_sources } /// Parse the json output of clippy and return a `ClippyWarning` fn parse_json_message(json_message: &str, krate: &Crate) -> ClippyWarning { let jmsg: Value = serde_json::from_str(&json_message).unwrap_or_else(|e| panic!("Failed to parse json:\n{:?}", e)); let file: String = jmsg["message"]["spans"][0]["file_name"] .to_string() .trim_matches('"') .into(); let file = if file.contains(".cargo") { // if we deal with macros, a filename may show the origin of a macro which can be inside a dep from // the registry. // don't show the full path in that case. // /home/matthias/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.63/src/custom_keyword.rs let path = PathBuf::from(file); let mut piter = path.iter(); // consume all elements until we find ".cargo", so that "/home/matthias" is skipped let _: Option<&OsStr> = piter.find(|x| x == &std::ffi::OsString::from(".cargo")); // collect the remaining segments let file = piter.collect::<PathBuf>(); format!("{}", file.display()) } else { file }; ClippyWarning { crate
Crate
identifier_name
main.rs
}, CrateSource::Git { name, url, commit, options, } => { let repo_path = { let mut repo_path = PathBuf::from(LINTCHECK_SOURCES); // add a -git suffix in case we have the same crate from crates.io and a git repo repo_path.push(format!("{}-git", name)); repo_path }; // clone the repo if we have not done so if!repo_path.is_dir() { println!("Cloning {} and checking out {}", url, commit); if!Command::new("git") .arg("clone") .arg(url) .arg(&repo_path) .status() .expect("Failed to clone git repo!") .success() { eprintln!("Failed to clone {} into {}", url, repo_path.display()) } } // check out the commit/branch/whatever if!Command::new("git") .arg("checkout") .arg(commit) .current_dir(&repo_path) .status() .expect("Failed to check out commit") .success() { eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display()) } Crate { version: commit.clone(), name: name.clone(), path: repo_path, options: options.clone(), } }, CrateSource::Path { name, path, options } => { use fs_extra::dir; // simply copy the entire directory into our target dir let copy_dest = PathBuf::from(format!("{}/", LINTCHECK_SOURCES)); // the source path of the crate we copied, ${copy_dest}/crate_name let crate_root = copy_dest.join(name); //.../crates/local_crate if crate_root.exists() { println!( "Not copying {} to {}, destination already exists", path.display(), crate_root.display() ); } else { println!("Copying {} to {}", path.display(), copy_dest.display()); dir::copy(path, &copy_dest, &dir::CopyOptions::new()).unwrap_or_else(|_| { panic!("Failed to copy from {}, to {}", path.display(), crate_root.display()) }); } Crate { version: String::from("local"), name: name.clone(), path: crate_root, options: options.clone(), } }, } } } impl Crate { /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy /// issued fn run_clippy_lints( &self, cargo_clippy_path: &Path, target_dir_index: &AtomicUsize, thread_limit: usize, total_crates_to_lint: usize, fix: bool, ) -> Vec<ClippyWarning> { // advance the atomic index by one let index = target_dir_index.fetch_add(1, Ordering::SeqCst); // "loop" the index within 0..thread_limit let thread_index = index % thread_limit; let perc = (index * 100) / total_crates_to_lint; if thread_limit == 1 { println!( "{}/{} {}% Linting {} {}", index, total_crates_to_lint, perc, &self.name, &self.version ); } else { println!( "{}/{} {}% Linting {} {} in target dir {:?}", index, total_crates_to_lint, perc, &self.name, &self.version, thread_index ); } let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap(); let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir"); let mut args = if fix { vec!["--fix", "--allow-no-vcs", "--", "--cap-lints=warn"] } else { vec!["--", "--message-format=json", "--", "--cap-lints=warn"] }; if let Some(options) = &self.options
else { args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"]) } let all_output = std::process::Command::new(&cargo_clippy_path) // use the looping index to create individual target dirs .env( "CARGO_TARGET_DIR", shared_target_dir.join(format!("_{:?}", thread_index)), ) // lint warnings will look like this: // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter` .args(&args) .current_dir(&self.path) .output() .unwrap_or_else(|error| { panic!( "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n", error, &cargo_clippy_path.display(), &self.path.display() ); }); let stdout = String::from_utf8_lossy(&all_output.stdout); let stderr = String::from_utf8_lossy(&all_output.stderr); let status = &all_output.status; if!status.success() { eprintln!( "\nWARNING: bad exit status after checking {} {} \n", self.name, self.version ); } if fix { if let Some(stderr) = stderr .lines() .find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate")) { let subcrate = &stderr[63..]; println!( "ERROR: failed to apply some suggetion to {} / to (sub)crate {}", self.name, subcrate ); } // fast path, we don't need the warnings anyway return Vec::new(); } let output_lines = stdout.lines(); let warnings: Vec<ClippyWarning> = output_lines .into_iter() // get all clippy warnings and ICEs .filter(|line| filter_clippy_warnings(&line)) .map(|json_msg| parse_json_message(json_msg, &self)) .collect(); warnings } } #[derive(Debug)] struct LintcheckConfig { // max number of jobs to spawn (default 1) max_jobs: usize, // we read the sources to check from here sources_toml_path: PathBuf, // we save the clippy lint results here lintcheck_results_path: PathBuf, // whether to just run --fix and not collect all the warnings fix: bool, } impl LintcheckConfig { fn from_clap(clap_config: &ArgMatches) -> Self { // first, check if we got anything passed via the LINTCHECK_TOML env var, // if not, ask clap if we got any value for --crates-toml <foo> // if not, use the default "lintcheck/lintcheck_crates.toml" let sources_toml = env::var("LINTCHECK_TOML").unwrap_or_else(|_| { clap_config .value_of("crates-toml") .clone() .unwrap_or("lintcheck/lintcheck_crates.toml") .to_string() }); let sources_toml_path = PathBuf::from(sources_toml); // for the path where we save the lint results, get the filename without extension (so for // wasd.toml, use "wasd"...) let filename: PathBuf = sources_toml_path.file_stem().unwrap().into(); let lintcheck_results_path = PathBuf::from(format!("lintcheck-logs/{}_logs.txt", filename.display())); // look at the --threads arg, if 0 is passed, ask rayon rayon how many threads it would spawn and // use half of that for the physical core count // by default use a single thread let max_jobs = match clap_config.value_of("threads") { Some(threads) => { let threads: usize = threads .parse() .unwrap_or_else(|_| panic!("Failed to parse '{}' to a digit", threads)); if threads == 0 { // automatic choice // Rayon seems to return thread count so half that for core count (rayon::current_num_threads() / 2) as usize } else { threads } }, // no -j passed, use a single thread None => 1, }; let fix: bool = clap_config.is_present("fix"); LintcheckConfig { max_jobs, sources_toml_path, lintcheck_results_path, fix, } } } /// takes a single json-formatted clippy warnings and returns true (we are interested in that line) /// or false (we aren't) fn filter_clippy_warnings(line: &str) -> bool { // we want to collect ICEs because clippy might have crashed. // these are summarized later if line.contains("internal compiler error: ") { return true; } // in general, we want all clippy warnings // however due to some kind of bug, sometimes there are absolute paths // to libcore files inside the message // or we end up with cargo-metadata output (https://github.com/rust-lang/rust-clippy/issues/6508) // filter out these message to avoid unnecessary noise in the logs if line.contains("clippy::") &&!(line.contains("could not read cargo metadata") || (line.contains(".rustup") && line.contains("toolchains"))) { return true; } false } /// Builds clippy inside the repo to make sure we have a clippy executable we can use. fn build_clippy() { let status = Command::new("cargo") .arg("build") .status() .expect("Failed to build clippy!"); if!status.success() { eprintln!("Error: Failed to compile Clippy!"); std::process::exit(1); } } /// Read a `toml` file and return a list of `CrateSources` that we want to check with clippy fn read_crates(toml_path: &Path) -> Vec<CrateSource> { let toml_content: String = std::fs::read_to_string(&toml_path).unwrap_or_else(|_| panic!("Failed to read {}", toml_path.display())); let crate_list: SourceList = toml::from_str(&toml_content).unwrap_or_else(|e| panic!("Failed to parse {}: \n{}", toml_path.display(), e)); // parse the hashmap of the toml file into a list of crates let tomlcrates: Vec<TomlCrate> = crate_list .crates .into_iter() .map(|(_cratename, tomlcrate)| tomlcrate) .collect(); // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate => // multiple Cratesources) let mut crate_sources = Vec::new(); tomlcrates.into_iter().for_each(|tk| { if let Some(ref path) = tk.path { crate_sources.push(CrateSource::Path { name: tk.name.clone(), path: PathBuf::from(path), options: tk.options.clone(), }); } // if we have multiple versions, save each one if let Some(ref versions) = tk.versions { versions.iter().for_each(|ver| { crate_sources.push(CrateSource::CratesIo { name: tk.name.clone(), version: ver.to_string(), options: tk.options.clone(), }); }) } // otherwise, we should have a git source if tk.git_url.is_some() && tk.git_hash.is_some() { crate_sources.push(CrateSource::Git { name: tk.name.clone(), url: tk.git_url.clone().unwrap(), commit: tk.git_hash.clone().unwrap(), options: tk.options.clone(), }); } // if we have a version as well as a git data OR only one git data, something is funky if tk.versions.is_some() && (tk.git_url.is_some() || tk.git_hash.is_some()) || tk.git_hash.is_some()!= tk.git_url.is_some() { eprintln!("tomlkrate: {:?}", tk); if tk.git_hash.is_some()!= tk.git_url.is_some() { panic!("Error: Encountered TomlCrate with only one of git_hash and git_url!"); } if tk.path.is_some() && (tk.git_hash.is_some() || tk.versions.is_some()) { panic!("Error: TomlCrate can only have one of 'git_.*','version' or 'path' fields"); } unreachable!("Failed to translate TomlCrate into CrateSource!"); } }); // sort the crates crate_sources.sort(); crate_sources } /// Parse the json output of clippy and return a `ClippyWarning` fn parse_json_message(json_message: &str, krate: &Crate) -> ClippyWarning { let jmsg: Value = serde_json::from_str(&json_message).unwrap_or_else(|e| panic!("Failed to parse json:\n{:?}", e)); let file: String = jmsg["message"]["spans"][0]["file_name"] .to_string() .trim_matches('"') .into(); let file = if file.contains(".cargo") { // if we deal with macros, a filename may show the origin of a macro which can be inside a dep from // the registry. // don't show the full path in that case. // /home/matthias/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.63/src/custom_keyword.rs let path = PathBuf::from(file); let mut piter = path.iter(); // consume all elements until we find ".cargo", so that "/home/matthias" is skipped let _: Option<&OsStr> = piter.find(|x| x == &std::ffi::OsString::from(".cargo")); // collect the remaining segments let file = piter.collect::<PathBuf>(); format!("{}", file.display()) } else { file }; ClippyWarning { crate_name: krate.name.to_string(), crate_version: krate.version.to_string(), file, line: jmsg["message"]["spans"][0]["line_start"] .to_string() .trim_matches('"') .into(), column: jmsg["message"]["spans"][0]["text"][0]["highlight_start"] .to_string() .trim_matches('"') .into(), linttype: jmsg["message"]["code"]["code"].to_string().trim_matches('"').into(), message: jmsg["message"]["message"].to_string().trim_matches('"').into(), is_ice: json_message.contains("internal compiler error: "), } } /// Generate a short list of occuring lints-types and their count fn gather_stats(clippy_warnings: &[ClippyWarning]) -> (String, HashMap<&String, usize>) { // count lint type occurrences let mut counter: HashMap<&String, usize> = HashMap::new(); clippy_warnings .iter() .for_each(|wrn| *counter.entry(&wrn.linttype).or_insert(0) += 1); // collect into a tupled list for sorting let mut stats: Vec<(&&String, &usize)> = counter.iter().map(|(lint, count)| (lint, count)).collect(); // sort by "000{count} {clippy::lintname}" // to not have a lint with 200 and 2 warnings take the same spot stats.sort_by_key(|(lint, count)| format!("{:0>4}, {}", count, lint)); let stats_string = stats .iter() .map(|(lint, count)| format!("{} {}\n", lint, count)) .collect::<String>(); (stats_string, counter) } /// check if the latest modification of the logfile is older than the modification date of the /// clippy binary, if this is true, we should clean the lintchec shared target directory and recheck fn lintcheck_needs_rerun(lintcheck_logs_path: &Path) -> bool { if!lintcheck_logs_path.exists() { return true; } let clippy_modified: std::time::SystemTime = { let mut times = [CLIPPY_DRIVER_PATH, CARGO_CLIPPY_PATH].iter().map(|p| { std::fs::metadata(p) .expect("failed to get metadata of file") .modified() .expect("failed to get modification date") }); // the oldest modification of either of the binaries std::cmp::max(times.next().unwrap(), times.next().unwrap()) }; let logs_modified: std::time::SystemTime = std::fs::metadata(lintcheck_logs_path) .expect("failed to get metadata of file") .modified() .expect("failed to get modification date"); // time is represented in seconds since X // logs_modified 2 and clippy_modified 5 means clippy binary is older and we need to recheck logs_modified < clippy_modified } fn is_in_clippy_root() -> bool { if let Ok(pb) = std::env::current_dir() { if let Some(file) = pb.file_name() { return file == PathBuf::from("rust-clippy"); } } false } /// lintchecks `main()` function /// /// # Panics /// /// This function panics if the clippy binaries don't exist /// or if lintcheck is executed from the wrong directory (aka none-repo-root) pub fn main() { // assert that we launch lintcheck from the repo root (via cargo lintcheck) if!is_in_clippy_root() { eprintln!("lintcheck needs to be run from clippys repo root!\nUse `cargo lintcheck` alternatively."); std::process::exit(3); } let clap_config = &get_clap_config(); let config = LintcheckConfig::from_clap(clap_config); println!("Compiling cli
{ for opt in options { args.push(opt); } }
conditional_block
main.rs
}, CrateSource::Git { name, url, commit, options, } => { let repo_path = { let mut repo_path = PathBuf::from(LINTCHECK_SOURCES); // add a -git suffix in case we have the same crate from crates.io and a git repo repo_path.push(format!("{}-git", name)); repo_path }; // clone the repo if we have not done so if!repo_path.is_dir() { println!("Cloning {} and checking out {}", url, commit); if!Command::new("git") .arg("clone") .arg(url) .arg(&repo_path) .status() .expect("Failed to clone git repo!") .success() { eprintln!("Failed to clone {} into {}", url, repo_path.display()) } } // check out the commit/branch/whatever if!Command::new("git") .arg("checkout") .arg(commit) .current_dir(&repo_path) .status() .expect("Failed to check out commit") .success() { eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display()) } Crate { version: commit.clone(), name: name.clone(), path: repo_path, options: options.clone(), } }, CrateSource::Path { name, path, options } => { use fs_extra::dir; // simply copy the entire directory into our target dir let copy_dest = PathBuf::from(format!("{}/", LINTCHECK_SOURCES)); // the source path of the crate we copied, ${copy_dest}/crate_name let crate_root = copy_dest.join(name); //.../crates/local_crate if crate_root.exists() { println!( "Not copying {} to {}, destination already exists", path.display(), crate_root.display() ); } else { println!("Copying {} to {}", path.display(), copy_dest.display()); dir::copy(path, &copy_dest, &dir::CopyOptions::new()).unwrap_or_else(|_| { panic!("Failed to copy from {}, to {}", path.display(), crate_root.display()) }); } Crate { version: String::from("local"), name: name.clone(), path: crate_root, options: options.clone(), } }, } } } impl Crate { /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy /// issued fn run_clippy_lints( &self, cargo_clippy_path: &Path, target_dir_index: &AtomicUsize, thread_limit: usize, total_crates_to_lint: usize, fix: bool, ) -> Vec<ClippyWarning> { // advance the atomic index by one let index = target_dir_index.fetch_add(1, Ordering::SeqCst); // "loop" the index within 0..thread_limit let thread_index = index % thread_limit; let perc = (index * 100) / total_crates_to_lint; if thread_limit == 1 { println!( "{}/{} {}% Linting {} {}", index, total_crates_to_lint, perc, &self.name, &self.version ); } else { println!( "{}/{} {}% Linting {} {} in target dir {:?}", index, total_crates_to_lint, perc, &self.name, &self.version, thread_index ); } let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap(); let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir"); let mut args = if fix { vec!["--fix", "--allow-no-vcs", "--", "--cap-lints=warn"] } else { vec!["--", "--message-format=json", "--", "--cap-lints=warn"] }; if let Some(options) = &self.options { for opt in options { args.push(opt); } } else { args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"]) } let all_output = std::process::Command::new(&cargo_clippy_path) // use the looping index to create individual target dirs .env( "CARGO_TARGET_DIR", shared_target_dir.join(format!("_{:?}", thread_index)), ) // lint warnings will look like this: // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter` .args(&args) .current_dir(&self.path) .output() .unwrap_or_else(|error| { panic!( "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n", error, &cargo_clippy_path.display(), &self.path.display() ); }); let stdout = String::from_utf8_lossy(&all_output.stdout); let stderr = String::from_utf8_lossy(&all_output.stderr); let status = &all_output.status; if!status.success() { eprintln!( "\nWARNING: bad exit status after checking {} {} \n", self.name, self.version ); } if fix { if let Some(stderr) = stderr .lines() .find(|line| line.contains("failed to automatically apply fixes suggested by rustc to crate")) { let subcrate = &stderr[63..]; println!( "ERROR: failed to apply some suggetion to {} / to (sub)crate {}", self.name, subcrate ); } // fast path, we don't need the warnings anyway return Vec::new(); } let output_lines = stdout.lines(); let warnings: Vec<ClippyWarning> = output_lines .into_iter() // get all clippy warnings and ICEs .filter(|line| filter_clippy_warnings(&line)) .map(|json_msg| parse_json_message(json_msg, &self)) .collect(); warnings } } #[derive(Debug)] struct LintcheckConfig { // max number of jobs to spawn (default 1) max_jobs: usize, // we read the sources to check from here sources_toml_path: PathBuf, // we save the clippy lint results here lintcheck_results_path: PathBuf, // whether to just run --fix and not collect all the warnings fix: bool, } impl LintcheckConfig { fn from_clap(clap_config: &ArgMatches) -> Self { // first, check if we got anything passed via the LINTCHECK_TOML env var, // if not, ask clap if we got any value for --crates-toml <foo> // if not, use the default "lintcheck/lintcheck_crates.toml" let sources_toml = env::var("LINTCHECK_TOML").unwrap_or_else(|_| { clap_config .value_of("crates-toml") .clone() .unwrap_or("lintcheck/lintcheck_crates.toml") .to_string() }); let sources_toml_path = PathBuf::from(sources_toml); // for the path where we save the lint results, get the filename without extension (so for // wasd.toml, use "wasd"...) let filename: PathBuf = sources_toml_path.file_stem().unwrap().into(); let lintcheck_results_path = PathBuf::from(format!("lintcheck-logs/{}_logs.txt", filename.display())); // look at the --threads arg, if 0 is passed, ask rayon rayon how many threads it would spawn and // use half of that for the physical core count // by default use a single thread let max_jobs = match clap_config.value_of("threads") { Some(threads) => { let threads: usize = threads .parse() .unwrap_or_else(|_| panic!("Failed to parse '{}' to a digit", threads)); if threads == 0 { // automatic choice // Rayon seems to return thread count so half that for core count (rayon::current_num_threads() / 2) as usize } else { threads } }, // no -j passed, use a single thread None => 1, }; let fix: bool = clap_config.is_present("fix"); LintcheckConfig { max_jobs, sources_toml_path, lintcheck_results_path, fix, } } } /// takes a single json-formatted clippy warnings and returns true (we are interested in that line) /// or false (we aren't) fn filter_clippy_warnings(line: &str) -> bool { // we want to collect ICEs because clippy might have crashed. // these are summarized later if line.contains("internal compiler error: ") { return true; } // in general, we want all clippy warnings // however due to some kind of bug, sometimes there are absolute paths // to libcore files inside the message // or we end up with cargo-metadata output (https://github.com/rust-lang/rust-clippy/issues/6508) // filter out these message to avoid unnecessary noise in the logs if line.contains("clippy::") &&!(line.contains("could not read cargo metadata") || (line.contains(".rustup") && line.contains("toolchains"))) { return true; } false } /// Builds clippy inside the repo to make sure we have a clippy executable we can use. fn build_clippy() { let status = Command::new("cargo") .arg("build") .status() .expect("Failed to build clippy!"); if!status.success() { eprintln!("Error: Failed to compile Clippy!"); std::process::exit(1); } } /// Read a `toml` file and return a list of `CrateSources` that we want to check with clippy fn read_crates(toml_path: &Path) -> Vec<CrateSource> { let toml_content: String = std::fs::read_to_string(&toml_path).unwrap_or_else(|_| panic!("Failed to read {}", toml_path.display())); let crate_list: SourceList = toml::from_str(&toml_content).unwrap_or_else(|e| panic!("Failed to parse {}: \n{}", toml_path.display(), e)); // parse the hashmap of the toml file into a list of crates let tomlcrates: Vec<TomlCrate> = crate_list .crates .into_iter() .map(|(_cratename, tomlcrate)| tomlcrate) .collect(); // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate => // multiple Cratesources) let mut crate_sources = Vec::new(); tomlcrates.into_iter().for_each(|tk| { if let Some(ref path) = tk.path { crate_sources.push(CrateSource::Path { name: tk.name.clone(), path: PathBuf::from(path), options: tk.options.clone(), }); } // if we have multiple versions, save each one if let Some(ref versions) = tk.versions { versions.iter().for_each(|ver| { crate_sources.push(CrateSource::CratesIo { name: tk.name.clone(), version: ver.to_string(), options: tk.options.clone(), }); }) } // otherwise, we should have a git source if tk.git_url.is_some() && tk.git_hash.is_some() { crate_sources.push(CrateSource::Git { name: tk.name.clone(), url: tk.git_url.clone().unwrap(), commit: tk.git_hash.clone().unwrap(), options: tk.options.clone(), }); }
if tk.versions.is_some() && (tk.git_url.is_some() || tk.git_hash.is_some()) || tk.git_hash.is_some()!= tk.git_url.is_some() { eprintln!("tomlkrate: {:?}", tk); if tk.git_hash.is_some()!= tk.git_url.is_some() { panic!("Error: Encountered TomlCrate with only one of git_hash and git_url!"); } if tk.path.is_some() && (tk.git_hash.is_some() || tk.versions.is_some()) { panic!("Error: TomlCrate can only have one of 'git_.*','version' or 'path' fields"); } unreachable!("Failed to translate TomlCrate into CrateSource!"); } }); // sort the crates crate_sources.sort(); crate_sources } /// Parse the json output of clippy and return a `ClippyWarning` fn parse_json_message(json_message: &str, krate: &Crate) -> ClippyWarning { let jmsg: Value = serde_json::from_str(&json_message).unwrap_or_else(|e| panic!("Failed to parse json:\n{:?}", e)); let file: String = jmsg["message"]["spans"][0]["file_name"] .to_string() .trim_matches('"') .into(); let file = if file.contains(".cargo") { // if we deal with macros, a filename may show the origin of a macro which can be inside a dep from // the registry. // don't show the full path in that case. // /home/matthias/.cargo/registry/src/github.com-1ecc6299db9ec823/syn-1.0.63/src/custom_keyword.rs let path = PathBuf::from(file); let mut piter = path.iter(); // consume all elements until we find ".cargo", so that "/home/matthias" is skipped let _: Option<&OsStr> = piter.find(|x| x == &std::ffi::OsString::from(".cargo")); // collect the remaining segments let file = piter.collect::<PathBuf>(); format!("{}", file.display()) } else { file }; ClippyWarning { crate_name: krate.name.to_string(), crate_version: krate.version.to_string(), file, line: jmsg["message"]["spans"][0]["line_start"] .to_string() .trim_matches('"') .into(), column: jmsg["message"]["spans"][0]["text"][0]["highlight_start"] .to_string() .trim_matches('"') .into(), linttype: jmsg["message"]["code"]["code"].to_string().trim_matches('"').into(), message: jmsg["message"]["message"].to_string().trim_matches('"').into(), is_ice: json_message.contains("internal compiler error: "), } } /// Generate a short list of occuring lints-types and their count fn gather_stats(clippy_warnings: &[ClippyWarning]) -> (String, HashMap<&String, usize>) { // count lint type occurrences let mut counter: HashMap<&String, usize> = HashMap::new(); clippy_warnings .iter() .for_each(|wrn| *counter.entry(&wrn.linttype).or_insert(0) += 1); // collect into a tupled list for sorting let mut stats: Vec<(&&String, &usize)> = counter.iter().map(|(lint, count)| (lint, count)).collect(); // sort by "000{count} {clippy::lintname}" // to not have a lint with 200 and 2 warnings take the same spot stats.sort_by_key(|(lint, count)| format!("{:0>4}, {}", count, lint)); let stats_string = stats .iter() .map(|(lint, count)| format!("{} {}\n", lint, count)) .collect::<String>(); (stats_string, counter) } /// check if the latest modification of the logfile is older than the modification date of the /// clippy binary, if this is true, we should clean the lintchec shared target directory and recheck fn lintcheck_needs_rerun(lintcheck_logs_path: &Path) -> bool { if!lintcheck_logs_path.exists() { return true; } let clippy_modified: std::time::SystemTime = { let mut times = [CLIPPY_DRIVER_PATH, CARGO_CLIPPY_PATH].iter().map(|p| { std::fs::metadata(p) .expect("failed to get metadata of file") .modified() .expect("failed to get modification date") }); // the oldest modification of either of the binaries std::cmp::max(times.next().unwrap(), times.next().unwrap()) }; let logs_modified: std::time::SystemTime = std::fs::metadata(lintcheck_logs_path) .expect("failed to get metadata of file") .modified() .expect("failed to get modification date"); // time is represented in seconds since X // logs_modified 2 and clippy_modified 5 means clippy binary is older and we need to recheck logs_modified < clippy_modified } fn is_in_clippy_root() -> bool { if let Ok(pb) = std::env::current_dir() { if let Some(file) = pb.file_name() { return file == PathBuf::from("rust-clippy"); } } false } /// lintchecks `main()` function /// /// # Panics /// /// This function panics if the clippy binaries don't exist /// or if lintcheck is executed from the wrong directory (aka none-repo-root) pub fn main() { // assert that we launch lintcheck from the repo root (via cargo lintcheck) if!is_in_clippy_root() { eprintln!("lintcheck needs to be run from clippys repo root!\nUse `cargo lintcheck` alternatively."); std::process::exit(3); } let clap_config = &get_clap_config(); let config = LintcheckConfig::from_clap(clap_config); println!("Compiling clippy...");
// if we have a version as well as a git data OR only one git data, something is funky
random_line_split
helpers.rs
mod pkg_path_for; mod str_concat; mod str_join; mod str_replace; mod to_json; mod to_lowercase; mod to_toml; mod to_uppercase; mod to_yaml; pub use self::{each_alive::EACH_ALIVE, pkg_path_for::PKG_PATH_FOR, str_concat::STR_CONCAT, str_join::STR_JOIN, str_replace::STR_REPLACE, to_json::TO_JSON, to_lowercase::TO_LOWERCASE, to_toml::TO_TOML, to_uppercase::TO_UPPERCASE, to_yaml::TO_YAML}; use serde::Serialize; use serde_json::{self, Value as Json}; // Taken from `handlebars::context::JsonTruthy`. The trait is marked public but it's in a private // module. It's super useful so let's pull it into here. pub trait JsonTruthy { fn is_truthy(&self) -> bool; } impl JsonTruthy for Json { fn is_truthy(&self) -> bool { match *self { Json::Bool(ref i) => *i, Json::Number(ref n) => n.as_f64().map(|f| f.is_normal()).unwrap_or(false), Json::Null => false, Json::String(ref i) =>!i.is_empty(), Json::Array(ref i) =>!i.is_empty(), Json::Object(ref i) =>!i.is_empty(), } } } /// Helper which will serialize to Json the given reference or return `Json::Null` fn to_json<T>(src: &T) -> Json where T: Serialize { serde_json::to_value(src).unwrap_or(Json::Null) }
mod each_alive;
random_line_split
helpers.rs
mod each_alive; mod pkg_path_for; mod str_concat; mod str_join; mod str_replace; mod to_json; mod to_lowercase; mod to_toml; mod to_uppercase; mod to_yaml; pub use self::{each_alive::EACH_ALIVE, pkg_path_for::PKG_PATH_FOR, str_concat::STR_CONCAT, str_join::STR_JOIN, str_replace::STR_REPLACE, to_json::TO_JSON, to_lowercase::TO_LOWERCASE, to_toml::TO_TOML, to_uppercase::TO_UPPERCASE, to_yaml::TO_YAML}; use serde::Serialize; use serde_json::{self, Value as Json}; // Taken from `handlebars::context::JsonTruthy`. The trait is marked public but it's in a private // module. It's super useful so let's pull it into here. pub trait JsonTruthy { fn is_truthy(&self) -> bool; } impl JsonTruthy for Json { fn is_truthy(&self) -> bool { match *self { Json::Bool(ref i) => *i, Json::Number(ref n) => n.as_f64().map(|f| f.is_normal()).unwrap_or(false), Json::Null => false, Json::String(ref i) =>!i.is_empty(), Json::Array(ref i) =>!i.is_empty(), Json::Object(ref i) =>!i.is_empty(), } } } /// Helper which will serialize to Json the given reference or return `Json::Null` fn
<T>(src: &T) -> Json where T: Serialize { serde_json::to_value(src).unwrap_or(Json::Null) }
to_json
identifier_name
helpers.rs
mod each_alive; mod pkg_path_for; mod str_concat; mod str_join; mod str_replace; mod to_json; mod to_lowercase; mod to_toml; mod to_uppercase; mod to_yaml; pub use self::{each_alive::EACH_ALIVE, pkg_path_for::PKG_PATH_FOR, str_concat::STR_CONCAT, str_join::STR_JOIN, str_replace::STR_REPLACE, to_json::TO_JSON, to_lowercase::TO_LOWERCASE, to_toml::TO_TOML, to_uppercase::TO_UPPERCASE, to_yaml::TO_YAML}; use serde::Serialize; use serde_json::{self, Value as Json}; // Taken from `handlebars::context::JsonTruthy`. The trait is marked public but it's in a private // module. It's super useful so let's pull it into here. pub trait JsonTruthy { fn is_truthy(&self) -> bool; } impl JsonTruthy for Json { fn is_truthy(&self) -> bool { match *self { Json::Bool(ref i) => *i, Json::Number(ref n) => n.as_f64().map(|f| f.is_normal()).unwrap_or(false), Json::Null => false, Json::String(ref i) =>!i.is_empty(), Json::Array(ref i) =>!i.is_empty(), Json::Object(ref i) =>!i.is_empty(), } } } /// Helper which will serialize to Json the given reference or return `Json::Null` fn to_json<T>(src: &T) -> Json where T: Serialize
{ serde_json::to_value(src).unwrap_or(Json::Null) }
identifier_body
regions-outlives-projection-container-wc.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we are imposing the requirement that every associated // type of a bound that appears in the where clause on a struct must // outlive the location in which the type appears, even when the // constraint is in a where clause not a bound. Issue #22246. #![allow(dead_code)] /////////////////////////////////////////////////////////////////////////// pub trait TheTrait {
pub struct TheType<'b> { m: [fn(&'b()); 0] } impl<'b> TheTrait for TheType<'b> { type TheAssocType = &'b (); } /////////////////////////////////////////////////////////////////////////// pub struct WithAssoc<T> where T : TheTrait { m: [T; 0] } fn with_assoc<'a,'b>() { // For this type to be valid, the rules require that all // associated types of traits that appear in `WithAssoc` must // outlive 'a. In this case, that means TheType<'b>::TheAssocType, // which is &'b (), must outlive 'a. let _: &'a WithAssoc<TheType<'b>> = loop { }; //~^ ERROR reference has a longer lifetime } fn main() { }
type TheAssocType; }
random_line_split
regions-outlives-projection-container-wc.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we are imposing the requirement that every associated // type of a bound that appears in the where clause on a struct must // outlive the location in which the type appears, even when the // constraint is in a where clause not a bound. Issue #22246. #![allow(dead_code)] /////////////////////////////////////////////////////////////////////////// pub trait TheTrait { type TheAssocType; } pub struct TheType<'b> { m: [fn(&'b()); 0] } impl<'b> TheTrait for TheType<'b> { type TheAssocType = &'b (); } /////////////////////////////////////////////////////////////////////////// pub struct WithAssoc<T> where T : TheTrait { m: [T; 0] } fn with_assoc<'a,'b>()
fn main() { }
{ // For this type to be valid, the rules require that all // associated types of traits that appear in `WithAssoc` must // outlive 'a. In this case, that means TheType<'b>::TheAssocType, // which is &'b (), must outlive 'a. let _: &'a WithAssoc<TheType<'b>> = loop { }; //~^ ERROR reference has a longer lifetime }
identifier_body
regions-outlives-projection-container-wc.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we are imposing the requirement that every associated // type of a bound that appears in the where clause on a struct must // outlive the location in which the type appears, even when the // constraint is in a where clause not a bound. Issue #22246. #![allow(dead_code)] /////////////////////////////////////////////////////////////////////////// pub trait TheTrait { type TheAssocType; } pub struct TheType<'b> { m: [fn(&'b()); 0] } impl<'b> TheTrait for TheType<'b> { type TheAssocType = &'b (); } /////////////////////////////////////////////////////////////////////////// pub struct WithAssoc<T> where T : TheTrait { m: [T; 0] } fn with_assoc<'a,'b>() { // For this type to be valid, the rules require that all // associated types of traits that appear in `WithAssoc` must // outlive 'a. In this case, that means TheType<'b>::TheAssocType, // which is &'b (), must outlive 'a. let _: &'a WithAssoc<TheType<'b>> = loop { }; //~^ ERROR reference has a longer lifetime } fn
() { }
main
identifier_name
check.rs
use crate::gen::Opt; use crate::syntax::report::Errors; use crate::syntax::{error, Api}; use quote::{quote, quote_spanned}; use std::path::{Component, Path}; pub(super) use crate::syntax::check::{typecheck, Generator}; pub(super) fn precheck(cx: &mut Errors, apis: &[Api], opt: &Opt) { if!opt.allow_dot_includes { check_dot_includes(cx, apis); } } fn check_dot_includes(cx: &mut Errors, apis: &[Api]) { for api in apis { if let Api::Include(include) = api { let first_component = Path::new(&include.path).components().next(); if let Some(Component::CurDir) | Some(Component::ParentDir) = first_component {
let end = quote_spanned!(include.end_span=>.); let span = quote!(#begin #end); cx.error(span, error::DOT_INCLUDE.msg); } } } }
let begin = quote_spanned!(include.begin_span=> .);
random_line_split
check.rs
use crate::gen::Opt; use crate::syntax::report::Errors; use crate::syntax::{error, Api}; use quote::{quote, quote_spanned}; use std::path::{Component, Path}; pub(super) use crate::syntax::check::{typecheck, Generator}; pub(super) fn precheck(cx: &mut Errors, apis: &[Api], opt: &Opt) { if!opt.allow_dot_includes { check_dot_includes(cx, apis); } } fn check_dot_includes(cx: &mut Errors, apis: &[Api])
{ for api in apis { if let Api::Include(include) = api { let first_component = Path::new(&include.path).components().next(); if let Some(Component::CurDir) | Some(Component::ParentDir) = first_component { let begin = quote_spanned!(include.begin_span=> .); let end = quote_spanned!(include.end_span=> .); let span = quote!(#begin #end); cx.error(span, error::DOT_INCLUDE.msg); } } } }
identifier_body
check.rs
use crate::gen::Opt; use crate::syntax::report::Errors; use crate::syntax::{error, Api}; use quote::{quote, quote_spanned}; use std::path::{Component, Path}; pub(super) use crate::syntax::check::{typecheck, Generator}; pub(super) fn precheck(cx: &mut Errors, apis: &[Api], opt: &Opt) { if!opt.allow_dot_includes { check_dot_includes(cx, apis); } } fn check_dot_includes(cx: &mut Errors, apis: &[Api]) { for api in apis { if let Api::Include(include) = api
} }
{ let first_component = Path::new(&include.path).components().next(); if let Some(Component::CurDir) | Some(Component::ParentDir) = first_component { let begin = quote_spanned!(include.begin_span=> .); let end = quote_spanned!(include.end_span=> .); let span = quote!(#begin #end); cx.error(span, error::DOT_INCLUDE.msg); } }
conditional_block
check.rs
use crate::gen::Opt; use crate::syntax::report::Errors; use crate::syntax::{error, Api}; use quote::{quote, quote_spanned}; use std::path::{Component, Path}; pub(super) use crate::syntax::check::{typecheck, Generator}; pub(super) fn precheck(cx: &mut Errors, apis: &[Api], opt: &Opt) { if!opt.allow_dot_includes { check_dot_includes(cx, apis); } } fn
(cx: &mut Errors, apis: &[Api]) { for api in apis { if let Api::Include(include) = api { let first_component = Path::new(&include.path).components().next(); if let Some(Component::CurDir) | Some(Component::ParentDir) = first_component { let begin = quote_spanned!(include.begin_span=>.); let end = quote_spanned!(include.end_span=>.); let span = quote!(#begin #end); cx.error(span, error::DOT_INCLUDE.msg); } } } }
check_dot_includes
identifier_name
indexer.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// 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 // along with this program. If not, see <http://www.gnu.org/licenses/>. use burnchains::BurnchainBlock; use burnchains::Error as burnchain_error; use burnchains::*; use crate::types::chainstate::BurnchainHeaderHash; use core::StacksEpoch; // IPC messages between threads pub trait BurnHeaderIPC { type H: Send + Sync + Clone; fn height(&self) -> u64; fn header(&self) -> Self::H; fn header_hash(&self) -> [u8; 32]; } pub trait BurnBlockIPC { type H: BurnHeaderIPC + Sync + Send + Clone; type B: Send + Sync + Clone; fn height(&self) -> u64; fn header(&self) -> Self::H; fn block(&self) -> Self::B; } pub trait BurnchainBlockDownloader { type H: BurnHeaderIPC + Sync + Send + Clone; type B: BurnBlockIPC + Sync + Send + Clone; fn download(&mut self, header: &Self::H) -> Result<Self::B, burnchain_error>; } pub trait BurnchainBlockParser { type D: BurnchainBlockDownloader + Sync + Send; fn parse( &mut self, block: &<<Self as BurnchainBlockParser>::D as BurnchainBlockDownloader>::B, ) -> Result<BurnchainBlock, burnchain_error>; } pub trait BurnchainIndexer { type P: BurnchainBlockParser + Send + Sync; fn connect(&mut self) -> Result<(), burnchain_error>; fn get_first_block_height(&self) -> u64; fn get_first_block_header_hash(&self) -> Result<BurnchainHeaderHash, burnchain_error>; fn get_first_block_header_timestamp(&self) -> Result<u64, burnchain_error>; fn get_stacks_epochs(&self) -> Vec<StacksEpoch>; fn get_headers_path(&self) -> String; fn get_headers_height(&self) -> Result<u64, burnchain_error>; fn get_highest_header_height(&self) -> Result<u64, burnchain_error>; fn find_chain_reorg(&mut self) -> Result<u64, burnchain_error>; fn sync_headers( &mut self, start_height: u64, end_height: Option<u64>, ) -> Result<u64, burnchain_error>; fn drop_headers(&mut self, new_height: u64) -> Result<(), burnchain_error>; fn read_headers(&self, start_block: u64, end_block: u64) -> Result<Vec<<<<Self as BurnchainIndexer>::P as BurnchainBlockParser>::D as BurnchainBlockDownloader>::H>, burnchain_error>; fn downloader(&self) -> <<Self as BurnchainIndexer>::P as BurnchainBlockParser>::D; fn parser(&self) -> Self::P; }
// Copyright (C) 2020 Stacks Open Internet Foundation // // This program is free software: you can redistribute it and/or modify
random_line_split
enum.rs
enum Opaque { Foo(i32), Bar, } #[repr(u64)] enum A { a1 = 0, a2 = 2, a3, a4 = 5, } #[repr(u32)] enum B { b1 = 0, b2 = 2, b3, b4 = 5, } #[repr(u16)] enum C { c1 = 0, c2 = 2, c3, c4 = 5, } #[repr(u8)] enum D { d1 = 0, d2 = 2, d3, d4 = 5, } #[repr(usize)] enum E { e1 = 0, e2 = 2, e3, e4 = 5, } #[repr(isize)] enum F { f1 = 0, f2 = 2, f3, f4 = 5, } #[repr(u8)] enum G { Foo(i16), Bar { x: u8, y: i16 }, Baz, } /// cbindgen:prefix-with-name #[repr(C)] enum H { Foo(i16), Bar { x: u8, y: i16 }, Baz, } /// cbindgen:prefix-with-name #[repr(C, u8)] enum I { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C, u8, u16)] enum J { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C, u8, unknown_hint)] enum K { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C)] enum L { l1, l2, l3, l4, } #[repr(i8)] enum
{ m1 = -1, m2 = 0, m3 = 1, } /// cbindgen:enum-class=false #[repr(C)] enum N { n1, n2, n3, n4, } /// cbindgen:enum-class=false #[repr(i8)] enum O { o1, o2, o3, o4, } #[repr(C, u8)] enum P { P0(u8), P1(u8, u8, u8), } #[no_mangle] pub extern "C" fn root( opaque: *mut Opaque, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L, m: M, n: N, o: O, p: P, ) { }
M
identifier_name
enum.rs
enum Opaque { Foo(i32), Bar, } #[repr(u64)] enum A { a1 = 0, a2 = 2, a3, a4 = 5, } #[repr(u32)] enum B { b1 = 0, b2 = 2, b3, b4 = 5, } #[repr(u16)] enum C { c1 = 0, c2 = 2,
enum D { d1 = 0, d2 = 2, d3, d4 = 5, } #[repr(usize)] enum E { e1 = 0, e2 = 2, e3, e4 = 5, } #[repr(isize)] enum F { f1 = 0, f2 = 2, f3, f4 = 5, } #[repr(u8)] enum G { Foo(i16), Bar { x: u8, y: i16 }, Baz, } /// cbindgen:prefix-with-name #[repr(C)] enum H { Foo(i16), Bar { x: u8, y: i16 }, Baz, } /// cbindgen:prefix-with-name #[repr(C, u8)] enum I { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C, u8, u16)] enum J { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C, u8, unknown_hint)] enum K { Foo(i16), Bar { x: u8, y: i16 }, Baz, } #[repr(C)] enum L { l1, l2, l3, l4, } #[repr(i8)] enum M { m1 = -1, m2 = 0, m3 = 1, } /// cbindgen:enum-class=false #[repr(C)] enum N { n1, n2, n3, n4, } /// cbindgen:enum-class=false #[repr(i8)] enum O { o1, o2, o3, o4, } #[repr(C, u8)] enum P { P0(u8), P1(u8, u8, u8), } #[no_mangle] pub extern "C" fn root( opaque: *mut Opaque, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L, m: M, n: N, o: O, p: P, ) { }
c3, c4 = 5, } #[repr(u8)]
random_line_split
day14.rs
extern crate regex; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use regex::Regex; #[derive(Debug, Clone)] struct Reindeer { name: String, speed: isize, speed_time: isize, rest_time: isize, current_distance: isize, points: isize, rest_time_left: isize, speed_time_left: isize, } impl Reindeer { fn distance_traveled(&self, seconds: isize) -> isize { let mut distance = 0; let mut seconds = seconds; while seconds > 0 { if seconds > self.speed_time { distance += self.speed * self.speed_time; seconds -= self.speed_time; } else { distance += self.speed * seconds; break; } seconds -= self.rest_time; } return distance; } /// Move the race forward one second. fn tick(&mut self) { if self.speed_time_left > 0 { self.current_distance += self.speed; self.speed_time_left -= 1; if self.speed_time_left == 0 { self.rest_time_left = self.rest_time; } } else { self.rest_time_left -= 1; if self.rest_time_left == 0 { self.speed_time_left = self.speed_time; } } } } fn award_points(reindeers: &mut Vec<Reindeer>) { let mut max_distance = 0; for r in reindeers.iter() { if r.current_distance > max_distance { max_distance = r.current_distance; } } for r in reindeers.iter_mut() { if r.current_distance >= max_distance { r.points += 1; } } } fn part1(reindeers: Vec<Reindeer>) { let time_in_secs = 2503; for r in reindeers.iter() { println!("{:10} traveled {:4} km in {:5} seconds", r.name, r.distance_traveled(time_in_secs), time_in_secs); } } fn part2(reindeers: Vec<Reindeer>)
fn main() { let file = File::open("input.txt").unwrap(); let reader = BufReader::new(&file); let regex = Regex::new(r"(?P<name>[[:alpha:]]+) can fly (?P<speed>[[:digit:]]+) km/s for (?P<speed_time>[[:digit:]]+) seconds, but then must rest for (?P<rest_time>[[:digit:]]+) seconds.").unwrap(); let mut reindeers: Vec<Reindeer> = Vec::with_capacity(10); for wrapped_line in reader.lines() { let line = wrapped_line.unwrap(); let maybe_match = regex.captures(line.as_str()); match maybe_match { Some(capture) => { let name = capture.name("name").unwrap().as_str(); let speed = capture.name("speed").unwrap().as_str().parse::<isize>().unwrap(); let speed_time = capture.name("speed_time").unwrap().as_str().parse::<isize>().unwrap(); let rest_time = capture.name("rest_time").unwrap().as_str().parse::<isize>().unwrap(); reindeers.push(Reindeer { name: String::from(name), speed: speed, speed_time: speed_time, rest_time: rest_time, current_distance: 0, points: 0, rest_time_left: 0, speed_time_left: speed_time, }); } None => panic!("No match for '{}'", line), } } part1(reindeers.clone()); part2(reindeers); }
{ let mut reindeers = reindeers; let time_in_secs = 2503; for _ in 0..time_in_secs { for r in reindeers.iter_mut() { r.tick(); } // Find the winning reindeer and award them a point. award_points(&mut reindeers); } for r in reindeers.iter() { println!("{:10} traveled {:4} km in {:5} seconds and received {:5} points.", r.name, r.distance_traveled(time_in_secs), time_in_secs, r.points); } }
identifier_body
day14.rs
extern crate regex; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use regex::Regex; #[derive(Debug, Clone)] struct Reindeer { name: String, speed: isize, speed_time: isize, rest_time: isize, current_distance: isize, points: isize, rest_time_left: isize, speed_time_left: isize, } impl Reindeer { fn distance_traveled(&self, seconds: isize) -> isize { let mut distance = 0; let mut seconds = seconds; while seconds > 0 { if seconds > self.speed_time { distance += self.speed * self.speed_time; seconds -= self.speed_time; } else { distance += self.speed * seconds; break; } seconds -= self.rest_time; } return distance; } /// Move the race forward one second. fn tick(&mut self) { if self.speed_time_left > 0
else { self.rest_time_left -= 1; if self.rest_time_left == 0 { self.speed_time_left = self.speed_time; } } } } fn award_points(reindeers: &mut Vec<Reindeer>) { let mut max_distance = 0; for r in reindeers.iter() { if r.current_distance > max_distance { max_distance = r.current_distance; } } for r in reindeers.iter_mut() { if r.current_distance >= max_distance { r.points += 1; } } } fn part1(reindeers: Vec<Reindeer>) { let time_in_secs = 2503; for r in reindeers.iter() { println!("{:10} traveled {:4} km in {:5} seconds", r.name, r.distance_traveled(time_in_secs), time_in_secs); } } fn part2(reindeers: Vec<Reindeer>) { let mut reindeers = reindeers; let time_in_secs = 2503; for _ in 0..time_in_secs { for r in reindeers.iter_mut() { r.tick(); } // Find the winning reindeer and award them a point. award_points(&mut reindeers); } for r in reindeers.iter() { println!("{:10} traveled {:4} km in {:5} seconds and received {:5} points.", r.name, r.distance_traveled(time_in_secs), time_in_secs, r.points); } } fn main() { let file = File::open("input.txt").unwrap(); let reader = BufReader::new(&file); let regex = Regex::new(r"(?P<name>[[:alpha:]]+) can fly (?P<speed>[[:digit:]]+) km/s for (?P<speed_time>[[:digit:]]+) seconds, but then must rest for (?P<rest_time>[[:digit:]]+) seconds.").unwrap(); let mut reindeers: Vec<Reindeer> = Vec::with_capacity(10); for wrapped_line in reader.lines() { let line = wrapped_line.unwrap(); let maybe_match = regex.captures(line.as_str()); match maybe_match { Some(capture) => { let name = capture.name("name").unwrap().as_str(); let speed = capture.name("speed").unwrap().as_str().parse::<isize>().unwrap(); let speed_time = capture.name("speed_time").unwrap().as_str().parse::<isize>().unwrap(); let rest_time = capture.name("rest_time").unwrap().as_str().parse::<isize>().unwrap(); reindeers.push(Reindeer { name: String::from(name), speed: speed, speed_time: speed_time, rest_time: rest_time, current_distance: 0, points: 0, rest_time_left: 0, speed_time_left: speed_time, }); } None => panic!("No match for '{}'", line), } } part1(reindeers.clone()); part2(reindeers); }
{ self.current_distance += self.speed; self.speed_time_left -= 1; if self.speed_time_left == 0 { self.rest_time_left = self.rest_time; } }
conditional_block
day14.rs
extern crate regex; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use regex::Regex; #[derive(Debug, Clone)] struct Reindeer { name: String, speed: isize, speed_time: isize, rest_time: isize, current_distance: isize, points: isize, rest_time_left: isize, speed_time_left: isize, } impl Reindeer { fn distance_traveled(&self, seconds: isize) -> isize { let mut distance = 0; let mut seconds = seconds; while seconds > 0 { if seconds > self.speed_time { distance += self.speed * self.speed_time; seconds -= self.speed_time; } else { distance += self.speed * seconds; break; } seconds -= self.rest_time; } return distance; } /// Move the race forward one second. fn tick(&mut self) { if self.speed_time_left > 0 { self.current_distance += self.speed; self.speed_time_left -= 1; if self.speed_time_left == 0 { self.rest_time_left = self.rest_time; } } else { self.rest_time_left -= 1; if self.rest_time_left == 0 { self.speed_time_left = self.speed_time; } } } } fn award_points(reindeers: &mut Vec<Reindeer>) { let mut max_distance = 0; for r in reindeers.iter() { if r.current_distance > max_distance { max_distance = r.current_distance; } } for r in reindeers.iter_mut() { if r.current_distance >= max_distance { r.points += 1; } }
} fn part1(reindeers: Vec<Reindeer>) { let time_in_secs = 2503; for r in reindeers.iter() { println!("{:10} traveled {:4} km in {:5} seconds", r.name, r.distance_traveled(time_in_secs), time_in_secs); } } fn part2(reindeers: Vec<Reindeer>) { let mut reindeers = reindeers; let time_in_secs = 2503; for _ in 0..time_in_secs { for r in reindeers.iter_mut() { r.tick(); } // Find the winning reindeer and award them a point. award_points(&mut reindeers); } for r in reindeers.iter() { println!("{:10} traveled {:4} km in {:5} seconds and received {:5} points.", r.name, r.distance_traveled(time_in_secs), time_in_secs, r.points); } } fn main() { let file = File::open("input.txt").unwrap(); let reader = BufReader::new(&file); let regex = Regex::new(r"(?P<name>[[:alpha:]]+) can fly (?P<speed>[[:digit:]]+) km/s for (?P<speed_time>[[:digit:]]+) seconds, but then must rest for (?P<rest_time>[[:digit:]]+) seconds.").unwrap(); let mut reindeers: Vec<Reindeer> = Vec::with_capacity(10); for wrapped_line in reader.lines() { let line = wrapped_line.unwrap(); let maybe_match = regex.captures(line.as_str()); match maybe_match { Some(capture) => { let name = capture.name("name").unwrap().as_str(); let speed = capture.name("speed").unwrap().as_str().parse::<isize>().unwrap(); let speed_time = capture.name("speed_time").unwrap().as_str().parse::<isize>().unwrap(); let rest_time = capture.name("rest_time").unwrap().as_str().parse::<isize>().unwrap(); reindeers.push(Reindeer { name: String::from(name), speed: speed, speed_time: speed_time, rest_time: rest_time, current_distance: 0, points: 0, rest_time_left: 0, speed_time_left: speed_time, }); } None => panic!("No match for '{}'", line), } } part1(reindeers.clone()); part2(reindeers); }
random_line_split
day14.rs
extern crate regex; use std::io::prelude::*; use std::io::BufReader; use std::fs::File; use regex::Regex; #[derive(Debug, Clone)] struct Reindeer { name: String, speed: isize, speed_time: isize, rest_time: isize, current_distance: isize, points: isize, rest_time_left: isize, speed_time_left: isize, } impl Reindeer { fn distance_traveled(&self, seconds: isize) -> isize { let mut distance = 0; let mut seconds = seconds; while seconds > 0 { if seconds > self.speed_time { distance += self.speed * self.speed_time; seconds -= self.speed_time; } else { distance += self.speed * seconds; break; } seconds -= self.rest_time; } return distance; } /// Move the race forward one second. fn tick(&mut self) { if self.speed_time_left > 0 { self.current_distance += self.speed; self.speed_time_left -= 1; if self.speed_time_left == 0 { self.rest_time_left = self.rest_time; } } else { self.rest_time_left -= 1; if self.rest_time_left == 0 { self.speed_time_left = self.speed_time; } } } } fn award_points(reindeers: &mut Vec<Reindeer>) { let mut max_distance = 0; for r in reindeers.iter() { if r.current_distance > max_distance { max_distance = r.current_distance; } } for r in reindeers.iter_mut() { if r.current_distance >= max_distance { r.points += 1; } } } fn part1(reindeers: Vec<Reindeer>) { let time_in_secs = 2503; for r in reindeers.iter() { println!("{:10} traveled {:4} km in {:5} seconds", r.name, r.distance_traveled(time_in_secs), time_in_secs); } } fn
(reindeers: Vec<Reindeer>) { let mut reindeers = reindeers; let time_in_secs = 2503; for _ in 0..time_in_secs { for r in reindeers.iter_mut() { r.tick(); } // Find the winning reindeer and award them a point. award_points(&mut reindeers); } for r in reindeers.iter() { println!("{:10} traveled {:4} km in {:5} seconds and received {:5} points.", r.name, r.distance_traveled(time_in_secs), time_in_secs, r.points); } } fn main() { let file = File::open("input.txt").unwrap(); let reader = BufReader::new(&file); let regex = Regex::new(r"(?P<name>[[:alpha:]]+) can fly (?P<speed>[[:digit:]]+) km/s for (?P<speed_time>[[:digit:]]+) seconds, but then must rest for (?P<rest_time>[[:digit:]]+) seconds.").unwrap(); let mut reindeers: Vec<Reindeer> = Vec::with_capacity(10); for wrapped_line in reader.lines() { let line = wrapped_line.unwrap(); let maybe_match = regex.captures(line.as_str()); match maybe_match { Some(capture) => { let name = capture.name("name").unwrap().as_str(); let speed = capture.name("speed").unwrap().as_str().parse::<isize>().unwrap(); let speed_time = capture.name("speed_time").unwrap().as_str().parse::<isize>().unwrap(); let rest_time = capture.name("rest_time").unwrap().as_str().parse::<isize>().unwrap(); reindeers.push(Reindeer { name: String::from(name), speed: speed, speed_time: speed_time, rest_time: rest_time, current_distance: 0, points: 0, rest_time_left: 0, speed_time_left: speed_time, }); } None => panic!("No match for '{}'", line), } } part1(reindeers.clone()); part2(reindeers); }
part2
identifier_name
req.rs
use crate::codec::*; use crate::endpoint::Endpoint; use crate::error::*; use crate::transport::AcceptStopHandle; use crate::util::{Peer, PeerIdentity}; use crate::*; use crate::{SocketType, ZmqResult}; use async_trait::async_trait; use bytes::Bytes; use crossbeam::queue::SegQueue; use dashmap::DashMap; use futures::{SinkExt, StreamExt}; use std::collections::HashMap; use std::sync::Arc; struct ReqSocketBackend {
pub struct ReqSocket { backend: Arc<ReqSocketBackend>, current_request: Option<PeerIdentity>, binds: HashMap<Endpoint, AcceptStopHandle>, } impl Drop for ReqSocket { fn drop(&mut self) { self.backend.shutdown(); } } #[async_trait] impl SocketSend for ReqSocket { async fn send(&mut self, mut message: ZmqMessage) -> ZmqResult<()> { if self.current_request.is_some() { return Err(ZmqError::ReturnToSender { reason: "Unable to send message. Request already in progress", message, }); } // In normal scenario this will always be only 1 iteration // There can be special case when peer has disconnected and his id is still in // RR queue This happens because SegQueue don't have an api to delete // items from queue. So in such case we'll just pop item and skip it if // we don't have a matching peer in peers map loop { let next_peer_id = match self.backend.round_robin.pop() { Ok(peer) => peer, Err(_) => { return Err(ZmqError::ReturnToSender { reason: "Not connected to peers. Unable to send messages", message, }) } }; match self.backend.peers.get_mut(&next_peer_id) { Some(mut peer) => { self.backend.round_robin.push(next_peer_id.clone()); message.push_front(Bytes::new()); peer.send_queue.send(Message::Message(message)).await?; self.current_request = Some(next_peer_id); return Ok(()); } None => continue, } } } } #[async_trait] impl SocketRecv for ReqSocket { async fn recv(&mut self) -> ZmqResult<ZmqMessage> { match self.current_request.take() { Some(peer_id) => { if let Some(mut peer) = self.backend.peers.get_mut(&peer_id) { let message = peer.recv_queue.next().await; match message { Some(Ok(Message::Message(mut m))) => { assert!(m.len() > 1); assert!(m.pop_front().unwrap().is_empty()); // Ensure that we have delimeter as first part Ok(m) } Some(_) => todo!(), None => Err(ZmqError::NoMessage), } } else { Err(ZmqError::Other("Server disconnected")) } } None => Err(ZmqError::Other("Unable to recv. No request in progress")), } } } #[async_trait] impl Socket for ReqSocket { fn with_options(options: SocketOptions) -> Self { Self { backend: Arc::new(ReqSocketBackend { peers: DashMap::new(), round_robin: SegQueue::new(), socket_monitor: Mutex::new(None), socket_options: options, }), current_request: None, binds: HashMap::new(), } } fn backend(&self) -> Arc<dyn MultiPeerBackend> { self.backend.clone() } fn binds(&mut self) -> &mut HashMap<Endpoint, AcceptStopHandle> { &mut self.binds } fn monitor(&mut self) -> mpsc::Receiver<SocketEvent> { let (sender, receiver) = mpsc::channel(1024); self.backend.socket_monitor.lock().replace(sender); receiver } } #[async_trait] impl MultiPeerBackend for ReqSocketBackend { async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) { let (recv_queue, send_queue) = io.into_parts(); self.peers.insert( peer_id.clone(), Peer { _identity: peer_id.clone(), send_queue, recv_queue, }, ); self.round_robin.push(peer_id.clone()); } fn peer_disconnected(&self, peer_id: &PeerIdentity) { self.peers.remove(peer_id); } } impl SocketBackend for ReqSocketBackend { fn socket_type(&self) -> SocketType { SocketType::REQ } fn socket_options(&self) -> &SocketOptions { &self.socket_options } fn shutdown(&self) { self.peers.clear(); } fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>> { &self.socket_monitor } }
pub(crate) peers: DashMap<PeerIdentity, Peer>, pub(crate) round_robin: SegQueue<PeerIdentity>, socket_monitor: Mutex<Option<mpsc::Sender<SocketEvent>>>, socket_options: SocketOptions, }
random_line_split