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
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod heartbeat; mod lsp_notification_dispatch; mod lsp_request_dispatch; mod lsp_state; mod lsp_state_resources; mod task_queue; use crate::{ code_action::on_code_action, completion::{on_completion, on_resolve_completion_item}, explore_schema_for_type::{on_explore_schema_for_type, ExploreSchemaForType}, goto_definition::{ on_get_source_location_of_type_definition, on_goto_definition, GetSourceLocationOfTypeDefinition, }, graphql_tools::on_graphql_execute_query, graphql_tools::GraphQLExecuteQuery, hover::on_hover, js_language_server::JSLanguageServer, lsp_process_error::LSPProcessResult, lsp_runtime_error::LSPRuntimeError, references::on_references, resolved_types_at_location::{on_get_resolved_types_at_location, ResolvedTypesAtLocation}, search_schema_items::{on_search_schema_items, SearchSchemaItems}, server::{ lsp_state::handle_lsp_state_tasks, lsp_state_resources::LSPStateResources, task_queue::TaskQueue, }, shutdown::{on_exit, on_shutdown}, status_reporter::LSPStatusReporter, status_updater::set_initializing_status, text_documents::{ on_cancel, on_did_change_text_document, on_did_close_text_document, on_did_open_text_document, on_did_save_text_document, }, }; use common::{PerfLogEvent, PerfLogger}; use crossbeam::{channel::Receiver, select}; use log::debug; pub use lsp_notification_dispatch::LSPNotificationDispatch; pub use lsp_request_dispatch::LSPRequestDispatch; use lsp_server::{ Connection, ErrorCode, Message, Notification, Response as ServerResponse, ResponseError, }; use lsp_types::{ notification::{ Cancel, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, Exit, }, request::{ CodeActionRequest, Completion, GotoDefinition, HoverRequest, References, ResolveCompletionItem, Shutdown, }, CodeActionProviderCapability, CompletionOptions, InitializeParams, ServerCapabilities, TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, }; use relay_compiler::{config::Config, NoopArtifactWriter}; use schema_documentation::{SchemaDocumentation, SchemaDocumentationLoader}; use std::sync::Arc; pub use crate::LSPExtraDataProvider; pub use lsp_state::{convert_diagnostic, GlobalState, LSPState, Schemas, SourcePrograms}; use heartbeat::{on_heartbeat, HeartbeatRequest}; use self::task_queue::TaskProcessor; /// Initializes an LSP connection, handling the `initialize` message and `initialized` notification /// handshake. pub fn initialize(connection: &Connection) -> LSPProcessResult<InitializeParams> { let server_capabilities = ServerCapabilities { // Enable text document syncing so we can know when files are opened/changed/saved/closed text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::Full)), completion_provider: Some(CompletionOptions { resolve_provider: Some(true), trigger_characters: Some(vec!["(".into(), "\n".into(), ",".into(), "@".into()]), work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None, }, ..Default::default() }), hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)), definition_provider: Some(lsp_types::OneOf::Left(true)), references_provider: Some(lsp_types::OneOf::Left(true)), code_action_provider: Some(CodeActionProviderCapability::Simple(true)), ..Default::default() }; let server_capabilities = serde_json::to_value(&server_capabilities)?; let params = connection.initialize(server_capabilities)?; let params: InitializeParams = serde_json::from_value(params)?; Ok(params) } #[derive(Debug)] pub enum Task { InboundMessage(lsp_server::Message), LSPState(lsp_state::Task), } /// Run the main server loop pub async fn
< TPerfLogger: PerfLogger +'static, TSchemaDocumentation: SchemaDocumentation +'static, >( connection: Connection, mut config: Config, _params: InitializeParams, perf_logger: Arc<TPerfLogger>, extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>, schema_documentation_loader: Option<Box<dyn SchemaDocumentationLoader<TSchemaDocumentation>>>, js_resource: Option< Box<dyn JSLanguageServer<TState = LSPState<TPerfLogger, TSchemaDocumentation>>>, >, ) -> LSPProcessResult<()> where TPerfLogger: PerfLogger +'static, { debug!( "Running language server with config root {:?}", config.root_dir ); set_initializing_status(&connection.sender); let task_processor = LSPTaskProcessor; let task_queue = TaskQueue::new(Arc::new(task_processor)); let task_scheduler = task_queue.get_scheduler(); config.artifact_writer = Box::new(NoopArtifactWriter); config.status_reporter = Box::new(LSPStatusReporter::new( config.root_dir.clone(), connection.sender.clone(), )); let lsp_state = Arc::new(LSPState::new( Arc::new(config), connection.sender.clone(), Arc::clone(&task_scheduler), Arc::clone(&perf_logger), extra_data_provider, schema_documentation_loader, js_resource, )); LSPStateResources::new(Arc::clone(&lsp_state)).watch(); while let Some(task) = next_task(&connection.receiver, &task_queue.receiver) { task_queue.process(Arc::clone(&lsp_state), task); } panic!("Client exited without proper shutdown sequence.") } fn next_task( lsp_receiver: &Receiver<Message>, task_queue_receiver: &Receiver<Task>, ) -> Option<Task> { select! { recv(lsp_receiver) -> message => message.ok().map(Task::InboundMessage), recv(task_queue_receiver) -> task => task.ok() } } struct LSPTaskProcessor; impl<TPerfLogger: PerfLogger +'static, TSchemaDocumentation: SchemaDocumentation +'static> TaskProcessor<LSPState<TPerfLogger, TSchemaDocumentation>, Task> for LSPTaskProcessor { fn process(&self, state: Arc<LSPState<TPerfLogger, TSchemaDocumentation>>, task: Task) { match task { Task::InboundMessage(Message::Request(request)) => handle_request(state, request), Task::InboundMessage(Message::Notification(notification)) => { handle_notification(state, notification); } Task::LSPState(lsp_task) => { handle_lsp_state_tasks(state, lsp_task); } Task::InboundMessage(Message::Response(_)) => { // TODO: handle response from the client -> cancel message, etc } } } } fn handle_request<TPerfLogger: PerfLogger +'static, TSchemaDocumentation: SchemaDocumentation>( lsp_state: Arc<LSPState<TPerfLogger, TSchemaDocumentation>>, request: lsp_server::Request, ) { debug!("request received {:?}", request); let get_server_response_bound = |req| dispatch_request(req, lsp_state.as_ref()); let get_response = with_request_logging(&lsp_state.perf_logger, get_server_response_bound); lsp_state .send_message(Message::Response(get_response(request))) .expect("Unable to send message to a client."); } fn dispatch_request(request: lsp_server::Request, lsp_state: &impl GlobalState) -> ServerResponse { let get_response = || -> Result<_, ServerResponse> { let request = LSPRequestDispatch::new(request, lsp_state) .on_request_sync::<ResolvedTypesAtLocation>(on_get_resolved_types_at_location)? .on_request_sync::<SearchSchemaItems>(on_search_schema_items)? .on_request_sync::<ExploreSchemaForType>(on_explore_schema_for_type)? .on_request_sync::<GetSourceLocationOfTypeDefinition>( on_get_source_location_of_type_definition, )? .on_request_sync::<HoverRequest>(on_hover)? .on_request_sync::<GotoDefinition>(on_goto_definition)? .on_request_sync::<References>(on_references)? .on_request_sync::<Completion>(on_completion)? .on_request_sync::<ResolveCompletionItem>(on_resolve_completion_item)? .on_request_sync::<CodeActionRequest>(on_code_action)? .on_request_sync::<Shutdown>(on_shutdown)? .on_request_sync::<GraphQLExecuteQuery>(on_graphql_execute_query)? .on_request_sync::<HeartbeatRequest>(on_heartbeat)? .request(); // If we have gotten here, we have not handled the request Ok(ServerResponse { id: request.id, result: None, error: Some(ResponseError { code: ErrorCode::MethodNotFound as i32, data: None, message: format!("No handler registered for method '{}'", request.method), }), }) }; get_response().unwrap_or_else(|response| response) } fn with_request_logging<'a, TPerfLogger: PerfLogger +'static>( perf_logger: &'a Arc<TPerfLogger>, get_response: impl FnOnce(lsp_server::Request) -> ServerResponse + 'a, ) -> impl FnOnce(lsp_server::Request) -> ServerResponse + 'a { move |request| { let lsp_request_event = perf_logger.create_event("lsp_message"); lsp_request_event.string("lsp_method", request.method.clone()); lsp_request_event.string("lsp_type", "request".to_string()); let lsp_request_processing_time = lsp_request_event.start("lsp_message_processing_time"); let response = get_response(request); if response.result.is_some() { lsp_request_event.string("lsp_outcome", "success".to_string()); } else if let Some(error) = &response.error { if error.code == ErrorCode::RequestCanceled as i32 { lsp_request_event.string("lsp_outcome", "canceled".to_string()); } else { lsp_request_event.string("lsp_outcome", "error".to_string()); lsp_request_event.string("lsp_error_message", error.message.to_string()); if let Some(data) = &error.data { lsp_request_event.string("lsp_error_data", data.to_string()); } } } // N.B. we don't handle the case where the ServerResponse has neither a result nor // an error, which is an invalid state. lsp_request_event.stop(lsp_request_processing_time); lsp_request_event.complete(); response } } fn handle_notification< TPerfLogger: PerfLogger +'static, TSchemaDocumentation: SchemaDocumentation, >( lsp_state: Arc<LSPState<TPerfLogger, TSchemaDocumentation>>, notification: Notification, ) { debug!("notification received {:?}", notification); let lsp_notification_event = lsp_state.perf_logger.create_event("lsp_message"); lsp_notification_event.string("lsp_method", notification.method.clone()); lsp_notification_event.string("lsp_type", "notification".to_string()); let lsp_notification_processing_time = lsp_notification_event.start("lsp_message_processing_time"); let notification_result = dispatch_notification(notification, lsp_state.as_ref()); match notification_result { Ok(()) => { // The notification is not handled lsp_notification_event.string("lsp_outcome", "error".to_string()); } Err(err) => { if let Some(err) = err { lsp_notification_event.string("lsp_outcome", "error".to_string()); if let LSPRuntimeError::UnexpectedError(message) = err { lsp_notification_event.string("lsp_error_message", message); } } else { lsp_notification_event.string("lsp_outcome", "success".to_string()); } } } lsp_notification_event.stop(lsp_notification_processing_time); lsp_notification_event.complete(); } fn dispatch_notification( notification: lsp_server::Notification, lsp_state: &impl GlobalState, ) -> Result<(), Option<LSPRuntimeError>> { let notification = LSPNotificationDispatch::new(notification, lsp_state) .on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document)? .on_notification_sync::<DidCloseTextDocument>(on_did_close_text_document)? .on_notification_sync::<DidChangeTextDocument>(on_did_change_text_document)? .on_notification_sync::<DidSaveTextDocument>(on_did_save_text_document)? .on_notification_sync::<Cancel>(on_cancel)? .on_notification_sync::<Exit>(on_exit)? .notification(); // If we have gotten here, we have not handled the notification debug!( "Error: no handler registered for notification '{}'", notification.method ); Ok(()) }
run
identifier_name
mod.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ mod heartbeat; mod lsp_notification_dispatch; mod lsp_request_dispatch; mod lsp_state; mod lsp_state_resources; mod task_queue; use crate::{ code_action::on_code_action, completion::{on_completion, on_resolve_completion_item}, explore_schema_for_type::{on_explore_schema_for_type, ExploreSchemaForType}, goto_definition::{ on_get_source_location_of_type_definition, on_goto_definition, GetSourceLocationOfTypeDefinition, }, graphql_tools::on_graphql_execute_query, graphql_tools::GraphQLExecuteQuery, hover::on_hover, js_language_server::JSLanguageServer, lsp_process_error::LSPProcessResult, lsp_runtime_error::LSPRuntimeError, references::on_references, resolved_types_at_location::{on_get_resolved_types_at_location, ResolvedTypesAtLocation}, search_schema_items::{on_search_schema_items, SearchSchemaItems}, server::{ lsp_state::handle_lsp_state_tasks, lsp_state_resources::LSPStateResources, task_queue::TaskQueue, }, shutdown::{on_exit, on_shutdown}, status_reporter::LSPStatusReporter, status_updater::set_initializing_status, text_documents::{ on_cancel, on_did_change_text_document, on_did_close_text_document, on_did_open_text_document, on_did_save_text_document, }, }; use common::{PerfLogEvent, PerfLogger}; use crossbeam::{channel::Receiver, select}; use log::debug; pub use lsp_notification_dispatch::LSPNotificationDispatch; pub use lsp_request_dispatch::LSPRequestDispatch; use lsp_server::{ Connection, ErrorCode, Message, Notification, Response as ServerResponse, ResponseError, }; use lsp_types::{ notification::{ Cancel, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, Exit, }, request::{ CodeActionRequest, Completion, GotoDefinition, HoverRequest, References, ResolveCompletionItem, Shutdown, }, CodeActionProviderCapability, CompletionOptions, InitializeParams, ServerCapabilities, TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, }; use relay_compiler::{config::Config, NoopArtifactWriter}; use schema_documentation::{SchemaDocumentation, SchemaDocumentationLoader}; use std::sync::Arc; pub use crate::LSPExtraDataProvider; pub use lsp_state::{convert_diagnostic, GlobalState, LSPState, Schemas, SourcePrograms}; use heartbeat::{on_heartbeat, HeartbeatRequest}; use self::task_queue::TaskProcessor; /// Initializes an LSP connection, handling the `initialize` message and `initialized` notification /// handshake. pub fn initialize(connection: &Connection) -> LSPProcessResult<InitializeParams> { let server_capabilities = ServerCapabilities { // Enable text document syncing so we can know when files are opened/changed/saved/closed text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::Full)), completion_provider: Some(CompletionOptions { resolve_provider: Some(true), trigger_characters: Some(vec!["(".into(), "\n".into(), ",".into(), "@".into()]), work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None, }, ..Default::default() }), hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)), definition_provider: Some(lsp_types::OneOf::Left(true)), references_provider: Some(lsp_types::OneOf::Left(true)), code_action_provider: Some(CodeActionProviderCapability::Simple(true)), ..Default::default() }; let server_capabilities = serde_json::to_value(&server_capabilities)?; let params = connection.initialize(server_capabilities)?; let params: InitializeParams = serde_json::from_value(params)?; Ok(params) } #[derive(Debug)] pub enum Task { InboundMessage(lsp_server::Message), LSPState(lsp_state::Task), } /// Run the main server loop pub async fn run< TPerfLogger: PerfLogger +'static, TSchemaDocumentation: SchemaDocumentation +'static, >( connection: Connection, mut config: Config, _params: InitializeParams, perf_logger: Arc<TPerfLogger>, extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>, schema_documentation_loader: Option<Box<dyn SchemaDocumentationLoader<TSchemaDocumentation>>>, js_resource: Option< Box<dyn JSLanguageServer<TState = LSPState<TPerfLogger, TSchemaDocumentation>>>, >, ) -> LSPProcessResult<()> where TPerfLogger: PerfLogger +'static, { debug!( "Running language server with config root {:?}", config.root_dir ); set_initializing_status(&connection.sender); let task_processor = LSPTaskProcessor; let task_queue = TaskQueue::new(Arc::new(task_processor)); let task_scheduler = task_queue.get_scheduler(); config.artifact_writer = Box::new(NoopArtifactWriter); config.status_reporter = Box::new(LSPStatusReporter::new( config.root_dir.clone(), connection.sender.clone(), )); let lsp_state = Arc::new(LSPState::new( Arc::new(config), connection.sender.clone(), Arc::clone(&task_scheduler), Arc::clone(&perf_logger), extra_data_provider, schema_documentation_loader, js_resource, )); LSPStateResources::new(Arc::clone(&lsp_state)).watch(); while let Some(task) = next_task(&connection.receiver, &task_queue.receiver) { task_queue.process(Arc::clone(&lsp_state), task); } panic!("Client exited without proper shutdown sequence.") } fn next_task( lsp_receiver: &Receiver<Message>, task_queue_receiver: &Receiver<Task>, ) -> Option<Task> { select! { recv(lsp_receiver) -> message => message.ok().map(Task::InboundMessage), recv(task_queue_receiver) -> task => task.ok() } } struct LSPTaskProcessor; impl<TPerfLogger: PerfLogger +'static, TSchemaDocumentation: SchemaDocumentation +'static> TaskProcessor<LSPState<TPerfLogger, TSchemaDocumentation>, Task> for LSPTaskProcessor { fn process(&self, state: Arc<LSPState<TPerfLogger, TSchemaDocumentation>>, task: Task) { match task { Task::InboundMessage(Message::Request(request)) => handle_request(state, request), Task::InboundMessage(Message::Notification(notification)) => { handle_notification(state, notification); } Task::LSPState(lsp_task) =>
Task::InboundMessage(Message::Response(_)) => { // TODO: handle response from the client -> cancel message, etc } } } } fn handle_request<TPerfLogger: PerfLogger +'static, TSchemaDocumentation: SchemaDocumentation>( lsp_state: Arc<LSPState<TPerfLogger, TSchemaDocumentation>>, request: lsp_server::Request, ) { debug!("request received {:?}", request); let get_server_response_bound = |req| dispatch_request(req, lsp_state.as_ref()); let get_response = with_request_logging(&lsp_state.perf_logger, get_server_response_bound); lsp_state .send_message(Message::Response(get_response(request))) .expect("Unable to send message to a client."); } fn dispatch_request(request: lsp_server::Request, lsp_state: &impl GlobalState) -> ServerResponse { let get_response = || -> Result<_, ServerResponse> { let request = LSPRequestDispatch::new(request, lsp_state) .on_request_sync::<ResolvedTypesAtLocation>(on_get_resolved_types_at_location)? .on_request_sync::<SearchSchemaItems>(on_search_schema_items)? .on_request_sync::<ExploreSchemaForType>(on_explore_schema_for_type)? .on_request_sync::<GetSourceLocationOfTypeDefinition>( on_get_source_location_of_type_definition, )? .on_request_sync::<HoverRequest>(on_hover)? .on_request_sync::<GotoDefinition>(on_goto_definition)? .on_request_sync::<References>(on_references)? .on_request_sync::<Completion>(on_completion)? .on_request_sync::<ResolveCompletionItem>(on_resolve_completion_item)? .on_request_sync::<CodeActionRequest>(on_code_action)? .on_request_sync::<Shutdown>(on_shutdown)? .on_request_sync::<GraphQLExecuteQuery>(on_graphql_execute_query)? .on_request_sync::<HeartbeatRequest>(on_heartbeat)? .request(); // If we have gotten here, we have not handled the request Ok(ServerResponse { id: request.id, result: None, error: Some(ResponseError { code: ErrorCode::MethodNotFound as i32, data: None, message: format!("No handler registered for method '{}'", request.method), }), }) }; get_response().unwrap_or_else(|response| response) } fn with_request_logging<'a, TPerfLogger: PerfLogger +'static>( perf_logger: &'a Arc<TPerfLogger>, get_response: impl FnOnce(lsp_server::Request) -> ServerResponse + 'a, ) -> impl FnOnce(lsp_server::Request) -> ServerResponse + 'a { move |request| { let lsp_request_event = perf_logger.create_event("lsp_message"); lsp_request_event.string("lsp_method", request.method.clone()); lsp_request_event.string("lsp_type", "request".to_string()); let lsp_request_processing_time = lsp_request_event.start("lsp_message_processing_time"); let response = get_response(request); if response.result.is_some() { lsp_request_event.string("lsp_outcome", "success".to_string()); } else if let Some(error) = &response.error { if error.code == ErrorCode::RequestCanceled as i32 { lsp_request_event.string("lsp_outcome", "canceled".to_string()); } else { lsp_request_event.string("lsp_outcome", "error".to_string()); lsp_request_event.string("lsp_error_message", error.message.to_string()); if let Some(data) = &error.data { lsp_request_event.string("lsp_error_data", data.to_string()); } } } // N.B. we don't handle the case where the ServerResponse has neither a result nor // an error, which is an invalid state. lsp_request_event.stop(lsp_request_processing_time); lsp_request_event.complete(); response } } fn handle_notification< TPerfLogger: PerfLogger +'static, TSchemaDocumentation: SchemaDocumentation, >( lsp_state: Arc<LSPState<TPerfLogger, TSchemaDocumentation>>, notification: Notification, ) { debug!("notification received {:?}", notification); let lsp_notification_event = lsp_state.perf_logger.create_event("lsp_message"); lsp_notification_event.string("lsp_method", notification.method.clone()); lsp_notification_event.string("lsp_type", "notification".to_string()); let lsp_notification_processing_time = lsp_notification_event.start("lsp_message_processing_time"); let notification_result = dispatch_notification(notification, lsp_state.as_ref()); match notification_result { Ok(()) => { // The notification is not handled lsp_notification_event.string("lsp_outcome", "error".to_string()); } Err(err) => { if let Some(err) = err { lsp_notification_event.string("lsp_outcome", "error".to_string()); if let LSPRuntimeError::UnexpectedError(message) = err { lsp_notification_event.string("lsp_error_message", message); } } else { lsp_notification_event.string("lsp_outcome", "success".to_string()); } } } lsp_notification_event.stop(lsp_notification_processing_time); lsp_notification_event.complete(); } fn dispatch_notification( notification: lsp_server::Notification, lsp_state: &impl GlobalState, ) -> Result<(), Option<LSPRuntimeError>> { let notification = LSPNotificationDispatch::new(notification, lsp_state) .on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document)? .on_notification_sync::<DidCloseTextDocument>(on_did_close_text_document)? .on_notification_sync::<DidChangeTextDocument>(on_did_change_text_document)? .on_notification_sync::<DidSaveTextDocument>(on_did_save_text_document)? .on_notification_sync::<Cancel>(on_cancel)? .on_notification_sync::<Exit>(on_exit)? .notification(); // If we have gotten here, we have not handled the notification debug!( "Error: no handler registered for notification '{}'", notification.method ); Ok(()) }
{ handle_lsp_state_tasks(state, lsp_task); }
conditional_block
lib.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. #![warn(missing_docs)] #![cfg_attr(all(nightly, feature="dev"), feature(plugin))] #![cfg_attr(all(nightly, feature="dev"), plugin(clippy))] //! Signer module //! //! This module manages your private keys and accounts/identities //! that can be used within Dapps. //! //! It exposes API (over `WebSockets`) accessed by Signer UIs. //! Each transaction sent by Dapp is broadcasted to Signer UIs //! and their responsibility is to confirm (or confirm and sign) //! the transaction for you. //! //! ``` //! extern crate jsonrpc_core; //! extern crate ethcore_signer; //! extern crate ethcore_rpc; //! //! use std::sync::Arc; //! use jsonrpc_core::IoHandler; //! use jsonrpc_core::reactor::RpcEventLoop; //! use ethcore_signer::ServerBuilder; //! use ethcore_rpc::ConfirmationsQueue; //! //! fn main() { //! let queue = Arc::new(ConfirmationsQueue::default());
//! ``` #[macro_use] extern crate log; extern crate env_logger; extern crate rand; extern crate ethcore_util as util; extern crate ethcore_rpc as rpc; extern crate ethcore_io as io; extern crate jsonrpc_core; extern crate ws; extern crate ethcore_devtools as devtools; mod authcode_store; mod ws_server; /// Exported tests for use in signer RPC client testing pub mod tests; pub use authcode_store::*; pub use ws_server::*;
//! let io = Arc::new(IoHandler::new().into()); //! let event_loop = RpcEventLoop::spawn(); //! let _server = ServerBuilder::new(queue, "/tmp/authcodes".into()) //! .start("127.0.0.1:8084".parse().unwrap(), event_loop.handler(io)); //! }
random_line_split
lib.rs
//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event //! notification, and other useful utilities for building high performance IO //! apps. //! //! # Goals //! //! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...) //! * Zero allocations //! * A scalable readiness-based API, similar to epoll on Linux //! * Design to allow for stack allocated buffers when possible (avoid double buffering). //! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab. //! //! # Usage //! //! Using mio starts by creating an [EventLoop](struct.EventLoop.html), which //! handles receiving events from the OS and dispatching them to a supplied //! [Handler](handler/trait.Handler.html). //! //! # Example //! //! ``` //! use mio::*; //! use mio::tcp::{TcpListener, TcpStream}; //! //! // Setup some tokens to allow us to identify which event is //! // for which socket. //! const SERVER: Token = Token(0); //! const CLIENT: Token = Token(1); //! # //! # // level() isn't implemented on windows yet //! # if cfg!(windows) { return } //! //! let addr = "127.0.0.1:13265".parse().unwrap(); //! //! // Setup the server socket //! let server = TcpListener::bind(&addr).unwrap(); //! //! // Create an event loop //! let mut event_loop = EventLoop::new().unwrap(); //! //! // Start listening for incoming connections //! event_loop.register(&server, SERVER, EventSet::readable(), //! PollOpt::edge()).unwrap(); //! //! // Setup the client socket //! let sock = TcpStream::connect(&addr).unwrap(); //! //! // Register the socket //! event_loop.register(&sock, CLIENT, EventSet::readable(), //! PollOpt::edge()).unwrap(); //! //! // Define a handler to process the events //! struct MyHandler(TcpListener); //!
//! type Message = (); //! //! fn ready(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: EventSet) { //! match token { //! SERVER => { //! let MyHandler(ref mut server) = *self; //! // Accept and drop the socket immediately, this will close //! // the socket and notify the client of the EOF. //! let _ = server.accept(); //! } //! CLIENT => { //! // The server just shuts down the socket, let's just //! // shutdown the event loop //! event_loop.shutdown(); //! } //! _ => panic!("unexpected token"), //! } //! } //! } //! //! // Start handling events //! event_loop.run(&mut MyHandler(server)).unwrap(); //! //! ``` #![crate_name = "mio"] #![cfg_attr(unix, deny(warnings))] extern crate bytes; extern crate time; extern crate slab; extern crate libc; #[cfg(unix)] extern crate nix; extern crate winapi; extern crate miow; extern crate net2; #[macro_use] extern crate log; #[cfg(test)] extern crate env_logger; pub mod util; mod event; mod event_loop; mod handler; mod io; mod net; mod notify; mod poll; mod sys; mod timer; mod token; pub use event::{ PollOpt, EventSet, }; pub use event_loop::{ EventLoop, EventLoopConfig, Sender, }; pub use handler::{ Handler, }; pub use io::{ TryRead, TryWrite, Evented, TryAccept, }; pub use net::{ tcp, udp, IpAddr, Ipv4Addr, Ipv6Addr, }; #[cfg(unix)] pub mod unix { pub use net::unix::{ pipe, PipeReader, PipeWriter, UnixListener, UnixSocket, UnixStream, }; pub use sys::{ EventedFd, }; } pub use notify::{ NotifyError, }; pub use poll::{ Poll }; pub use timer::{ Timeout, TimerError, TimerResult }; pub use token::{ Token, }; #[cfg(unix)] pub use sys::Io; pub use sys::Selector; pub mod prelude { pub use super::{ EventLoop, TryRead, TryWrite, }; }
//! impl Handler for MyHandler { //! type Timeout = ();
random_line_split
base64.rs
#![feature(test)] extern crate test; extern crate rustc_serialize; use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; use test::Bencher; #[bench] fn bench_to_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; b.iter(|| { s.as_bytes().to_base64(STANDARD); }); b.bytes = s.len() as u64; }
γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; let sb = s.as_bytes().to_base64(STANDARD); b.iter(|| { sb.from_base64().unwrap(); }); b.bytes = sb.len() as u64; } #[bench] fn bench_to_base64_large(b: &mut Bencher) { let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect(); b.iter(|| { s.to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] fn bench_from_base64_large(b: &mut Bencher) { let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect(); let sb = s.to_base64(STANDARD); b.iter(|| { sb.from_base64().unwrap(); }); b.bytes = sb.len() as u64; }
#[bench] fn bench_from_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \
random_line_split
base64.rs
#![feature(test)] extern crate test; extern crate rustc_serialize; use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; use test::Bencher; #[bench] fn
(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; b.iter(|| { s.as_bytes().to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] fn bench_from_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; let sb = s.as_bytes().to_base64(STANDARD); b.iter(|| { sb.from_base64().unwrap(); }); b.bytes = sb.len() as u64; } #[bench] fn bench_to_base64_large(b: &mut Bencher) { let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect(); b.iter(|| { s.to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] fn bench_from_base64_large(b: &mut Bencher) { let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect(); let sb = s.to_base64(STANDARD); b.iter(|| { sb.from_base64().unwrap(); }); b.bytes = sb.len() as u64; }
bench_to_base64
identifier_name
base64.rs
#![feature(test)] extern crate test; extern crate rustc_serialize; use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; use test::Bencher; #[bench] fn bench_to_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; b.iter(|| { s.as_bytes().to_base64(STANDARD); }); b.bytes = s.len() as u64; } #[bench] fn bench_from_base64(b: &mut Bencher) { let s = "γ‚€γƒ­γƒγƒ‹γƒ›γƒ˜γƒˆ チγƒͺγƒŒγƒ«γƒ² ワカヨタレソ γƒ„γƒγƒŠγƒ©γƒ  \ γ‚¦γƒ°γƒŽγ‚ͺγ‚―γƒ€γƒž ケフコエテ γ‚’γ‚΅γ‚­γƒ¦γƒ‘γƒŸγ‚· ヱヒヒセスン"; let
); b.bytes = s.len() as u64; } #[bench] fn bench_from_base64_large(b: &mut Bencher) { let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect(); let sb = s.to_base64(STANDARD); b.iter(|| { sb.from_base64().unwrap(); }); b.bytes = sb.len() as u64; }
sb = s.as_bytes().to_base64(STANDARD); b.iter(|| { sb.from_base64().unwrap(); }); b.bytes = sb.len() as u64; } #[bench] fn bench_to_base64_large(b: &mut Bencher) { let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect(); b.iter(|| { s.to_base64(STANDARD); }
identifier_body
jmethodid.rs
use std::marker::PhantomData; use sys::jmethodID; /// Wrapper around `sys::jmethodid` that adds a lifetime. This prevents it from /// outliving the context in which it was acquired and getting GC'd out from /// under us. It matches C's representation of the raw pointer, so it can be /// used in any of the extern function argument positions that would take a /// `jmethodid`. #[repr(C)] #[derive(Copy, Clone)] pub struct JMethodID<'a> { internal: jmethodID, lifetime: PhantomData<&'a ()>, } impl<'a> From<jmethodID> for JMethodID<'a> { fn from(other: jmethodID) -> Self { JMethodID { internal: other, lifetime: PhantomData,
impl<'a> JMethodID<'a> { /// Unwrap to the internal jni type. pub fn into_inner(self) -> jmethodID { self.internal } }
} } }
random_line_split
jmethodid.rs
use std::marker::PhantomData; use sys::jmethodID; /// Wrapper around `sys::jmethodid` that adds a lifetime. This prevents it from /// outliving the context in which it was acquired and getting GC'd out from /// under us. It matches C's representation of the raw pointer, so it can be /// used in any of the extern function argument positions that would take a /// `jmethodid`. #[repr(C)] #[derive(Copy, Clone)] pub struct JMethodID<'a> { internal: jmethodID, lifetime: PhantomData<&'a ()>, } impl<'a> From<jmethodID> for JMethodID<'a> { fn from(other: jmethodID) -> Self { JMethodID { internal: other, lifetime: PhantomData, } } } impl<'a> JMethodID<'a> { /// Unwrap to the internal jni type. pub fn
(self) -> jmethodID { self.internal } }
into_inner
identifier_name
jmethodid.rs
use std::marker::PhantomData; use sys::jmethodID; /// Wrapper around `sys::jmethodid` that adds a lifetime. This prevents it from /// outliving the context in which it was acquired and getting GC'd out from /// under us. It matches C's representation of the raw pointer, so it can be /// used in any of the extern function argument positions that would take a /// `jmethodid`. #[repr(C)] #[derive(Copy, Clone)] pub struct JMethodID<'a> { internal: jmethodID, lifetime: PhantomData<&'a ()>, } impl<'a> From<jmethodID> for JMethodID<'a> { fn from(other: jmethodID) -> Self { JMethodID { internal: other, lifetime: PhantomData, } } } impl<'a> JMethodID<'a> { /// Unwrap to the internal jni type. pub fn into_inner(self) -> jmethodID
}
{ self.internal }
identifier_body
error.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::error; use std::fmt; use svgdom; /// List of all errors. #[derive(Debug)] pub enum
{ /// Only `svg` and `svgz` suffixes are supported. InvalidFileSuffix, /// Failed to open the provided file. FileOpenFailed, /// Only UTF-8 content are supported. NotAnUtf8Str, /// Compressed SVG must use the GZip algorithm. MalformedGZip, /// SVG doesn't have a valid size. /// /// Occurs when width and/or height are <= 0. /// /// Also occurs if width, height and viewBox are not set. /// This is against the SVG spec, but an automatic size detection is not supported yet. InvalidSize, /// Failed to parse an SVG data. ParsingFailed(svgdom::ParserError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::InvalidFileSuffix => { write!(f, "invalid file suffix") } Error::FileOpenFailed => { write!(f, "failed to open the provided file") } Error::NotAnUtf8Str => { write!(f, "provided data has not an UTF-8 encoding") } Error::MalformedGZip => { write!(f, "provided data has a malformed GZip content") } Error::InvalidSize => { write!(f, "SVG has an invalid size") } Error::ParsingFailed(ref e) => { write!(f, "SVG data parsing failed cause {}", e) } } } } impl error::Error for Error { fn description(&self) -> &str { "an SVG simplification error" } }
Error
identifier_name
error.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::error; use std::fmt; use svgdom; /// List of all errors. #[derive(Debug)] pub enum Error { /// Only `svg` and `svgz` suffixes are supported. InvalidFileSuffix, /// Failed to open the provided file. FileOpenFailed, /// Only UTF-8 content are supported. NotAnUtf8Str, /// Compressed SVG must use the GZip algorithm. MalformedGZip, /// SVG doesn't have a valid size. /// /// Occurs when width and/or height are <= 0. /// /// Also occurs if width, height and viewBox are not set. /// This is against the SVG spec, but an automatic size detection is not supported yet. InvalidSize, /// Failed to parse an SVG data. ParsingFailed(svgdom::ParserError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::InvalidFileSuffix =>
Error::FileOpenFailed => { write!(f, "failed to open the provided file") } Error::NotAnUtf8Str => { write!(f, "provided data has not an UTF-8 encoding") } Error::MalformedGZip => { write!(f, "provided data has a malformed GZip content") } Error::InvalidSize => { write!(f, "SVG has an invalid size") } Error::ParsingFailed(ref e) => { write!(f, "SVG data parsing failed cause {}", e) } } } } impl error::Error for Error { fn description(&self) -> &str { "an SVG simplification error" } }
{ write!(f, "invalid file suffix") }
conditional_block
error.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::error; use std::fmt; use svgdom; /// List of all errors. #[derive(Debug)] pub enum Error { /// Only `svg` and `svgz` suffixes are supported. InvalidFileSuffix,
/// Failed to open the provided file. FileOpenFailed, /// Only UTF-8 content are supported. NotAnUtf8Str, /// Compressed SVG must use the GZip algorithm. MalformedGZip, /// SVG doesn't have a valid size. /// /// Occurs when width and/or height are <= 0. /// /// Also occurs if width, height and viewBox are not set. /// This is against the SVG spec, but an automatic size detection is not supported yet. InvalidSize, /// Failed to parse an SVG data. ParsingFailed(svgdom::ParserError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::InvalidFileSuffix => { write!(f, "invalid file suffix") } Error::FileOpenFailed => { write!(f, "failed to open the provided file") } Error::NotAnUtf8Str => { write!(f, "provided data has not an UTF-8 encoding") } Error::MalformedGZip => { write!(f, "provided data has a malformed GZip content") } Error::InvalidSize => { write!(f, "SVG has an invalid size") } Error::ParsingFailed(ref e) => { write!(f, "SVG data parsing failed cause {}", e) } } } } impl error::Error for Error { fn description(&self) -> &str { "an SVG simplification error" } }
random_line_split
mod.rs
use serde::{Deserialize, Serialize}; use std::error::Error; use std::fs::File; use std::path::Path; #[derive(Serialize, Deserialize)] pub struct Database { pub repository: String, } #[derive(Serialize, Deserialize)] pub struct
{ pub port: u16, pub address: String, pub hostname: String, } #[derive(Serialize, Deserialize)] pub struct Display { pub width: u32, pub height: u32, } #[derive(Serialize, Deserialize)] pub struct Poetry { pub font: String, pub speed: f32, } #[derive(Serialize, Deserialize)] pub struct Emulator { pub roms: String, #[serde(default)] pub dmg: bool, #[serde(default = "default_fps")] pub fps: u32, } #[derive(Serialize, Deserialize, Clone)] pub struct Mqtt { pub server: String, pub port: Option<u16>, pub username: Option<String>, pub password: Option<String>, pub topic: String, } fn default_fps() -> u32 { 60 } #[derive(Serialize, Deserialize)] pub struct Config { pub logconfig: String, pub database: Database, pub server: Server, pub display: Display, pub poetry: Poetry, pub emulator: Emulator, pub mqtt: Option<Mqtt>, } impl Config { pub fn new<P: AsRef<Path>>(path: P) -> Result<Config, Box<dyn Error>> { let file = File::open(path)?; let u: Config = serde_json::from_reader(file)?; Ok(u) } }
Server
identifier_name
mod.rs
use serde::{Deserialize, Serialize}; use std::error::Error; use std::fs::File; use std::path::Path; #[derive(Serialize, Deserialize)] pub struct Database { pub repository: String, } #[derive(Serialize, Deserialize)] pub struct Server { pub port: u16, pub address: String, pub hostname: String, } #[derive(Serialize, Deserialize)] pub struct Display { pub width: u32, pub height: u32, } #[derive(Serialize, Deserialize)] pub struct Poetry { pub font: String, pub speed: f32, } #[derive(Serialize, Deserialize)] pub struct Emulator { pub roms: String, #[serde(default)] pub dmg: bool,
#[derive(Serialize, Deserialize, Clone)] pub struct Mqtt { pub server: String, pub port: Option<u16>, pub username: Option<String>, pub password: Option<String>, pub topic: String, } fn default_fps() -> u32 { 60 } #[derive(Serialize, Deserialize)] pub struct Config { pub logconfig: String, pub database: Database, pub server: Server, pub display: Display, pub poetry: Poetry, pub emulator: Emulator, pub mqtt: Option<Mqtt>, } impl Config { pub fn new<P: AsRef<Path>>(path: P) -> Result<Config, Box<dyn Error>> { let file = File::open(path)?; let u: Config = serde_json::from_reader(file)?; Ok(u) } }
#[serde(default = "default_fps")] pub fps: u32, }
random_line_split
constants.rs
/// Ο€ <https://oeis.org/A000796> pub const PI: f64 = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214; /// sqrt(2) <https://oeis.org/A002193> pub const SQRT_2: f64 = 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157f64; /// sqrt(3) <https://oeis.org/A002194> pub const SQRT_3: f64 = 1.7320508075688772935274463415058723669428052538103806280558069794519330169088000370811461867572485756756261414154f64; /// sqrt(6) <https://oeis.org/A010464>
pub const SQRT_2_BY_3: f64 = 0.816496580927726032732428024901963797321982493552223376144230855750320125819105008846619811034880078272864f64; /// sqt(3/2) <https://oeis.org/A115754> pub const SQRT_3_BY_2: f64 = 1.22474487139158904909864203735294569598297374032833506421634628362548018872865751326992971655232011f64; /// 1/3 pub const ONE_BY_3: f64 = 0.33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333f64; /// 2/3 pub const TWO_BY_3: f64 = 0.66666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666f64;
pub const SQRT_6: f64 = 2.44948974278317809819728407470589139196594748065667012843269256725096037745731502653985943310464023f64; /// sqrt(2/3) <https://oeis.org/A157697>
random_line_split
shuffle_split.rs
//! Validation via repeated random shuffling //! of the data and splitting into a training and test set. //! //! # Examples //! //! ``` //! use rustlearn::prelude::*; //! use rustlearn::datasets::iris; //! use rustlearn::cross_validation::ShuffleSplit; //! //! //! let (X, y) = iris::load_data(); //! //! let num_splits = 10; //! let test_percentage = 0.2; //! //! for (train_idx, test_idx) in ShuffleSplit::new(X.rows(), num_splits, test_percentage) { //! //! let X_train = X.get_rows(&train_idx); //! let y_train = y.get_rows(&train_idx); //! let X_test = X.get_rows(&test_idx); //! let y_test = y.get_rows(&test_idx); //! //! // Model fitting happens here //! } //! ``` use std::iter::Iterator; use rand; use rand::Rng; pub struct ShuffleSplit { n: usize, n_iter: usize, test_size: f32, rng: rand::StdRng, iter: usize, } impl ShuffleSplit { /// Create a new instance of the shuffle split utility. /// /// Iterating over it will split the dataset of size `n_samples` /// into a train set of `(1.0 - test_size) * n_samples` rows /// and a test set of `test_size * n_samples` rows, `n_iter` times. pub fn new(n_samples: usize, n_iter: usize, test_size: f32) -> ShuffleSplit { ShuffleSplit { n: n_samples, n_iter: n_iter, test_size: test_size, rng: rand::StdRng::new().unwrap(), iter: 0, } } /// Set the random number generator. pub fn set_rng(&mut self, rng: rand::StdRng) { self.rng = rng; } fn get_shuffled_indices(&mut self) -> Vec<usize> { let mut indices = (0..self.n).collect::<Vec<usize>>(); self.rng.shuffle(&mut indices); indices } } impl Iterator for ShuffleSplit { type Item = (Vec<usize>, Vec<usize>); fn next(&mut self) -> Option<(Vec<usize>, Vec<usize>)> { let ret = if self.iter < self.n_iter
else { None }; self.iter += 1; ret } } #[cfg(test)] mod tests { use super::*; extern crate rand; use rand::{SeedableRng, StdRng}; #[test] fn iteration() { let split = ShuffleSplit::new(100, 4, 0.2); let mut count = 0; for _ in split { count += 1; } assert!(count == 4); } #[test] fn size_split() { let split = ShuffleSplit::new(100, 4, 0.2); for (train, test) in split { assert!(train.len() == 80); assert!(test.len() == 20); } } #[test] #[should_panic] fn shuffle_differs() { let set1 = ShuffleSplit::new(1000, 1, 0.2).collect::<Vec<_>>(); let set2 = ShuffleSplit::new(1000, 1, 0.2).collect::<Vec<_>>(); assert!(set1[0].0 == set2[0].0); } #[test] fn set_rng() { let seed: &[_] = &[1, 2, 3, 4]; let rng1: StdRng = SeedableRng::from_seed(seed); let rng2: StdRng = SeedableRng::from_seed(seed); let mut split1 = ShuffleSplit::new(1000, 1, 0.2); let mut split2 = ShuffleSplit::new(1000, 1, 0.2); split1.set_rng(rng1); split2.set_rng(rng2); let set1 = split1.collect::<Vec<_>>(); let set2 = split2.collect::<Vec<_>>(); assert!(set1[0].0 == set2[0].0); } }
{ let split_idx: usize = (self.n as f32 * (1.0 - self.test_size)).floor() as usize; let shuffled_indices = self.get_shuffled_indices(); let (train, test) = shuffled_indices.split_at(split_idx); Some((train.to_owned(), test.to_owned())) }
conditional_block
shuffle_split.rs
//! Validation via repeated random shuffling //! of the data and splitting into a training and test set. //! //! # Examples //! //! ``` //! use rustlearn::prelude::*; //! use rustlearn::datasets::iris; //! use rustlearn::cross_validation::ShuffleSplit; //! //! //! let (X, y) = iris::load_data(); //! //! let num_splits = 10; //! let test_percentage = 0.2; //! //! for (train_idx, test_idx) in ShuffleSplit::new(X.rows(), num_splits, test_percentage) { //! //! let X_train = X.get_rows(&train_idx); //! let y_train = y.get_rows(&train_idx); //! let X_test = X.get_rows(&test_idx); //! let y_test = y.get_rows(&test_idx); //! //! // Model fitting happens here //! } //! ``` use std::iter::Iterator; use rand; use rand::Rng; pub struct ShuffleSplit { n: usize, n_iter: usize, test_size: f32, rng: rand::StdRng, iter: usize, } impl ShuffleSplit { /// Create a new instance of the shuffle split utility. /// /// Iterating over it will split the dataset of size `n_samples` /// into a train set of `(1.0 - test_size) * n_samples` rows /// and a test set of `test_size * n_samples` rows, `n_iter` times. pub fn new(n_samples: usize, n_iter: usize, test_size: f32) -> ShuffleSplit { ShuffleSplit { n: n_samples, n_iter: n_iter, test_size: test_size, rng: rand::StdRng::new().unwrap(), iter: 0, } } /// Set the random number generator. pub fn set_rng(&mut self, rng: rand::StdRng) { self.rng = rng; } fn get_shuffled_indices(&mut self) -> Vec<usize> { let mut indices = (0..self.n).collect::<Vec<usize>>(); self.rng.shuffle(&mut indices); indices } } impl Iterator for ShuffleSplit { type Item = (Vec<usize>, Vec<usize>); fn next(&mut self) -> Option<(Vec<usize>, Vec<usize>)> { let ret = if self.iter < self.n_iter { let split_idx: usize = (self.n as f32 * (1.0 - self.test_size)).floor() as usize; let shuffled_indices = self.get_shuffled_indices(); let (train, test) = shuffled_indices.split_at(split_idx); Some((train.to_owned(), test.to_owned())) } else { None }; self.iter += 1; ret } } #[cfg(test)] mod tests { use super::*; extern crate rand; use rand::{SeedableRng, StdRng}; #[test] fn iteration() { let split = ShuffleSplit::new(100, 4, 0.2); let mut count = 0; for _ in split { count += 1; } assert!(count == 4); } #[test] fn size_split() { let split = ShuffleSplit::new(100, 4, 0.2); for (train, test) in split { assert!(train.len() == 80); assert!(test.len() == 20); } } #[test] #[should_panic] fn shuffle_differs() { let set1 = ShuffleSplit::new(1000, 1, 0.2).collect::<Vec<_>>(); let set2 = ShuffleSplit::new(1000, 1, 0.2).collect::<Vec<_>>(); assert!(set1[0].0 == set2[0].0); } #[test] fn set_rng() { let seed: &[_] = &[1, 2, 3, 4]; let rng1: StdRng = SeedableRng::from_seed(seed); let rng2: StdRng = SeedableRng::from_seed(seed); let mut split1 = ShuffleSplit::new(1000, 1, 0.2); let mut split2 = ShuffleSplit::new(1000, 1, 0.2); split1.set_rng(rng1); split2.set_rng(rng2);
let set2 = split2.collect::<Vec<_>>(); assert!(set1[0].0 == set2[0].0); } }
let set1 = split1.collect::<Vec<_>>();
random_line_split
shuffle_split.rs
//! Validation via repeated random shuffling //! of the data and splitting into a training and test set. //! //! # Examples //! //! ``` //! use rustlearn::prelude::*; //! use rustlearn::datasets::iris; //! use rustlearn::cross_validation::ShuffleSplit; //! //! //! let (X, y) = iris::load_data(); //! //! let num_splits = 10; //! let test_percentage = 0.2; //! //! for (train_idx, test_idx) in ShuffleSplit::new(X.rows(), num_splits, test_percentage) { //! //! let X_train = X.get_rows(&train_idx); //! let y_train = y.get_rows(&train_idx); //! let X_test = X.get_rows(&test_idx); //! let y_test = y.get_rows(&test_idx); //! //! // Model fitting happens here //! } //! ``` use std::iter::Iterator; use rand; use rand::Rng; pub struct ShuffleSplit { n: usize, n_iter: usize, test_size: f32, rng: rand::StdRng, iter: usize, } impl ShuffleSplit { /// Create a new instance of the shuffle split utility. /// /// Iterating over it will split the dataset of size `n_samples` /// into a train set of `(1.0 - test_size) * n_samples` rows /// and a test set of `test_size * n_samples` rows, `n_iter` times. pub fn new(n_samples: usize, n_iter: usize, test_size: f32) -> ShuffleSplit { ShuffleSplit { n: n_samples, n_iter: n_iter, test_size: test_size, rng: rand::StdRng::new().unwrap(), iter: 0, } } /// Set the random number generator. pub fn set_rng(&mut self, rng: rand::StdRng) { self.rng = rng; } fn get_shuffled_indices(&mut self) -> Vec<usize> { let mut indices = (0..self.n).collect::<Vec<usize>>(); self.rng.shuffle(&mut indices); indices } } impl Iterator for ShuffleSplit { type Item = (Vec<usize>, Vec<usize>); fn
(&mut self) -> Option<(Vec<usize>, Vec<usize>)> { let ret = if self.iter < self.n_iter { let split_idx: usize = (self.n as f32 * (1.0 - self.test_size)).floor() as usize; let shuffled_indices = self.get_shuffled_indices(); let (train, test) = shuffled_indices.split_at(split_idx); Some((train.to_owned(), test.to_owned())) } else { None }; self.iter += 1; ret } } #[cfg(test)] mod tests { use super::*; extern crate rand; use rand::{SeedableRng, StdRng}; #[test] fn iteration() { let split = ShuffleSplit::new(100, 4, 0.2); let mut count = 0; for _ in split { count += 1; } assert!(count == 4); } #[test] fn size_split() { let split = ShuffleSplit::new(100, 4, 0.2); for (train, test) in split { assert!(train.len() == 80); assert!(test.len() == 20); } } #[test] #[should_panic] fn shuffle_differs() { let set1 = ShuffleSplit::new(1000, 1, 0.2).collect::<Vec<_>>(); let set2 = ShuffleSplit::new(1000, 1, 0.2).collect::<Vec<_>>(); assert!(set1[0].0 == set2[0].0); } #[test] fn set_rng() { let seed: &[_] = &[1, 2, 3, 4]; let rng1: StdRng = SeedableRng::from_seed(seed); let rng2: StdRng = SeedableRng::from_seed(seed); let mut split1 = ShuffleSplit::new(1000, 1, 0.2); let mut split2 = ShuffleSplit::new(1000, 1, 0.2); split1.set_rng(rng1); split2.set_rng(rng2); let set1 = split1.collect::<Vec<_>>(); let set2 = split2.collect::<Vec<_>>(); assert!(set1[0].0 == set2[0].0); } }
next
identifier_name
shuffle_split.rs
//! Validation via repeated random shuffling //! of the data and splitting into a training and test set. //! //! # Examples //! //! ``` //! use rustlearn::prelude::*; //! use rustlearn::datasets::iris; //! use rustlearn::cross_validation::ShuffleSplit; //! //! //! let (X, y) = iris::load_data(); //! //! let num_splits = 10; //! let test_percentage = 0.2; //! //! for (train_idx, test_idx) in ShuffleSplit::new(X.rows(), num_splits, test_percentage) { //! //! let X_train = X.get_rows(&train_idx); //! let y_train = y.get_rows(&train_idx); //! let X_test = X.get_rows(&test_idx); //! let y_test = y.get_rows(&test_idx); //! //! // Model fitting happens here //! } //! ``` use std::iter::Iterator; use rand; use rand::Rng; pub struct ShuffleSplit { n: usize, n_iter: usize, test_size: f32, rng: rand::StdRng, iter: usize, } impl ShuffleSplit { /// Create a new instance of the shuffle split utility. /// /// Iterating over it will split the dataset of size `n_samples` /// into a train set of `(1.0 - test_size) * n_samples` rows /// and a test set of `test_size * n_samples` rows, `n_iter` times. pub fn new(n_samples: usize, n_iter: usize, test_size: f32) -> ShuffleSplit { ShuffleSplit { n: n_samples, n_iter: n_iter, test_size: test_size, rng: rand::StdRng::new().unwrap(), iter: 0, } } /// Set the random number generator. pub fn set_rng(&mut self, rng: rand::StdRng)
fn get_shuffled_indices(&mut self) -> Vec<usize> { let mut indices = (0..self.n).collect::<Vec<usize>>(); self.rng.shuffle(&mut indices); indices } } impl Iterator for ShuffleSplit { type Item = (Vec<usize>, Vec<usize>); fn next(&mut self) -> Option<(Vec<usize>, Vec<usize>)> { let ret = if self.iter < self.n_iter { let split_idx: usize = (self.n as f32 * (1.0 - self.test_size)).floor() as usize; let shuffled_indices = self.get_shuffled_indices(); let (train, test) = shuffled_indices.split_at(split_idx); Some((train.to_owned(), test.to_owned())) } else { None }; self.iter += 1; ret } } #[cfg(test)] mod tests { use super::*; extern crate rand; use rand::{SeedableRng, StdRng}; #[test] fn iteration() { let split = ShuffleSplit::new(100, 4, 0.2); let mut count = 0; for _ in split { count += 1; } assert!(count == 4); } #[test] fn size_split() { let split = ShuffleSplit::new(100, 4, 0.2); for (train, test) in split { assert!(train.len() == 80); assert!(test.len() == 20); } } #[test] #[should_panic] fn shuffle_differs() { let set1 = ShuffleSplit::new(1000, 1, 0.2).collect::<Vec<_>>(); let set2 = ShuffleSplit::new(1000, 1, 0.2).collect::<Vec<_>>(); assert!(set1[0].0 == set2[0].0); } #[test] fn set_rng() { let seed: &[_] = &[1, 2, 3, 4]; let rng1: StdRng = SeedableRng::from_seed(seed); let rng2: StdRng = SeedableRng::from_seed(seed); let mut split1 = ShuffleSplit::new(1000, 1, 0.2); let mut split2 = ShuffleSplit::new(1000, 1, 0.2); split1.set_rng(rng1); split2.set_rng(rng2); let set1 = split1.collect::<Vec<_>>(); let set2 = split2.collect::<Vec<_>>(); assert!(set1[0].0 == set2[0].0); } }
{ self.rng = rng; }
identifier_body
sieve.rs
extern crate sieve; use sieve::*; #[test] fn limit_lower_than_the_first_prime() { assert_eq!(sieve::primes_up_to(1), []); } #[test] fn limit_is_the_first_prime() { assert_eq!(sieve::primes_up_to(2), [2]); } #[test] fn primes_up_to_10() { assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]); } #[test] fn limit_is_prime() { assert_eq!(sieve::primes_up_to(13), [2, 3, 5, 7, 11, 13]); } #[test] fn
() { let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; assert_eq!(sieve::primes_up_to(1000), expected); }
limit_of_1000
identifier_name
sieve.rs
extern crate sieve; use sieve::*; #[test] fn limit_lower_than_the_first_prime() { assert_eq!(sieve::primes_up_to(1), []); } #[test] fn limit_is_the_first_prime() { assert_eq!(sieve::primes_up_to(2), [2]); }
fn primes_up_to_10() { assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]); } #[test] fn limit_is_prime() { assert_eq!(sieve::primes_up_to(13), [2, 3, 5, 7, 11, 13]); } #[test] fn limit_of_1000() { let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; assert_eq!(sieve::primes_up_to(1000), expected); }
#[test]
random_line_split
sieve.rs
extern crate sieve; use sieve::*; #[test] fn limit_lower_than_the_first_prime() { assert_eq!(sieve::primes_up_to(1), []); } #[test] fn limit_is_the_first_prime() { assert_eq!(sieve::primes_up_to(2), [2]); } #[test] fn primes_up_to_10() { assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]); } #[test] fn limit_is_prime()
#[test] fn limit_of_1000() { let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; assert_eq!(sieve::primes_up_to(1000), expected); }
{ assert_eq!(sieve::primes_up_to(13), [2, 3, 5, 7, 11, 13]); }
identifier_body
load.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Used by `rustc` when loading a plugin. use driver::session::Session; use metadata::creader::PluginMetadataReader; use plugin::registry::Registry; use std::mem; use std::os; use std::dynamic_lib::DynamicLibrary; use syntax::ast; use syntax::attr; use syntax::visit; use syntax::visit::Visitor; use syntax::ext::expand::ExportedMacros; use syntax::attr::AttrMetaMethods; /// Plugin-related crate metadata. pub struct PluginMetadata { /// Source code of macros exported by the crate. pub macros: Vec<String>, /// Path to the shared library file. pub lib: Option<Path>, /// Symbol name of the plugin registrar function. pub registrar_symbol: Option<String>, } /// Pointer to a registrar function. pub type PluginRegistrarFun = fn(&mut Registry); /// Information about loaded plugins. pub struct Plugins { /// Source code of exported macros. pub macros: Vec<ExportedMacros>, /// Registrars, as function pointers. pub registrars: Vec<PluginRegistrarFun>, } struct PluginLoader<'a> { sess: &'a Session, reader: PluginMetadataReader<'a>, plugins: Plugins, } impl<'a> PluginLoader<'a> { fn new(sess: &'a Session) -> PluginLoader<'a> { PluginLoader { sess: sess, reader: PluginMetadataReader::new(sess), plugins: Plugins { macros: vec!(), registrars: vec!(), }, } } } /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, krate: &ast::Crate, addl_plugins: Option<Plugins>) -> Plugins { let mut loader = PluginLoader::new(sess); visit::walk_crate(&mut loader, krate); let mut plugins = loader.plugins; match addl_plugins { Some(addl_plugins) => { // Add in the additional plugins requested by the frontend let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins; plugins.macros.extend(addl_macros.into_iter()); plugins.registrars.extend(addl_registrars.into_iter()); } None => () } return plugins; } // note that macros aren't expanded yet, and therefore macros can't add plugins. impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { fn visit_view_item(&mut self, vi: &ast::ViewItem)
self.reader.read_plugin_metadata(vi); self.plugins.macros.push(ExportedMacros { crate_name: name, macros: macros, }); match (lib, registrar_symbol) { (Some(lib), Some(symbol)) => self.dylink_registrar(vi, lib, symbol), _ => (), } } _ => (), } } fn visit_mac(&mut self, _: &ast::Mac) { // bummer... can't see plugins inside macros. // do nothing. } } impl<'a> PluginLoader<'a> { // Dynamically link a registrar function into the compiler process. fn dylink_registrar(&mut self, vi: &ast::ViewItem, path: Path, symbol: String) { // Make sure the path contains a / or the linker will search for it. let path = os::make_absolute(&path); let lib = match DynamicLibrary::open(Some(&path)) { Ok(lib) => lib, // this is fatal: there are almost certainly macros we need // inside this crate, so continue would spew "macro undefined" // errors Err(err) => self.sess.span_fatal(vi.span, err.as_slice()) }; unsafe { let registrar = match lib.symbol(symbol.as_slice()) { Ok(registrar) => { mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros Err(err) => self.sess.span_fatal(vi.span, err.as_slice()) }; self.plugins.registrars.push(registrar); // Intentionally leak the dynamic library. We can't ever unload it // since the library can make things that will live arbitrarily long // (e.g. an @-box cycle or a task). mem::forget(lib); } } }
{ match vi.node { ast::ViewItemExternCrate(name, _, _) => { let mut plugin_phase = false; for attr in vi.attrs.iter().filter(|a| a.check_name("phase")) { let phases = attr.meta_item_list().unwrap_or(&[]); if attr::contains_name(phases, "plugin") { plugin_phase = true; } if attr::contains_name(phases, "syntax") { plugin_phase = true; self.sess.span_warn(attr.span, "phase(syntax) is a deprecated synonym for phase(plugin)"); } } if !plugin_phase { return; } let PluginMetadata { macros, lib, registrar_symbol } =
identifier_body
load.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Used by `rustc` when loading a plugin. use driver::session::Session; use metadata::creader::PluginMetadataReader; use plugin::registry::Registry; use std::mem; use std::os; use std::dynamic_lib::DynamicLibrary; use syntax::ast; use syntax::attr; use syntax::visit; use syntax::visit::Visitor; use syntax::ext::expand::ExportedMacros; use syntax::attr::AttrMetaMethods; /// Plugin-related crate metadata. pub struct PluginMetadata { /// Source code of macros exported by the crate. pub macros: Vec<String>, /// Path to the shared library file. pub lib: Option<Path>, /// Symbol name of the plugin registrar function. pub registrar_symbol: Option<String>, } /// Pointer to a registrar function. pub type PluginRegistrarFun = fn(&mut Registry); /// Information about loaded plugins. pub struct Plugins { /// Source code of exported macros. pub macros: Vec<ExportedMacros>, /// Registrars, as function pointers. pub registrars: Vec<PluginRegistrarFun>, } struct PluginLoader<'a> { sess: &'a Session, reader: PluginMetadataReader<'a>, plugins: Plugins, } impl<'a> PluginLoader<'a> { fn new(sess: &'a Session) -> PluginLoader<'a> { PluginLoader { sess: sess, reader: PluginMetadataReader::new(sess), plugins: Plugins { macros: vec!(), registrars: vec!(), }, } } } /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, krate: &ast::Crate, addl_plugins: Option<Plugins>) -> Plugins { let mut loader = PluginLoader::new(sess); visit::walk_crate(&mut loader, krate); let mut plugins = loader.plugins; match addl_plugins { Some(addl_plugins) => { // Add in the additional plugins requested by the frontend let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins; plugins.macros.extend(addl_macros.into_iter()); plugins.registrars.extend(addl_registrars.into_iter());
return plugins; } // note that macros aren't expanded yet, and therefore macros can't add plugins. impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { fn visit_view_item(&mut self, vi: &ast::ViewItem) { match vi.node { ast::ViewItemExternCrate(name, _, _) => { let mut plugin_phase = false; for attr in vi.attrs.iter().filter(|a| a.check_name("phase")) { let phases = attr.meta_item_list().unwrap_or(&[]); if attr::contains_name(phases, "plugin") { plugin_phase = true; } if attr::contains_name(phases, "syntax") { plugin_phase = true; self.sess.span_warn(attr.span, "phase(syntax) is a deprecated synonym for phase(plugin)"); } } if!plugin_phase { return; } let PluginMetadata { macros, lib, registrar_symbol } = self.reader.read_plugin_metadata(vi); self.plugins.macros.push(ExportedMacros { crate_name: name, macros: macros, }); match (lib, registrar_symbol) { (Some(lib), Some(symbol)) => self.dylink_registrar(vi, lib, symbol), _ => (), } } _ => (), } } fn visit_mac(&mut self, _: &ast::Mac) { // bummer... can't see plugins inside macros. // do nothing. } } impl<'a> PluginLoader<'a> { // Dynamically link a registrar function into the compiler process. fn dylink_registrar(&mut self, vi: &ast::ViewItem, path: Path, symbol: String) { // Make sure the path contains a / or the linker will search for it. let path = os::make_absolute(&path); let lib = match DynamicLibrary::open(Some(&path)) { Ok(lib) => lib, // this is fatal: there are almost certainly macros we need // inside this crate, so continue would spew "macro undefined" // errors Err(err) => self.sess.span_fatal(vi.span, err.as_slice()) }; unsafe { let registrar = match lib.symbol(symbol.as_slice()) { Ok(registrar) => { mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros Err(err) => self.sess.span_fatal(vi.span, err.as_slice()) }; self.plugins.registrars.push(registrar); // Intentionally leak the dynamic library. We can't ever unload it // since the library can make things that will live arbitrarily long // (e.g. an @-box cycle or a task). mem::forget(lib); } } }
} None => () }
random_line_split
load.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Used by `rustc` when loading a plugin. use driver::session::Session; use metadata::creader::PluginMetadataReader; use plugin::registry::Registry; use std::mem; use std::os; use std::dynamic_lib::DynamicLibrary; use syntax::ast; use syntax::attr; use syntax::visit; use syntax::visit::Visitor; use syntax::ext::expand::ExportedMacros; use syntax::attr::AttrMetaMethods; /// Plugin-related crate metadata. pub struct
{ /// Source code of macros exported by the crate. pub macros: Vec<String>, /// Path to the shared library file. pub lib: Option<Path>, /// Symbol name of the plugin registrar function. pub registrar_symbol: Option<String>, } /// Pointer to a registrar function. pub type PluginRegistrarFun = fn(&mut Registry); /// Information about loaded plugins. pub struct Plugins { /// Source code of exported macros. pub macros: Vec<ExportedMacros>, /// Registrars, as function pointers. pub registrars: Vec<PluginRegistrarFun>, } struct PluginLoader<'a> { sess: &'a Session, reader: PluginMetadataReader<'a>, plugins: Plugins, } impl<'a> PluginLoader<'a> { fn new(sess: &'a Session) -> PluginLoader<'a> { PluginLoader { sess: sess, reader: PluginMetadataReader::new(sess), plugins: Plugins { macros: vec!(), registrars: vec!(), }, } } } /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, krate: &ast::Crate, addl_plugins: Option<Plugins>) -> Plugins { let mut loader = PluginLoader::new(sess); visit::walk_crate(&mut loader, krate); let mut plugins = loader.plugins; match addl_plugins { Some(addl_plugins) => { // Add in the additional plugins requested by the frontend let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins; plugins.macros.extend(addl_macros.into_iter()); plugins.registrars.extend(addl_registrars.into_iter()); } None => () } return plugins; } // note that macros aren't expanded yet, and therefore macros can't add plugins. impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { fn visit_view_item(&mut self, vi: &ast::ViewItem) { match vi.node { ast::ViewItemExternCrate(name, _, _) => { let mut plugin_phase = false; for attr in vi.attrs.iter().filter(|a| a.check_name("phase")) { let phases = attr.meta_item_list().unwrap_or(&[]); if attr::contains_name(phases, "plugin") { plugin_phase = true; } if attr::contains_name(phases, "syntax") { plugin_phase = true; self.sess.span_warn(attr.span, "phase(syntax) is a deprecated synonym for phase(plugin)"); } } if!plugin_phase { return; } let PluginMetadata { macros, lib, registrar_symbol } = self.reader.read_plugin_metadata(vi); self.plugins.macros.push(ExportedMacros { crate_name: name, macros: macros, }); match (lib, registrar_symbol) { (Some(lib), Some(symbol)) => self.dylink_registrar(vi, lib, symbol), _ => (), } } _ => (), } } fn visit_mac(&mut self, _: &ast::Mac) { // bummer... can't see plugins inside macros. // do nothing. } } impl<'a> PluginLoader<'a> { // Dynamically link a registrar function into the compiler process. fn dylink_registrar(&mut self, vi: &ast::ViewItem, path: Path, symbol: String) { // Make sure the path contains a / or the linker will search for it. let path = os::make_absolute(&path); let lib = match DynamicLibrary::open(Some(&path)) { Ok(lib) => lib, // this is fatal: there are almost certainly macros we need // inside this crate, so continue would spew "macro undefined" // errors Err(err) => self.sess.span_fatal(vi.span, err.as_slice()) }; unsafe { let registrar = match lib.symbol(symbol.as_slice()) { Ok(registrar) => { mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros Err(err) => self.sess.span_fatal(vi.span, err.as_slice()) }; self.plugins.registrars.push(registrar); // Intentionally leak the dynamic library. We can't ever unload it // since the library can make things that will live arbitrarily long // (e.g. an @-box cycle or a task). mem::forget(lib); } } }
PluginMetadata
identifier_name
io.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::old_io::{IoError, IoResult, SeekStyle}; use std::old_io; use std::slice; use std::iter::repeat; static BUF_CAPACITY: uint = 128; fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> { // compute offset as signed and clamp to prevent overflow let pos = match seek { old_io::SeekSet => 0, old_io::SeekEnd => end, old_io::SeekCur => cur, } as i64; if offset + pos < 0 { Err(IoError { kind: old_io::InvalidInput, desc: "invalid seek to a negative offset", detail: None }) } else { Ok((offset + pos) as u64) } } /// Writes to an owned, growable byte vector that supports seeking. /// /// # Example /// /// ```rust /// # #![allow(unused_must_use)] /// use rbml::io::SeekableMemWriter; /// /// let mut w = SeekableMemWriter::new(); /// w.write(&[0, 1, 2]); /// /// assert_eq!(w.unwrap(), vec!(0, 1, 2)); /// ``` pub struct SeekableMemWriter { buf: Vec<u8>, pos: uint, } impl SeekableMemWriter { /// Create a new `SeekableMemWriter`. #[inline] pub fn new() -> SeekableMemWriter { SeekableMemWriter::with_capacity(BUF_CAPACITY) } /// Create a new `SeekableMemWriter`, allocating at least `n` bytes for /// the internal buffer. #[inline] pub fn with_capacity(n: uint) -> SeekableMemWriter { SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 } } /// Acquires an immutable reference to the underlying buffer of this /// `SeekableMemWriter`. /// /// No method is exposed for acquiring a mutable reference to the buffer /// because it could corrupt the state of this `MemWriter`. #[inline] pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf } /// Unwraps this `SeekableMemWriter`, returning the underlying buffer #[inline] pub fn unwrap(self) -> Vec<u8> { self.buf } } impl Writer for SeekableMemWriter { #[inline] fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { if self.pos == self.buf.len() { self.buf.push_all(buf) } else { // Make sure the internal buffer is as least as big as where we // currently are let difference = self.pos as i64 - self.buf.len() as i64; if difference > 0 { self.buf.extend(repeat(0).take(difference as uint)); } // Figure out what bytes will be used to overwrite what's currently // there (left), and what will be appended on the end (right) let cap = self.buf.len() - self.pos; let (left, right) = if cap <= buf.len() { (&buf[..cap], &buf[cap..]) } else { let result: (_, &[_]) = (buf, &[]); result }; // Do the necessary writes if left.len() > 0 { slice::bytes::copy_memory(&mut self.buf[self.pos..], left); } if right.len() > 0 { self.buf.push_all(right); } } // Bump us forward self.pos += buf.len(); Ok(()) } } impl Seek for SeekableMemWriter { #[inline] fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) } #[inline] fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> { let new = try!(combine(style, self.pos, self.buf.len(), pos)); self.pos = new as uint; Ok(()) } } #[cfg(test)] mod tests { extern crate test; use super::SeekableMemWriter; use std::old_io; use std::iter::repeat; use test::Bencher; #[test] fn test_seekable_mem_writer() { let mut writer = SeekableMemWriter::new(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[0]).unwrap(); assert_eq!(writer.tell(), Ok(1)); writer.write(&[1, 2, 3]).unwrap(); writer.write(&[4, 5, 6, 7]).unwrap(); assert_eq!(writer.tell(), Ok(8)); let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(0, old_io::SeekSet).unwrap(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[3, 4]).unwrap(); let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(1, old_io::SeekCur).unwrap(); writer.write(&[0, 1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(-1, old_io::SeekEnd).unwrap(); writer.write(&[1, 2]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2]; assert_eq!(writer.get_ref(), b); writer.seek(1, old_io::SeekEnd).unwrap(); writer.write(&[1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1]; assert_eq!(writer.get_ref(), b); } #[test] fn seek_past_end() { let mut r = SeekableMemWriter::new(); r.seek(10, old_io::SeekSet).unwrap(); assert!(r.write(&[3]).is_ok()); } #[test] fn seek_before_0() { let mut r = SeekableMemWriter::new(); assert!(r.seek(-1, old_io::SeekSet).is_err()); } fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) { let src: Vec<u8> = repeat(5).take(len).collect(); b.bytes = (times * len) as u64; b.iter(|| { let mut wr = SeekableMemWriter::new(); for _ in 0..times { wr.write(&src).unwrap(); } let v = wr.unwrap(); assert_eq!(v.len(), times * len); assert!(v.iter().all(|x| *x == 5)); }); } #[bench] fn
(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 0) } #[bench] fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 10) } #[bench] fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 100) } #[bench] fn bench_seekable_mem_writer_001_1000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 1000) } #[bench] fn bench_seekable_mem_writer_100_0000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 0) } #[bench] fn bench_seekable_mem_writer_100_0010(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 10) } #[bench] fn bench_seekable_mem_writer_100_0100(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 100) } #[bench] fn bench_seekable_mem_writer_100_1000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 1000) } }
bench_seekable_mem_writer_001_0000
identifier_name
io.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::old_io::{IoError, IoResult, SeekStyle}; use std::old_io; use std::slice; use std::iter::repeat; static BUF_CAPACITY: uint = 128; fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> { // compute offset as signed and clamp to prevent overflow let pos = match seek { old_io::SeekSet => 0, old_io::SeekEnd => end, old_io::SeekCur => cur, } as i64; if offset + pos < 0 { Err(IoError { kind: old_io::InvalidInput, desc: "invalid seek to a negative offset", detail: None }) } else { Ok((offset + pos) as u64) } } /// Writes to an owned, growable byte vector that supports seeking. /// /// # Example /// /// ```rust /// # #![allow(unused_must_use)] /// use rbml::io::SeekableMemWriter; /// /// let mut w = SeekableMemWriter::new(); /// w.write(&[0, 1, 2]); /// /// assert_eq!(w.unwrap(), vec!(0, 1, 2)); /// ``` pub struct SeekableMemWriter { buf: Vec<u8>, pos: uint, } impl SeekableMemWriter { /// Create a new `SeekableMemWriter`. #[inline] pub fn new() -> SeekableMemWriter { SeekableMemWriter::with_capacity(BUF_CAPACITY) } /// Create a new `SeekableMemWriter`, allocating at least `n` bytes for /// the internal buffer. #[inline] pub fn with_capacity(n: uint) -> SeekableMemWriter { SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 } } /// Acquires an immutable reference to the underlying buffer of this /// `SeekableMemWriter`. /// /// No method is exposed for acquiring a mutable reference to the buffer /// because it could corrupt the state of this `MemWriter`. #[inline] pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf } /// Unwraps this `SeekableMemWriter`, returning the underlying buffer #[inline] pub fn unwrap(self) -> Vec<u8> { self.buf } } impl Writer for SeekableMemWriter { #[inline] fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { if self.pos == self.buf.len() { self.buf.push_all(buf) } else { // Make sure the internal buffer is as least as big as where we
// currently are let difference = self.pos as i64 - self.buf.len() as i64; if difference > 0 { self.buf.extend(repeat(0).take(difference as uint)); } // Figure out what bytes will be used to overwrite what's currently // there (left), and what will be appended on the end (right) let cap = self.buf.len() - self.pos; let (left, right) = if cap <= buf.len() { (&buf[..cap], &buf[cap..]) } else { let result: (_, &[_]) = (buf, &[]); result }; // Do the necessary writes if left.len() > 0 { slice::bytes::copy_memory(&mut self.buf[self.pos..], left); } if right.len() > 0 { self.buf.push_all(right); } } // Bump us forward self.pos += buf.len(); Ok(()) } } impl Seek for SeekableMemWriter { #[inline] fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) } #[inline] fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> { let new = try!(combine(style, self.pos, self.buf.len(), pos)); self.pos = new as uint; Ok(()) } } #[cfg(test)] mod tests { extern crate test; use super::SeekableMemWriter; use std::old_io; use std::iter::repeat; use test::Bencher; #[test] fn test_seekable_mem_writer() { let mut writer = SeekableMemWriter::new(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[0]).unwrap(); assert_eq!(writer.tell(), Ok(1)); writer.write(&[1, 2, 3]).unwrap(); writer.write(&[4, 5, 6, 7]).unwrap(); assert_eq!(writer.tell(), Ok(8)); let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(0, old_io::SeekSet).unwrap(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[3, 4]).unwrap(); let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(1, old_io::SeekCur).unwrap(); writer.write(&[0, 1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(-1, old_io::SeekEnd).unwrap(); writer.write(&[1, 2]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2]; assert_eq!(writer.get_ref(), b); writer.seek(1, old_io::SeekEnd).unwrap(); writer.write(&[1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1]; assert_eq!(writer.get_ref(), b); } #[test] fn seek_past_end() { let mut r = SeekableMemWriter::new(); r.seek(10, old_io::SeekSet).unwrap(); assert!(r.write(&[3]).is_ok()); } #[test] fn seek_before_0() { let mut r = SeekableMemWriter::new(); assert!(r.seek(-1, old_io::SeekSet).is_err()); } fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) { let src: Vec<u8> = repeat(5).take(len).collect(); b.bytes = (times * len) as u64; b.iter(|| { let mut wr = SeekableMemWriter::new(); for _ in 0..times { wr.write(&src).unwrap(); } let v = wr.unwrap(); assert_eq!(v.len(), times * len); assert!(v.iter().all(|x| *x == 5)); }); } #[bench] fn bench_seekable_mem_writer_001_0000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 0) } #[bench] fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 10) } #[bench] fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 100) } #[bench] fn bench_seekable_mem_writer_001_1000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 1000) } #[bench] fn bench_seekable_mem_writer_100_0000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 0) } #[bench] fn bench_seekable_mem_writer_100_0010(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 10) } #[bench] fn bench_seekable_mem_writer_100_0100(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 100) } #[bench] fn bench_seekable_mem_writer_100_1000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 1000) } }
random_line_split
io.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::old_io::{IoError, IoResult, SeekStyle}; use std::old_io; use std::slice; use std::iter::repeat; static BUF_CAPACITY: uint = 128; fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> { // compute offset as signed and clamp to prevent overflow let pos = match seek { old_io::SeekSet => 0, old_io::SeekEnd => end, old_io::SeekCur => cur, } as i64; if offset + pos < 0 { Err(IoError { kind: old_io::InvalidInput, desc: "invalid seek to a negative offset", detail: None }) } else { Ok((offset + pos) as u64) } } /// Writes to an owned, growable byte vector that supports seeking. /// /// # Example /// /// ```rust /// # #![allow(unused_must_use)] /// use rbml::io::SeekableMemWriter; /// /// let mut w = SeekableMemWriter::new(); /// w.write(&[0, 1, 2]); /// /// assert_eq!(w.unwrap(), vec!(0, 1, 2)); /// ``` pub struct SeekableMemWriter { buf: Vec<u8>, pos: uint, } impl SeekableMemWriter { /// Create a new `SeekableMemWriter`. #[inline] pub fn new() -> SeekableMemWriter { SeekableMemWriter::with_capacity(BUF_CAPACITY) } /// Create a new `SeekableMemWriter`, allocating at least `n` bytes for /// the internal buffer. #[inline] pub fn with_capacity(n: uint) -> SeekableMemWriter { SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 } } /// Acquires an immutable reference to the underlying buffer of this /// `SeekableMemWriter`. /// /// No method is exposed for acquiring a mutable reference to the buffer /// because it could corrupt the state of this `MemWriter`. #[inline] pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf } /// Unwraps this `SeekableMemWriter`, returning the underlying buffer #[inline] pub fn unwrap(self) -> Vec<u8> { self.buf } } impl Writer for SeekableMemWriter { #[inline] fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { if self.pos == self.buf.len() { self.buf.push_all(buf) } else { // Make sure the internal buffer is as least as big as where we // currently are let difference = self.pos as i64 - self.buf.len() as i64; if difference > 0 { self.buf.extend(repeat(0).take(difference as uint)); } // Figure out what bytes will be used to overwrite what's currently // there (left), and what will be appended on the end (right) let cap = self.buf.len() - self.pos; let (left, right) = if cap <= buf.len() { (&buf[..cap], &buf[cap..]) } else { let result: (_, &[_]) = (buf, &[]); result }; // Do the necessary writes if left.len() > 0 { slice::bytes::copy_memory(&mut self.buf[self.pos..], left); } if right.len() > 0 { self.buf.push_all(right); } } // Bump us forward self.pos += buf.len(); Ok(()) } } impl Seek for SeekableMemWriter { #[inline] fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) } #[inline] fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> { let new = try!(combine(style, self.pos, self.buf.len(), pos)); self.pos = new as uint; Ok(()) } } #[cfg(test)] mod tests { extern crate test; use super::SeekableMemWriter; use std::old_io; use std::iter::repeat; use test::Bencher; #[test] fn test_seekable_mem_writer() { let mut writer = SeekableMemWriter::new(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[0]).unwrap(); assert_eq!(writer.tell(), Ok(1)); writer.write(&[1, 2, 3]).unwrap(); writer.write(&[4, 5, 6, 7]).unwrap(); assert_eq!(writer.tell(), Ok(8)); let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(0, old_io::SeekSet).unwrap(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[3, 4]).unwrap(); let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(1, old_io::SeekCur).unwrap(); writer.write(&[0, 1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(-1, old_io::SeekEnd).unwrap(); writer.write(&[1, 2]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2]; assert_eq!(writer.get_ref(), b); writer.seek(1, old_io::SeekEnd).unwrap(); writer.write(&[1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1]; assert_eq!(writer.get_ref(), b); } #[test] fn seek_past_end() { let mut r = SeekableMemWriter::new(); r.seek(10, old_io::SeekSet).unwrap(); assert!(r.write(&[3]).is_ok()); } #[test] fn seek_before_0() { let mut r = SeekableMemWriter::new(); assert!(r.seek(-1, old_io::SeekSet).is_err()); } fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint)
#[bench] fn bench_seekable_mem_writer_001_0000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 0) } #[bench] fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 10) } #[bench] fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 100) } #[bench] fn bench_seekable_mem_writer_001_1000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 1000) } #[bench] fn bench_seekable_mem_writer_100_0000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 0) } #[bench] fn bench_seekable_mem_writer_100_0010(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 10) } #[bench] fn bench_seekable_mem_writer_100_0100(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 100) } #[bench] fn bench_seekable_mem_writer_100_1000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 1000) } }
{ let src: Vec<u8> = repeat(5).take(len).collect(); b.bytes = (times * len) as u64; b.iter(|| { let mut wr = SeekableMemWriter::new(); for _ in 0..times { wr.write(&src).unwrap(); } let v = wr.unwrap(); assert_eq!(v.len(), times * len); assert!(v.iter().all(|x| *x == 5)); }); }
identifier_body
io.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::old_io::{IoError, IoResult, SeekStyle}; use std::old_io; use std::slice; use std::iter::repeat; static BUF_CAPACITY: uint = 128; fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> { // compute offset as signed and clamp to prevent overflow let pos = match seek { old_io::SeekSet => 0, old_io::SeekEnd => end, old_io::SeekCur => cur, } as i64; if offset + pos < 0 { Err(IoError { kind: old_io::InvalidInput, desc: "invalid seek to a negative offset", detail: None }) } else { Ok((offset + pos) as u64) } } /// Writes to an owned, growable byte vector that supports seeking. /// /// # Example /// /// ```rust /// # #![allow(unused_must_use)] /// use rbml::io::SeekableMemWriter; /// /// let mut w = SeekableMemWriter::new(); /// w.write(&[0, 1, 2]); /// /// assert_eq!(w.unwrap(), vec!(0, 1, 2)); /// ``` pub struct SeekableMemWriter { buf: Vec<u8>, pos: uint, } impl SeekableMemWriter { /// Create a new `SeekableMemWriter`. #[inline] pub fn new() -> SeekableMemWriter { SeekableMemWriter::with_capacity(BUF_CAPACITY) } /// Create a new `SeekableMemWriter`, allocating at least `n` bytes for /// the internal buffer. #[inline] pub fn with_capacity(n: uint) -> SeekableMemWriter { SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 } } /// Acquires an immutable reference to the underlying buffer of this /// `SeekableMemWriter`. /// /// No method is exposed for acquiring a mutable reference to the buffer /// because it could corrupt the state of this `MemWriter`. #[inline] pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf } /// Unwraps this `SeekableMemWriter`, returning the underlying buffer #[inline] pub fn unwrap(self) -> Vec<u8> { self.buf } } impl Writer for SeekableMemWriter { #[inline] fn write_all(&mut self, buf: &[u8]) -> IoResult<()> { if self.pos == self.buf.len() { self.buf.push_all(buf) } else { // Make sure the internal buffer is as least as big as where we // currently are let difference = self.pos as i64 - self.buf.len() as i64; if difference > 0
// Figure out what bytes will be used to overwrite what's currently // there (left), and what will be appended on the end (right) let cap = self.buf.len() - self.pos; let (left, right) = if cap <= buf.len() { (&buf[..cap], &buf[cap..]) } else { let result: (_, &[_]) = (buf, &[]); result }; // Do the necessary writes if left.len() > 0 { slice::bytes::copy_memory(&mut self.buf[self.pos..], left); } if right.len() > 0 { self.buf.push_all(right); } } // Bump us forward self.pos += buf.len(); Ok(()) } } impl Seek for SeekableMemWriter { #[inline] fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) } #[inline] fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> { let new = try!(combine(style, self.pos, self.buf.len(), pos)); self.pos = new as uint; Ok(()) } } #[cfg(test)] mod tests { extern crate test; use super::SeekableMemWriter; use std::old_io; use std::iter::repeat; use test::Bencher; #[test] fn test_seekable_mem_writer() { let mut writer = SeekableMemWriter::new(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[0]).unwrap(); assert_eq!(writer.tell(), Ok(1)); writer.write(&[1, 2, 3]).unwrap(); writer.write(&[4, 5, 6, 7]).unwrap(); assert_eq!(writer.tell(), Ok(8)); let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(0, old_io::SeekSet).unwrap(); assert_eq!(writer.tell(), Ok(0)); writer.write(&[3, 4]).unwrap(); let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(1, old_io::SeekCur).unwrap(); writer.write(&[0, 1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7]; assert_eq!(writer.get_ref(), b); writer.seek(-1, old_io::SeekEnd).unwrap(); writer.write(&[1, 2]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2]; assert_eq!(writer.get_ref(), b); writer.seek(1, old_io::SeekEnd).unwrap(); writer.write(&[1]).unwrap(); let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1]; assert_eq!(writer.get_ref(), b); } #[test] fn seek_past_end() { let mut r = SeekableMemWriter::new(); r.seek(10, old_io::SeekSet).unwrap(); assert!(r.write(&[3]).is_ok()); } #[test] fn seek_before_0() { let mut r = SeekableMemWriter::new(); assert!(r.seek(-1, old_io::SeekSet).is_err()); } fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) { let src: Vec<u8> = repeat(5).take(len).collect(); b.bytes = (times * len) as u64; b.iter(|| { let mut wr = SeekableMemWriter::new(); for _ in 0..times { wr.write(&src).unwrap(); } let v = wr.unwrap(); assert_eq!(v.len(), times * len); assert!(v.iter().all(|x| *x == 5)); }); } #[bench] fn bench_seekable_mem_writer_001_0000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 0) } #[bench] fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 10) } #[bench] fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 100) } #[bench] fn bench_seekable_mem_writer_001_1000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 1, 1000) } #[bench] fn bench_seekable_mem_writer_100_0000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 0) } #[bench] fn bench_seekable_mem_writer_100_0010(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 10) } #[bench] fn bench_seekable_mem_writer_100_0100(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 100) } #[bench] fn bench_seekable_mem_writer_100_1000(b: &mut Bencher) { do_bench_seekable_mem_writer(b, 100, 1000) } }
{ self.buf.extend(repeat(0).take(difference as uint)); }
conditional_block
expr-block-generic-box1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; type compare<T> ='static |@T, @T| -> bool; fn
<T>(expected: @T, eq: compare<T>) { let actual: @T = { expected }; assert!((eq(expected, actual))); } fn test_box() { fn compare_box(b1: @bool, b2: @bool) -> bool { info!("{}", *b1); info!("{}", *b2); return *b1 == *b2; } test_generic::<bool>(@true, compare_box); } pub fn main() { test_box(); }
test_generic
identifier_name
expr-block-generic-box1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; type compare<T> ='static |@T, @T| -> bool; fn test_generic<T>(expected: @T, eq: compare<T>) { let actual: @T = { expected }; assert!((eq(expected, actual))); } fn test_box() { fn compare_box(b1: @bool, b2: @bool) -> bool { info!("{}", *b1); info!("{}", *b2); return *b1 == *b2; } test_generic::<bool>(@true, compare_box); } pub fn main() { test_box(); }
// 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
random_line_split
expr-block-generic-box1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; type compare<T> ='static |@T, @T| -> bool; fn test_generic<T>(expected: @T, eq: compare<T>)
fn test_box() { fn compare_box(b1: @bool, b2: @bool) -> bool { info!("{}", *b1); info!("{}", *b2); return *b1 == *b2; } test_generic::<bool>(@true, compare_box); } pub fn main() { test_box(); }
{ let actual: @T = { expected }; assert!((eq(expected, actual))); }
identifier_body
send_str_treemap.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate collections; use std::collections::{ Map, MutableMap}; use std::str::{SendStr, Owned, Slice}; use std::to_string::ToString; use self::collections::TreeMap; use std::option::Some; pub fn
() { let mut map: TreeMap<SendStr, uint> = TreeMap::new(); assert!(map.insert(Slice("foo"), 42)); assert!(!map.insert(Owned("foo".to_string()), 42)); assert!(!map.insert(Slice("foo"), 42)); assert!(!map.insert(Owned("foo".to_string()), 42)); assert!(!map.insert(Slice("foo"), 43)); assert!(!map.insert(Owned("foo".to_string()), 44)); assert!(!map.insert(Slice("foo"), 45)); assert!(!map.insert(Owned("foo".to_string()), 46)); let v = 46; assert_eq!(map.find(&Owned("foo".to_string())), Some(&v)); assert_eq!(map.find(&Slice("foo")), Some(&v)); let (a, b, c, d) = (50, 51, 52, 53); assert!(map.insert(Slice("abc"), a)); assert!(map.insert(Owned("bcd".to_string()), b)); assert!(map.insert(Slice("cde"), c)); assert!(map.insert(Owned("def".to_string()), d)); assert!(!map.insert(Slice("abc"), a)); assert!(!map.insert(Owned("bcd".to_string()), b)); assert!(!map.insert(Slice("cde"), c)); assert!(!map.insert(Owned("def".to_string()), d)); assert!(!map.insert(Owned("abc".to_string()), a)); assert!(!map.insert(Slice("bcd"), b)); assert!(!map.insert(Owned("cde".to_string()), c)); assert!(!map.insert(Slice("def"), d)); assert_eq!(map.find(&Slice("abc")), Some(&a)); assert_eq!(map.find(&Slice("bcd")), Some(&b)); assert_eq!(map.find(&Slice("cde")), Some(&c)); assert_eq!(map.find(&Slice("def")), Some(&d)); assert_eq!(map.find(&Owned("abc".to_string())), Some(&a)); assert_eq!(map.find(&Owned("bcd".to_string())), Some(&b)); assert_eq!(map.find(&Owned("cde".to_string())), Some(&c)); assert_eq!(map.find(&Owned("def".to_string())), Some(&d)); assert!(map.pop(&Slice("foo")).is_some()); assert_eq!(map.move_iter().map(|(k, v)| format!("{}{}", k, v)) .collect::<Vec<String>>() .concat(), "abc50bcd51cde52def53".to_string()); }
main
identifier_name
send_str_treemap.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate collections; use std::collections::{ Map, MutableMap}; use std::str::{SendStr, Owned, Slice}; use std::to_string::ToString; use self::collections::TreeMap; use std::option::Some; pub fn main() { let mut map: TreeMap<SendStr, uint> = TreeMap::new(); assert!(map.insert(Slice("foo"), 42)); assert!(!map.insert(Owned("foo".to_string()), 42)); assert!(!map.insert(Slice("foo"), 42)); assert!(!map.insert(Owned("foo".to_string()), 42)); assert!(!map.insert(Slice("foo"), 43)); assert!(!map.insert(Owned("foo".to_string()), 44)); assert!(!map.insert(Slice("foo"), 45)); assert!(!map.insert(Owned("foo".to_string()), 46)); let v = 46; assert_eq!(map.find(&Owned("foo".to_string())), Some(&v)); assert_eq!(map.find(&Slice("foo")), Some(&v)); let (a, b, c, d) = (50, 51, 52, 53);
assert!(!map.insert(Slice("abc"), a)); assert!(!map.insert(Owned("bcd".to_string()), b)); assert!(!map.insert(Slice("cde"), c)); assert!(!map.insert(Owned("def".to_string()), d)); assert!(!map.insert(Owned("abc".to_string()), a)); assert!(!map.insert(Slice("bcd"), b)); assert!(!map.insert(Owned("cde".to_string()), c)); assert!(!map.insert(Slice("def"), d)); assert_eq!(map.find(&Slice("abc")), Some(&a)); assert_eq!(map.find(&Slice("bcd")), Some(&b)); assert_eq!(map.find(&Slice("cde")), Some(&c)); assert_eq!(map.find(&Slice("def")), Some(&d)); assert_eq!(map.find(&Owned("abc".to_string())), Some(&a)); assert_eq!(map.find(&Owned("bcd".to_string())), Some(&b)); assert_eq!(map.find(&Owned("cde".to_string())), Some(&c)); assert_eq!(map.find(&Owned("def".to_string())), Some(&d)); assert!(map.pop(&Slice("foo")).is_some()); assert_eq!(map.move_iter().map(|(k, v)| format!("{}{}", k, v)) .collect::<Vec<String>>() .concat(), "abc50bcd51cde52def53".to_string()); }
assert!(map.insert(Slice("abc"), a)); assert!(map.insert(Owned("bcd".to_string()), b)); assert!(map.insert(Slice("cde"), c)); assert!(map.insert(Owned("def".to_string()), d));
random_line_split
send_str_treemap.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate collections; use std::collections::{ Map, MutableMap}; use std::str::{SendStr, Owned, Slice}; use std::to_string::ToString; use self::collections::TreeMap; use std::option::Some; pub fn main()
assert!(map.insert(Owned("bcd".to_string()), b)); assert!(map.insert(Slice("cde"), c)); assert!(map.insert(Owned("def".to_string()), d)); assert!(!map.insert(Slice("abc"), a)); assert!(!map.insert(Owned("bcd".to_string()), b)); assert!(!map.insert(Slice("cde"), c)); assert!(!map.insert(Owned("def".to_string()), d)); assert!(!map.insert(Owned("abc".to_string()), a)); assert!(!map.insert(Slice("bcd"), b)); assert!(!map.insert(Owned("cde".to_string()), c)); assert!(!map.insert(Slice("def"), d)); assert_eq!(map.find(&Slice("abc")), Some(&a)); assert_eq!(map.find(&Slice("bcd")), Some(&b)); assert_eq!(map.find(&Slice("cde")), Some(&c)); assert_eq!(map.find(&Slice("def")), Some(&d)); assert_eq!(map.find(&Owned("abc".to_string())), Some(&a)); assert_eq!(map.find(&Owned("bcd".to_string())), Some(&b)); assert_eq!(map.find(&Owned("cde".to_string())), Some(&c)); assert_eq!(map.find(&Owned("def".to_string())), Some(&d)); assert!(map.pop(&Slice("foo")).is_some()); assert_eq!(map.move_iter().map(|(k, v)| format!("{}{}", k, v)) .collect::<Vec<String>>() .concat(), "abc50bcd51cde52def53".to_string()); }
{ let mut map: TreeMap<SendStr, uint> = TreeMap::new(); assert!(map.insert(Slice("foo"), 42)); assert!(!map.insert(Owned("foo".to_string()), 42)); assert!(!map.insert(Slice("foo"), 42)); assert!(!map.insert(Owned("foo".to_string()), 42)); assert!(!map.insert(Slice("foo"), 43)); assert!(!map.insert(Owned("foo".to_string()), 44)); assert!(!map.insert(Slice("foo"), 45)); assert!(!map.insert(Owned("foo".to_string()), 46)); let v = 46; assert_eq!(map.find(&Owned("foo".to_string())), Some(&v)); assert_eq!(map.find(&Slice("foo")), Some(&v)); let (a, b, c, d) = (50, 51, 52, 53); assert!(map.insert(Slice("abc"), a));
identifier_body
md5.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::iter::range_step; use cryptoutil::{write_u32_le, read_u32v_le, FixedBuffer, FixedBuffer64, StandardPadding}; use digest::Digest; // A structure that represents that state of a digest computation for the MD5 digest function struct Md5State { s0: u32, s1: u32, s2: u32, s3: u32 } impl Md5State { fn new() -> Md5State
fn reset(&mut self) { self.s0 = 0x67452301; self.s1 = 0xefcdab89; self.s2 = 0x98badcfe; self.s3 = 0x10325476; } fn process_block(&mut self, input: &[u8]) { fn f(u: u32, v: u32, w: u32) -> u32 { return (u & v) | (!u & w); } fn g(u: u32, v: u32, w: u32) -> u32 { return (u & w) | (v &!w); } fn h(u: u32, v: u32, w: u32) -> u32 { return u ^ v ^ w; } fn i(u: u32, v: u32, w: u32) -> u32 { return v ^ (u |!w); } fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + f(x, y, z) + m).rotate_left(s as uint) + x; } fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + g(x, y, z) + m).rotate_left(s as uint) + x; } fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + h(x, y, z) + m).rotate_left(s as uint) + x; } fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + i(x, y, z) + m).rotate_left(s as uint) + x; } let mut a = self.s0; let mut b = self.s1; let mut c = self.s2; let mut d = self.s3; let mut data = [0u32,..16]; read_u32v_le(data, input); // round 1 for i in range_step(0u, 16, 4) { a = op_f(a, b, c, d, data[i] + C1[i], 7); d = op_f(d, a, b, c, data[i + 1] + C1[i + 1], 12); c = op_f(c, d, a, b, data[i + 2] + C1[i + 2], 17); b = op_f(b, c, d, a, data[i + 3] + C1[i + 3], 22); } // round 2 let mut t = 1; for i in range_step(0u, 16, 4) { a = op_g(a, b, c, d, data[t & 0x0f] + C2[i], 5); d = op_g(d, a, b, c, data[(t + 5) & 0x0f] + C2[i + 1], 9); c = op_g(c, d, a, b, data[(t + 10) & 0x0f] + C2[i + 2], 14); b = op_g(b, c, d, a, data[(t + 15) & 0x0f] + C2[i + 3], 20); t += 20; } // round 3 t = 5; for i in range_step(0u, 16, 4) { a = op_h(a, b, c, d, data[t & 0x0f] + C3[i], 4); d = op_h(d, a, b, c, data[(t + 3) & 0x0f] + C3[i + 1], 11); c = op_h(c, d, a, b, data[(t + 6) & 0x0f] + C3[i + 2], 16); b = op_h(b, c, d, a, data[(t + 9) & 0x0f] + C3[i + 3], 23); t += 12; } // round 4 t = 0; for i in range_step(0u, 16, 4) { a = op_i(a, b, c, d, data[t & 0x0f] + C4[i], 6); d = op_i(d, a, b, c, data[(t + 7) & 0x0f] + C4[i + 1], 10); c = op_i(c, d, a, b, data[(t + 14) & 0x0f] + C4[i + 2], 15); b = op_i(b, c, d, a, data[(t + 21) & 0x0f] + C4[i + 3], 21); t += 28; } self.s0 += a; self.s1 += b; self.s2 += c; self.s3 += d; } } // Round 1 constants static C1: [u32,..16] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ]; // Round 2 constants static C2: [u32,..16] = [ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ]; // Round 3 constants static C3: [u32,..16] = [ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ]; // Round 4 constants static C4: [u32,..16] = [ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]; /// The MD5 Digest algorithm pub struct Md5 { length_bytes: u64, buffer: FixedBuffer64, state: Md5State, finished: bool, } impl Md5 { /// Construct a new instance of the MD5 Digest. pub fn new() -> Md5 { return Md5 { length_bytes: 0, buffer: FixedBuffer64::new(), state: Md5State::new(), finished: false } } } impl Digest for Md5 { fn input(&mut self, input: &[u8]) { assert!(!self.finished); // Unlike Sha1 and Sha2, the length value in MD5 is defined as the length of the message mod // 2^64 - ie: integer overflow is OK. self.length_bytes += input.len() as u64; let self_state = &mut self.state; self.buffer.input(input, |d: &[u8]| { self_state.process_block(d); }); } fn reset(&mut self) { self.length_bytes = 0; self.buffer.reset(); self.state.reset(); self.finished = false; } fn result(&mut self, out: &mut [u8]) { if!self.finished { let self_state = &mut self.state; self.buffer.standard_padding(8, |d: &[u8]| { self_state.process_block(d); }); write_u32_le(self.buffer.next(4), (self.length_bytes << 3) as u32); write_u32_le(self.buffer.next(4), (self.length_bytes >> 29) as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } write_u32_le(out.mut_slice(0, 4), self.state.s0); write_u32_le(out.mut_slice(4, 8), self.state.s1); write_u32_le(out.mut_slice(8, 12), self.state.s2); write_u32_le(out.mut_slice(12, 16), self.state.s3); } fn output_bits(&self) -> uint { 128 } fn block_size(&self) -> uint { 64 } } #[cfg(test)] mod tests { use cryptoutil::test::test_digest_1million_random; use digest::Digest; use md5::Md5; struct Test { input: &'static str, output_str: &'static str, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.input_str(t.input); let out_str = sh.result_str(); assert!(out_str.as_slice() == t.output_str); sh.reset(); } // Test that it works when accepting the message in pieces for t in tests.iter() { let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input.slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str.as_slice() == t.output_str); sh.reset(); } } #[test] fn test_md5() { // Examples from wikipedia let wikipedia_tests = vec![ Test { input: "", output_str: "d41d8cd98f00b204e9800998ecf8427e" }, Test { input: "The quick brown fox jumps over the lazy dog", output_str: "9e107d9d372bb6826bd81d3542a419d6" }, Test { input: "The quick brown fox jumps over the lazy dog.", output_str: "e4d909c290d0fb1ca068ffaddf22cbd0" }, ]; let tests = wikipedia_tests; let mut sh = Md5::new(); test_hash(&mut sh, tests.as_slice()); } #[test] fn test_1million_random_md5() { let mut sh = Md5::new(); test_digest_1million_random( &mut sh, 64, "7707d6ae4e027c70eea2a935c2296f21"); } } #[cfg(test)] mod bench { use test::Bencher; use digest::Digest; use md5::Md5; #[bench] pub fn md5_10(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..10]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn md5_1k(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..1024]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn md5_64k(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..65536]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } }
{ return Md5State { s0: 0x67452301, s1: 0xefcdab89, s2: 0x98badcfe, s3: 0x10325476 }; }
identifier_body
md5.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::iter::range_step; use cryptoutil::{write_u32_le, read_u32v_le, FixedBuffer, FixedBuffer64, StandardPadding}; use digest::Digest; // A structure that represents that state of a digest computation for the MD5 digest function struct Md5State { s0: u32, s1: u32, s2: u32, s3: u32 } impl Md5State { fn new() -> Md5State { return Md5State { s0: 0x67452301, s1: 0xefcdab89, s2: 0x98badcfe, s3: 0x10325476 }; } fn reset(&mut self) { self.s0 = 0x67452301; self.s1 = 0xefcdab89; self.s2 = 0x98badcfe; self.s3 = 0x10325476; } fn process_block(&mut self, input: &[u8]) { fn f(u: u32, v: u32, w: u32) -> u32 { return (u & v) | (!u & w); } fn g(u: u32, v: u32, w: u32) -> u32 { return (u & w) | (v &!w); } fn h(u: u32, v: u32, w: u32) -> u32 { return u ^ v ^ w; } fn i(u: u32, v: u32, w: u32) -> u32 { return v ^ (u |!w); } fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + f(x, y, z) + m).rotate_left(s as uint) + x; } fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + g(x, y, z) + m).rotate_left(s as uint) + x; } fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + h(x, y, z) + m).rotate_left(s as uint) + x; } fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + i(x, y, z) + m).rotate_left(s as uint) + x; } let mut a = self.s0; let mut b = self.s1; let mut c = self.s2; let mut d = self.s3; let mut data = [0u32,..16]; read_u32v_le(data, input); // round 1 for i in range_step(0u, 16, 4) { a = op_f(a, b, c, d, data[i] + C1[i], 7); d = op_f(d, a, b, c, data[i + 1] + C1[i + 1], 12); c = op_f(c, d, a, b, data[i + 2] + C1[i + 2], 17); b = op_f(b, c, d, a, data[i + 3] + C1[i + 3], 22); } // round 2 let mut t = 1; for i in range_step(0u, 16, 4) { a = op_g(a, b, c, d, data[t & 0x0f] + C2[i], 5); d = op_g(d, a, b, c, data[(t + 5) & 0x0f] + C2[i + 1], 9); c = op_g(c, d, a, b, data[(t + 10) & 0x0f] + C2[i + 2], 14); b = op_g(b, c, d, a, data[(t + 15) & 0x0f] + C2[i + 3], 20); t += 20; } // round 3 t = 5; for i in range_step(0u, 16, 4) { a = op_h(a, b, c, d, data[t & 0x0f] + C3[i], 4); d = op_h(d, a, b, c, data[(t + 3) & 0x0f] + C3[i + 1], 11); c = op_h(c, d, a, b, data[(t + 6) & 0x0f] + C3[i + 2], 16); b = op_h(b, c, d, a, data[(t + 9) & 0x0f] + C3[i + 3], 23); t += 12; } // round 4 t = 0; for i in range_step(0u, 16, 4) { a = op_i(a, b, c, d, data[t & 0x0f] + C4[i], 6); d = op_i(d, a, b, c, data[(t + 7) & 0x0f] + C4[i + 1], 10); c = op_i(c, d, a, b, data[(t + 14) & 0x0f] + C4[i + 2], 15); b = op_i(b, c, d, a, data[(t + 21) & 0x0f] + C4[i + 3], 21); t += 28; } self.s0 += a; self.s1 += b; self.s2 += c; self.s3 += d; } } // Round 1 constants static C1: [u32,..16] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ]; // Round 2 constants static C2: [u32,..16] = [ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ]; // Round 3 constants static C3: [u32,..16] = [ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ]; // Round 4 constants static C4: [u32,..16] = [ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]; /// The MD5 Digest algorithm pub struct Md5 { length_bytes: u64, buffer: FixedBuffer64, state: Md5State, finished: bool, } impl Md5 { /// Construct a new instance of the MD5 Digest. pub fn
() -> Md5 { return Md5 { length_bytes: 0, buffer: FixedBuffer64::new(), state: Md5State::new(), finished: false } } } impl Digest for Md5 { fn input(&mut self, input: &[u8]) { assert!(!self.finished); // Unlike Sha1 and Sha2, the length value in MD5 is defined as the length of the message mod // 2^64 - ie: integer overflow is OK. self.length_bytes += input.len() as u64; let self_state = &mut self.state; self.buffer.input(input, |d: &[u8]| { self_state.process_block(d); }); } fn reset(&mut self) { self.length_bytes = 0; self.buffer.reset(); self.state.reset(); self.finished = false; } fn result(&mut self, out: &mut [u8]) { if!self.finished { let self_state = &mut self.state; self.buffer.standard_padding(8, |d: &[u8]| { self_state.process_block(d); }); write_u32_le(self.buffer.next(4), (self.length_bytes << 3) as u32); write_u32_le(self.buffer.next(4), (self.length_bytes >> 29) as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } write_u32_le(out.mut_slice(0, 4), self.state.s0); write_u32_le(out.mut_slice(4, 8), self.state.s1); write_u32_le(out.mut_slice(8, 12), self.state.s2); write_u32_le(out.mut_slice(12, 16), self.state.s3); } fn output_bits(&self) -> uint { 128 } fn block_size(&self) -> uint { 64 } } #[cfg(test)] mod tests { use cryptoutil::test::test_digest_1million_random; use digest::Digest; use md5::Md5; struct Test { input: &'static str, output_str: &'static str, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.input_str(t.input); let out_str = sh.result_str(); assert!(out_str.as_slice() == t.output_str); sh.reset(); } // Test that it works when accepting the message in pieces for t in tests.iter() { let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input.slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str.as_slice() == t.output_str); sh.reset(); } } #[test] fn test_md5() { // Examples from wikipedia let wikipedia_tests = vec![ Test { input: "", output_str: "d41d8cd98f00b204e9800998ecf8427e" }, Test { input: "The quick brown fox jumps over the lazy dog", output_str: "9e107d9d372bb6826bd81d3542a419d6" }, Test { input: "The quick brown fox jumps over the lazy dog.", output_str: "e4d909c290d0fb1ca068ffaddf22cbd0" }, ]; let tests = wikipedia_tests; let mut sh = Md5::new(); test_hash(&mut sh, tests.as_slice()); } #[test] fn test_1million_random_md5() { let mut sh = Md5::new(); test_digest_1million_random( &mut sh, 64, "7707d6ae4e027c70eea2a935c2296f21"); } } #[cfg(test)] mod bench { use test::Bencher; use digest::Digest; use md5::Md5; #[bench] pub fn md5_10(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..10]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn md5_1k(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..1024]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn md5_64k(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..65536]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } }
new
identifier_name
md5.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::iter::range_step; use cryptoutil::{write_u32_le, read_u32v_le, FixedBuffer, FixedBuffer64, StandardPadding}; use digest::Digest; // A structure that represents that state of a digest computation for the MD5 digest function struct Md5State { s0: u32, s1: u32, s2: u32, s3: u32 } impl Md5State { fn new() -> Md5State { return Md5State { s0: 0x67452301, s1: 0xefcdab89, s2: 0x98badcfe, s3: 0x10325476 }; } fn reset(&mut self) { self.s0 = 0x67452301; self.s1 = 0xefcdab89; self.s2 = 0x98badcfe; self.s3 = 0x10325476; } fn process_block(&mut self, input: &[u8]) { fn f(u: u32, v: u32, w: u32) -> u32 { return (u & v) | (!u & w); } fn g(u: u32, v: u32, w: u32) -> u32 { return (u & w) | (v &!w); } fn h(u: u32, v: u32, w: u32) -> u32 { return u ^ v ^ w; } fn i(u: u32, v: u32, w: u32) -> u32 { return v ^ (u |!w); } fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + f(x, y, z) + m).rotate_left(s as uint) + x; } fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + g(x, y, z) + m).rotate_left(s as uint) + x; } fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + h(x, y, z) + m).rotate_left(s as uint) + x; } fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + i(x, y, z) + m).rotate_left(s as uint) + x; } let mut a = self.s0; let mut b = self.s1; let mut c = self.s2; let mut d = self.s3; let mut data = [0u32,..16]; read_u32v_le(data, input); // round 1 for i in range_step(0u, 16, 4) { a = op_f(a, b, c, d, data[i] + C1[i], 7); d = op_f(d, a, b, c, data[i + 1] + C1[i + 1], 12); c = op_f(c, d, a, b, data[i + 2] + C1[i + 2], 17); b = op_f(b, c, d, a, data[i + 3] + C1[i + 3], 22); } // round 2 let mut t = 1; for i in range_step(0u, 16, 4) { a = op_g(a, b, c, d, data[t & 0x0f] + C2[i], 5); d = op_g(d, a, b, c, data[(t + 5) & 0x0f] + C2[i + 1], 9); c = op_g(c, d, a, b, data[(t + 10) & 0x0f] + C2[i + 2], 14); b = op_g(b, c, d, a, data[(t + 15) & 0x0f] + C2[i + 3], 20); t += 20; } // round 3 t = 5; for i in range_step(0u, 16, 4) { a = op_h(a, b, c, d, data[t & 0x0f] + C3[i], 4); d = op_h(d, a, b, c, data[(t + 3) & 0x0f] + C3[i + 1], 11); c = op_h(c, d, a, b, data[(t + 6) & 0x0f] + C3[i + 2], 16); b = op_h(b, c, d, a, data[(t + 9) & 0x0f] + C3[i + 3], 23); t += 12; } // round 4 t = 0; for i in range_step(0u, 16, 4) { a = op_i(a, b, c, d, data[t & 0x0f] + C4[i], 6); d = op_i(d, a, b, c, data[(t + 7) & 0x0f] + C4[i + 1], 10); c = op_i(c, d, a, b, data[(t + 14) & 0x0f] + C4[i + 2], 15); b = op_i(b, c, d, a, data[(t + 21) & 0x0f] + C4[i + 3], 21); t += 28; } self.s0 += a; self.s1 += b; self.s2 += c; self.s3 += d; } } // Round 1 constants static C1: [u32,..16] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ]; // Round 2 constants static C2: [u32,..16] = [ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ]; // Round 3 constants static C3: [u32,..16] = [ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ]; // Round 4 constants static C4: [u32,..16] = [ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]; /// The MD5 Digest algorithm pub struct Md5 { length_bytes: u64, buffer: FixedBuffer64, state: Md5State, finished: bool, } impl Md5 { /// Construct a new instance of the MD5 Digest. pub fn new() -> Md5 { return Md5 { length_bytes: 0, buffer: FixedBuffer64::new(), state: Md5State::new(), finished: false } } } impl Digest for Md5 { fn input(&mut self, input: &[u8]) { assert!(!self.finished); // Unlike Sha1 and Sha2, the length value in MD5 is defined as the length of the message mod // 2^64 - ie: integer overflow is OK. self.length_bytes += input.len() as u64; let self_state = &mut self.state; self.buffer.input(input, |d: &[u8]| { self_state.process_block(d); }); } fn reset(&mut self) { self.length_bytes = 0; self.buffer.reset(); self.state.reset(); self.finished = false; } fn result(&mut self, out: &mut [u8]) { if!self.finished
write_u32_le(out.mut_slice(0, 4), self.state.s0); write_u32_le(out.mut_slice(4, 8), self.state.s1); write_u32_le(out.mut_slice(8, 12), self.state.s2); write_u32_le(out.mut_slice(12, 16), self.state.s3); } fn output_bits(&self) -> uint { 128 } fn block_size(&self) -> uint { 64 } } #[cfg(test)] mod tests { use cryptoutil::test::test_digest_1million_random; use digest::Digest; use md5::Md5; struct Test { input: &'static str, output_str: &'static str, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.input_str(t.input); let out_str = sh.result_str(); assert!(out_str.as_slice() == t.output_str); sh.reset(); } // Test that it works when accepting the message in pieces for t in tests.iter() { let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input.slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str.as_slice() == t.output_str); sh.reset(); } } #[test] fn test_md5() { // Examples from wikipedia let wikipedia_tests = vec![ Test { input: "", output_str: "d41d8cd98f00b204e9800998ecf8427e" }, Test { input: "The quick brown fox jumps over the lazy dog", output_str: "9e107d9d372bb6826bd81d3542a419d6" }, Test { input: "The quick brown fox jumps over the lazy dog.", output_str: "e4d909c290d0fb1ca068ffaddf22cbd0" }, ]; let tests = wikipedia_tests; let mut sh = Md5::new(); test_hash(&mut sh, tests.as_slice()); } #[test] fn test_1million_random_md5() { let mut sh = Md5::new(); test_digest_1million_random( &mut sh, 64, "7707d6ae4e027c70eea2a935c2296f21"); } } #[cfg(test)] mod bench { use test::Bencher; use digest::Digest; use md5::Md5; #[bench] pub fn md5_10(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..10]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn md5_1k(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..1024]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn md5_64k(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..65536]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } }
{ let self_state = &mut self.state; self.buffer.standard_padding(8, |d: &[u8]| { self_state.process_block(d); }); write_u32_le(self.buffer.next(4), (self.length_bytes << 3) as u32); write_u32_le(self.buffer.next(4), (self.length_bytes >> 29) as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; }
conditional_block
md5.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
use digest::Digest; // A structure that represents that state of a digest computation for the MD5 digest function struct Md5State { s0: u32, s1: u32, s2: u32, s3: u32 } impl Md5State { fn new() -> Md5State { return Md5State { s0: 0x67452301, s1: 0xefcdab89, s2: 0x98badcfe, s3: 0x10325476 }; } fn reset(&mut self) { self.s0 = 0x67452301; self.s1 = 0xefcdab89; self.s2 = 0x98badcfe; self.s3 = 0x10325476; } fn process_block(&mut self, input: &[u8]) { fn f(u: u32, v: u32, w: u32) -> u32 { return (u & v) | (!u & w); } fn g(u: u32, v: u32, w: u32) -> u32 { return (u & w) | (v &!w); } fn h(u: u32, v: u32, w: u32) -> u32 { return u ^ v ^ w; } fn i(u: u32, v: u32, w: u32) -> u32 { return v ^ (u |!w); } fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + f(x, y, z) + m).rotate_left(s as uint) + x; } fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + g(x, y, z) + m).rotate_left(s as uint) + x; } fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + h(x, y, z) + m).rotate_left(s as uint) + x; } fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 { return (w + i(x, y, z) + m).rotate_left(s as uint) + x; } let mut a = self.s0; let mut b = self.s1; let mut c = self.s2; let mut d = self.s3; let mut data = [0u32,..16]; read_u32v_le(data, input); // round 1 for i in range_step(0u, 16, 4) { a = op_f(a, b, c, d, data[i] + C1[i], 7); d = op_f(d, a, b, c, data[i + 1] + C1[i + 1], 12); c = op_f(c, d, a, b, data[i + 2] + C1[i + 2], 17); b = op_f(b, c, d, a, data[i + 3] + C1[i + 3], 22); } // round 2 let mut t = 1; for i in range_step(0u, 16, 4) { a = op_g(a, b, c, d, data[t & 0x0f] + C2[i], 5); d = op_g(d, a, b, c, data[(t + 5) & 0x0f] + C2[i + 1], 9); c = op_g(c, d, a, b, data[(t + 10) & 0x0f] + C2[i + 2], 14); b = op_g(b, c, d, a, data[(t + 15) & 0x0f] + C2[i + 3], 20); t += 20; } // round 3 t = 5; for i in range_step(0u, 16, 4) { a = op_h(a, b, c, d, data[t & 0x0f] + C3[i], 4); d = op_h(d, a, b, c, data[(t + 3) & 0x0f] + C3[i + 1], 11); c = op_h(c, d, a, b, data[(t + 6) & 0x0f] + C3[i + 2], 16); b = op_h(b, c, d, a, data[(t + 9) & 0x0f] + C3[i + 3], 23); t += 12; } // round 4 t = 0; for i in range_step(0u, 16, 4) { a = op_i(a, b, c, d, data[t & 0x0f] + C4[i], 6); d = op_i(d, a, b, c, data[(t + 7) & 0x0f] + C4[i + 1], 10); c = op_i(c, d, a, b, data[(t + 14) & 0x0f] + C4[i + 2], 15); b = op_i(b, c, d, a, data[(t + 21) & 0x0f] + C4[i + 3], 21); t += 28; } self.s0 += a; self.s1 += b; self.s2 += c; self.s3 += d; } } // Round 1 constants static C1: [u32,..16] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ]; // Round 2 constants static C2: [u32,..16] = [ 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ]; // Round 3 constants static C3: [u32,..16] = [ 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ]; // Round 4 constants static C4: [u32,..16] = [ 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]; /// The MD5 Digest algorithm pub struct Md5 { length_bytes: u64, buffer: FixedBuffer64, state: Md5State, finished: bool, } impl Md5 { /// Construct a new instance of the MD5 Digest. pub fn new() -> Md5 { return Md5 { length_bytes: 0, buffer: FixedBuffer64::new(), state: Md5State::new(), finished: false } } } impl Digest for Md5 { fn input(&mut self, input: &[u8]) { assert!(!self.finished); // Unlike Sha1 and Sha2, the length value in MD5 is defined as the length of the message mod // 2^64 - ie: integer overflow is OK. self.length_bytes += input.len() as u64; let self_state = &mut self.state; self.buffer.input(input, |d: &[u8]| { self_state.process_block(d); }); } fn reset(&mut self) { self.length_bytes = 0; self.buffer.reset(); self.state.reset(); self.finished = false; } fn result(&mut self, out: &mut [u8]) { if!self.finished { let self_state = &mut self.state; self.buffer.standard_padding(8, |d: &[u8]| { self_state.process_block(d); }); write_u32_le(self.buffer.next(4), (self.length_bytes << 3) as u32); write_u32_le(self.buffer.next(4), (self.length_bytes >> 29) as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } write_u32_le(out.mut_slice(0, 4), self.state.s0); write_u32_le(out.mut_slice(4, 8), self.state.s1); write_u32_le(out.mut_slice(8, 12), self.state.s2); write_u32_le(out.mut_slice(12, 16), self.state.s3); } fn output_bits(&self) -> uint { 128 } fn block_size(&self) -> uint { 64 } } #[cfg(test)] mod tests { use cryptoutil::test::test_digest_1million_random; use digest::Digest; use md5::Md5; struct Test { input: &'static str, output_str: &'static str, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.input_str(t.input); let out_str = sh.result_str(); assert!(out_str.as_slice() == t.output_str); sh.reset(); } // Test that it works when accepting the message in pieces for t in tests.iter() { let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input.slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str.as_slice() == t.output_str); sh.reset(); } } #[test] fn test_md5() { // Examples from wikipedia let wikipedia_tests = vec![ Test { input: "", output_str: "d41d8cd98f00b204e9800998ecf8427e" }, Test { input: "The quick brown fox jumps over the lazy dog", output_str: "9e107d9d372bb6826bd81d3542a419d6" }, Test { input: "The quick brown fox jumps over the lazy dog.", output_str: "e4d909c290d0fb1ca068ffaddf22cbd0" }, ]; let tests = wikipedia_tests; let mut sh = Md5::new(); test_hash(&mut sh, tests.as_slice()); } #[test] fn test_1million_random_md5() { let mut sh = Md5::new(); test_digest_1million_random( &mut sh, 64, "7707d6ae4e027c70eea2a935c2296f21"); } } #[cfg(test)] mod bench { use test::Bencher; use digest::Digest; use md5::Md5; #[bench] pub fn md5_10(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..10]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn md5_1k(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..1024]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn md5_64k(bh: & mut Bencher) { let mut sh = Md5::new(); let bytes = [1u8,..65536]; bh.iter( || { sh.input(bytes); }); bh.bytes = bytes.len() as u64; } }
use std::iter::range_step; use cryptoutil::{write_u32_le, read_u32v_le, FixedBuffer, FixedBuffer64, StandardPadding};
random_line_split
cstore.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] // The crate store - a central repo for information collected about external // crates and libraries pub use self::MetadataBlob::*; pub use self::LinkagePreference::*; pub use self::NativeLibraryKind::*; use back::svh::Svh; use metadata::{creader, decoder, loader}; use session::search_paths::PathKind; use util::nodemap::{FnvHashMap, NodeMap}; use std::cell::{RefCell, Ref}; use std::rc::Rc; use std::path::PathBuf; use flate::Bytes; use syntax::ast; use syntax::codemap; use syntax::parse::token; use syntax::parse::token::IdentInterner; use syntax::util::small_vector::SmallVector; use ast_map; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = FnvHashMap<ast::CrateNum, ast::CrateNum>; pub enum MetadataBlob { MetadataVec(Bytes), MetadataArchive(loader::ArchiveMetadata), } /// Holds information about a codemap::FileMap imported from another crate. /// See creader::import_codemap() for more information. pub struct ImportedFileMap { /// This FileMap's byte-offset within the codemap of its original crate pub original_start_pos: codemap::BytePos, /// The end of this FileMap within the codemap of its original crate pub original_end_pos: codemap::BytePos, /// The imported FileMap's representation within the local codemap pub translated_filemap: Rc<codemap::FileMap> } pub struct crate_metadata { pub name: String, pub local_path: RefCell<SmallVector<ast_map::PathElem>>, pub data: MetadataBlob, pub cnum_map: cnum_map, pub cnum: ast::CrateNum, pub codemap_import_info: RefCell<Vec<ImportedFileMap>>, pub span: codemap::Span, pub staged_api: bool } #[derive(Copy, Debug, PartialEq, Clone)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } enum_from_u32! { #[derive(Copy, Clone, PartialEq)] pub enum NativeLibraryKind { NativeStatic, // native static library (.a archive) NativeFramework, // OSX-specific NativeUnknown, // default way to specify a dynamic library } } // Where a crate came from on the local filesystem. One of these two options // must be non-None. #[derive(PartialEq, Clone)] pub struct CrateSource { pub dylib: Option<(PathBuf, PathKind)>, pub rlib: Option<(PathBuf, PathKind)>, pub cnum: ast::CrateNum, } pub struct CStore { metas: RefCell<FnvHashMap<ast::CrateNum, Rc<crate_metadata>>>, /// Map from NodeId's of local extern crate statements to crate numbers extern_mod_crate_map: RefCell<NodeMap<ast::CrateNum>>, used_crate_sources: RefCell<Vec<CrateSource>>, used_libraries: RefCell<Vec<(String, NativeLibraryKind)>>, used_link_args: RefCell<Vec<String>>, pub intr: Rc<IdentInterner>, } impl CStore { pub fn new(intr: Rc<IdentInterner>) -> CStore { CStore { metas: RefCell::new(FnvHashMap()), extern_mod_crate_map: RefCell::new(FnvHashMap()), used_crate_sources: RefCell::new(Vec::new()), used_libraries: RefCell::new(Vec::new()), used_link_args: RefCell::new(Vec::new()), intr: intr } } pub fn next_crate_num(&self) -> ast::CrateNum { self.metas.borrow().len() as ast::CrateNum + 1 } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> { self.metas.borrow().get(&cnum).unwrap().clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { let cdata = self.get_crate_data(cnum); decoder::get_crate_hash(cdata.data()) } pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) { self.metas.borrow_mut().insert(cnum, data); } pub fn iter_crate_data<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata), { for (&k, v) in self.metas.borrow().iter() { i(k, &**v); } } /// Like `iter_crate_data`, but passes source paths (if available) as well. pub fn iter_crate_data_origins<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata, Option<CrateSource>), { for (&k, v) in self.metas.borrow().iter() { let origin = self.get_used_crate_source(k); origin.as_ref().map(|cs| { assert!(k == cs.cnum); }); i(k, &**v, origin); } } pub fn add_used_crate_source(&self, src: CrateSource) { let mut used_crate_sources = self.used_crate_sources.borrow_mut(); if!used_crate_sources.contains(&src) { used_crate_sources.push(src); } } pub fn get_used_crate_source(&self, cnum: ast::CrateNum) -> Option<CrateSource> { self.used_crate_sources.borrow_mut() .iter().find(|source| source.cnum == cnum).cloned() } pub fn reset(&self) { self.metas.borrow_mut().clear(); self.extern_mod_crate_map.borrow_mut().clear(); self.used_crate_sources.borrow_mut().clear(); self.used_libraries.borrow_mut().clear(); self.used_link_args.borrow_mut().clear(); } // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn get_used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)> { let mut ordering = Vec::new(); fn visit(cstore: &CStore, cnum: ast::CrateNum, ordering: &mut Vec<ast::CrateNum>) { if ordering.contains(&cnum) { return } let meta = cstore.get_crate_data(cnum); for (_, &dep) in &meta.cnum_map { visit(cstore, dep, ordering); } ordering.push(cnum); }; for (&num, _) in self.metas.borrow().iter() { visit(self, num, &mut ordering); } ordering.reverse(); let mut libs = self.used_crate_sources.borrow() .iter() .map(|src| (src.cnum, match prefer { RequireDynamic => src.dylib.clone().map(|p| p.0), RequireStatic => src.rlib.clone().map(|p| p.0), })) .collect::<Vec<_>>(); libs.sort_by(|&(a, _), &(b, _)| { let a = ordering.iter().position(|x| *x == a); let b = ordering.iter().position(|x| *x == b); a.cmp(&b) }); libs } pub fn add_used_library(&self, lib: String, kind: NativeLibraryKind) { assert!(!lib.is_empty()); self.used_libraries.borrow_mut().push((lib, kind)); } pub fn get_used_libraries<'a>(&'a self) -> &'a RefCell<Vec<(String, NativeLibraryKind)>> { &self.used_libraries } pub fn add_used_link_args(&self, args: &str) { for s in args.split(' ').filter(|s|!s.is_empty()) { self.used_link_args.borrow_mut().push(s.to_string()); } } pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String> > { &self.used_link_args } pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: ast::CrateNum) { self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { self.extern_mod_crate_map.borrow().get(&emod_id).cloned() } } impl crate_metadata { pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() } pub fn name(&self) -> String { decoder::get_crate_name(self.data()) } pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) } pub fn imported_filemaps<'a>(&'a self, codemap: &codemap::CodeMap) -> Ref<'a, Vec<ImportedFileMap>> { let filemaps = self.codemap_import_info.borrow(); if filemaps.is_empty() { drop(filemaps); let filemaps = creader::import_codemap(codemap, &self.data); // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref. *self.codemap_import_info.borrow_mut() = filemaps; self.codemap_import_info.borrow() } else { filemaps } } pub fn with_local_path<T, F>(&self, f: F) -> T where F: Fn(&[ast_map::PathElem]) -> T { let cpath = self.local_path.borrow(); if cpath.is_empty() { let name = ast_map::PathMod(token::intern(&self.name)); f(&[name]) } else { f(cpath.as_slice()) } } pub fn update_local_path<'a, 'b>(&self, candidate: ast_map::PathElems<'a, 'b>) { let mut cpath = self.local_path.borrow_mut(); let cap = cpath.len(); match cap { 0 => *cpath = candidate.collect(), 1 => (), _ => { let candidate: SmallVector<_> = candidate.collect(); if candidate.len() < cap { *cpath = candidate; } }, } } } impl MetadataBlob { pub fn as_slice<'a>(&'a self) -> &'a [u8] { let slice = match *self { MetadataVec(ref vec) => &vec[..], MetadataArchive(ref ar) => ar.as_slice(), }; if slice.len() < 4 { &[] // corrupt metadata } else
} }
{ let len = (((slice[0] as u32) << 24) | ((slice[1] as u32) << 16) | ((slice[2] as u32) << 8) | ((slice[3] as u32) << 0)) as usize; if len + 4 <= slice.len() { &slice[4.. len + 4] } else { &[] // corrupt or old metadata } }
conditional_block
cstore.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] // The crate store - a central repo for information collected about external // crates and libraries pub use self::MetadataBlob::*; pub use self::LinkagePreference::*; pub use self::NativeLibraryKind::*; use back::svh::Svh; use metadata::{creader, decoder, loader}; use session::search_paths::PathKind; use util::nodemap::{FnvHashMap, NodeMap}; use std::cell::{RefCell, Ref}; use std::rc::Rc; use std::path::PathBuf; use flate::Bytes; use syntax::ast; use syntax::codemap; use syntax::parse::token; use syntax::parse::token::IdentInterner; use syntax::util::small_vector::SmallVector; use ast_map; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = FnvHashMap<ast::CrateNum, ast::CrateNum>; pub enum MetadataBlob { MetadataVec(Bytes), MetadataArchive(loader::ArchiveMetadata), } /// Holds information about a codemap::FileMap imported from another crate. /// See creader::import_codemap() for more information. pub struct ImportedFileMap { /// This FileMap's byte-offset within the codemap of its original crate pub original_start_pos: codemap::BytePos, /// The end of this FileMap within the codemap of its original crate pub original_end_pos: codemap::BytePos, /// The imported FileMap's representation within the local codemap pub translated_filemap: Rc<codemap::FileMap> } pub struct crate_metadata { pub name: String, pub local_path: RefCell<SmallVector<ast_map::PathElem>>, pub data: MetadataBlob, pub cnum_map: cnum_map, pub cnum: ast::CrateNum, pub codemap_import_info: RefCell<Vec<ImportedFileMap>>, pub span: codemap::Span, pub staged_api: bool } #[derive(Copy, Debug, PartialEq, Clone)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } enum_from_u32! { #[derive(Copy, Clone, PartialEq)] pub enum NativeLibraryKind { NativeStatic, // native static library (.a archive) NativeFramework, // OSX-specific NativeUnknown, // default way to specify a dynamic library } } // Where a crate came from on the local filesystem. One of these two options // must be non-None. #[derive(PartialEq, Clone)] pub struct CrateSource { pub dylib: Option<(PathBuf, PathKind)>, pub rlib: Option<(PathBuf, PathKind)>, pub cnum: ast::CrateNum, } pub struct CStore { metas: RefCell<FnvHashMap<ast::CrateNum, Rc<crate_metadata>>>, /// Map from NodeId's of local extern crate statements to crate numbers extern_mod_crate_map: RefCell<NodeMap<ast::CrateNum>>, used_crate_sources: RefCell<Vec<CrateSource>>, used_libraries: RefCell<Vec<(String, NativeLibraryKind)>>, used_link_args: RefCell<Vec<String>>, pub intr: Rc<IdentInterner>, } impl CStore { pub fn new(intr: Rc<IdentInterner>) -> CStore { CStore { metas: RefCell::new(FnvHashMap()), extern_mod_crate_map: RefCell::new(FnvHashMap()), used_crate_sources: RefCell::new(Vec::new()), used_libraries: RefCell::new(Vec::new()), used_link_args: RefCell::new(Vec::new()), intr: intr } } pub fn next_crate_num(&self) -> ast::CrateNum { self.metas.borrow().len() as ast::CrateNum + 1 } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> { self.metas.borrow().get(&cnum).unwrap().clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { let cdata = self.get_crate_data(cnum); decoder::get_crate_hash(cdata.data()) } pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) { self.metas.borrow_mut().insert(cnum, data); } pub fn iter_crate_data<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata), { for (&k, v) in self.metas.borrow().iter() { i(k, &**v); } } /// Like `iter_crate_data`, but passes source paths (if available) as well. pub fn iter_crate_data_origins<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata, Option<CrateSource>), { for (&k, v) in self.metas.borrow().iter() { let origin = self.get_used_crate_source(k); origin.as_ref().map(|cs| { assert!(k == cs.cnum); }); i(k, &**v, origin); } } pub fn add_used_crate_source(&self, src: CrateSource) { let mut used_crate_sources = self.used_crate_sources.borrow_mut(); if!used_crate_sources.contains(&src) { used_crate_sources.push(src); } } pub fn get_used_crate_source(&self, cnum: ast::CrateNum) -> Option<CrateSource> { self.used_crate_sources.borrow_mut() .iter().find(|source| source.cnum == cnum).cloned() } pub fn reset(&self) { self.metas.borrow_mut().clear(); self.extern_mod_crate_map.borrow_mut().clear(); self.used_crate_sources.borrow_mut().clear(); self.used_libraries.borrow_mut().clear(); self.used_link_args.borrow_mut().clear(); } // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn get_used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)> { let mut ordering = Vec::new(); fn visit(cstore: &CStore, cnum: ast::CrateNum, ordering: &mut Vec<ast::CrateNum>) { if ordering.contains(&cnum) { return } let meta = cstore.get_crate_data(cnum); for (_, &dep) in &meta.cnum_map { visit(cstore, dep, ordering); } ordering.push(cnum); }; for (&num, _) in self.metas.borrow().iter() { visit(self, num, &mut ordering); } ordering.reverse(); let mut libs = self.used_crate_sources.borrow() .iter() .map(|src| (src.cnum, match prefer { RequireDynamic => src.dylib.clone().map(|p| p.0), RequireStatic => src.rlib.clone().map(|p| p.0), })) .collect::<Vec<_>>(); libs.sort_by(|&(a, _), &(b, _)| { let a = ordering.iter().position(|x| *x == a); let b = ordering.iter().position(|x| *x == b); a.cmp(&b) }); libs } pub fn add_used_library(&self, lib: String, kind: NativeLibraryKind) { assert!(!lib.is_empty()); self.used_libraries.borrow_mut().push((lib, kind)); } pub fn get_used_libraries<'a>(&'a self) -> &'a RefCell<Vec<(String, NativeLibraryKind)>> { &self.used_libraries } pub fn add_used_link_args(&self, args: &str) { for s in args.split(' ').filter(|s|!s.is_empty()) { self.used_link_args.borrow_mut().push(s.to_string()); } } pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String> > { &self.used_link_args } pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: ast::CrateNum) { self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { self.extern_mod_crate_map.borrow().get(&emod_id).cloned() } } impl crate_metadata { pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() } pub fn name(&self) -> String { decoder::get_crate_name(self.data()) } pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) } pub fn imported_filemaps<'a>(&'a self, codemap: &codemap::CodeMap) -> Ref<'a, Vec<ImportedFileMap>> { let filemaps = self.codemap_import_info.borrow(); if filemaps.is_empty() { drop(filemaps); let filemaps = creader::import_codemap(codemap, &self.data);
*self.codemap_import_info.borrow_mut() = filemaps; self.codemap_import_info.borrow() } else { filemaps } } pub fn with_local_path<T, F>(&self, f: F) -> T where F: Fn(&[ast_map::PathElem]) -> T { let cpath = self.local_path.borrow(); if cpath.is_empty() { let name = ast_map::PathMod(token::intern(&self.name)); f(&[name]) } else { f(cpath.as_slice()) } } pub fn update_local_path<'a, 'b>(&self, candidate: ast_map::PathElems<'a, 'b>) { let mut cpath = self.local_path.borrow_mut(); let cap = cpath.len(); match cap { 0 => *cpath = candidate.collect(), 1 => (), _ => { let candidate: SmallVector<_> = candidate.collect(); if candidate.len() < cap { *cpath = candidate; } }, } } } impl MetadataBlob { pub fn as_slice<'a>(&'a self) -> &'a [u8] { let slice = match *self { MetadataVec(ref vec) => &vec[..], MetadataArchive(ref ar) => ar.as_slice(), }; if slice.len() < 4 { &[] // corrupt metadata } else { let len = (((slice[0] as u32) << 24) | ((slice[1] as u32) << 16) | ((slice[2] as u32) << 8) | ((slice[3] as u32) << 0)) as usize; if len + 4 <= slice.len() { &slice[4.. len + 4] } else { &[] // corrupt or old metadata } } } }
// This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
random_line_split
cstore.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] // The crate store - a central repo for information collected about external // crates and libraries pub use self::MetadataBlob::*; pub use self::LinkagePreference::*; pub use self::NativeLibraryKind::*; use back::svh::Svh; use metadata::{creader, decoder, loader}; use session::search_paths::PathKind; use util::nodemap::{FnvHashMap, NodeMap}; use std::cell::{RefCell, Ref}; use std::rc::Rc; use std::path::PathBuf; use flate::Bytes; use syntax::ast; use syntax::codemap; use syntax::parse::token; use syntax::parse::token::IdentInterner; use syntax::util::small_vector::SmallVector; use ast_map; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = FnvHashMap<ast::CrateNum, ast::CrateNum>; pub enum
{ MetadataVec(Bytes), MetadataArchive(loader::ArchiveMetadata), } /// Holds information about a codemap::FileMap imported from another crate. /// See creader::import_codemap() for more information. pub struct ImportedFileMap { /// This FileMap's byte-offset within the codemap of its original crate pub original_start_pos: codemap::BytePos, /// The end of this FileMap within the codemap of its original crate pub original_end_pos: codemap::BytePos, /// The imported FileMap's representation within the local codemap pub translated_filemap: Rc<codemap::FileMap> } pub struct crate_metadata { pub name: String, pub local_path: RefCell<SmallVector<ast_map::PathElem>>, pub data: MetadataBlob, pub cnum_map: cnum_map, pub cnum: ast::CrateNum, pub codemap_import_info: RefCell<Vec<ImportedFileMap>>, pub span: codemap::Span, pub staged_api: bool } #[derive(Copy, Debug, PartialEq, Clone)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } enum_from_u32! { #[derive(Copy, Clone, PartialEq)] pub enum NativeLibraryKind { NativeStatic, // native static library (.a archive) NativeFramework, // OSX-specific NativeUnknown, // default way to specify a dynamic library } } // Where a crate came from on the local filesystem. One of these two options // must be non-None. #[derive(PartialEq, Clone)] pub struct CrateSource { pub dylib: Option<(PathBuf, PathKind)>, pub rlib: Option<(PathBuf, PathKind)>, pub cnum: ast::CrateNum, } pub struct CStore { metas: RefCell<FnvHashMap<ast::CrateNum, Rc<crate_metadata>>>, /// Map from NodeId's of local extern crate statements to crate numbers extern_mod_crate_map: RefCell<NodeMap<ast::CrateNum>>, used_crate_sources: RefCell<Vec<CrateSource>>, used_libraries: RefCell<Vec<(String, NativeLibraryKind)>>, used_link_args: RefCell<Vec<String>>, pub intr: Rc<IdentInterner>, } impl CStore { pub fn new(intr: Rc<IdentInterner>) -> CStore { CStore { metas: RefCell::new(FnvHashMap()), extern_mod_crate_map: RefCell::new(FnvHashMap()), used_crate_sources: RefCell::new(Vec::new()), used_libraries: RefCell::new(Vec::new()), used_link_args: RefCell::new(Vec::new()), intr: intr } } pub fn next_crate_num(&self) -> ast::CrateNum { self.metas.borrow().len() as ast::CrateNum + 1 } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> { self.metas.borrow().get(&cnum).unwrap().clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { let cdata = self.get_crate_data(cnum); decoder::get_crate_hash(cdata.data()) } pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) { self.metas.borrow_mut().insert(cnum, data); } pub fn iter_crate_data<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata), { for (&k, v) in self.metas.borrow().iter() { i(k, &**v); } } /// Like `iter_crate_data`, but passes source paths (if available) as well. pub fn iter_crate_data_origins<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata, Option<CrateSource>), { for (&k, v) in self.metas.borrow().iter() { let origin = self.get_used_crate_source(k); origin.as_ref().map(|cs| { assert!(k == cs.cnum); }); i(k, &**v, origin); } } pub fn add_used_crate_source(&self, src: CrateSource) { let mut used_crate_sources = self.used_crate_sources.borrow_mut(); if!used_crate_sources.contains(&src) { used_crate_sources.push(src); } } pub fn get_used_crate_source(&self, cnum: ast::CrateNum) -> Option<CrateSource> { self.used_crate_sources.borrow_mut() .iter().find(|source| source.cnum == cnum).cloned() } pub fn reset(&self) { self.metas.borrow_mut().clear(); self.extern_mod_crate_map.borrow_mut().clear(); self.used_crate_sources.borrow_mut().clear(); self.used_libraries.borrow_mut().clear(); self.used_link_args.borrow_mut().clear(); } // This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn get_used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)> { let mut ordering = Vec::new(); fn visit(cstore: &CStore, cnum: ast::CrateNum, ordering: &mut Vec<ast::CrateNum>) { if ordering.contains(&cnum) { return } let meta = cstore.get_crate_data(cnum); for (_, &dep) in &meta.cnum_map { visit(cstore, dep, ordering); } ordering.push(cnum); }; for (&num, _) in self.metas.borrow().iter() { visit(self, num, &mut ordering); } ordering.reverse(); let mut libs = self.used_crate_sources.borrow() .iter() .map(|src| (src.cnum, match prefer { RequireDynamic => src.dylib.clone().map(|p| p.0), RequireStatic => src.rlib.clone().map(|p| p.0), })) .collect::<Vec<_>>(); libs.sort_by(|&(a, _), &(b, _)| { let a = ordering.iter().position(|x| *x == a); let b = ordering.iter().position(|x| *x == b); a.cmp(&b) }); libs } pub fn add_used_library(&self, lib: String, kind: NativeLibraryKind) { assert!(!lib.is_empty()); self.used_libraries.borrow_mut().push((lib, kind)); } pub fn get_used_libraries<'a>(&'a self) -> &'a RefCell<Vec<(String, NativeLibraryKind)>> { &self.used_libraries } pub fn add_used_link_args(&self, args: &str) { for s in args.split(' ').filter(|s|!s.is_empty()) { self.used_link_args.borrow_mut().push(s.to_string()); } } pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String> > { &self.used_link_args } pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: ast::CrateNum) { self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { self.extern_mod_crate_map.borrow().get(&emod_id).cloned() } } impl crate_metadata { pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() } pub fn name(&self) -> String { decoder::get_crate_name(self.data()) } pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) } pub fn imported_filemaps<'a>(&'a self, codemap: &codemap::CodeMap) -> Ref<'a, Vec<ImportedFileMap>> { let filemaps = self.codemap_import_info.borrow(); if filemaps.is_empty() { drop(filemaps); let filemaps = creader::import_codemap(codemap, &self.data); // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref. *self.codemap_import_info.borrow_mut() = filemaps; self.codemap_import_info.borrow() } else { filemaps } } pub fn with_local_path<T, F>(&self, f: F) -> T where F: Fn(&[ast_map::PathElem]) -> T { let cpath = self.local_path.borrow(); if cpath.is_empty() { let name = ast_map::PathMod(token::intern(&self.name)); f(&[name]) } else { f(cpath.as_slice()) } } pub fn update_local_path<'a, 'b>(&self, candidate: ast_map::PathElems<'a, 'b>) { let mut cpath = self.local_path.borrow_mut(); let cap = cpath.len(); match cap { 0 => *cpath = candidate.collect(), 1 => (), _ => { let candidate: SmallVector<_> = candidate.collect(); if candidate.len() < cap { *cpath = candidate; } }, } } } impl MetadataBlob { pub fn as_slice<'a>(&'a self) -> &'a [u8] { let slice = match *self { MetadataVec(ref vec) => &vec[..], MetadataArchive(ref ar) => ar.as_slice(), }; if slice.len() < 4 { &[] // corrupt metadata } else { let len = (((slice[0] as u32) << 24) | ((slice[1] as u32) << 16) | ((slice[2] as u32) << 8) | ((slice[3] as u32) << 0)) as usize; if len + 4 <= slice.len() { &slice[4.. len + 4] } else { &[] // corrupt or old metadata } } } }
MetadataBlob
identifier_name
cstore.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] // The crate store - a central repo for information collected about external // crates and libraries pub use self::MetadataBlob::*; pub use self::LinkagePreference::*; pub use self::NativeLibraryKind::*; use back::svh::Svh; use metadata::{creader, decoder, loader}; use session::search_paths::PathKind; use util::nodemap::{FnvHashMap, NodeMap}; use std::cell::{RefCell, Ref}; use std::rc::Rc; use std::path::PathBuf; use flate::Bytes; use syntax::ast; use syntax::codemap; use syntax::parse::token; use syntax::parse::token::IdentInterner; use syntax::util::small_vector::SmallVector; use ast_map; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = FnvHashMap<ast::CrateNum, ast::CrateNum>; pub enum MetadataBlob { MetadataVec(Bytes), MetadataArchive(loader::ArchiveMetadata), } /// Holds information about a codemap::FileMap imported from another crate. /// See creader::import_codemap() for more information. pub struct ImportedFileMap { /// This FileMap's byte-offset within the codemap of its original crate pub original_start_pos: codemap::BytePos, /// The end of this FileMap within the codemap of its original crate pub original_end_pos: codemap::BytePos, /// The imported FileMap's representation within the local codemap pub translated_filemap: Rc<codemap::FileMap> } pub struct crate_metadata { pub name: String, pub local_path: RefCell<SmallVector<ast_map::PathElem>>, pub data: MetadataBlob, pub cnum_map: cnum_map, pub cnum: ast::CrateNum, pub codemap_import_info: RefCell<Vec<ImportedFileMap>>, pub span: codemap::Span, pub staged_api: bool } #[derive(Copy, Debug, PartialEq, Clone)] pub enum LinkagePreference { RequireDynamic, RequireStatic, } enum_from_u32! { #[derive(Copy, Clone, PartialEq)] pub enum NativeLibraryKind { NativeStatic, // native static library (.a archive) NativeFramework, // OSX-specific NativeUnknown, // default way to specify a dynamic library } } // Where a crate came from on the local filesystem. One of these two options // must be non-None. #[derive(PartialEq, Clone)] pub struct CrateSource { pub dylib: Option<(PathBuf, PathKind)>, pub rlib: Option<(PathBuf, PathKind)>, pub cnum: ast::CrateNum, } pub struct CStore { metas: RefCell<FnvHashMap<ast::CrateNum, Rc<crate_metadata>>>, /// Map from NodeId's of local extern crate statements to crate numbers extern_mod_crate_map: RefCell<NodeMap<ast::CrateNum>>, used_crate_sources: RefCell<Vec<CrateSource>>, used_libraries: RefCell<Vec<(String, NativeLibraryKind)>>, used_link_args: RefCell<Vec<String>>, pub intr: Rc<IdentInterner>, } impl CStore { pub fn new(intr: Rc<IdentInterner>) -> CStore { CStore { metas: RefCell::new(FnvHashMap()), extern_mod_crate_map: RefCell::new(FnvHashMap()), used_crate_sources: RefCell::new(Vec::new()), used_libraries: RefCell::new(Vec::new()), used_link_args: RefCell::new(Vec::new()), intr: intr } } pub fn next_crate_num(&self) -> ast::CrateNum { self.metas.borrow().len() as ast::CrateNum + 1 } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> { self.metas.borrow().get(&cnum).unwrap().clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { let cdata = self.get_crate_data(cnum); decoder::get_crate_hash(cdata.data()) } pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) { self.metas.borrow_mut().insert(cnum, data); } pub fn iter_crate_data<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata), { for (&k, v) in self.metas.borrow().iter() { i(k, &**v); } } /// Like `iter_crate_data`, but passes source paths (if available) as well. pub fn iter_crate_data_origins<I>(&self, mut i: I) where I: FnMut(ast::CrateNum, &crate_metadata, Option<CrateSource>), { for (&k, v) in self.metas.borrow().iter() { let origin = self.get_used_crate_source(k); origin.as_ref().map(|cs| { assert!(k == cs.cnum); }); i(k, &**v, origin); } } pub fn add_used_crate_source(&self, src: CrateSource) { let mut used_crate_sources = self.used_crate_sources.borrow_mut(); if!used_crate_sources.contains(&src) { used_crate_sources.push(src); } } pub fn get_used_crate_source(&self, cnum: ast::CrateNum) -> Option<CrateSource> { self.used_crate_sources.borrow_mut() .iter().find(|source| source.cnum == cnum).cloned() } pub fn reset(&self)
// This method is used when generating the command line to pass through to // system linker. The linker expects undefined symbols on the left of the // command line to be defined in libraries on the right, not the other way // around. For more info, see some comments in the add_used_library function // below. // // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. pub fn get_used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)> { let mut ordering = Vec::new(); fn visit(cstore: &CStore, cnum: ast::CrateNum, ordering: &mut Vec<ast::CrateNum>) { if ordering.contains(&cnum) { return } let meta = cstore.get_crate_data(cnum); for (_, &dep) in &meta.cnum_map { visit(cstore, dep, ordering); } ordering.push(cnum); }; for (&num, _) in self.metas.borrow().iter() { visit(self, num, &mut ordering); } ordering.reverse(); let mut libs = self.used_crate_sources.borrow() .iter() .map(|src| (src.cnum, match prefer { RequireDynamic => src.dylib.clone().map(|p| p.0), RequireStatic => src.rlib.clone().map(|p| p.0), })) .collect::<Vec<_>>(); libs.sort_by(|&(a, _), &(b, _)| { let a = ordering.iter().position(|x| *x == a); let b = ordering.iter().position(|x| *x == b); a.cmp(&b) }); libs } pub fn add_used_library(&self, lib: String, kind: NativeLibraryKind) { assert!(!lib.is_empty()); self.used_libraries.borrow_mut().push((lib, kind)); } pub fn get_used_libraries<'a>(&'a self) -> &'a RefCell<Vec<(String, NativeLibraryKind)>> { &self.used_libraries } pub fn add_used_link_args(&self, args: &str) { for s in args.split(' ').filter(|s|!s.is_empty()) { self.used_link_args.borrow_mut().push(s.to_string()); } } pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String> > { &self.used_link_args } pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: ast::CrateNum) { self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { self.extern_mod_crate_map.borrow().get(&emod_id).cloned() } } impl crate_metadata { pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() } pub fn name(&self) -> String { decoder::get_crate_name(self.data()) } pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) } pub fn imported_filemaps<'a>(&'a self, codemap: &codemap::CodeMap) -> Ref<'a, Vec<ImportedFileMap>> { let filemaps = self.codemap_import_info.borrow(); if filemaps.is_empty() { drop(filemaps); let filemaps = creader::import_codemap(codemap, &self.data); // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref. *self.codemap_import_info.borrow_mut() = filemaps; self.codemap_import_info.borrow() } else { filemaps } } pub fn with_local_path<T, F>(&self, f: F) -> T where F: Fn(&[ast_map::PathElem]) -> T { let cpath = self.local_path.borrow(); if cpath.is_empty() { let name = ast_map::PathMod(token::intern(&self.name)); f(&[name]) } else { f(cpath.as_slice()) } } pub fn update_local_path<'a, 'b>(&self, candidate: ast_map::PathElems<'a, 'b>) { let mut cpath = self.local_path.borrow_mut(); let cap = cpath.len(); match cap { 0 => *cpath = candidate.collect(), 1 => (), _ => { let candidate: SmallVector<_> = candidate.collect(); if candidate.len() < cap { *cpath = candidate; } }, } } } impl MetadataBlob { pub fn as_slice<'a>(&'a self) -> &'a [u8] { let slice = match *self { MetadataVec(ref vec) => &vec[..], MetadataArchive(ref ar) => ar.as_slice(), }; if slice.len() < 4 { &[] // corrupt metadata } else { let len = (((slice[0] as u32) << 24) | ((slice[1] as u32) << 16) | ((slice[2] as u32) << 8) | ((slice[3] as u32) << 0)) as usize; if len + 4 <= slice.len() { &slice[4.. len + 4] } else { &[] // corrupt or old metadata } } } }
{ self.metas.borrow_mut().clear(); self.extern_mod_crate_map.borrow_mut().clear(); self.used_crate_sources.borrow_mut().clear(); self.used_libraries.borrow_mut().clear(); self.used_link_args.borrow_mut().clear(); }
identifier_body
wallet_library.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! The following document is a minimalist version of Diem Wallet. Note that this Wallet does //! not promote security as the mnemonic is stored in unencrypted form. In future iterations, //! we will be releasing more robust Wallet implementations. It is our intention to present a //! foundation that is simple to understand and incrementally improve the DiemWallet //! implementation and it's security guarantees throughout testnet. For a more robust wallet //! reference, the authors suggest to audit the file of the same name in the rust-wallet crate. //! That file can be found here: //! //! https://github.com/rust-bitcoin/rust-wallet/blob/master/wallet/src/walletlibrary.rs use crate::{ error::WalletError, io_utils, key_factory::{ChildNumber, KeyFactory, Seed}, mnemonic::Mnemonic, }; use anyhow::Result; use diem_crypto::ed25519::Ed25519PrivateKey; use diem_types::{ account_address::AccountAddress, transaction::{ authenticator::AuthenticationKey, helpers::TransactionSigner, RawTransaction, SignedTransaction, }, }; use rand::{rngs::OsRng, Rng}; use std::{collections::HashMap, path::Path}; /// WalletLibrary contains all the information needed to recreate a particular wallet pub struct WalletLibrary { mnemonic: Mnemonic, key_factory: KeyFactory, addr_map: HashMap<AccountAddress, ChildNumber>, key_leaf: ChildNumber, } impl WalletLibrary { /// Constructor that generates a Mnemonic from OS randomness and subsequently instantiates an /// empty WalletLibrary from that Mnemonic #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut rng = OsRng; let data: [u8; 32] = rng.gen(); let mnemonic = Mnemonic::mnemonic(&data).unwrap(); Self::new_from_mnemonic(mnemonic) } /// Constructor that instantiates a new WalletLibrary from Mnemonic pub fn new_from_mnemonic(mnemonic: Mnemonic) -> Self { let seed = Seed::new(&mnemonic, "DIEM"); WalletLibrary { mnemonic, key_factory: KeyFactory::new(&seed).unwrap(), addr_map: HashMap::new(), key_leaf: ChildNumber(0), } } /// Function that returns the string representation of the WalletLibrary Mnemonic /// NOTE: This is not secure, and in general the mnemonic should be stored in encrypted format pub fn mnemonic(&self) -> String { self.mnemonic.to_string() } /// Function that writes the wallet Mnemonic to file /// NOTE: This is not secure, and in general the Mnemonic would need to be decrypted before it /// can be written to file; otherwise the encrypted Mnemonic should be written to file pub fn write_recovery(&self, output_file_path: &Path) -> Result<()> { io_utils::write_recovery(&self, &output_file_path)?; Ok(()) } /// Recover wallet from input_file_path pub fn recover(input_file_path: &Path) -> Result<WalletLibrary> { io_utils::recover(&input_file_path) } /// Get the current ChildNumber in u64 format pub fn key_leaf(&self) -> u64 { self.key_leaf.0 } /// Function that iterates from the current key_leaf until the supplied depth pub fn generate_addresses(&mut self, depth: u64) -> Result<()> { let current = self.key_leaf.0; if current > depth { return Err(WalletError::DiemWalletGeneric( "Addresses already generated up to the supplied depth".to_string(), ) .into()); } while self.key_leaf!= ChildNumber(depth) { let _ = self.new_address(); } Ok(()) } /// Function that allows to get the address of a particular key at a certain ChildNumber pub fn new_address_at_child_number( &mut self, child_number: ChildNumber, ) -> Result<AccountAddress> { let child = self.key_factory.private_child(child_number)?; Ok(child.get_address()) } /// Function that generates a new key and adds it to the addr_map and subsequently returns the /// AuthenticationKey associated to the PrivateKey, along with it's ChildNumber pub fn new_address(&mut self) -> Result<(AuthenticationKey, ChildNumber)> { let child = self.key_factory.private_child(self.key_leaf)?; let authentication_key = child.get_authentication_key(); let old_key_leaf = self.key_leaf; self.key_leaf.increment(); if self .addr_map .insert(authentication_key.derived_address(), old_key_leaf) .is_none() { Ok((authentication_key, old_key_leaf)) } else { Err(WalletError::DiemWalletGeneric( "This address is already in your wallet".to_string(), ) .into()) } } /// Returns a list of all addresses controlled by this wallet that are currently held by the /// addr_map pub fn get_addresses(&self) -> Result<Vec<AccountAddress>> { let mut ret = Vec::with_capacity(self.addr_map.len()); let rev_map = self .addr_map .iter() .map(|(&k, &v)| (v.as_ref().to_owned(), k.to_owned())) .collect::<HashMap<_, _>>(); for i in 0..self.addr_map.len() as u64 { match rev_map.get(&i) { Some(account_address) => { ret.push(*account_address); } None => { return Err(WalletError::DiemWalletGeneric(format!( "Child num {} not exist while depth is {}", i, self.addr_map.len() )) .into()) } } } Ok(ret) } /// Simple public function that allows to sign a Diem RawTransaction with the PrivateKey /// associated to a particular AccountAddress. If the PrivateKey associated to an /// AccountAddress is not contained in the addr_map, then this function will return an Error pub fn sign_txn(&self, txn: RawTransaction) -> Result<SignedTransaction> { if let Some(child) = self.addr_map.get(&txn.sender()) { let child_key = self.key_factory.private_child(*child)?; let signature = child_key.sign(&txn); Ok(SignedTransaction::new( txn, child_key.get_public(), signature, )) } else { Err(WalletError::DiemWalletGeneric( "Well, that address is nowhere to be found... This is awkward".to_string(), ) .into()) } } /// Return private key for an address in the wallet pub fn get_private_key(&self, address: &AccountAddress) -> Result<Ed25519PrivateKey> { if let Some(child) = self.addr_map.get(&address) { Ok(self.key_factory.private_child(*child)?.get_private_key()) } else { Err(WalletError::DiemWalletGeneric("missing address".to_string()).into()) } } /// Return authentication key (AuthenticationKey) for an address in the wallet pub fn
(&self, address: &AccountAddress) -> Result<AuthenticationKey> { if let Some(child) = self.addr_map.get(&address) { Ok(self .key_factory .private_child(*child)? .get_authentication_key()) } else { Err(WalletError::DiemWalletGeneric("missing address".to_string()).into()) } } } /// WalletLibrary naturally support TransactionSigner trait. impl TransactionSigner for WalletLibrary { fn sign_txn(&self, raw_txn: RawTransaction) -> Result<SignedTransaction, anyhow::Error> { Ok(self.sign_txn(raw_txn)?) } }
get_authentication_key
identifier_name
wallet_library.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! The following document is a minimalist version of Diem Wallet. Note that this Wallet does //! not promote security as the mnemonic is stored in unencrypted form. In future iterations, //! we will be releasing more robust Wallet implementations. It is our intention to present a //! foundation that is simple to understand and incrementally improve the DiemWallet //! implementation and it's security guarantees throughout testnet. For a more robust wallet //! reference, the authors suggest to audit the file of the same name in the rust-wallet crate. //! That file can be found here: //! //! https://github.com/rust-bitcoin/rust-wallet/blob/master/wallet/src/walletlibrary.rs use crate::{ error::WalletError, io_utils, key_factory::{ChildNumber, KeyFactory, Seed}, mnemonic::Mnemonic, }; use anyhow::Result; use diem_crypto::ed25519::Ed25519PrivateKey; use diem_types::{ account_address::AccountAddress, transaction::{ authenticator::AuthenticationKey, helpers::TransactionSigner, RawTransaction, SignedTransaction, }, }; use rand::{rngs::OsRng, Rng}; use std::{collections::HashMap, path::Path}; /// WalletLibrary contains all the information needed to recreate a particular wallet pub struct WalletLibrary { mnemonic: Mnemonic, key_factory: KeyFactory, addr_map: HashMap<AccountAddress, ChildNumber>, key_leaf: ChildNumber, } impl WalletLibrary { /// Constructor that generates a Mnemonic from OS randomness and subsequently instantiates an /// empty WalletLibrary from that Mnemonic #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut rng = OsRng; let data: [u8; 32] = rng.gen(); let mnemonic = Mnemonic::mnemonic(&data).unwrap(); Self::new_from_mnemonic(mnemonic) } /// Constructor that instantiates a new WalletLibrary from Mnemonic pub fn new_from_mnemonic(mnemonic: Mnemonic) -> Self { let seed = Seed::new(&mnemonic, "DIEM"); WalletLibrary { mnemonic, key_factory: KeyFactory::new(&seed).unwrap(), addr_map: HashMap::new(), key_leaf: ChildNumber(0), } } /// Function that returns the string representation of the WalletLibrary Mnemonic /// NOTE: This is not secure, and in general the mnemonic should be stored in encrypted format pub fn mnemonic(&self) -> String { self.mnemonic.to_string() } /// Function that writes the wallet Mnemonic to file /// NOTE: This is not secure, and in general the Mnemonic would need to be decrypted before it /// can be written to file; otherwise the encrypted Mnemonic should be written to file pub fn write_recovery(&self, output_file_path: &Path) -> Result<()> { io_utils::write_recovery(&self, &output_file_path)?; Ok(()) } /// Recover wallet from input_file_path pub fn recover(input_file_path: &Path) -> Result<WalletLibrary> { io_utils::recover(&input_file_path) } /// Get the current ChildNumber in u64 format pub fn key_leaf(&self) -> u64 { self.key_leaf.0 } /// Function that iterates from the current key_leaf until the supplied depth pub fn generate_addresses(&mut self, depth: u64) -> Result<()> { let current = self.key_leaf.0; if current > depth { return Err(WalletError::DiemWalletGeneric( "Addresses already generated up to the supplied depth".to_string(), ) .into()); } while self.key_leaf!= ChildNumber(depth) { let _ = self.new_address(); } Ok(()) } /// Function that allows to get the address of a particular key at a certain ChildNumber pub fn new_address_at_child_number( &mut self, child_number: ChildNumber, ) -> Result<AccountAddress> { let child = self.key_factory.private_child(child_number)?; Ok(child.get_address()) } /// Function that generates a new key and adds it to the addr_map and subsequently returns the /// AuthenticationKey associated to the PrivateKey, along with it's ChildNumber pub fn new_address(&mut self) -> Result<(AuthenticationKey, ChildNumber)> { let child = self.key_factory.private_child(self.key_leaf)?; let authentication_key = child.get_authentication_key(); let old_key_leaf = self.key_leaf; self.key_leaf.increment(); if self .addr_map .insert(authentication_key.derived_address(), old_key_leaf) .is_none() { Ok((authentication_key, old_key_leaf)) } else { Err(WalletError::DiemWalletGeneric( "This address is already in your wallet".to_string(), ) .into()) } } /// Returns a list of all addresses controlled by this wallet that are currently held by the /// addr_map pub fn get_addresses(&self) -> Result<Vec<AccountAddress>> { let mut ret = Vec::with_capacity(self.addr_map.len()); let rev_map = self .addr_map .iter() .map(|(&k, &v)| (v.as_ref().to_owned(), k.to_owned())) .collect::<HashMap<_, _>>(); for i in 0..self.addr_map.len() as u64 { match rev_map.get(&i) { Some(account_address) => { ret.push(*account_address); } None => { return Err(WalletError::DiemWalletGeneric(format!( "Child num {} not exist while depth is {}", i, self.addr_map.len() )) .into()) } } } Ok(ret) } /// Simple public function that allows to sign a Diem RawTransaction with the PrivateKey /// associated to a particular AccountAddress. If the PrivateKey associated to an /// AccountAddress is not contained in the addr_map, then this function will return an Error pub fn sign_txn(&self, txn: RawTransaction) -> Result<SignedTransaction> { if let Some(child) = self.addr_map.get(&txn.sender()) { let child_key = self.key_factory.private_child(*child)?; let signature = child_key.sign(&txn); Ok(SignedTransaction::new( txn, child_key.get_public(), signature, )) } else { Err(WalletError::DiemWalletGeneric( "Well, that address is nowhere to be found... This is awkward".to_string(), ) .into()) } } /// Return private key for an address in the wallet pub fn get_private_key(&self, address: &AccountAddress) -> Result<Ed25519PrivateKey> { if let Some(child) = self.addr_map.get(&address) { Ok(self.key_factory.private_child(*child)?.get_private_key()) } else { Err(WalletError::DiemWalletGeneric("missing address".to_string()).into()) } } /// Return authentication key (AuthenticationKey) for an address in the wallet pub fn get_authentication_key(&self, address: &AccountAddress) -> Result<AuthenticationKey> { if let Some(child) = self.addr_map.get(&address) { Ok(self .key_factory .private_child(*child)? .get_authentication_key()) } else { Err(WalletError::DiemWalletGeneric("missing address".to_string()).into()) } } } /// WalletLibrary naturally support TransactionSigner trait. impl TransactionSigner for WalletLibrary { fn sign_txn(&self, raw_txn: RawTransaction) -> Result<SignedTransaction, anyhow::Error> { Ok(self.sign_txn(raw_txn)?) }
}
random_line_split
wallet_library.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! The following document is a minimalist version of Diem Wallet. Note that this Wallet does //! not promote security as the mnemonic is stored in unencrypted form. In future iterations, //! we will be releasing more robust Wallet implementations. It is our intention to present a //! foundation that is simple to understand and incrementally improve the DiemWallet //! implementation and it's security guarantees throughout testnet. For a more robust wallet //! reference, the authors suggest to audit the file of the same name in the rust-wallet crate. //! That file can be found here: //! //! https://github.com/rust-bitcoin/rust-wallet/blob/master/wallet/src/walletlibrary.rs use crate::{ error::WalletError, io_utils, key_factory::{ChildNumber, KeyFactory, Seed}, mnemonic::Mnemonic, }; use anyhow::Result; use diem_crypto::ed25519::Ed25519PrivateKey; use diem_types::{ account_address::AccountAddress, transaction::{ authenticator::AuthenticationKey, helpers::TransactionSigner, RawTransaction, SignedTransaction, }, }; use rand::{rngs::OsRng, Rng}; use std::{collections::HashMap, path::Path}; /// WalletLibrary contains all the information needed to recreate a particular wallet pub struct WalletLibrary { mnemonic: Mnemonic, key_factory: KeyFactory, addr_map: HashMap<AccountAddress, ChildNumber>, key_leaf: ChildNumber, } impl WalletLibrary { /// Constructor that generates a Mnemonic from OS randomness and subsequently instantiates an /// empty WalletLibrary from that Mnemonic #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut rng = OsRng; let data: [u8; 32] = rng.gen(); let mnemonic = Mnemonic::mnemonic(&data).unwrap(); Self::new_from_mnemonic(mnemonic) } /// Constructor that instantiates a new WalletLibrary from Mnemonic pub fn new_from_mnemonic(mnemonic: Mnemonic) -> Self { let seed = Seed::new(&mnemonic, "DIEM"); WalletLibrary { mnemonic, key_factory: KeyFactory::new(&seed).unwrap(), addr_map: HashMap::new(), key_leaf: ChildNumber(0), } } /// Function that returns the string representation of the WalletLibrary Mnemonic /// NOTE: This is not secure, and in general the mnemonic should be stored in encrypted format pub fn mnemonic(&self) -> String { self.mnemonic.to_string() } /// Function that writes the wallet Mnemonic to file /// NOTE: This is not secure, and in general the Mnemonic would need to be decrypted before it /// can be written to file; otherwise the encrypted Mnemonic should be written to file pub fn write_recovery(&self, output_file_path: &Path) -> Result<()> { io_utils::write_recovery(&self, &output_file_path)?; Ok(()) } /// Recover wallet from input_file_path pub fn recover(input_file_path: &Path) -> Result<WalletLibrary> { io_utils::recover(&input_file_path) } /// Get the current ChildNumber in u64 format pub fn key_leaf(&self) -> u64 { self.key_leaf.0 } /// Function that iterates from the current key_leaf until the supplied depth pub fn generate_addresses(&mut self, depth: u64) -> Result<()> { let current = self.key_leaf.0; if current > depth { return Err(WalletError::DiemWalletGeneric( "Addresses already generated up to the supplied depth".to_string(), ) .into()); } while self.key_leaf!= ChildNumber(depth) { let _ = self.new_address(); } Ok(()) } /// Function that allows to get the address of a particular key at a certain ChildNumber pub fn new_address_at_child_number( &mut self, child_number: ChildNumber, ) -> Result<AccountAddress> { let child = self.key_factory.private_child(child_number)?; Ok(child.get_address()) } /// Function that generates a new key and adds it to the addr_map and subsequently returns the /// AuthenticationKey associated to the PrivateKey, along with it's ChildNumber pub fn new_address(&mut self) -> Result<(AuthenticationKey, ChildNumber)> { let child = self.key_factory.private_child(self.key_leaf)?; let authentication_key = child.get_authentication_key(); let old_key_leaf = self.key_leaf; self.key_leaf.increment(); if self .addr_map .insert(authentication_key.derived_address(), old_key_leaf) .is_none() { Ok((authentication_key, old_key_leaf)) } else { Err(WalletError::DiemWalletGeneric( "This address is already in your wallet".to_string(), ) .into()) } } /// Returns a list of all addresses controlled by this wallet that are currently held by the /// addr_map pub fn get_addresses(&self) -> Result<Vec<AccountAddress>> { let mut ret = Vec::with_capacity(self.addr_map.len()); let rev_map = self .addr_map .iter() .map(|(&k, &v)| (v.as_ref().to_owned(), k.to_owned())) .collect::<HashMap<_, _>>(); for i in 0..self.addr_map.len() as u64 { match rev_map.get(&i) { Some(account_address) => { ret.push(*account_address); } None => { return Err(WalletError::DiemWalletGeneric(format!( "Child num {} not exist while depth is {}", i, self.addr_map.len() )) .into()) } } } Ok(ret) } /// Simple public function that allows to sign a Diem RawTransaction with the PrivateKey /// associated to a particular AccountAddress. If the PrivateKey associated to an /// AccountAddress is not contained in the addr_map, then this function will return an Error pub fn sign_txn(&self, txn: RawTransaction) -> Result<SignedTransaction> { if let Some(child) = self.addr_map.get(&txn.sender()) { let child_key = self.key_factory.private_child(*child)?; let signature = child_key.sign(&txn); Ok(SignedTransaction::new( txn, child_key.get_public(), signature, )) } else { Err(WalletError::DiemWalletGeneric( "Well, that address is nowhere to be found... This is awkward".to_string(), ) .into()) } } /// Return private key for an address in the wallet pub fn get_private_key(&self, address: &AccountAddress) -> Result<Ed25519PrivateKey>
/// Return authentication key (AuthenticationKey) for an address in the wallet pub fn get_authentication_key(&self, address: &AccountAddress) -> Result<AuthenticationKey> { if let Some(child) = self.addr_map.get(&address) { Ok(self .key_factory .private_child(*child)? .get_authentication_key()) } else { Err(WalletError::DiemWalletGeneric("missing address".to_string()).into()) } } } /// WalletLibrary naturally support TransactionSigner trait. impl TransactionSigner for WalletLibrary { fn sign_txn(&self, raw_txn: RawTransaction) -> Result<SignedTransaction, anyhow::Error> { Ok(self.sign_txn(raw_txn)?) } }
{ if let Some(child) = self.addr_map.get(&address) { Ok(self.key_factory.private_child(*child)?.get_private_key()) } else { Err(WalletError::DiemWalletGeneric("missing address".to_string()).into()) } }
identifier_body
mod.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The compiler code necessary to implement the `#[deriving]` extensions. FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is the standard library, and "std" is the core library. */ use ast::{Item, MetaItem, MetaList, MetaNameValue, MetaWord}; use ext::base::ExtCtxt; use codemap::Span; pub mod clone; pub mod encodable; pub mod decodable; pub mod hash; pub mod rand; pub mod show; pub mod zero; pub mod default; pub mod primitive; #[path="cmp/eq.rs"] pub mod eq; #[path="cmp/totaleq.rs"] pub mod totaleq; #[path="cmp/ord.rs"] pub mod ord; #[path="cmp/totalord.rs"] pub mod totalord; pub mod generic; pub fn expand_meta_deriving(cx: &mut ExtCtxt, _span: Span, mitem: @MetaItem, item: @Item, push: |@Item|)
match tname.get() { "Clone" => expand!(clone::expand_deriving_clone), "Hash" => expand!(hash::expand_deriving_hash), "Encodable" => expand!(encodable::expand_deriving_encodable), "Decodable" => expand!(decodable::expand_deriving_decodable), "Eq" => expand!(eq::expand_deriving_eq), "TotalEq" => expand!(totaleq::expand_deriving_totaleq), "Ord" => expand!(ord::expand_deriving_ord), "TotalOrd" => expand!(totalord::expand_deriving_totalord), "Rand" => expand!(rand::expand_deriving_rand), "Show" => expand!(show::expand_deriving_show), "Zero" => expand!(zero::expand_deriving_zero), "Default" => expand!(default::expand_deriving_default), "FromPrimitive" => expand!(primitive::expand_deriving_from_primitive), ref tname => { cx.span_err(titem.span, format!("unknown \ `deriving` trait: `{}`", *tname)); } }; } } } } } }
{ match mitem.node { MetaNameValue(_, ref l) => { cx.span_err(l.span, "unexpected value in `deriving`"); } MetaWord(_) => { cx.span_warn(mitem.span, "empty trait list in `deriving`"); } MetaList(_, ref titems) if titems.len() == 0 => { cx.span_warn(mitem.span, "empty trait list in `deriving`"); } MetaList(_, ref titems) => { for &titem in titems.iter().rev() { match titem.node { MetaNameValue(ref tname, _) | MetaList(ref tname, _) | MetaWord(ref tname) => { macro_rules! expand(($func:path) => ($func(cx, titem.span, titem, item, |i| push(i))));
identifier_body
mod.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The compiler code necessary to implement the `#[deriving]` extensions. FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is the standard library, and "std" is the core library. */ use ast::{Item, MetaItem, MetaList, MetaNameValue, MetaWord}; use ext::base::ExtCtxt; use codemap::Span; pub mod clone; pub mod encodable; pub mod decodable; pub mod hash; pub mod rand; pub mod show; pub mod zero; pub mod default; pub mod primitive; #[path="cmp/eq.rs"] pub mod eq; #[path="cmp/totaleq.rs"] pub mod totaleq; #[path="cmp/ord.rs"] pub mod ord; #[path="cmp/totalord.rs"] pub mod totalord; pub mod generic; pub fn
(cx: &mut ExtCtxt, _span: Span, mitem: @MetaItem, item: @Item, push: |@Item|) { match mitem.node { MetaNameValue(_, ref l) => { cx.span_err(l.span, "unexpected value in `deriving`"); } MetaWord(_) => { cx.span_warn(mitem.span, "empty trait list in `deriving`"); } MetaList(_, ref titems) if titems.len() == 0 => { cx.span_warn(mitem.span, "empty trait list in `deriving`"); } MetaList(_, ref titems) => { for &titem in titems.iter().rev() { match titem.node { MetaNameValue(ref tname, _) | MetaList(ref tname, _) | MetaWord(ref tname) => { macro_rules! expand(($func:path) => ($func(cx, titem.span, titem, item, |i| push(i)))); match tname.get() { "Clone" => expand!(clone::expand_deriving_clone), "Hash" => expand!(hash::expand_deriving_hash), "Encodable" => expand!(encodable::expand_deriving_encodable), "Decodable" => expand!(decodable::expand_deriving_decodable), "Eq" => expand!(eq::expand_deriving_eq), "TotalEq" => expand!(totaleq::expand_deriving_totaleq), "Ord" => expand!(ord::expand_deriving_ord), "TotalOrd" => expand!(totalord::expand_deriving_totalord), "Rand" => expand!(rand::expand_deriving_rand), "Show" => expand!(show::expand_deriving_show), "Zero" => expand!(zero::expand_deriving_zero), "Default" => expand!(default::expand_deriving_default), "FromPrimitive" => expand!(primitive::expand_deriving_from_primitive), ref tname => { cx.span_err(titem.span, format!("unknown \ `deriving` trait: `{}`", *tname)); } }; } } } } } }
expand_meta_deriving
identifier_name
mod.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The compiler code necessary to implement the `#[deriving]` extensions. FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is the standard library, and "std" is the core library. */ use ast::{Item, MetaItem, MetaList, MetaNameValue, MetaWord}; use ext::base::ExtCtxt; use codemap::Span; pub mod clone; pub mod encodable;
pub mod default; pub mod primitive; #[path="cmp/eq.rs"] pub mod eq; #[path="cmp/totaleq.rs"] pub mod totaleq; #[path="cmp/ord.rs"] pub mod ord; #[path="cmp/totalord.rs"] pub mod totalord; pub mod generic; pub fn expand_meta_deriving(cx: &mut ExtCtxt, _span: Span, mitem: @MetaItem, item: @Item, push: |@Item|) { match mitem.node { MetaNameValue(_, ref l) => { cx.span_err(l.span, "unexpected value in `deriving`"); } MetaWord(_) => { cx.span_warn(mitem.span, "empty trait list in `deriving`"); } MetaList(_, ref titems) if titems.len() == 0 => { cx.span_warn(mitem.span, "empty trait list in `deriving`"); } MetaList(_, ref titems) => { for &titem in titems.iter().rev() { match titem.node { MetaNameValue(ref tname, _) | MetaList(ref tname, _) | MetaWord(ref tname) => { macro_rules! expand(($func:path) => ($func(cx, titem.span, titem, item, |i| push(i)))); match tname.get() { "Clone" => expand!(clone::expand_deriving_clone), "Hash" => expand!(hash::expand_deriving_hash), "Encodable" => expand!(encodable::expand_deriving_encodable), "Decodable" => expand!(decodable::expand_deriving_decodable), "Eq" => expand!(eq::expand_deriving_eq), "TotalEq" => expand!(totaleq::expand_deriving_totaleq), "Ord" => expand!(ord::expand_deriving_ord), "TotalOrd" => expand!(totalord::expand_deriving_totalord), "Rand" => expand!(rand::expand_deriving_rand), "Show" => expand!(show::expand_deriving_show), "Zero" => expand!(zero::expand_deriving_zero), "Default" => expand!(default::expand_deriving_default), "FromPrimitive" => expand!(primitive::expand_deriving_from_primitive), ref tname => { cx.span_err(titem.span, format!("unknown \ `deriving` trait: `{}`", *tname)); } }; } } } } } }
pub mod decodable; pub mod hash; pub mod rand; pub mod show; pub mod zero;
random_line_split
init-res-into-things.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: @mut int, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn finalize(&self) { unsafe { *(self.i) = *(self.i) + 1; } } } fn r(i: @mut int) -> r { r { i: i } } fn test_box() { let i = @mut 0; { let a = @r(i); } assert!(*i == 1); } fn test_rec() { let i = @mut 0; { let a = Box {x: r(i)}; } assert!(*i == 1); } fn test_tag() { enum t { t0(r), } let i = @mut 0; { let a = t0(r(i)); } assert!(*i == 1); } fn test_tup() { let i = @mut 0; { let a = (r(i), 0); } assert!(*i == 1); } fn test_unique() { let i = @mut 0; { let a = ~r(i); } assert!(*i == 1); } fn test_box_rec() { let i = @mut 0; { let a = @Box { x: r(i) }; } assert!(*i == 1); } pub fn
() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }
main
identifier_name
init-res-into-things.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: @mut int, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn finalize(&self) { unsafe { *(self.i) = *(self.i) + 1; } } } fn r(i: @mut int) -> r { r { i: i } } fn test_box() { let i = @mut 0; { let a = @r(i); } assert!(*i == 1); } fn test_rec() { let i = @mut 0; { let a = Box {x: r(i)}; } assert!(*i == 1); } fn test_tag() { enum t { t0(r), } let i = @mut 0; { let a = t0(r(i)); } assert!(*i == 1); } fn test_tup() { let i = @mut 0; { let a = (r(i), 0); } assert!(*i == 1); } fn test_unique() { let i = @mut 0; { let a = ~r(i); } assert!(*i == 1); } fn test_box_rec() { let i = @mut 0; { let a = @Box { x: r(i) }; } assert!(*i == 1); } pub fn main() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }
// 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.
random_line_split
init-res-into-things.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: @mut int, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn finalize(&self) { unsafe { *(self.i) = *(self.i) + 1; } } } fn r(i: @mut int) -> r
fn test_box() { let i = @mut 0; { let a = @r(i); } assert!(*i == 1); } fn test_rec() { let i = @mut 0; { let a = Box {x: r(i)}; } assert!(*i == 1); } fn test_tag() { enum t { t0(r), } let i = @mut 0; { let a = t0(r(i)); } assert!(*i == 1); } fn test_tup() { let i = @mut 0; { let a = (r(i), 0); } assert!(*i == 1); } fn test_unique() { let i = @mut 0; { let a = ~r(i); } assert!(*i == 1); } fn test_box_rec() { let i = @mut 0; { let a = @Box { x: r(i) }; } assert!(*i == 1); } pub fn main() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }
{ r { i: i } }
identifier_body
test_type_error.rs
/* * Copyright 2021 Google LLC. * * 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. */ #[cfg(test)] mod test { use crate::{ast::*, compilation_top_level::*, souffle::souffle_interface::*}; use std::fs; #[test] #[should_panic] fn test_type_error()
}
{ compile("type_error", "test_inputs", "test_outputs", ""); }
identifier_body
test_type_error.rs
/* * Copyright 2021 Google LLC. * * 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. */ #[cfg(test)] mod test { use crate::{ast::*, compilation_top_level::*, souffle::souffle_interface::*}; use std::fs; #[test] #[should_panic] fn
() { compile("type_error", "test_inputs", "test_outputs", ""); } }
test_type_error
identifier_name
test_type_error.rs
* * 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. */ #[cfg(test)] mod test { use crate::{ast::*, compilation_top_level::*, souffle::souffle_interface::*}; use std::fs; #[test] #[should_panic] fn test_type_error() { compile("type_error", "test_inputs", "test_outputs", ""); } }
/* * Copyright 2021 Google LLC.
random_line_split
lib.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The main library for xi-core. extern crate serde; #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate time; extern crate syntect; #[cfg(target_os = "fuchsia")] extern crate magenta; #[cfg(target_os = "fuchsia")] extern crate magenta_sys; #[cfg(target_os = "fuchsia")] extern crate mxruntime; #[cfg(target_os = "fuchsia")] #[macro_use] extern crate fidl; #[cfg(target_os = "fuchsia")] extern crate apps_ledger_services_public; #[cfg(target_os = "fuchsia")] extern crate sha2; use serde_json::Value; #[macro_use] mod macros; pub mod rpc; /// Internal data structures and logic. /// /// These internals are not part of the public API (for the purpose of binding to /// a front-end), but are exposed here, largely so they appear in documentation. #[path=""] pub mod internal { pub mod tabs; pub mod editor; pub mod view; pub mod linewrap; pub mod plugins; #[cfg(target_os = "fuchsia")] pub mod fuchsia; pub mod styles; pub mod word_boundaries; pub mod index_set; pub mod selection; pub mod movement; pub mod syntax; pub mod layers; } use internal::tabs; use internal::editor; use internal::view; use internal::linewrap; use internal::plugins; use internal::styles; use internal::word_boundaries; use internal::index_set; use internal::selection; use internal::movement; use internal::syntax; use internal::layers; #[cfg(target_os = "fuchsia")] use internal::fuchsia; use tabs::Documents; use rpc::Request; #[cfg(target_os = "fuchsia")] use apps_ledger_services_public::Ledger_Proxy; extern crate xi_rope; extern crate xi_unicode; extern crate xi_rpc; use xi_rpc::{RpcPeer, RpcCtx, Handler}; pub type MainPeer = RpcPeer; pub struct MainState { tabs: Documents, } impl MainState { pub fn new() -> Self { MainState { tabs: Documents::new(), } } #[cfg(target_os = "fuchsia")] pub fn set_ledger(&mut self, ledger: Ledger_Proxy, session_id: (u64, u32)) { self.tabs.setup_ledger(ledger, session_id); } } impl Handler for MainState { fn handle_notification(&mut self, mut ctx: RpcCtx, method: &str, params: &Value)
fn handle_request(&mut self, mut ctx: RpcCtx, method: &str, params: &Value) -> Result<Value, Value> { match Request::from_json(method, params) { Ok(req) => { let result = self.handle_req(req, &mut ctx); result.ok_or_else(|| json!("return value missing")) } Err(e) => { print_err!("Error {} decoding RPC request {}", e, method); Err(json!("error decoding request")) } } } fn idle(&mut self, _ctx: RpcCtx, _token: usize) { self.tabs.handle_idle(); } } impl MainState { fn handle_req(&mut self, request: Request, rpc_ctx: &mut RpcCtx) -> Option<Value> { match request { Request::CoreCommand { core_command } => self.tabs.do_rpc(core_command, rpc_ctx) } } }
{ match Request::from_json(method, params) { Ok(req) => { if let Some(_) = self.handle_req(req, &mut ctx) { print_err!("Unexpected return value for notification {}", method) } } Err(e) => print_err!("Error {} decoding RPC request {}", e, method) } }
identifier_body
lib.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The main library for xi-core. extern crate serde; #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate time; extern crate syntect; #[cfg(target_os = "fuchsia")] extern crate magenta; #[cfg(target_os = "fuchsia")] extern crate magenta_sys; #[cfg(target_os = "fuchsia")] extern crate mxruntime; #[cfg(target_os = "fuchsia")] #[macro_use] extern crate fidl; #[cfg(target_os = "fuchsia")] extern crate apps_ledger_services_public; #[cfg(target_os = "fuchsia")] extern crate sha2; use serde_json::Value; #[macro_use] mod macros; pub mod rpc; /// Internal data structures and logic. /// /// These internals are not part of the public API (for the purpose of binding to /// a front-end), but are exposed here, largely so they appear in documentation. #[path=""] pub mod internal { pub mod tabs; pub mod editor; pub mod view; pub mod linewrap; pub mod plugins; #[cfg(target_os = "fuchsia")] pub mod fuchsia; pub mod styles; pub mod word_boundaries; pub mod index_set; pub mod selection; pub mod movement; pub mod syntax; pub mod layers; } use internal::tabs; use internal::editor; use internal::view; use internal::linewrap; use internal::plugins; use internal::styles; use internal::word_boundaries; use internal::index_set; use internal::selection; use internal::movement; use internal::syntax; use internal::layers; #[cfg(target_os = "fuchsia")] use internal::fuchsia; use tabs::Documents; use rpc::Request; #[cfg(target_os = "fuchsia")] use apps_ledger_services_public::Ledger_Proxy; extern crate xi_rope; extern crate xi_unicode; extern crate xi_rpc; use xi_rpc::{RpcPeer, RpcCtx, Handler}; pub type MainPeer = RpcPeer; pub struct MainState { tabs: Documents, } impl MainState { pub fn new() -> Self { MainState { tabs: Documents::new(), } } #[cfg(target_os = "fuchsia")] pub fn set_ledger(&mut self, ledger: Ledger_Proxy, session_id: (u64, u32)) { self.tabs.setup_ledger(ledger, session_id); } } impl Handler for MainState { fn handle_notification(&mut self, mut ctx: RpcCtx, method: &str, params: &Value) { match Request::from_json(method, params) { Ok(req) => { if let Some(_) = self.handle_req(req, &mut ctx) { print_err!("Unexpected return value for notification {}", method) } } Err(e) => print_err!("Error {} decoding RPC request {}", e, method) } } fn handle_request(&mut self, mut ctx: RpcCtx, method: &str, params: &Value) -> Result<Value, Value> { match Request::from_json(method, params) { Ok(req) => { let result = self.handle_req(req, &mut ctx); result.ok_or_else(|| json!("return value missing")) }
print_err!("Error {} decoding RPC request {}", e, method); Err(json!("error decoding request")) } } } fn idle(&mut self, _ctx: RpcCtx, _token: usize) { self.tabs.handle_idle(); } } impl MainState { fn handle_req(&mut self, request: Request, rpc_ctx: &mut RpcCtx) -> Option<Value> { match request { Request::CoreCommand { core_command } => self.tabs.do_rpc(core_command, rpc_ctx) } } }
Err(e) => {
random_line_split
lib.rs
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! The main library for xi-core. extern crate serde; #[macro_use] extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate time; extern crate syntect; #[cfg(target_os = "fuchsia")] extern crate magenta; #[cfg(target_os = "fuchsia")] extern crate magenta_sys; #[cfg(target_os = "fuchsia")] extern crate mxruntime; #[cfg(target_os = "fuchsia")] #[macro_use] extern crate fidl; #[cfg(target_os = "fuchsia")] extern crate apps_ledger_services_public; #[cfg(target_os = "fuchsia")] extern crate sha2; use serde_json::Value; #[macro_use] mod macros; pub mod rpc; /// Internal data structures and logic. /// /// These internals are not part of the public API (for the purpose of binding to /// a front-end), but are exposed here, largely so they appear in documentation. #[path=""] pub mod internal { pub mod tabs; pub mod editor; pub mod view; pub mod linewrap; pub mod plugins; #[cfg(target_os = "fuchsia")] pub mod fuchsia; pub mod styles; pub mod word_boundaries; pub mod index_set; pub mod selection; pub mod movement; pub mod syntax; pub mod layers; } use internal::tabs; use internal::editor; use internal::view; use internal::linewrap; use internal::plugins; use internal::styles; use internal::word_boundaries; use internal::index_set; use internal::selection; use internal::movement; use internal::syntax; use internal::layers; #[cfg(target_os = "fuchsia")] use internal::fuchsia; use tabs::Documents; use rpc::Request; #[cfg(target_os = "fuchsia")] use apps_ledger_services_public::Ledger_Proxy; extern crate xi_rope; extern crate xi_unicode; extern crate xi_rpc; use xi_rpc::{RpcPeer, RpcCtx, Handler}; pub type MainPeer = RpcPeer; pub struct MainState { tabs: Documents, } impl MainState { pub fn new() -> Self { MainState { tabs: Documents::new(), } } #[cfg(target_os = "fuchsia")] pub fn set_ledger(&mut self, ledger: Ledger_Proxy, session_id: (u64, u32)) { self.tabs.setup_ledger(ledger, session_id); } } impl Handler for MainState { fn handle_notification(&mut self, mut ctx: RpcCtx, method: &str, params: &Value) { match Request::from_json(method, params) { Ok(req) => { if let Some(_) = self.handle_req(req, &mut ctx) { print_err!("Unexpected return value for notification {}", method) } } Err(e) => print_err!("Error {} decoding RPC request {}", e, method) } } fn handle_request(&mut self, mut ctx: RpcCtx, method: &str, params: &Value) -> Result<Value, Value> { match Request::from_json(method, params) { Ok(req) => { let result = self.handle_req(req, &mut ctx); result.ok_or_else(|| json!("return value missing")) } Err(e) => { print_err!("Error {} decoding RPC request {}", e, method); Err(json!("error decoding request")) } } } fn idle(&mut self, _ctx: RpcCtx, _token: usize) { self.tabs.handle_idle(); } } impl MainState { fn
(&mut self, request: Request, rpc_ctx: &mut RpcCtx) -> Option<Value> { match request { Request::CoreCommand { core_command } => self.tabs.do_rpc(core_command, rpc_ctx) } } }
handle_req
identifier_name
nok.rs
use std::marker::PhantomData; /// `Nok` contains the content of an error response from the CouchDB server. /// /// # Summary /// /// * `Nok` has public members instead of accessor methods because there are no /// invariants restricting the data. /// /// * `Nok` implements `Deserialize`. /// /// # Remarks /// /// When the CouchDB server responds with a 4xx- or 5xx status code, the /// response usually has a body containing a JSON object with an β€œerror” string /// and a β€œreason” string. For example: /// /// ```text /// { /// "error": "file_exists", /// "reason": "The database could not be created, the file already exists." /// } /// ``` /// /// The `Nok` type contains the information from the response body. /// /// ``` /// extern crate couchdb; /// extern crate serde_json; /// /// # let body = br#"{ /// # "error": "file_exists", /// # "reason": "The database could not be created, the file already exists." /// # }"#; /// # /// let nok: couchdb::Nok = serde_json::from_slice(body).unwrap(); /// /// assert_eq!(nok.error, "file_exists"); /// assert_eq!(nok.reason, /// "The database could not be created, the file already exists."); /// ``` /// /// # Compatibility /// /// `Nok` contains a dummy private member in order to prevent applications from /// directly constructing a `Nok` instance. This allows new fields to be added /// to `Nok` in future releases without it being a breaking change. /// #[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Nok {
ub error: String, pub reason: String, #[serde(default = "PhantomData::default")] _private_guard: PhantomData<()>, }
p
identifier_name
nok.rs
use std::marker::PhantomData; /// `Nok` contains the content of an error response from the CouchDB server. /// /// # Summary /// /// * `Nok` has public members instead of accessor methods because there are no /// invariants restricting the data. /// /// * `Nok` implements `Deserialize`. /// /// # Remarks /// /// When the CouchDB server responds with a 4xx- or 5xx status code, the /// response usually has a body containing a JSON object with an β€œerror” string /// and a β€œreason” string. For example: /// /// ```text /// { /// "error": "file_exists", /// "reason": "The database could not be created, the file already exists." /// } /// ``` /// /// The `Nok` type contains the information from the response body. /// /// ``` /// extern crate couchdb; /// extern crate serde_json; /// /// # let body = br#"{ /// # "error": "file_exists", /// # "reason": "The database could not be created, the file already exists." /// # }"#; /// # /// let nok: couchdb::Nok = serde_json::from_slice(body).unwrap(); /// /// assert_eq!(nok.error, "file_exists"); /// assert_eq!(nok.reason, /// "The database could not be created, the file already exists.");
/// /// `Nok` contains a dummy private member in order to prevent applications from /// directly constructing a `Nok` instance. This allows new fields to be added /// to `Nok` in future releases without it being a breaking change. /// #[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Nok { pub error: String, pub reason: String, #[serde(default = "PhantomData::default")] _private_guard: PhantomData<()>, }
/// ``` /// /// # Compatibility
random_line_split
helloworld.rs
extern crate redis; use std::thread; use redis::{RedisResult, Value as RedisValue, Commands}; fn main()
let connection = client.get_connection().expect("Couldn't open connection"); let thread_handle = thread::spawn(move || { for _ in 0..10 { let msgs = [ format!("message 1 from producer {}", consumer_num), format!("message 2 from producer {}", consumer_num), ]; let result = connection.rpush(queue_name, &msgs); assert_eq!(result, Ok(2)); } }); thread_handles.push(thread_handle); } // start two consumer threads for channel_1 and one for channel_2 for &channel_name in &["channel_1", "channel_1", "channel_2"] { let connection = client.get_connection().expect("Couldn't open connection"); let thread_handle = thread::spawn(move || { loop { let maybe_result: RedisResult<Vec<Vec<RedisValue>>> = redis::cmd("HMGET") .arg(queue_name).arg(channel_name).arg(get_count).arg(get_timeout) .query(&connection); let result = match maybe_result { Err(_) => maybe_result.unwrap(), Ok(ref result) if result.is_empty() => { println!("{} received no messages after {} seconds, will exit", channel_name, get_timeout); break } Ok(result) => result }; let mut tickets = Vec::new(); for msg in result { let id: u64 = redis::from_redis_value(&msg[0]).unwrap(); let ticket: i64 = redis::from_redis_value(&msg[1]).unwrap(); let body: String = redis::from_redis_value(&msg[2]).unwrap(); tickets.push(ticket); println!("{} received msg: id {} ticket {} body {:?}", channel_name, id, ticket, body); } // ack the messages let _: usize = redis::cmd("HDEL") .arg(queue_name).arg(channel_name).arg(&tickets[..]) .query(&connection).unwrap(); } }); thread_handles.push(thread_handle); } for thread_handle in thread_handles { thread_handle.join().unwrap(); } // print some info { let result: RedisResult<Vec<String>> = redis::cmd("INFO").arg("queues").query(&connection); println!("queue info\n{}", result.unwrap()[0]); let result: RedisResult<Vec<String>> = redis::cmd("INFO").arg("server").query(&connection); println!("server info\n{}", result.unwrap()[0]); let result: RedisResult<Vec<String>> = redis::cmd("CONFIG").arg("GET").arg("server").query(&connection); println!("server config\n{}", result.unwrap()[0]); } }
{ // connect to local host, default port let queue_name = "my_queue"; let get_timeout = 5; let get_count = 2; let client = redis::Client::open("redis://127.0.0.1:9797/").unwrap(); let mut thread_handles = Vec::new(); let connection = client.get_connection().expect("Couldn't open connection"); // delete any previous the queue let result: RedisResult<bool> = connection.del(queue_name); assert_eq!(result, Ok(true)); // create the queue and two channels for &channel_name in &["channel_1", "channel_2"] { let result: RedisResult<bool> = connection.set_nx(queue_name, channel_name); assert_eq!(result, Ok(true)); } // start two producer threads for consumer_num in 0..2 {
identifier_body
helloworld.rs
extern crate redis; use std::thread; use redis::{RedisResult, Value as RedisValue, Commands}; fn
() { // connect to local host, default port let queue_name = "my_queue"; let get_timeout = 5; let get_count = 2; let client = redis::Client::open("redis://127.0.0.1:9797/").unwrap(); let mut thread_handles = Vec::new(); let connection = client.get_connection().expect("Couldn't open connection"); // delete any previous the queue let result: RedisResult<bool> = connection.del(queue_name); assert_eq!(result, Ok(true)); // create the queue and two channels for &channel_name in &["channel_1", "channel_2"] { let result: RedisResult<bool> = connection.set_nx(queue_name, channel_name); assert_eq!(result, Ok(true)); } // start two producer threads for consumer_num in 0..2 { let connection = client.get_connection().expect("Couldn't open connection"); let thread_handle = thread::spawn(move || { for _ in 0..10 { let msgs = [ format!("message 1 from producer {}", consumer_num), format!("message 2 from producer {}", consumer_num), ]; let result = connection.rpush(queue_name, &msgs); assert_eq!(result, Ok(2)); } }); thread_handles.push(thread_handle); } // start two consumer threads for channel_1 and one for channel_2 for &channel_name in &["channel_1", "channel_1", "channel_2"] { let connection = client.get_connection().expect("Couldn't open connection"); let thread_handle = thread::spawn(move || { loop { let maybe_result: RedisResult<Vec<Vec<RedisValue>>> = redis::cmd("HMGET") .arg(queue_name).arg(channel_name).arg(get_count).arg(get_timeout) .query(&connection); let result = match maybe_result { Err(_) => maybe_result.unwrap(), Ok(ref result) if result.is_empty() => { println!("{} received no messages after {} seconds, will exit", channel_name, get_timeout); break } Ok(result) => result }; let mut tickets = Vec::new(); for msg in result { let id: u64 = redis::from_redis_value(&msg[0]).unwrap(); let ticket: i64 = redis::from_redis_value(&msg[1]).unwrap(); let body: String = redis::from_redis_value(&msg[2]).unwrap(); tickets.push(ticket); println!("{} received msg: id {} ticket {} body {:?}", channel_name, id, ticket, body); } // ack the messages let _: usize = redis::cmd("HDEL") .arg(queue_name).arg(channel_name).arg(&tickets[..]) .query(&connection).unwrap(); } }); thread_handles.push(thread_handle); } for thread_handle in thread_handles { thread_handle.join().unwrap(); } // print some info { let result: RedisResult<Vec<String>> = redis::cmd("INFO").arg("queues").query(&connection); println!("queue info\n{}", result.unwrap()[0]); let result: RedisResult<Vec<String>> = redis::cmd("INFO").arg("server").query(&connection); println!("server info\n{}", result.unwrap()[0]); let result: RedisResult<Vec<String>> = redis::cmd("CONFIG").arg("GET").arg("server").query(&connection); println!("server config\n{}", result.unwrap()[0]); } }
main
identifier_name
helloworld.rs
extern crate redis; use std::thread; use redis::{RedisResult, Value as RedisValue, Commands}; fn main() { // connect to local host, default port let queue_name = "my_queue"; let get_timeout = 5; let get_count = 2; let client = redis::Client::open("redis://127.0.0.1:9797/").unwrap(); let mut thread_handles = Vec::new(); let connection = client.get_connection().expect("Couldn't open connection"); // delete any previous the queue let result: RedisResult<bool> = connection.del(queue_name); assert_eq!(result, Ok(true)); // create the queue and two channels for &channel_name in &["channel_1", "channel_2"] { let result: RedisResult<bool> = connection.set_nx(queue_name, channel_name); assert_eq!(result, Ok(true)); } // start two producer threads for consumer_num in 0..2 { let connection = client.get_connection().expect("Couldn't open connection"); let thread_handle = thread::spawn(move || { for _ in 0..10 { let msgs = [ format!("message 1 from producer {}", consumer_num), format!("message 2 from producer {}", consumer_num), ]; let result = connection.rpush(queue_name, &msgs); assert_eq!(result, Ok(2)); } }); thread_handles.push(thread_handle); } // start two consumer threads for channel_1 and one for channel_2 for &channel_name in &["channel_1", "channel_1", "channel_2"] { let connection = client.get_connection().expect("Couldn't open connection");
let maybe_result: RedisResult<Vec<Vec<RedisValue>>> = redis::cmd("HMGET") .arg(queue_name).arg(channel_name).arg(get_count).arg(get_timeout) .query(&connection); let result = match maybe_result { Err(_) => maybe_result.unwrap(), Ok(ref result) if result.is_empty() => { println!("{} received no messages after {} seconds, will exit", channel_name, get_timeout); break } Ok(result) => result }; let mut tickets = Vec::new(); for msg in result { let id: u64 = redis::from_redis_value(&msg[0]).unwrap(); let ticket: i64 = redis::from_redis_value(&msg[1]).unwrap(); let body: String = redis::from_redis_value(&msg[2]).unwrap(); tickets.push(ticket); println!("{} received msg: id {} ticket {} body {:?}", channel_name, id, ticket, body); } // ack the messages let _: usize = redis::cmd("HDEL") .arg(queue_name).arg(channel_name).arg(&tickets[..]) .query(&connection).unwrap(); } }); thread_handles.push(thread_handle); } for thread_handle in thread_handles { thread_handle.join().unwrap(); } // print some info { let result: RedisResult<Vec<String>> = redis::cmd("INFO").arg("queues").query(&connection); println!("queue info\n{}", result.unwrap()[0]); let result: RedisResult<Vec<String>> = redis::cmd("INFO").arg("server").query(&connection); println!("server info\n{}", result.unwrap()[0]); let result: RedisResult<Vec<String>> = redis::cmd("CONFIG").arg("GET").arg("server").query(&connection); println!("server config\n{}", result.unwrap()[0]); } }
let thread_handle = thread::spawn(move || { loop {
random_line_split
test_md5mesh.rs
use implement::file::md5common; use implement::file::md5mesh; #[test] fn test_parse_md5mesh(){ let file_content = md5common::file_open( "core/asset/md5/qshambler.md5mesh" ).expect("file open invalid"); println!("file content length: {}", file_content.len() ); let _mesh_root = md5mesh::parse( &file_content ).expect("parse unsuccessful"); // for i in mesh_root._joints.iter() { // println!( "joint name: {:?}, parent index: {:?}, pos: {:?}, orient: {:?}, rot: {:?}", i._name, i._parent_index, i._pos, i._orient, i._rot ); // } // for (idx, i) in mesh_root._meshes.iter().enumerate() { // println!( "mesh {} {{", idx ); // println!( "shader: {}", i._shader ); // println!( "numverts: {}", i._numverts ); // for j in i._verts.iter() { // println!( "vert index: {}, tex coords: {:?}, weight start: {}, weight count: {}", j._index, j._tex_coords, j._weight_start, j._weight_count ); // } // println!( "numtris: {}", i._numtris ); // for j in i._tris.iter() { // println!( "tri index: {}, vert indices: {:?}", j._index, j._vert_indices );
// for j in i._weights.iter() { // println!("weight index: {}, joint index: {}, weight bias: {}, pos: {:?}", j._index, j._joint_index, j._weight_bias, j._pos ); // } // println!( "}}" ); // } }
// } // println!( "numweights: {}", i._numweights );
random_line_split
test_md5mesh.rs
use implement::file::md5common; use implement::file::md5mesh; #[test] fn test_parse_md5mesh()
// println!( "numweights: {}", i._numweights ); // for j in i._weights.iter() { // println!("weight index: {}, joint index: {}, weight bias: {}, pos: {:?}", j._index, j._joint_index, j._weight_bias, j._pos ); // } // println!( "}}" ); // } }
{ let file_content = md5common::file_open( "core/asset/md5/qshambler.md5mesh" ).expect("file open invalid"); println!("file content length: {}", file_content.len() ); let _mesh_root = md5mesh::parse( &file_content ).expect("parse unsuccessful"); // for i in mesh_root._joints.iter() { // println!( "joint name: {:?}, parent index: {:?}, pos: {:?}, orient: {:?}, rot: {:?}", i._name, i._parent_index, i._pos, i._orient, i._rot ); // } // for (idx, i) in mesh_root._meshes.iter().enumerate() { // println!( "mesh {} {{", idx ); // println!( "shader: {}", i._shader ); // println!( "numverts: {}", i._numverts ); // for j in i._verts.iter() { // println!( "vert index: {}, tex coords: {:?}, weight start: {}, weight count: {}", j._index, j._tex_coords, j._weight_start, j._weight_count ); // } // println!( "numtris: {}", i._numtris ); // for j in i._tris.iter() { // println!( "tri index: {}, vert indices: {:?}", j._index, j._vert_indices ); // }
identifier_body
test_md5mesh.rs
use implement::file::md5common; use implement::file::md5mesh; #[test] fn
(){ let file_content = md5common::file_open( "core/asset/md5/qshambler.md5mesh" ).expect("file open invalid"); println!("file content length: {}", file_content.len() ); let _mesh_root = md5mesh::parse( &file_content ).expect("parse unsuccessful"); // for i in mesh_root._joints.iter() { // println!( "joint name: {:?}, parent index: {:?}, pos: {:?}, orient: {:?}, rot: {:?}", i._name, i._parent_index, i._pos, i._orient, i._rot ); // } // for (idx, i) in mesh_root._meshes.iter().enumerate() { // println!( "mesh {} {{", idx ); // println!( "shader: {}", i._shader ); // println!( "numverts: {}", i._numverts ); // for j in i._verts.iter() { // println!( "vert index: {}, tex coords: {:?}, weight start: {}, weight count: {}", j._index, j._tex_coords, j._weight_start, j._weight_count ); // } // println!( "numtris: {}", i._numtris ); // for j in i._tris.iter() { // println!( "tri index: {}, vert indices: {:?}", j._index, j._vert_indices ); // } // println!( "numweights: {}", i._numweights ); // for j in i._weights.iter() { // println!("weight index: {}, joint index: {}, weight bias: {}, pos: {:?}", j._index, j._joint_index, j._weight_bias, j._pos ); // } // println!( "}}" ); // } }
test_parse_md5mesh
identifier_name
m_1_2_01.rs
// M_1_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * order vs random! * how to interpolate between a free composition (random) and a circle shape (order) * * MOUSE * position x : fade between random and circle shape * * KEYS * s : save png */ use nannou::prelude::*; use nannou::rand::rngs::StdRng; use nannou::rand::{Rng, SeedableRng}; fn main() { nannou::app(model).run(); } struct Model { act_random_seed: u64, count: usize, } fn model(app: &App) -> Model { let _window = app .new_window() .size(800, 800) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .build() .unwrap(); Model { act_random_seed: 0, count: 150, } } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); let win = app.window_rect(); draw.background().color(WHITE); let fader_x = map_range(app.mouse.x, win.left(), win.right(), 0.0, 1.0); let mut rng = StdRng::seed_from_u64(model.act_random_seed); let angle = deg_to_rad(360.0 / model.count as f32); for i in 0..model.count { // positions let random_x = rng.gen_range(win.left(), win.right() + 1.0); let random_y = rng.gen_range(win.bottom(), win.top() + 1.0); let circle_x = (angle * i as f32).cos() * 300.0; let circle_y = (angle * i as f32).sin() * 300.0; let x = nannou::geom::Range::new(random_x, circle_x).lerp(fader_x); let y = nannou::geom::Range::new(random_y, circle_y).lerp(fader_x); draw.ellipse().x_y(x, y).w_h(11.0, 11.0).rgb8(0, 130, 163); } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.act_random_seed = (random_f32() * 100000.0) as u64; }
} }
fn key_pressed(app: &App, _model: &mut Model, key: Key) { if key == Key::S { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png");
random_line_split
m_1_2_01.rs
// M_1_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * order vs random! * how to interpolate between a free composition (random) and a circle shape (order) * * MOUSE * position x : fade between random and circle shape * * KEYS * s : save png */ use nannou::prelude::*; use nannou::rand::rngs::StdRng; use nannou::rand::{Rng, SeedableRng}; fn main() { nannou::app(model).run(); } struct Model { act_random_seed: u64, count: usize, } fn model(app: &App) -> Model { let _window = app .new_window() .size(800, 800) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .build() .unwrap(); Model { act_random_seed: 0, count: 150, } } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); let win = app.window_rect(); draw.background().color(WHITE); let fader_x = map_range(app.mouse.x, win.left(), win.right(), 0.0, 1.0); let mut rng = StdRng::seed_from_u64(model.act_random_seed); let angle = deg_to_rad(360.0 / model.count as f32); for i in 0..model.count { // positions let random_x = rng.gen_range(win.left(), win.right() + 1.0); let random_y = rng.gen_range(win.bottom(), win.top() + 1.0); let circle_x = (angle * i as f32).cos() * 300.0; let circle_y = (angle * i as f32).sin() * 300.0; let x = nannou::geom::Range::new(random_x, circle_x).lerp(fader_x); let y = nannou::geom::Range::new(random_y, circle_y).lerp(fader_x); draw.ellipse().x_y(x, y).w_h(11.0, 11.0).rgb8(0, 130, 163); } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.act_random_seed = (random_f32() * 100000.0) as u64; } fn key_pressed(app: &App, _model: &mut Model, key: Key) { if key == Key::S {
app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } }
conditional_block
m_1_2_01.rs
// M_1_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * order vs random! * how to interpolate between a free composition (random) and a circle shape (order) * * MOUSE * position x : fade between random and circle shape * * KEYS * s : save png */ use nannou::prelude::*; use nannou::rand::rngs::StdRng; use nannou::rand::{Rng, SeedableRng}; fn main() { nannou::app(model).run(); } struct Model { act_random_seed: u64, count: usize, } fn model(app: &App) -> Model { let _window = app .new_window() .size(800, 800) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .build() .unwrap(); Model { act_random_seed: 0, count: 150, } } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); let win = app.window_rect(); draw.background().color(WHITE); let fader_x = map_range(app.mouse.x, win.left(), win.right(), 0.0, 1.0); let mut rng = StdRng::seed_from_u64(model.act_random_seed); let angle = deg_to_rad(360.0 / model.count as f32); for i in 0..model.count { // positions let random_x = rng.gen_range(win.left(), win.right() + 1.0); let random_y = rng.gen_range(win.bottom(), win.top() + 1.0); let circle_x = (angle * i as f32).cos() * 300.0; let circle_y = (angle * i as f32).sin() * 300.0; let x = nannou::geom::Range::new(random_x, circle_x).lerp(fader_x); let y = nannou::geom::Range::new(random_y, circle_y).lerp(fader_x); draw.ellipse().x_y(x, y).w_h(11.0, 11.0).rgb8(0, 130, 163); } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.act_random_seed = (random_f32() * 100000.0) as u64; } fn key
p: &App, _model: &mut Model, key: Key) { if key == Key::S { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } }
_pressed(ap
identifier_name
m_1_2_01.rs
// M_1_2_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * order vs random! * how to interpolate between a free composition (random) and a circle shape (order) * * MOUSE * position x : fade between random and circle shape * * KEYS * s : save png */ use nannou::prelude::*; use nannou::rand::rngs::StdRng; use nannou::rand::{Rng, SeedableRng}; fn main() { nannou::app(model).run(); } struct Model { act_random_seed: u64, count: usize, } fn model(app: &App) -> Model { let _window = app .new_window() .size(800, 800) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .build() .unwrap(); Model { act_random_seed: 0, count: 150, } } fn view(app: &App, model: &Model, frame: Frame) {
draw.ellipse().x_y(x, y).w_h(11.0, 11.0).rgb8(0, 130, 163); } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } f n mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.act_random_seed = (random_f32() * 100000.0) as u64; } fn key_pressed(app: &App, _model: &mut Model, key: Key) { if key == Key::S { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } }
let draw = app.draw(); let win = app.window_rect(); draw.background().color(WHITE); let fader_x = map_range(app.mouse.x, win.left(), win.right(), 0.0, 1.0); let mut rng = StdRng::seed_from_u64(model.act_random_seed); let angle = deg_to_rad(360.0 / model.count as f32); for i in 0..model.count { // positions let random_x = rng.gen_range(win.left(), win.right() + 1.0); let random_y = rng.gen_range(win.bottom(), win.top() + 1.0); let circle_x = (angle * i as f32).cos() * 300.0; let circle_y = (angle * i as f32).sin() * 300.0; let x = nannou::geom::Range::new(random_x, circle_x).lerp(fader_x); let y = nannou::geom::Range::new(random_y, circle_y).lerp(fader_x);
identifier_body
stream.rs
.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. /// Stream channels /// /// This is the flavor of channels which are optimized for one sender and one /// receiver. The sender will be upgraded to a shared channel if the channel is /// cloned. /// /// High level implementation details can be found in the comment of the parent /// module. pub use self::Failure::*; pub use self::UpgradeResult::*; pub use self::SelectionResult::*; use self::Message::*; use core::prelude::*; use core::cmp; use core::isize; use thread; use sync::atomic::{AtomicIsize, AtomicUsize, Ordering, AtomicBool}; use sync::mpsc::Receiver; use sync::mpsc::blocking::{self, SignalToken}; use sync::mpsc::spsc_queue as spsc; const DISCONNECTED: isize = isize::MIN; #[cfg(test)] const MAX_STEALS: isize = 5; #[cfg(not(test))] const MAX_STEALS: isize = 1 << 20; pub struct Packet<T> { queue: spsc::Queue<Message<T>>, // internal queue for all message cnt: AtomicIsize, // How many items are on this channel steals: isize, // How many times has a port received without blocking? to_wake: AtomicUsize, // SignalToken for the blocked thread to wake up port_dropped: AtomicBool, // flag if the channel has been destroyed. } pub enum Failure<T> { Empty, Disconnected, Upgraded(Receiver<T>), } pub enum UpgradeResult { UpSuccess, UpDisconnected, UpWoke(SignalToken), } pub enum SelectionResult<T> { SelSuccess, SelCanceled, SelUpgraded(SignalToken, Receiver<T>), } // Any message could contain an "upgrade request" to a new shared port, so the // internal queue it's a queue of T, but rather Message<T> enum Message<T> { Data(T), GoUp(Receiver<T>), } impl<T> Packet<T> { pub fn new() -> Packet<T> { Packet { queue: unsafe { spsc::Queue::new(128) }, cnt: AtomicIsize::new(0), steals: 0, to_wake: AtomicUsize::new(0), port_dropped: AtomicBool::new(false), } } pub fn send(&mut self, t: T) -> Result<(), T> { // If the other port has deterministically gone away, then definitely // must return the data back up the stack. Otherwise, the data is // considered as being sent. if self.port_dropped.load(Ordering::SeqCst) { return Err(t) } match self.do_send(Data(t)) { UpSuccess | UpDisconnected => {}, UpWoke(token) => { token.signal(); } } Ok(()) } pub fn
(&mut self, up: Receiver<T>) -> UpgradeResult { // If the port has gone away, then there's no need to proceed any // further. if self.port_dropped.load(Ordering::SeqCst) { return UpDisconnected } self.do_send(GoUp(up)) } fn do_send(&mut self, t: Message<T>) -> UpgradeResult { self.queue.push(t); match self.cnt.fetch_add(1, Ordering::SeqCst) { // As described in the mod's doc comment, -1 == wakeup -1 => UpWoke(self.take_to_wake()), // As as described before, SPSC queues must be >= -2 -2 => UpSuccess, // Be sure to preserve the disconnected state, and the return value // in this case is going to be whether our data was received or not. // This manifests itself on whether we have an empty queue or not. // // Primarily, are required to drain the queue here because the port // will never remove this data. We can only have at most one item to // drain (the port drains the rest). DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); let first = self.queue.pop(); let second = self.queue.pop(); assert!(second.is_none()); match first { Some(..) => UpSuccess, // we failed to send the data None => UpDisconnected, // we successfully sent data } } // Otherwise we just sent some data on a non-waiting queue, so just // make sure the world is sane and carry on! n => { assert!(n >= 0); UpSuccess } } } // Consumes ownership of the 'to_wake' field. fn take_to_wake(&mut self) -> SignalToken { let ptr = self.to_wake.load(Ordering::SeqCst); self.to_wake.store(0, Ordering::SeqCst); assert!(ptr!= 0); unsafe { SignalToken::cast_from_usize(ptr) } } // Decrements the count on the channel for a sleeper, returning the sleeper // back if it shouldn't sleep. Note that this is the location where we take // steals into account. fn decrement(&mut self, token: SignalToken) -> Result<(), SignalToken> { assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); let ptr = unsafe { token.cast_to_usize() }; self.to_wake.store(ptr, Ordering::SeqCst); let steals = self.steals; self.steals = 0; match self.cnt.fetch_sub(1 + steals, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); } // If we factor in our steals and notice that the channel has no // data, we successfully sleep n => { assert!(n >= 0); if n - steals <= 0 { return Ok(()) } } } self.to_wake.store(0, Ordering::SeqCst); Err(unsafe { SignalToken::cast_from_usize(ptr) }) } pub fn recv(&mut self) -> Result<T, Failure<T>> { // Optimistic preflight check (scheduling is expensive). match self.try_recv() { Err(Empty) => {} data => return data, } // Welp, our channel has no data. Deschedule the current task and // initiate the blocking protocol. let (wait_token, signal_token) = blocking::tokens(); if self.decrement(signal_token).is_ok() { wait_token.wait() } match self.try_recv() { // Messages which actually popped from the queue shouldn't count as // a steal, so offset the decrement here (we already have our // "steal" factored into the channel count above). data @ Ok(..) | data @ Err(Upgraded(..)) => { self.steals -= 1; data } data => data, } } pub fn try_recv(&mut self) -> Result<T, Failure<T>> { match self.queue.pop() { // If we stole some data, record to that effect (this will be // factored into cnt later on). // // Note that we don't allow steals to grow without bound in order to // prevent eventual overflow of either steals or cnt as an overflow // would have catastrophic results. Sometimes, steals > cnt, but // other times cnt > steals, so we don't know the relation between // steals and cnt. This code path is executed only rarely, so we do // a pretty slow operation, of swapping 0 into cnt, taking steals // down as much as possible (without going negative), and then // adding back in whatever we couldn't factor into steals. Some(data) => { if self.steals > MAX_STEALS { match self.cnt.swap(0, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); } n => { let m = cmp::min(n, self.steals); self.steals -= m; self.bump(n - m); } } assert!(self.steals >= 0); } self.steals += 1; match data { Data(t) => Ok(t), GoUp(up) => Err(Upgraded(up)), } } None => { match self.cnt.load(Ordering::SeqCst) { n if n!= DISCONNECTED => Err(Empty), // This is a little bit of a tricky case. We failed to pop // data above, and then we have viewed that the channel is // disconnected. In this window more data could have been // sent on the channel. It doesn't really make sense to // return that the channel is disconnected when there's // actually data on it, so be extra sure there's no data by // popping one more time. // // We can ignore steals because the other end is // disconnected and we'll never need to really factor in our // steals again. _ => { match self.queue.pop() { Some(Data(t)) => Ok(t), Some(GoUp(up)) => Err(Upgraded(up)), None => Err(Disconnected), } } } } } } pub fn drop_chan(&mut self) { // Dropping a channel is pretty simple, we just flag it as disconnected // and then wakeup a blocker if there is one. match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) { -1 => { self.take_to_wake().signal(); } DISCONNECTED => {} n => { assert!(n >= 0); } } } pub fn drop_port(&mut self) { // Dropping a port seems like a fairly trivial thing. In theory all we // need to do is flag that we're disconnected and then everything else // can take over (we don't have anyone to wake up). // // The catch for Ports is that we want to drop the entire contents of // the queue. There are multiple reasons for having this property, the // largest of which is that if another chan is waiting in this channel // (but not received yet), then waiting on that port will cause a // deadlock. // // So if we accept that we must now destroy the entire contents of the // queue, this code may make a bit more sense. The tricky part is that // we can't let any in-flight sends go un-dropped, we have to make sure // *everything* is dropped and nothing new will come onto the channel. // The first thing we do is set a flag saying that we're done for. All // sends are gated on this flag, so we're immediately guaranteed that // there are a bounded number of active sends that we'll have to deal // with. self.port_dropped.store(true, Ordering::SeqCst); // Now that we're guaranteed to deal with a bounded number of senders, // we need to drain the queue. This draining process happens atomically // with respect to the "count" of the channel. If the count is nonzero // (with steals taken into account), then there must be data on the // channel. In this case we drain everything and then try again. We will // continue to fail while active senders send data while we're dropping // data, but eventually we're guaranteed to break out of this loop // (because there is a bounded number of senders). let mut steals = self.steals; while { let cnt = self.cnt.compare_and_swap( steals, DISCONNECTED, Ordering::SeqCst); cnt!= DISCONNECTED && cnt!= steals } { loop { match self.queue.pop() { Some(..) => { steals += 1; } None => break } } } // At this point in time, we have gated all future senders from sending, // and we have flagged the channel as being disconnected. The senders // still have some responsibility, however, because some sends may not // complete until after we flag the disconnection. There are more // details in the sending methods that see DISCONNECTED } //////////////////////////////////////////////////////////////////////////// // select implementation //////////////////////////////////////////////////////////////////////////// // Tests to see whether this port can receive without blocking. If Ok is // returned, then that's the answer. If Err is returned, then the returned // port needs to be queried instead (an upgrade happened) pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> { // We peek at the queue to see if there's anything on it, and we use // this return value to determine if we should pop from the queue and // upgrade this channel immediately. If it looks like we've got an // upgrade pending, then go through the whole recv rigamarole to update // the internal state. match self.queue.peek() { Some(&mut GoUp(..)) => { match self.recv() { Err(Upgraded(port)) => Err(port), _ => unreachable!(), } } Some(..) => Ok(true), None => Ok(false) } } // increment the count on the channel (used for selection) fn bump(&mut self, amt: isize) -> isize { match self.cnt.fetch_add(amt, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); DISCONNECTED } n => n } } // Attempts to start selecting on this port. Like a oneshot, this can fail // immediately because of an upgrade. pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> { match self.decrement(token) { Ok(()) => SelSuccess, Err(token) => { let ret = match self.queue.peek() { Some(&mut GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => SelUpgraded(token, port), _ => unreachable!(), } } Some(..) => SelCanceled, None => SelCanceled, }; // Undo our decrement above, and we should be guaranteed that the // previous value is positive because we're not going to sleep let prev = self.bump(1); assert!(prev == DISCONNECTED || prev >= 0); return ret; } } } // Removes a previous task from being blocked in this port pub fn abort_selection(&mut self, was_upgrade: bool) -> Result<bool, Receiver<T>> { // If we're aborting selection after upgrading from a oneshot, then // we're guarantee that no one is waiting. The only way that we could // have seen the upgrade is if data was actually sent on the channel // half again. For us, this means that there is guaranteed to be data on // this channel. Furthermore, we're guaranteed that there was no // start_selection previously, so there's no need to modify `self.cnt` // at all. // // Hence, because of these invariants, we immediately return `Ok(true)`. // Note that the data may not actually be sent on the channel just yet. // The other end could have flagged the upgrade but not sent data to // this end. This is fine because we know it's a small bounded windows // of time until the data is actually sent. if was_upgrade { assert_eq!(self.steals, 0); assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); return Ok(true) } // We want to make sure that the count on the channel goes non-negative, // and in the stream case we can have at most one steal, so just assume // that we had one steal. let steals = 1; let prev = self.bump(steals + 1); // If we were previously disconnected, then we know for sure that there // is no task in to_wake, so just keep going let has_data = if prev == DISCONNECTED { assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); true // there is data, that data is that we're disconnected } else { let cur = prev + steals + 1; assert!(cur >= 0); // If the previous count was negative, then we just made things go // positive, hence we passed the -1 boundary and we're responsible // for removing the to_wake() field and trashing it. // // If the previous count was positive then we're in a tougher // situation. A possible race is that a sender just incremented // through -1 (meaning it's going to try to wake a task up), but it // hasn't yet read the to_wake. In order to prevent a future recv() // from waking up too early (this sender picking up the plastered // over to_wake), we spin loop here waiting for to_wake to be 0. // Note that this entire select() implementation needs an overhaul, // and this is *not* the worst part of it, so this is not done as a // final solution but rather out of necessity for now to get // something working. if prev < 0 { drop(self.take_to_wake()); } else { while self.to_wake.load(Ordering::SeqCst)!= 0 { thread::yield_now(); } } assert_eq!(self.steals, 0); self.steals = steals; // if we were previously positive, then there's surely data to // receive prev >= 0 }; // Now that we've determined that this queue "has data", we peek at the // queue to see if the data is an upgrade or not. If it's an upgrade, // then we need to destroy this port and abort selection on the // upgraded port. if has_data { match self.queue.peek() { Some(&mut GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => Err(port), _ => unreachable!(), } } _ => Ok(true), } } else { Ok(false) } } } #[unsafe_destructor] impl<T> Drop for Packet<T> { fn drop(&
upgrade
identifier_name
stream.rs
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. /// Stream channels /// /// This is the flavor of channels which are optimized for one sender and one /// receiver. The sender will be upgraded to a shared channel if the channel is /// cloned. /// /// High level implementation details can be found in the comment of the parent /// module. pub use self::Failure::*; pub use self::UpgradeResult::*; pub use self::SelectionResult::*; use self::Message::*;
use thread; use sync::atomic::{AtomicIsize, AtomicUsize, Ordering, AtomicBool}; use sync::mpsc::Receiver; use sync::mpsc::blocking::{self, SignalToken}; use sync::mpsc::spsc_queue as spsc; const DISCONNECTED: isize = isize::MIN; #[cfg(test)] const MAX_STEALS: isize = 5; #[cfg(not(test))] const MAX_STEALS: isize = 1 << 20; pub struct Packet<T> { queue: spsc::Queue<Message<T>>, // internal queue for all message cnt: AtomicIsize, // How many items are on this channel steals: isize, // How many times has a port received without blocking? to_wake: AtomicUsize, // SignalToken for the blocked thread to wake up port_dropped: AtomicBool, // flag if the channel has been destroyed. } pub enum Failure<T> { Empty, Disconnected, Upgraded(Receiver<T>), } pub enum UpgradeResult { UpSuccess, UpDisconnected, UpWoke(SignalToken), } pub enum SelectionResult<T> { SelSuccess, SelCanceled, SelUpgraded(SignalToken, Receiver<T>), } // Any message could contain an "upgrade request" to a new shared port, so the // internal queue it's a queue of T, but rather Message<T> enum Message<T> { Data(T), GoUp(Receiver<T>), } impl<T> Packet<T> { pub fn new() -> Packet<T> { Packet { queue: unsafe { spsc::Queue::new(128) }, cnt: AtomicIsize::new(0), steals: 0, to_wake: AtomicUsize::new(0), port_dropped: AtomicBool::new(false), } } pub fn send(&mut self, t: T) -> Result<(), T> { // If the other port has deterministically gone away, then definitely // must return the data back up the stack. Otherwise, the data is // considered as being sent. if self.port_dropped.load(Ordering::SeqCst) { return Err(t) } match self.do_send(Data(t)) { UpSuccess | UpDisconnected => {}, UpWoke(token) => { token.signal(); } } Ok(()) } pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult { // If the port has gone away, then there's no need to proceed any // further. if self.port_dropped.load(Ordering::SeqCst) { return UpDisconnected } self.do_send(GoUp(up)) } fn do_send(&mut self, t: Message<T>) -> UpgradeResult { self.queue.push(t); match self.cnt.fetch_add(1, Ordering::SeqCst) { // As described in the mod's doc comment, -1 == wakeup -1 => UpWoke(self.take_to_wake()), // As as described before, SPSC queues must be >= -2 -2 => UpSuccess, // Be sure to preserve the disconnected state, and the return value // in this case is going to be whether our data was received or not. // This manifests itself on whether we have an empty queue or not. // // Primarily, are required to drain the queue here because the port // will never remove this data. We can only have at most one item to // drain (the port drains the rest). DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); let first = self.queue.pop(); let second = self.queue.pop(); assert!(second.is_none()); match first { Some(..) => UpSuccess, // we failed to send the data None => UpDisconnected, // we successfully sent data } } // Otherwise we just sent some data on a non-waiting queue, so just // make sure the world is sane and carry on! n => { assert!(n >= 0); UpSuccess } } } // Consumes ownership of the 'to_wake' field. fn take_to_wake(&mut self) -> SignalToken { let ptr = self.to_wake.load(Ordering::SeqCst); self.to_wake.store(0, Ordering::SeqCst); assert!(ptr!= 0); unsafe { SignalToken::cast_from_usize(ptr) } } // Decrements the count on the channel for a sleeper, returning the sleeper // back if it shouldn't sleep. Note that this is the location where we take // steals into account. fn decrement(&mut self, token: SignalToken) -> Result<(), SignalToken> { assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); let ptr = unsafe { token.cast_to_usize() }; self.to_wake.store(ptr, Ordering::SeqCst); let steals = self.steals; self.steals = 0; match self.cnt.fetch_sub(1 + steals, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); } // If we factor in our steals and notice that the channel has no // data, we successfully sleep n => { assert!(n >= 0); if n - steals <= 0 { return Ok(()) } } } self.to_wake.store(0, Ordering::SeqCst); Err(unsafe { SignalToken::cast_from_usize(ptr) }) } pub fn recv(&mut self) -> Result<T, Failure<T>> { // Optimistic preflight check (scheduling is expensive). match self.try_recv() { Err(Empty) => {} data => return data, } // Welp, our channel has no data. Deschedule the current task and // initiate the blocking protocol. let (wait_token, signal_token) = blocking::tokens(); if self.decrement(signal_token).is_ok() { wait_token.wait() } match self.try_recv() { // Messages which actually popped from the queue shouldn't count as // a steal, so offset the decrement here (we already have our // "steal" factored into the channel count above). data @ Ok(..) | data @ Err(Upgraded(..)) => { self.steals -= 1; data } data => data, } } pub fn try_recv(&mut self) -> Result<T, Failure<T>> { match self.queue.pop() { // If we stole some data, record to that effect (this will be // factored into cnt later on). // // Note that we don't allow steals to grow without bound in order to // prevent eventual overflow of either steals or cnt as an overflow // would have catastrophic results. Sometimes, steals > cnt, but // other times cnt > steals, so we don't know the relation between // steals and cnt. This code path is executed only rarely, so we do // a pretty slow operation, of swapping 0 into cnt, taking steals // down as much as possible (without going negative), and then // adding back in whatever we couldn't factor into steals. Some(data) => { if self.steals > MAX_STEALS { match self.cnt.swap(0, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); } n => { let m = cmp::min(n, self.steals); self.steals -= m; self.bump(n - m); } } assert!(self.steals >= 0); } self.steals += 1; match data { Data(t) => Ok(t), GoUp(up) => Err(Upgraded(up)), } } None => { match self.cnt.load(Ordering::SeqCst) { n if n!= DISCONNECTED => Err(Empty), // This is a little bit of a tricky case. We failed to pop // data above, and then we have viewed that the channel is // disconnected. In this window more data could have been // sent on the channel. It doesn't really make sense to // return that the channel is disconnected when there's // actually data on it, so be extra sure there's no data by // popping one more time. // // We can ignore steals because the other end is // disconnected and we'll never need to really factor in our // steals again. _ => { match self.queue.pop() { Some(Data(t)) => Ok(t), Some(GoUp(up)) => Err(Upgraded(up)), None => Err(Disconnected), } } } } } } pub fn drop_chan(&mut self) { // Dropping a channel is pretty simple, we just flag it as disconnected // and then wakeup a blocker if there is one. match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) { -1 => { self.take_to_wake().signal(); } DISCONNECTED => {} n => { assert!(n >= 0); } } } pub fn drop_port(&mut self) { // Dropping a port seems like a fairly trivial thing. In theory all we // need to do is flag that we're disconnected and then everything else // can take over (we don't have anyone to wake up). // // The catch for Ports is that we want to drop the entire contents of // the queue. There are multiple reasons for having this property, the // largest of which is that if another chan is waiting in this channel // (but not received yet), then waiting on that port will cause a // deadlock. // // So if we accept that we must now destroy the entire contents of the // queue, this code may make a bit more sense. The tricky part is that // we can't let any in-flight sends go un-dropped, we have to make sure // *everything* is dropped and nothing new will come onto the channel. // The first thing we do is set a flag saying that we're done for. All // sends are gated on this flag, so we're immediately guaranteed that // there are a bounded number of active sends that we'll have to deal // with. self.port_dropped.store(true, Ordering::SeqCst); // Now that we're guaranteed to deal with a bounded number of senders, // we need to drain the queue. This draining process happens atomically // with respect to the "count" of the channel. If the count is nonzero // (with steals taken into account), then there must be data on the // channel. In this case we drain everything and then try again. We will // continue to fail while active senders send data while we're dropping // data, but eventually we're guaranteed to break out of this loop // (because there is a bounded number of senders). let mut steals = self.steals; while { let cnt = self.cnt.compare_and_swap( steals, DISCONNECTED, Ordering::SeqCst); cnt!= DISCONNECTED && cnt!= steals } { loop { match self.queue.pop() { Some(..) => { steals += 1; } None => break } } } // At this point in time, we have gated all future senders from sending, // and we have flagged the channel as being disconnected. The senders // still have some responsibility, however, because some sends may not // complete until after we flag the disconnection. There are more // details in the sending methods that see DISCONNECTED } //////////////////////////////////////////////////////////////////////////// // select implementation //////////////////////////////////////////////////////////////////////////// // Tests to see whether this port can receive without blocking. If Ok is // returned, then that's the answer. If Err is returned, then the returned // port needs to be queried instead (an upgrade happened) pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> { // We peek at the queue to see if there's anything on it, and we use // this return value to determine if we should pop from the queue and // upgrade this channel immediately. If it looks like we've got an // upgrade pending, then go through the whole recv rigamarole to update // the internal state. match self.queue.peek() { Some(&mut GoUp(..)) => { match self.recv() { Err(Upgraded(port)) => Err(port), _ => unreachable!(), } } Some(..) => Ok(true), None => Ok(false) } } // increment the count on the channel (used for selection) fn bump(&mut self, amt: isize) -> isize { match self.cnt.fetch_add(amt, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); DISCONNECTED } n => n } } // Attempts to start selecting on this port. Like a oneshot, this can fail // immediately because of an upgrade. pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> { match self.decrement(token) { Ok(()) => SelSuccess, Err(token) => { let ret = match self.queue.peek() { Some(&mut GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => SelUpgraded(token, port), _ => unreachable!(), } } Some(..) => SelCanceled, None => SelCanceled, }; // Undo our decrement above, and we should be guaranteed that the // previous value is positive because we're not going to sleep let prev = self.bump(1); assert!(prev == DISCONNECTED || prev >= 0); return ret; } } } // Removes a previous task from being blocked in this port pub fn abort_selection(&mut self, was_upgrade: bool) -> Result<bool, Receiver<T>> { // If we're aborting selection after upgrading from a oneshot, then // we're guarantee that no one is waiting. The only way that we could // have seen the upgrade is if data was actually sent on the channel // half again. For us, this means that there is guaranteed to be data on // this channel. Furthermore, we're guaranteed that there was no // start_selection previously, so there's no need to modify `self.cnt` // at all. // // Hence, because of these invariants, we immediately return `Ok(true)`. // Note that the data may not actually be sent on the channel just yet. // The other end could have flagged the upgrade but not sent data to // this end. This is fine because we know it's a small bounded windows // of time until the data is actually sent. if was_upgrade { assert_eq!(self.steals, 0); assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); return Ok(true) } // We want to make sure that the count on the channel goes non-negative, // and in the stream case we can have at most one steal, so just assume // that we had one steal. let steals = 1; let prev = self.bump(steals + 1); // If we were previously disconnected, then we know for sure that there // is no task in to_wake, so just keep going let has_data = if prev == DISCONNECTED { assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); true // there is data, that data is that we're disconnected } else { let cur = prev + steals + 1; assert!(cur >= 0); // If the previous count was negative, then we just made things go // positive, hence we passed the -1 boundary and we're responsible // for removing the to_wake() field and trashing it. // // If the previous count was positive then we're in a tougher // situation. A possible race is that a sender just incremented // through -1 (meaning it's going to try to wake a task up), but it // hasn't yet read the to_wake. In order to prevent a future recv() // from waking up too early (this sender picking up the plastered // over to_wake), we spin loop here waiting for to_wake to be 0. // Note that this entire select() implementation needs an overhaul, // and this is *not* the worst part of it, so this is not done as a // final solution but rather out of necessity for now to get // something working. if prev < 0 { drop(self.take_to_wake()); } else { while self.to_wake.load(Ordering::SeqCst)!= 0 { thread::yield_now(); } } assert_eq!(self.steals, 0); self.steals = steals; // if we were previously positive, then there's surely data to // receive prev >= 0 }; // Now that we've determined that this queue "has data", we peek at the // queue to see if the data is an upgrade or not. If it's an upgrade, // then we need to destroy this port and abort selection on the // upgraded port. if has_data { match self.queue.peek() { Some(&mut GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => Err(port), _ => unreachable!(), } } _ => Ok(true), } } else { Ok(false) } } } #[unsafe_destructor] impl<T> Drop for Packet<T> { fn drop(&mut self
use core::prelude::*; use core::cmp; use core::isize;
random_line_split
stream.rs
.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. /// Stream channels /// /// This is the flavor of channels which are optimized for one sender and one /// receiver. The sender will be upgraded to a shared channel if the channel is /// cloned. /// /// High level implementation details can be found in the comment of the parent /// module. pub use self::Failure::*; pub use self::UpgradeResult::*; pub use self::SelectionResult::*; use self::Message::*; use core::prelude::*; use core::cmp; use core::isize; use thread; use sync::atomic::{AtomicIsize, AtomicUsize, Ordering, AtomicBool}; use sync::mpsc::Receiver; use sync::mpsc::blocking::{self, SignalToken}; use sync::mpsc::spsc_queue as spsc; const DISCONNECTED: isize = isize::MIN; #[cfg(test)] const MAX_STEALS: isize = 5; #[cfg(not(test))] const MAX_STEALS: isize = 1 << 20; pub struct Packet<T> { queue: spsc::Queue<Message<T>>, // internal queue for all message cnt: AtomicIsize, // How many items are on this channel steals: isize, // How many times has a port received without blocking? to_wake: AtomicUsize, // SignalToken for the blocked thread to wake up port_dropped: AtomicBool, // flag if the channel has been destroyed. } pub enum Failure<T> { Empty, Disconnected, Upgraded(Receiver<T>), } pub enum UpgradeResult { UpSuccess, UpDisconnected, UpWoke(SignalToken), } pub enum SelectionResult<T> { SelSuccess, SelCanceled, SelUpgraded(SignalToken, Receiver<T>), } // Any message could contain an "upgrade request" to a new shared port, so the // internal queue it's a queue of T, but rather Message<T> enum Message<T> { Data(T), GoUp(Receiver<T>), } impl<T> Packet<T> { pub fn new() -> Packet<T> { Packet { queue: unsafe { spsc::Queue::new(128) }, cnt: AtomicIsize::new(0), steals: 0, to_wake: AtomicUsize::new(0), port_dropped: AtomicBool::new(false), } } pub fn send(&mut self, t: T) -> Result<(), T> { // If the other port has deterministically gone away, then definitely // must return the data back up the stack. Otherwise, the data is // considered as being sent. if self.port_dropped.load(Ordering::SeqCst) { return Err(t) } match self.do_send(Data(t)) { UpSuccess | UpDisconnected => {}, UpWoke(token) => { token.signal(); } } Ok(()) } pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult { // If the port has gone away, then there's no need to proceed any // further. if self.port_dropped.load(Ordering::SeqCst) { return UpDisconnected } self.do_send(GoUp(up)) } fn do_send(&mut self, t: Message<T>) -> UpgradeResult { self.queue.push(t); match self.cnt.fetch_add(1, Ordering::SeqCst) { // As described in the mod's doc comment, -1 == wakeup -1 => UpWoke(self.take_to_wake()), // As as described before, SPSC queues must be >= -2 -2 => UpSuccess, // Be sure to preserve the disconnected state, and the return value // in this case is going to be whether our data was received or not. // This manifests itself on whether we have an empty queue or not. // // Primarily, are required to drain the queue here because the port // will never remove this data. We can only have at most one item to // drain (the port drains the rest). DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); let first = self.queue.pop(); let second = self.queue.pop(); assert!(second.is_none()); match first { Some(..) => UpSuccess, // we failed to send the data None => UpDisconnected, // we successfully sent data } } // Otherwise we just sent some data on a non-waiting queue, so just // make sure the world is sane and carry on! n => { assert!(n >= 0); UpSuccess } } } // Consumes ownership of the 'to_wake' field. fn take_to_wake(&mut self) -> SignalToken { let ptr = self.to_wake.load(Ordering::SeqCst); self.to_wake.store(0, Ordering::SeqCst); assert!(ptr!= 0); unsafe { SignalToken::cast_from_usize(ptr) } } // Decrements the count on the channel for a sleeper, returning the sleeper // back if it shouldn't sleep. Note that this is the location where we take // steals into account. fn decrement(&mut self, token: SignalToken) -> Result<(), SignalToken> { assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); let ptr = unsafe { token.cast_to_usize() }; self.to_wake.store(ptr, Ordering::SeqCst); let steals = self.steals; self.steals = 0; match self.cnt.fetch_sub(1 + steals, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); } // If we factor in our steals and notice that the channel has no // data, we successfully sleep n => { assert!(n >= 0); if n - steals <= 0 { return Ok(()) } } } self.to_wake.store(0, Ordering::SeqCst); Err(unsafe { SignalToken::cast_from_usize(ptr) }) } pub fn recv(&mut self) -> Result<T, Failure<T>>
self.steals -= 1; data } data => data, } } pub fn try_recv(&mut self) -> Result<T, Failure<T>> { match self.queue.pop() { // If we stole some data, record to that effect (this will be // factored into cnt later on). // // Note that we don't allow steals to grow without bound in order to // prevent eventual overflow of either steals or cnt as an overflow // would have catastrophic results. Sometimes, steals > cnt, but // other times cnt > steals, so we don't know the relation between // steals and cnt. This code path is executed only rarely, so we do // a pretty slow operation, of swapping 0 into cnt, taking steals // down as much as possible (without going negative), and then // adding back in whatever we couldn't factor into steals. Some(data) => { if self.steals > MAX_STEALS { match self.cnt.swap(0, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); } n => { let m = cmp::min(n, self.steals); self.steals -= m; self.bump(n - m); } } assert!(self.steals >= 0); } self.steals += 1; match data { Data(t) => Ok(t), GoUp(up) => Err(Upgraded(up)), } } None => { match self.cnt.load(Ordering::SeqCst) { n if n!= DISCONNECTED => Err(Empty), // This is a little bit of a tricky case. We failed to pop // data above, and then we have viewed that the channel is // disconnected. In this window more data could have been // sent on the channel. It doesn't really make sense to // return that the channel is disconnected when there's // actually data on it, so be extra sure there's no data by // popping one more time. // // We can ignore steals because the other end is // disconnected and we'll never need to really factor in our // steals again. _ => { match self.queue.pop() { Some(Data(t)) => Ok(t), Some(GoUp(up)) => Err(Upgraded(up)), None => Err(Disconnected), } } } } } } pub fn drop_chan(&mut self) { // Dropping a channel is pretty simple, we just flag it as disconnected // and then wakeup a blocker if there is one. match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) { -1 => { self.take_to_wake().signal(); } DISCONNECTED => {} n => { assert!(n >= 0); } } } pub fn drop_port(&mut self) { // Dropping a port seems like a fairly trivial thing. In theory all we // need to do is flag that we're disconnected and then everything else // can take over (we don't have anyone to wake up). // // The catch for Ports is that we want to drop the entire contents of // the queue. There are multiple reasons for having this property, the // largest of which is that if another chan is waiting in this channel // (but not received yet), then waiting on that port will cause a // deadlock. // // So if we accept that we must now destroy the entire contents of the // queue, this code may make a bit more sense. The tricky part is that // we can't let any in-flight sends go un-dropped, we have to make sure // *everything* is dropped and nothing new will come onto the channel. // The first thing we do is set a flag saying that we're done for. All // sends are gated on this flag, so we're immediately guaranteed that // there are a bounded number of active sends that we'll have to deal // with. self.port_dropped.store(true, Ordering::SeqCst); // Now that we're guaranteed to deal with a bounded number of senders, // we need to drain the queue. This draining process happens atomically // with respect to the "count" of the channel. If the count is nonzero // (with steals taken into account), then there must be data on the // channel. In this case we drain everything and then try again. We will // continue to fail while active senders send data while we're dropping // data, but eventually we're guaranteed to break out of this loop // (because there is a bounded number of senders). let mut steals = self.steals; while { let cnt = self.cnt.compare_and_swap( steals, DISCONNECTED, Ordering::SeqCst); cnt!= DISCONNECTED && cnt!= steals } { loop { match self.queue.pop() { Some(..) => { steals += 1; } None => break } } } // At this point in time, we have gated all future senders from sending, // and we have flagged the channel as being disconnected. The senders // still have some responsibility, however, because some sends may not // complete until after we flag the disconnection. There are more // details in the sending methods that see DISCONNECTED } //////////////////////////////////////////////////////////////////////////// // select implementation //////////////////////////////////////////////////////////////////////////// // Tests to see whether this port can receive without blocking. If Ok is // returned, then that's the answer. If Err is returned, then the returned // port needs to be queried instead (an upgrade happened) pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> { // We peek at the queue to see if there's anything on it, and we use // this return value to determine if we should pop from the queue and // upgrade this channel immediately. If it looks like we've got an // upgrade pending, then go through the whole recv rigamarole to update // the internal state. match self.queue.peek() { Some(&mut GoUp(..)) => { match self.recv() { Err(Upgraded(port)) => Err(port), _ => unreachable!(), } } Some(..) => Ok(true), None => Ok(false) } } // increment the count on the channel (used for selection) fn bump(&mut self, amt: isize) -> isize { match self.cnt.fetch_add(amt, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); DISCONNECTED } n => n } } // Attempts to start selecting on this port. Like a oneshot, this can fail // immediately because of an upgrade. pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> { match self.decrement(token) { Ok(()) => SelSuccess, Err(token) => { let ret = match self.queue.peek() { Some(&mut GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => SelUpgraded(token, port), _ => unreachable!(), } } Some(..) => SelCanceled, None => SelCanceled, }; // Undo our decrement above, and we should be guaranteed that the // previous value is positive because we're not going to sleep let prev = self.bump(1); assert!(prev == DISCONNECTED || prev >= 0); return ret; } } } // Removes a previous task from being blocked in this port pub fn abort_selection(&mut self, was_upgrade: bool) -> Result<bool, Receiver<T>> { // If we're aborting selection after upgrading from a oneshot, then // we're guarantee that no one is waiting. The only way that we could // have seen the upgrade is if data was actually sent on the channel // half again. For us, this means that there is guaranteed to be data on // this channel. Furthermore, we're guaranteed that there was no // start_selection previously, so there's no need to modify `self.cnt` // at all. // // Hence, because of these invariants, we immediately return `Ok(true)`. // Note that the data may not actually be sent on the channel just yet. // The other end could have flagged the upgrade but not sent data to // this end. This is fine because we know it's a small bounded windows // of time until the data is actually sent. if was_upgrade { assert_eq!(self.steals, 0); assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); return Ok(true) } // We want to make sure that the count on the channel goes non-negative, // and in the stream case we can have at most one steal, so just assume // that we had one steal. let steals = 1; let prev = self.bump(steals + 1); // If we were previously disconnected, then we know for sure that there // is no task in to_wake, so just keep going let has_data = if prev == DISCONNECTED { assert_eq!(self.to_wake.load(Ordering::SeqCst), 0); true // there is data, that data is that we're disconnected } else { let cur = prev + steals + 1; assert!(cur >= 0); // If the previous count was negative, then we just made things go // positive, hence we passed the -1 boundary and we're responsible // for removing the to_wake() field and trashing it. // // If the previous count was positive then we're in a tougher // situation. A possible race is that a sender just incremented // through -1 (meaning it's going to try to wake a task up), but it // hasn't yet read the to_wake. In order to prevent a future recv() // from waking up too early (this sender picking up the plastered // over to_wake), we spin loop here waiting for to_wake to be 0. // Note that this entire select() implementation needs an overhaul, // and this is *not* the worst part of it, so this is not done as a // final solution but rather out of necessity for now to get // something working. if prev < 0 { drop(self.take_to_wake()); } else { while self.to_wake.load(Ordering::SeqCst)!= 0 { thread::yield_now(); } } assert_eq!(self.steals, 0); self.steals = steals; // if we were previously positive, then there's surely data to // receive prev >= 0 }; // Now that we've determined that this queue "has data", we peek at the // queue to see if the data is an upgrade or not. If it's an upgrade, // then we need to destroy this port and abort selection on the // upgraded port. if has_data { match self.queue.peek() { Some(&mut GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => Err(port), _ => unreachable!(), } } _ => Ok(true), } } else { Ok(false) } } } #[unsafe_destructor] impl<T> Drop for Packet<T> { fn drop(&
{ // Optimistic preflight check (scheduling is expensive). match self.try_recv() { Err(Empty) => {} data => return data, } // Welp, our channel has no data. Deschedule the current task and // initiate the blocking protocol. let (wait_token, signal_token) = blocking::tokens(); if self.decrement(signal_token).is_ok() { wait_token.wait() } match self.try_recv() { // Messages which actually popped from the queue shouldn't count as // a steal, so offset the decrement here (we already have our // "steal" factored into the channel count above). data @ Ok(..) | data @ Err(Upgraded(..)) => {
identifier_body
arm64.rs
use execstate::ExecState; use object::{Obj, Ref}; pub use self::param::*; pub use self::reg::*; pub mod asm; pub mod param; pub mod reg; pub mod trap; pub fn flush_icache(start: *const u8, len: usize) { let start = start as usize; let end = start + len; let (icacheline_size, dcacheline_size) = cacheline_sizes(); let istart = start &!(icacheline_size - 1); let dstart = start &!(dcacheline_size - 1); let mut ptr = dstart; while ptr < end { unsafe { asm!("dc civac, $0":: "r"(ptr) : "memory" : "volatile"); } ptr += dcacheline_size; } unsafe { asm!("dsb ish" ::: "memory" : "volatile"); } ptr = istart; while ptr < end { unsafe { asm!("ic ivau, $0":: "r"(ptr) : "memory" : "volatile"); } ptr += icacheline_size; } unsafe { asm!("dsb ish isb" ::: "memory" : "volatile"); } } pub fn cacheline_sizes() -> (usize, usize) { let value: usize; unsafe { asm!("mrs $0, ctr_el0": "=r"(value)::: "volatile"); } let insn = 4 << (value & 0xF); let data = 4 << ((value >> 16) & 0xF); (insn, data) } pub fn fp_from_execstate(es: &ExecState) -> usize { es.regs[REG_FP.asm() as usize] } pub fn
(es: &ExecState) -> Ref<Obj> { let obj: Ref<Obj> = es.regs[REG_RESULT.asm() as usize].into(); obj } pub fn ra_from_execstate(es: &ExecState) -> usize { es.regs[REG_LR.asm() as usize] }
get_exception_object
identifier_name
arm64.rs
use execstate::ExecState; use object::{Obj, Ref}; pub use self::param::*; pub use self::reg::*; pub mod asm; pub mod param; pub mod reg; pub mod trap; pub fn flush_icache(start: *const u8, len: usize) { let start = start as usize; let end = start + len; let (icacheline_size, dcacheline_size) = cacheline_sizes(); let istart = start &!(icacheline_size - 1); let dstart = start &!(dcacheline_size - 1); let mut ptr = dstart;
unsafe { asm!("dc civac, $0":: "r"(ptr) : "memory" : "volatile"); } ptr += dcacheline_size; } unsafe { asm!("dsb ish" ::: "memory" : "volatile"); } ptr = istart; while ptr < end { unsafe { asm!("ic ivau, $0":: "r"(ptr) : "memory" : "volatile"); } ptr += icacheline_size; } unsafe { asm!("dsb ish isb" ::: "memory" : "volatile"); } } pub fn cacheline_sizes() -> (usize, usize) { let value: usize; unsafe { asm!("mrs $0, ctr_el0": "=r"(value)::: "volatile"); } let insn = 4 << (value & 0xF); let data = 4 << ((value >> 16) & 0xF); (insn, data) } pub fn fp_from_execstate(es: &ExecState) -> usize { es.regs[REG_FP.asm() as usize] } pub fn get_exception_object(es: &ExecState) -> Ref<Obj> { let obj: Ref<Obj> = es.regs[REG_RESULT.asm() as usize].into(); obj } pub fn ra_from_execstate(es: &ExecState) -> usize { es.regs[REG_LR.asm() as usize] }
while ptr < end {
random_line_split
arm64.rs
use execstate::ExecState; use object::{Obj, Ref}; pub use self::param::*; pub use self::reg::*; pub mod asm; pub mod param; pub mod reg; pub mod trap; pub fn flush_icache(start: *const u8, len: usize) { let start = start as usize; let end = start + len; let (icacheline_size, dcacheline_size) = cacheline_sizes(); let istart = start &!(icacheline_size - 1); let dstart = start &!(dcacheline_size - 1); let mut ptr = dstart; while ptr < end { unsafe { asm!("dc civac, $0":: "r"(ptr) : "memory" : "volatile"); } ptr += dcacheline_size; } unsafe { asm!("dsb ish" ::: "memory" : "volatile"); } ptr = istart; while ptr < end { unsafe { asm!("ic ivau, $0":: "r"(ptr) : "memory" : "volatile"); } ptr += icacheline_size; } unsafe { asm!("dsb ish isb" ::: "memory" : "volatile"); } } pub fn cacheline_sizes() -> (usize, usize) { let value: usize; unsafe { asm!("mrs $0, ctr_el0": "=r"(value)::: "volatile"); } let insn = 4 << (value & 0xF); let data = 4 << ((value >> 16) & 0xF); (insn, data) } pub fn fp_from_execstate(es: &ExecState) -> usize { es.regs[REG_FP.asm() as usize] } pub fn get_exception_object(es: &ExecState) -> Ref<Obj>
pub fn ra_from_execstate(es: &ExecState) -> usize { es.regs[REG_LR.asm() as usize] }
{ let obj: Ref<Obj> = es.regs[REG_RESULT.asm() as usize].into(); obj }
identifier_body
htmlunknownelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLUnknownElementBinding; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; #[dom_struct] pub struct HTMLUnknownElement { htmlelement: HTMLElement } impl HTMLUnknownElement { fn new_inherited(localName: Atom,
prefix: Option<DOMString>, document: &Document) -> HTMLUnknownElement { HTMLUnknownElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLUnknownElement> { Node::reflect_node(box HTMLUnknownElement::new_inherited(localName, prefix, document), document, HTMLUnknownElementBinding::Wrap) } }
random_line_split
htmlunknownelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLUnknownElementBinding; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; #[dom_struct] pub struct
{ htmlelement: HTMLElement } impl HTMLUnknownElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUnknownElement { HTMLUnknownElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLUnknownElement> { Node::reflect_node(box HTMLUnknownElement::new_inherited(localName, prefix, document), document, HTMLUnknownElementBinding::Wrap) } }
HTMLUnknownElement
identifier_name
htmlunknownelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLUnknownElementBinding; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; #[dom_struct] pub struct HTMLUnknownElement { htmlelement: HTMLElement } impl HTMLUnknownElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUnknownElement { HTMLUnknownElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLUnknownElement>
}
{ Node::reflect_node(box HTMLUnknownElement::new_inherited(localName, prefix, document), document, HTMLUnknownElementBinding::Wrap) }
identifier_body
error.rs
use std::io; use std::result; use mqtt3; use tokio_timer::TimerError; pub type Result<T> = result::Result<T, Error>; quick_error! { #[derive(Debug)] pub enum Error { Io(err: io::Error) { from() description("io error") display("I/O error: {}", err) cause(err) } Mqtt3(err: mqtt3::Error) { from() display("mqtt3 error: {}", err) description("Mqtt3 error {}") cause(err) } Timer(err: TimerError) { from() description("Timer error") cause(err) display("timer error: {}", err) } NoClient { description("No client with this ID") }
} InvalidMqttPacket { description("Invalid Mqtt Packet") } InvalidClientId { description("Invalid Client ID") } DisconnectRequest { description("Received Disconnect Request") } NotInQueue { description("Couldn't find requested message in the queue") } DisconnectPacket { description("Received disconnect packet from client") } Other } }
ClientIdExists { description("Client with that ID already exists")
random_line_split
main.rs
macro_rules! timeit { ($func:expr) => ({ let t1 = std::time::Instant::now(); println!("{:?}", $func); let t2 = std::time::Instant::now().duration_since(t1); println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00); }) } fn main()
{ fn fib(n: usize) -> usize { match n <= 3 { true => n, false => return fib(n - 1) + fib(n - 2), } } fn even_fibs(n: usize) -> usize { (1..) .map(|x| fib(x)) .take_while(|&x| x <= n as usize) .filter(|&x| x % 2 == 0) .fold(0, |acc, item| acc + item) } timeit!(even_fibs(4000000)) }
identifier_body
main.rs
macro_rules! timeit { ($func:expr) => ({ let t1 = std::time::Instant::now(); println!("{:?}", $func); let t2 = std::time::Instant::now().duration_since(t1); println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00); }) } fn main() { fn fib(n: usize) -> usize { match n <= 3 {
false => return fib(n - 1) + fib(n - 2), } } fn even_fibs(n: usize) -> usize { (1..) .map(|x| fib(x)) .take_while(|&x| x <= n as usize) .filter(|&x| x % 2 == 0) .fold(0, |acc, item| acc + item) } timeit!(even_fibs(4000000)) }
true => n,
random_line_split
main.rs
macro_rules! timeit { ($func:expr) => ({ let t1 = std::time::Instant::now(); println!("{:?}", $func); let t2 = std::time::Instant::now().duration_since(t1); println!("{}", t2.as_secs() as f64 + t2.subsec_nanos() as f64 / 1000000000.00); }) } fn main() { fn fib(n: usize) -> usize { match n <= 3 { true => n, false => return fib(n - 1) + fib(n - 2), } } fn
(n: usize) -> usize { (1..) .map(|x| fib(x)) .take_while(|&x| x <= n as usize) .filter(|&x| x % 2 == 0) .fold(0, |acc, item| acc + item) } timeit!(even_fibs(4000000)) }
even_fibs
identifier_name
lexical-scope-in-match.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-win32 // ignore-android: FIXME(#10381) // compile-flags:-g // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print shadowed // check:$1 = 231 // debugger:print not_shadowed // check:$2 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$3 = 233 // debugger:print not_shadowed // check:$4 = 232 // debugger:print local_to_arm // check:$5 = 234 // debugger:continue // debugger:finish // debugger:print shadowed // check:$6 = 236 // debugger:print not_shadowed // check:$7 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$8 = 237 // debugger:print not_shadowed // check:$9 = 232 // debugger:print local_to_arm // check:$10 = 238 // debugger:continue // debugger:finish // debugger:print shadowed // check:$11 = 239 // debugger:print not_shadowed // check:$12 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$13 = 241 // debugger:print not_shadowed // check:$14 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$15 = 243 // debugger:print *local_to_arm // check:$16 = 244 // debugger:continue // debugger:finish // debugger:print shadowed // check:$17 = 231 // debugger:print not_shadowed // check:$18 = 232 // debugger:continue struct Struct { x: int, y: int } fn main() { let shadowed = 231; let not_shadowed = 232; zzz(); sentinel(); match (233, 234) { (shadowed, local_to_arm) =>
} match (235, 236) { // with literal (235, shadowed) => { zzz(); sentinel(); } _ => {} } match Struct { x: 237, y: 238 } { Struct { x: shadowed, y: local_to_arm } => { zzz(); sentinel(); } } match Struct { x: 239, y: 240 } { // ignored field Struct { x: shadowed,.. } => { zzz(); sentinel(); } } match Struct { x: 241, y: 242 } { // with literal Struct { x: shadowed, y: 242 } => { zzz(); sentinel(); } _ => {} } match (243, 244) { (shadowed, ref local_to_arm) => { zzz(); sentinel(); } } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
{ zzz(); sentinel(); }
conditional_block
lexical-scope-in-match.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-win32 // ignore-android: FIXME(#10381) // compile-flags:-g // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print shadowed // check:$1 = 231 // debugger:print not_shadowed // check:$2 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$3 = 233 // debugger:print not_shadowed // check:$4 = 232 // debugger:print local_to_arm // check:$5 = 234 // debugger:continue // debugger:finish // debugger:print shadowed // check:$6 = 236 // debugger:print not_shadowed // check:$7 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$8 = 237 // debugger:print not_shadowed // check:$9 = 232 // debugger:print local_to_arm // check:$10 = 238 // debugger:continue // debugger:finish // debugger:print shadowed // check:$11 = 239 // debugger:print not_shadowed // check:$12 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$13 = 241 // debugger:print not_shadowed // check:$14 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$15 = 243 // debugger:print *local_to_arm // check:$16 = 244 // debugger:continue // debugger:finish // debugger:print shadowed // check:$17 = 231 // debugger:print not_shadowed // check:$18 = 232 // debugger:continue struct
{ x: int, y: int } fn main() { let shadowed = 231; let not_shadowed = 232; zzz(); sentinel(); match (233, 234) { (shadowed, local_to_arm) => { zzz(); sentinel(); } } match (235, 236) { // with literal (235, shadowed) => { zzz(); sentinel(); } _ => {} } match Struct { x: 237, y: 238 } { Struct { x: shadowed, y: local_to_arm } => { zzz(); sentinel(); } } match Struct { x: 239, y: 240 } { // ignored field Struct { x: shadowed,.. } => { zzz(); sentinel(); } } match Struct { x: 241, y: 242 } { // with literal Struct { x: shadowed, y: 242 } => { zzz(); sentinel(); } _ => {} } match (243, 244) { (shadowed, ref local_to_arm) => { zzz(); sentinel(); } } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
Struct
identifier_name
lexical-scope-in-match.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-win32
// compile-flags:-g // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print shadowed // check:$1 = 231 // debugger:print not_shadowed // check:$2 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$3 = 233 // debugger:print not_shadowed // check:$4 = 232 // debugger:print local_to_arm // check:$5 = 234 // debugger:continue // debugger:finish // debugger:print shadowed // check:$6 = 236 // debugger:print not_shadowed // check:$7 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$8 = 237 // debugger:print not_shadowed // check:$9 = 232 // debugger:print local_to_arm // check:$10 = 238 // debugger:continue // debugger:finish // debugger:print shadowed // check:$11 = 239 // debugger:print not_shadowed // check:$12 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$13 = 241 // debugger:print not_shadowed // check:$14 = 232 // debugger:continue // debugger:finish // debugger:print shadowed // check:$15 = 243 // debugger:print *local_to_arm // check:$16 = 244 // debugger:continue // debugger:finish // debugger:print shadowed // check:$17 = 231 // debugger:print not_shadowed // check:$18 = 232 // debugger:continue struct Struct { x: int, y: int } fn main() { let shadowed = 231; let not_shadowed = 232; zzz(); sentinel(); match (233, 234) { (shadowed, local_to_arm) => { zzz(); sentinel(); } } match (235, 236) { // with literal (235, shadowed) => { zzz(); sentinel(); } _ => {} } match Struct { x: 237, y: 238 } { Struct { x: shadowed, y: local_to_arm } => { zzz(); sentinel(); } } match Struct { x: 239, y: 240 } { // ignored field Struct { x: shadowed,.. } => { zzz(); sentinel(); } } match Struct { x: 241, y: 242 } { // with literal Struct { x: shadowed, y: 242 } => { zzz(); sentinel(); } _ => {} } match (243, 244) { (shadowed, ref local_to_arm) => { zzz(); sentinel(); } } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
// ignore-android: FIXME(#10381)
random_line_split
serviceworkerglobalscope.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 devtools; use devtools_traits::DevtoolScriptControlMsg; use dom::abstractworker::WorkerScriptMsg; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::extendableevent::ExtendableEvent; use dom::extendablemessageevent::ExtendableMessageEvent; use dom::globalscope::GlobalScope; use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::{self, IpcSender, IpcReceiver}; use ipc_channel::router::ROUTER; use js::jsapi::{JS_SetInterruptCallback, JSAutoCompartment, JSContext}; use js::jsval::UndefinedValue; use js::rust::Runtime; use net_traits::{load_whole_resource, IpcSend, CustomResponseMediator}; use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType}; use rand::random; use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx, ScriptChan}; use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg, WorkerScriptLoadOrigin}; use servo_url::ServoUrl; use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel}; use std::thread; use std::time::Duration; use style::thread_state::{self, IN_WORKER, SCRIPT}; use util::prefs::PREFS; use util::thread::spawn_named; /// Messages used to control service worker event loop pub enum ServiceWorkerScriptMsg { /// Message common to all workers CommonWorker(WorkerScriptMsg), // Message to request a custom response by the service worker Response(CustomResponseMediator) } pub enum MixedMessage { FromServiceWorker(ServiceWorkerScriptMsg), FromDevtools(DevtoolScriptControlMsg), FromTimeoutThread(()) } #[derive(JSTraceable, Clone)] pub struct ServiceWorkerChan { pub sender: Sender<ServiceWorkerScriptMsg> } impl ScriptChan for ServiceWorkerChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { self.sender .send(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg))) .map_err(|_| ()) } fn clone(&self) -> Box<ScriptChan + Send> { box ServiceWorkerChan { sender: self.sender.clone(), } } } #[dom_struct] pub struct ServiceWorkerGlobalScope { workerglobalscope: WorkerGlobalScope, #[ignore_heap_size_of = "Defined in std"] receiver: Receiver<ServiceWorkerScriptMsg>, #[ignore_heap_size_of = "Defined in std"] own_sender: Sender<ServiceWorkerScriptMsg>, #[ignore_heap_size_of = "Defined in std"] timer_event_port: Receiver<()>, #[ignore_heap_size_of = "Defined in std"] swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl, } impl ServiceWorkerGlobalScope { fn new_inherited(init: WorkerGlobalScopeInit, worker_url: ServoUrl, from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, runtime: Runtime, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, timer_event_chan: IpcSender<TimerEvent>, timer_event_port: Receiver<()>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) -> ServiceWorkerGlobalScope { ServiceWorkerGlobalScope { workerglobalscope: WorkerGlobalScope::new_inherited(init, worker_url, runtime, from_devtools_receiver, timer_event_chan, None), receiver: receiver, timer_event_port: timer_event_port, own_sender: own_sender, swmanager_sender: swmanager_sender, scope_url: scope_url } } #[allow(unsafe_code)] pub fn new(init: WorkerGlobalScopeInit, worker_url: ServoUrl, from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, runtime: Runtime, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, timer_event_chan: IpcSender<TimerEvent>, timer_event_port: Receiver<()>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) -> Root<ServiceWorkerGlobalScope> { let cx = runtime.cx(); let scope = box ServiceWorkerGlobalScope::new_inherited(init, worker_url, from_devtools_receiver, runtime, own_sender, receiver, timer_event_chan, timer_event_port, swmanager_sender, scope_url); unsafe { ServiceWorkerGlobalScopeBinding::Wrap(cx, scope) } } #[allow(unsafe_code)] pub fn run_serviceworker_scope(scope_things: ScopeThings, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) { let ScopeThings { script_url, init, worker_load_origin, .. } = scope_things; let serialized_worker_url = script_url.to_string(); spawn_named(format!("ServiceWorker for {}", serialized_worker_url), move || { thread_state::initialize(SCRIPT | IN_WORKER); let roots = RootCollection::new(); let _stack_roots_tls = StackRootTLS::new(&roots); let WorkerScriptLoadOrigin { referrer_url, referrer_policy, pipeline_id } = worker_load_origin; let request = RequestInit { url: script_url.clone(), type_: RequestType::Script, destination: Destination::ServiceWorker, credentials_mode: CredentialsMode::Include, use_url_credentials: true, origin: script_url, pipeline_id: pipeline_id, referrer_url: referrer_url, referrer_policy: referrer_policy, .. RequestInit::default() }; let (url, source) = match load_whole_resource(request, &init.resource_threads.sender()) { Err(_) => { println!("error loading script {}", serialized_worker_url); return; } Ok((metadata, bytes)) => { (metadata.final_url, String::from_utf8(bytes).unwrap()) } }; let runtime = unsafe { new_rt_and_cx() }; let (devtools_mpsc_chan, devtools_mpsc_port) = channel(); ROUTER.route_ipc_receiver_to_mpsc_sender(devtools_receiver, devtools_mpsc_chan); // TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap(); let (timer_chan, timer_port) = channel(); let global = ServiceWorkerGlobalScope::new( init, url, devtools_mpsc_port, runtime, own_sender, receiver, timer_ipc_chan, timer_port, swmanager_sender, scope_url); let scope = global.upcast::<WorkerGlobalScope>(); unsafe { // Handle interrupt requests JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback)); } scope.execute_script(DOMString::from(source)); // Service workers are time limited spawn_named("SWTimeoutThread".to_owned(), move || { let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap(); thread::sleep(Duration::new(sw_lifetime_timeout, 0)); let _ = timer_chan.send(()); }); global.dispatch_activate(); let reporter_name = format!("service-worker-reporter-{}", random::<u64>()); scope.upcast::<GlobalScope>().mem_profiler_chan().run_with_memory_reporting(|| { while let Ok(event) = global.receive_event() { if!global.handle_event(event) { break; } } }, reporter_name, scope.script_chan(), CommonScriptMsg::CollectReports); }); } fn handle_event(&self, event: MixedMessage) -> bool { match event { MixedMessage::FromDevtools(msg) => { match msg { DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => devtools::handle_evaluate_js(self.upcast(), string, sender), DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => devtools::handle_get_cached_messages(pipe_id, message_types, sender), DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => devtools::handle_wants_live_notifications(self.upcast(), bool_val), _ => debug!("got an unusable devtools control message inside the worker!"), } true } MixedMessage::FromServiceWorker(msg) => { self.handle_script_event(msg); true } MixedMessage::FromTimeoutThread(_) => { let _ = self.swmanager_sender.send(ServiceWorkerMsg::Timeout(self.scope_url.clone())); false } } } fn handle_script_event(&self, msg: ServiceWorkerScriptMsg) { use self::ServiceWorkerScriptMsg::*; match msg { CommonWorker(WorkerScriptMsg::DOMMessage(data)) => { let scope = self.upcast::<WorkerGlobalScope>(); let target = self.upcast(); let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => { runnable.handler() }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::CollectReports(reports_chan))) => { let scope = self.upcast::<WorkerGlobalScope>(); let cx = scope.get_cx(); let path_seg = format!("url({})", scope.get_url()); let reports = get_reports(cx, path_seg); reports_chan.send(reports); }, Response(mediator) => { // TODO XXXcreativcoder This will eventually use a FetchEvent interface to fire event // when we have the Request and Response dom api's implemented // https://slightlyoff.github.io/ServiceWorker/spec/service_worker_1/index.html#fetch-event-section self.upcast::<EventTarget>().fire_event(atom!("fetch")); let _ = mediator.response_chan.send(None); } } } #[allow(unsafe_code)] fn receive_event(&self) -> Result<MixedMessage, RecvError> { let scope = self.upcast::<WorkerGlobalScope>(); let worker_port = &self.receiver; let devtools_port = scope.from_devtools_receiver(); let timer_event_port = &self.timer_event_port; let sel = Select::new(); let mut worker_handle = sel.handle(worker_port); let mut devtools_handle = sel.handle(devtools_port); let mut timer_port_handle = sel.handle(timer_event_port); unsafe { worker_handle.add(); if scope.from_devtools_sender().is_some() { devtools_handle.add(); } timer_port_handle.add(); } let ret = sel.wait(); if ret == worker_handle.id() { Ok(MixedMessage::FromServiceWorker(try!(worker_port.recv()))) }else if ret == devtools_handle.id() { Ok(MixedMessage::FromDevtools(try!(devtools_port.recv()))) } else if ret == timer_port_handle.id()
else { panic!("unexpected select result!") } } pub fn process_event(&self, msg: CommonScriptMsg) { self.handle_script_event(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg))); } pub fn script_chan(&self) -> Box<ScriptChan + Send> { box ServiceWorkerChan { sender: self.own_sender.clone() } } fn dispatch_activate(&self) { let event = ExtendableEvent::new(self, atom!("activate"), false, false); let event = (&*event).upcast::<Event>(); self.upcast::<EventTarget>().dispatch_event(event); } } #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { let worker = Root::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx)) .expect("global is not a worker scope"); assert!(worker.is::<ServiceWorkerGlobalScope>()); // A false response causes the script to terminate !worker.is_closing() } impl ServiceWorkerGlobalScopeMethods for ServiceWorkerGlobalScope { // https://w3c.github.io/ServiceWorker/#service-worker-global-scope-onmessage-attribute event_handler!(message, GetOnmessage, SetOnmessage); }
{ Ok(MixedMessage::FromTimeoutThread(try!(timer_event_port.recv()))) }
conditional_block
serviceworkerglobalscope.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 devtools; use devtools_traits::DevtoolScriptControlMsg; use dom::abstractworker::WorkerScriptMsg; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::extendableevent::ExtendableEvent; use dom::extendablemessageevent::ExtendableMessageEvent; use dom::globalscope::GlobalScope; use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::{self, IpcSender, IpcReceiver}; use ipc_channel::router::ROUTER; use js::jsapi::{JS_SetInterruptCallback, JSAutoCompartment, JSContext}; use js::jsval::UndefinedValue; use js::rust::Runtime; use net_traits::{load_whole_resource, IpcSend, CustomResponseMediator}; use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType}; use rand::random; use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx, ScriptChan}; use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg, WorkerScriptLoadOrigin}; use servo_url::ServoUrl; use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel}; use std::thread; use std::time::Duration; use style::thread_state::{self, IN_WORKER, SCRIPT}; use util::prefs::PREFS; use util::thread::spawn_named; /// Messages used to control service worker event loop pub enum ServiceWorkerScriptMsg { /// Message common to all workers CommonWorker(WorkerScriptMsg), // Message to request a custom response by the service worker Response(CustomResponseMediator) } pub enum MixedMessage { FromServiceWorker(ServiceWorkerScriptMsg), FromDevtools(DevtoolScriptControlMsg), FromTimeoutThread(()) } #[derive(JSTraceable, Clone)] pub struct ServiceWorkerChan { pub sender: Sender<ServiceWorkerScriptMsg> } impl ScriptChan for ServiceWorkerChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { self.sender .send(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg))) .map_err(|_| ()) } fn clone(&self) -> Box<ScriptChan + Send> { box ServiceWorkerChan { sender: self.sender.clone(), } } } #[dom_struct] pub struct
{ workerglobalscope: WorkerGlobalScope, #[ignore_heap_size_of = "Defined in std"] receiver: Receiver<ServiceWorkerScriptMsg>, #[ignore_heap_size_of = "Defined in std"] own_sender: Sender<ServiceWorkerScriptMsg>, #[ignore_heap_size_of = "Defined in std"] timer_event_port: Receiver<()>, #[ignore_heap_size_of = "Defined in std"] swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl, } impl ServiceWorkerGlobalScope { fn new_inherited(init: WorkerGlobalScopeInit, worker_url: ServoUrl, from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, runtime: Runtime, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, timer_event_chan: IpcSender<TimerEvent>, timer_event_port: Receiver<()>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) -> ServiceWorkerGlobalScope { ServiceWorkerGlobalScope { workerglobalscope: WorkerGlobalScope::new_inherited(init, worker_url, runtime, from_devtools_receiver, timer_event_chan, None), receiver: receiver, timer_event_port: timer_event_port, own_sender: own_sender, swmanager_sender: swmanager_sender, scope_url: scope_url } } #[allow(unsafe_code)] pub fn new(init: WorkerGlobalScopeInit, worker_url: ServoUrl, from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, runtime: Runtime, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, timer_event_chan: IpcSender<TimerEvent>, timer_event_port: Receiver<()>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) -> Root<ServiceWorkerGlobalScope> { let cx = runtime.cx(); let scope = box ServiceWorkerGlobalScope::new_inherited(init, worker_url, from_devtools_receiver, runtime, own_sender, receiver, timer_event_chan, timer_event_port, swmanager_sender, scope_url); unsafe { ServiceWorkerGlobalScopeBinding::Wrap(cx, scope) } } #[allow(unsafe_code)] pub fn run_serviceworker_scope(scope_things: ScopeThings, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) { let ScopeThings { script_url, init, worker_load_origin, .. } = scope_things; let serialized_worker_url = script_url.to_string(); spawn_named(format!("ServiceWorker for {}", serialized_worker_url), move || { thread_state::initialize(SCRIPT | IN_WORKER); let roots = RootCollection::new(); let _stack_roots_tls = StackRootTLS::new(&roots); let WorkerScriptLoadOrigin { referrer_url, referrer_policy, pipeline_id } = worker_load_origin; let request = RequestInit { url: script_url.clone(), type_: RequestType::Script, destination: Destination::ServiceWorker, credentials_mode: CredentialsMode::Include, use_url_credentials: true, origin: script_url, pipeline_id: pipeline_id, referrer_url: referrer_url, referrer_policy: referrer_policy, .. RequestInit::default() }; let (url, source) = match load_whole_resource(request, &init.resource_threads.sender()) { Err(_) => { println!("error loading script {}", serialized_worker_url); return; } Ok((metadata, bytes)) => { (metadata.final_url, String::from_utf8(bytes).unwrap()) } }; let runtime = unsafe { new_rt_and_cx() }; let (devtools_mpsc_chan, devtools_mpsc_port) = channel(); ROUTER.route_ipc_receiver_to_mpsc_sender(devtools_receiver, devtools_mpsc_chan); // TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap(); let (timer_chan, timer_port) = channel(); let global = ServiceWorkerGlobalScope::new( init, url, devtools_mpsc_port, runtime, own_sender, receiver, timer_ipc_chan, timer_port, swmanager_sender, scope_url); let scope = global.upcast::<WorkerGlobalScope>(); unsafe { // Handle interrupt requests JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback)); } scope.execute_script(DOMString::from(source)); // Service workers are time limited spawn_named("SWTimeoutThread".to_owned(), move || { let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap(); thread::sleep(Duration::new(sw_lifetime_timeout, 0)); let _ = timer_chan.send(()); }); global.dispatch_activate(); let reporter_name = format!("service-worker-reporter-{}", random::<u64>()); scope.upcast::<GlobalScope>().mem_profiler_chan().run_with_memory_reporting(|| { while let Ok(event) = global.receive_event() { if!global.handle_event(event) { break; } } }, reporter_name, scope.script_chan(), CommonScriptMsg::CollectReports); }); } fn handle_event(&self, event: MixedMessage) -> bool { match event { MixedMessage::FromDevtools(msg) => { match msg { DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => devtools::handle_evaluate_js(self.upcast(), string, sender), DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => devtools::handle_get_cached_messages(pipe_id, message_types, sender), DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => devtools::handle_wants_live_notifications(self.upcast(), bool_val), _ => debug!("got an unusable devtools control message inside the worker!"), } true } MixedMessage::FromServiceWorker(msg) => { self.handle_script_event(msg); true } MixedMessage::FromTimeoutThread(_) => { let _ = self.swmanager_sender.send(ServiceWorkerMsg::Timeout(self.scope_url.clone())); false } } } fn handle_script_event(&self, msg: ServiceWorkerScriptMsg) { use self::ServiceWorkerScriptMsg::*; match msg { CommonWorker(WorkerScriptMsg::DOMMessage(data)) => { let scope = self.upcast::<WorkerGlobalScope>(); let target = self.upcast(); let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => { runnable.handler() }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::CollectReports(reports_chan))) => { let scope = self.upcast::<WorkerGlobalScope>(); let cx = scope.get_cx(); let path_seg = format!("url({})", scope.get_url()); let reports = get_reports(cx, path_seg); reports_chan.send(reports); }, Response(mediator) => { // TODO XXXcreativcoder This will eventually use a FetchEvent interface to fire event // when we have the Request and Response dom api's implemented // https://slightlyoff.github.io/ServiceWorker/spec/service_worker_1/index.html#fetch-event-section self.upcast::<EventTarget>().fire_event(atom!("fetch")); let _ = mediator.response_chan.send(None); } } } #[allow(unsafe_code)] fn receive_event(&self) -> Result<MixedMessage, RecvError> { let scope = self.upcast::<WorkerGlobalScope>(); let worker_port = &self.receiver; let devtools_port = scope.from_devtools_receiver(); let timer_event_port = &self.timer_event_port; let sel = Select::new(); let mut worker_handle = sel.handle(worker_port); let mut devtools_handle = sel.handle(devtools_port); let mut timer_port_handle = sel.handle(timer_event_port); unsafe { worker_handle.add(); if scope.from_devtools_sender().is_some() { devtools_handle.add(); } timer_port_handle.add(); } let ret = sel.wait(); if ret == worker_handle.id() { Ok(MixedMessage::FromServiceWorker(try!(worker_port.recv()))) }else if ret == devtools_handle.id() { Ok(MixedMessage::FromDevtools(try!(devtools_port.recv()))) } else if ret == timer_port_handle.id() { Ok(MixedMessage::FromTimeoutThread(try!(timer_event_port.recv()))) } else { panic!("unexpected select result!") } } pub fn process_event(&self, msg: CommonScriptMsg) { self.handle_script_event(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg))); } pub fn script_chan(&self) -> Box<ScriptChan + Send> { box ServiceWorkerChan { sender: self.own_sender.clone() } } fn dispatch_activate(&self) { let event = ExtendableEvent::new(self, atom!("activate"), false, false); let event = (&*event).upcast::<Event>(); self.upcast::<EventTarget>().dispatch_event(event); } } #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { let worker = Root::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx)) .expect("global is not a worker scope"); assert!(worker.is::<ServiceWorkerGlobalScope>()); // A false response causes the script to terminate !worker.is_closing() } impl ServiceWorkerGlobalScopeMethods for ServiceWorkerGlobalScope { // https://w3c.github.io/ServiceWorker/#service-worker-global-scope-onmessage-attribute event_handler!(message, GetOnmessage, SetOnmessage); }
ServiceWorkerGlobalScope
identifier_name
serviceworkerglobalscope.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 devtools; use devtools_traits::DevtoolScriptControlMsg; use dom::abstractworker::WorkerScriptMsg; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::extendableevent::ExtendableEvent; use dom::extendablemessageevent::ExtendableMessageEvent; use dom::globalscope::GlobalScope; use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::{self, IpcSender, IpcReceiver}; use ipc_channel::router::ROUTER; use js::jsapi::{JS_SetInterruptCallback, JSAutoCompartment, JSContext}; use js::jsval::UndefinedValue; use js::rust::Runtime; use net_traits::{load_whole_resource, IpcSend, CustomResponseMediator}; use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType}; use rand::random; use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx, ScriptChan}; use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg, WorkerScriptLoadOrigin}; use servo_url::ServoUrl; use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel}; use std::thread; use std::time::Duration; use style::thread_state::{self, IN_WORKER, SCRIPT}; use util::prefs::PREFS; use util::thread::spawn_named; /// Messages used to control service worker event loop pub enum ServiceWorkerScriptMsg { /// Message common to all workers CommonWorker(WorkerScriptMsg), // Message to request a custom response by the service worker Response(CustomResponseMediator) } pub enum MixedMessage { FromServiceWorker(ServiceWorkerScriptMsg), FromDevtools(DevtoolScriptControlMsg), FromTimeoutThread(()) } #[derive(JSTraceable, Clone)] pub struct ServiceWorkerChan { pub sender: Sender<ServiceWorkerScriptMsg> } impl ScriptChan for ServiceWorkerChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { self.sender .send(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg))) .map_err(|_| ()) } fn clone(&self) -> Box<ScriptChan + Send> { box ServiceWorkerChan { sender: self.sender.clone(), } } } #[dom_struct] pub struct ServiceWorkerGlobalScope { workerglobalscope: WorkerGlobalScope, #[ignore_heap_size_of = "Defined in std"] receiver: Receiver<ServiceWorkerScriptMsg>, #[ignore_heap_size_of = "Defined in std"] own_sender: Sender<ServiceWorkerScriptMsg>, #[ignore_heap_size_of = "Defined in std"] timer_event_port: Receiver<()>, #[ignore_heap_size_of = "Defined in std"] swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl, } impl ServiceWorkerGlobalScope { fn new_inherited(init: WorkerGlobalScopeInit, worker_url: ServoUrl, from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, runtime: Runtime, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, timer_event_chan: IpcSender<TimerEvent>, timer_event_port: Receiver<()>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) -> ServiceWorkerGlobalScope { ServiceWorkerGlobalScope { workerglobalscope: WorkerGlobalScope::new_inherited(init, worker_url, runtime, from_devtools_receiver, timer_event_chan, None), receiver: receiver, timer_event_port: timer_event_port, own_sender: own_sender, swmanager_sender: swmanager_sender, scope_url: scope_url } } #[allow(unsafe_code)] pub fn new(init: WorkerGlobalScopeInit, worker_url: ServoUrl, from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, runtime: Runtime, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, timer_event_chan: IpcSender<TimerEvent>, timer_event_port: Receiver<()>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) -> Root<ServiceWorkerGlobalScope> { let cx = runtime.cx(); let scope = box ServiceWorkerGlobalScope::new_inherited(init, worker_url, from_devtools_receiver, runtime, own_sender, receiver, timer_event_chan, timer_event_port, swmanager_sender, scope_url); unsafe { ServiceWorkerGlobalScopeBinding::Wrap(cx, scope) } } #[allow(unsafe_code)] pub fn run_serviceworker_scope(scope_things: ScopeThings, own_sender: Sender<ServiceWorkerScriptMsg>, receiver: Receiver<ServiceWorkerScriptMsg>, devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>, swmanager_sender: IpcSender<ServiceWorkerMsg>, scope_url: ServoUrl) { let ScopeThings { script_url, init, worker_load_origin, .. } = scope_things; let serialized_worker_url = script_url.to_string(); spawn_named(format!("ServiceWorker for {}", serialized_worker_url), move || { thread_state::initialize(SCRIPT | IN_WORKER); let roots = RootCollection::new(); let _stack_roots_tls = StackRootTLS::new(&roots); let WorkerScriptLoadOrigin { referrer_url, referrer_policy, pipeline_id } = worker_load_origin; let request = RequestInit { url: script_url.clone(), type_: RequestType::Script, destination: Destination::ServiceWorker, credentials_mode: CredentialsMode::Include, use_url_credentials: true, origin: script_url, pipeline_id: pipeline_id, referrer_url: referrer_url, referrer_policy: referrer_policy, .. RequestInit::default() }; let (url, source) = match load_whole_resource(request, &init.resource_threads.sender()) { Err(_) => { println!("error loading script {}", serialized_worker_url); return; } Ok((metadata, bytes)) => { (metadata.final_url, String::from_utf8(bytes).unwrap()) } }; let runtime = unsafe { new_rt_and_cx() }; let (devtools_mpsc_chan, devtools_mpsc_port) = channel(); ROUTER.route_ipc_receiver_to_mpsc_sender(devtools_receiver, devtools_mpsc_chan); // TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap(); let (timer_chan, timer_port) = channel(); let global = ServiceWorkerGlobalScope::new( init, url, devtools_mpsc_port, runtime, own_sender, receiver, timer_ipc_chan, timer_port, swmanager_sender, scope_url); let scope = global.upcast::<WorkerGlobalScope>(); unsafe { // Handle interrupt requests JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback)); } scope.execute_script(DOMString::from(source)); // Service workers are time limited spawn_named("SWTimeoutThread".to_owned(), move || {
let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap(); thread::sleep(Duration::new(sw_lifetime_timeout, 0)); let _ = timer_chan.send(()); }); global.dispatch_activate(); let reporter_name = format!("service-worker-reporter-{}", random::<u64>()); scope.upcast::<GlobalScope>().mem_profiler_chan().run_with_memory_reporting(|| { while let Ok(event) = global.receive_event() { if!global.handle_event(event) { break; } } }, reporter_name, scope.script_chan(), CommonScriptMsg::CollectReports); }); } fn handle_event(&self, event: MixedMessage) -> bool { match event { MixedMessage::FromDevtools(msg) => { match msg { DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => devtools::handle_evaluate_js(self.upcast(), string, sender), DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => devtools::handle_get_cached_messages(pipe_id, message_types, sender), DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => devtools::handle_wants_live_notifications(self.upcast(), bool_val), _ => debug!("got an unusable devtools control message inside the worker!"), } true } MixedMessage::FromServiceWorker(msg) => { self.handle_script_event(msg); true } MixedMessage::FromTimeoutThread(_) => { let _ = self.swmanager_sender.send(ServiceWorkerMsg::Timeout(self.scope_url.clone())); false } } } fn handle_script_event(&self, msg: ServiceWorkerScriptMsg) { use self::ServiceWorkerScriptMsg::*; match msg { CommonWorker(WorkerScriptMsg::DOMMessage(data)) => { let scope = self.upcast::<WorkerGlobalScope>(); let target = self.upcast(); let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => { runnable.handler() }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::CollectReports(reports_chan))) => { let scope = self.upcast::<WorkerGlobalScope>(); let cx = scope.get_cx(); let path_seg = format!("url({})", scope.get_url()); let reports = get_reports(cx, path_seg); reports_chan.send(reports); }, Response(mediator) => { // TODO XXXcreativcoder This will eventually use a FetchEvent interface to fire event // when we have the Request and Response dom api's implemented // https://slightlyoff.github.io/ServiceWorker/spec/service_worker_1/index.html#fetch-event-section self.upcast::<EventTarget>().fire_event(atom!("fetch")); let _ = mediator.response_chan.send(None); } } } #[allow(unsafe_code)] fn receive_event(&self) -> Result<MixedMessage, RecvError> { let scope = self.upcast::<WorkerGlobalScope>(); let worker_port = &self.receiver; let devtools_port = scope.from_devtools_receiver(); let timer_event_port = &self.timer_event_port; let sel = Select::new(); let mut worker_handle = sel.handle(worker_port); let mut devtools_handle = sel.handle(devtools_port); let mut timer_port_handle = sel.handle(timer_event_port); unsafe { worker_handle.add(); if scope.from_devtools_sender().is_some() { devtools_handle.add(); } timer_port_handle.add(); } let ret = sel.wait(); if ret == worker_handle.id() { Ok(MixedMessage::FromServiceWorker(try!(worker_port.recv()))) }else if ret == devtools_handle.id() { Ok(MixedMessage::FromDevtools(try!(devtools_port.recv()))) } else if ret == timer_port_handle.id() { Ok(MixedMessage::FromTimeoutThread(try!(timer_event_port.recv()))) } else { panic!("unexpected select result!") } } pub fn process_event(&self, msg: CommonScriptMsg) { self.handle_script_event(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg))); } pub fn script_chan(&self) -> Box<ScriptChan + Send> { box ServiceWorkerChan { sender: self.own_sender.clone() } } fn dispatch_activate(&self) { let event = ExtendableEvent::new(self, atom!("activate"), false, false); let event = (&*event).upcast::<Event>(); self.upcast::<EventTarget>().dispatch_event(event); } } #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { let worker = Root::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx)) .expect("global is not a worker scope"); assert!(worker.is::<ServiceWorkerGlobalScope>()); // A false response causes the script to terminate !worker.is_closing() } impl ServiceWorkerGlobalScopeMethods for ServiceWorkerGlobalScope { // https://w3c.github.io/ServiceWorker/#service-worker-global-scope-onmessage-attribute event_handler!(message, GetOnmessage, SetOnmessage); }
random_line_split
mods.rs
use std::collections::{HashSet}; use spiral; use spiral::to_spine::{ProgSt, Env, Res}; use spiral::to_spine::decls::{translate_decls}; use spine::onion::{Onion}; pub struct
{ module: spiral::Mod, required: HashSet<spiral::ModName>, } pub fn load_mods(prog: &spiral::Prog, mod_loader: &mut (FnMut(&spiral::ModName) -> Result<spiral::Mod, String>)) -> Res<Vec<LoadedMod>> { let mut loaded_mods = Vec::new(); let mut loaded_names = HashSet::new(); let mut required_names = spiral::imported::collect_prog(prog); loop { let mut new_mods = Vec::new(); for required_name in required_names.into_iter() { if!loaded_names.contains(&required_name) { let module = try!(mod_loader(&required_name)); if module.name!= required_name { return Err(format!("Loaded module '{}', but got '{}'", required_name.0, module.name.0)); } loaded_names.insert(required_name); new_mods.push(LoadedMod { required: spiral::imported::collect_mod(&module), module: module, }); } } if new_mods.is_empty() { break } else { required_names = HashSet::new(); for new_mod in new_mods.into_iter() { required_names.extend(new_mod.required.iter().cloned()); loaded_mods.push(new_mod); } } } Ok(loaded_mods) } pub fn translate_mods(st: &mut ProgSt, env: Env, loaded_mods: Vec<LoadedMod>) -> Res<(Vec<Onion>, Env)> { let mut remaining_mods = loaded_mods; let mut translated_names = HashSet::new(); let mut translated_onions = Vec::new(); let mut mods_env = env; while!remaining_mods.is_empty() { let mut any_translated = false; let mut still_remaining_mods = Vec::new(); for remaining_mod in remaining_mods.into_iter() { if remaining_mod.required.iter().all(|req| translated_names.contains(req)) { let (onion, exports) = try!(translate_decls(st, &mods_env, &remaining_mod.module.decls[..])); let mod_name = remaining_mod.module.name.clone(); translated_names.insert(mod_name.clone()); mods_env = mods_env.bind_mod(mod_name, exports); translated_onions.push(onion); any_translated = true; } else { still_remaining_mods.push(remaining_mod); } } if!any_translated { return Err(format!("some modules are mutually dependent")); } else { remaining_mods = still_remaining_mods; } } Ok((translated_onions, mods_env)) }
LoadedMod
identifier_name
mods.rs
use std::collections::{HashSet}; use spiral; use spiral::to_spine::{ProgSt, Env, Res}; use spiral::to_spine::decls::{translate_decls}; use spine::onion::{Onion}; pub struct LoadedMod { module: spiral::Mod, required: HashSet<spiral::ModName>, } pub fn load_mods(prog: &spiral::Prog, mod_loader: &mut (FnMut(&spiral::ModName) -> Result<spiral::Mod, String>)) -> Res<Vec<LoadedMod>> { let mut loaded_mods = Vec::new(); let mut loaded_names = HashSet::new(); let mut required_names = spiral::imported::collect_prog(prog); loop { let mut new_mods = Vec::new(); for required_name in required_names.into_iter() { if!loaded_names.contains(&required_name) { let module = try!(mod_loader(&required_name)); if module.name!= required_name { return Err(format!("Loaded module '{}', but got '{}'", required_name.0, module.name.0)); } loaded_names.insert(required_name); new_mods.push(LoadedMod { required: spiral::imported::collect_mod(&module), module: module, }); } } if new_mods.is_empty() { break } else
} Ok(loaded_mods) } pub fn translate_mods(st: &mut ProgSt, env: Env, loaded_mods: Vec<LoadedMod>) -> Res<(Vec<Onion>, Env)> { let mut remaining_mods = loaded_mods; let mut translated_names = HashSet::new(); let mut translated_onions = Vec::new(); let mut mods_env = env; while!remaining_mods.is_empty() { let mut any_translated = false; let mut still_remaining_mods = Vec::new(); for remaining_mod in remaining_mods.into_iter() { if remaining_mod.required.iter().all(|req| translated_names.contains(req)) { let (onion, exports) = try!(translate_decls(st, &mods_env, &remaining_mod.module.decls[..])); let mod_name = remaining_mod.module.name.clone(); translated_names.insert(mod_name.clone()); mods_env = mods_env.bind_mod(mod_name, exports); translated_onions.push(onion); any_translated = true; } else { still_remaining_mods.push(remaining_mod); } } if!any_translated { return Err(format!("some modules are mutually dependent")); } else { remaining_mods = still_remaining_mods; } } Ok((translated_onions, mods_env)) }
{ required_names = HashSet::new(); for new_mod in new_mods.into_iter() { required_names.extend(new_mod.required.iter().cloned()); loaded_mods.push(new_mod); } }
conditional_block
mods.rs
use std::collections::{HashSet}; use spiral; use spiral::to_spine::{ProgSt, Env, Res}; use spiral::to_spine::decls::{translate_decls}; use spine::onion::{Onion}; pub struct LoadedMod { module: spiral::Mod, required: HashSet<spiral::ModName>, } pub fn load_mods(prog: &spiral::Prog, mod_loader: &mut (FnMut(&spiral::ModName) -> Result<spiral::Mod, String>)) -> Res<Vec<LoadedMod>> { let mut loaded_mods = Vec::new(); let mut loaded_names = HashSet::new(); let mut required_names = spiral::imported::collect_prog(prog); loop { let mut new_mods = Vec::new(); for required_name in required_names.into_iter() { if!loaded_names.contains(&required_name) { let module = try!(mod_loader(&required_name)); if module.name!= required_name {
new_mods.push(LoadedMod { required: spiral::imported::collect_mod(&module), module: module, }); } } if new_mods.is_empty() { break } else { required_names = HashSet::new(); for new_mod in new_mods.into_iter() { required_names.extend(new_mod.required.iter().cloned()); loaded_mods.push(new_mod); } } } Ok(loaded_mods) } pub fn translate_mods(st: &mut ProgSt, env: Env, loaded_mods: Vec<LoadedMod>) -> Res<(Vec<Onion>, Env)> { let mut remaining_mods = loaded_mods; let mut translated_names = HashSet::new(); let mut translated_onions = Vec::new(); let mut mods_env = env; while!remaining_mods.is_empty() { let mut any_translated = false; let mut still_remaining_mods = Vec::new(); for remaining_mod in remaining_mods.into_iter() { if remaining_mod.required.iter().all(|req| translated_names.contains(req)) { let (onion, exports) = try!(translate_decls(st, &mods_env, &remaining_mod.module.decls[..])); let mod_name = remaining_mod.module.name.clone(); translated_names.insert(mod_name.clone()); mods_env = mods_env.bind_mod(mod_name, exports); translated_onions.push(onion); any_translated = true; } else { still_remaining_mods.push(remaining_mod); } } if!any_translated { return Err(format!("some modules are mutually dependent")); } else { remaining_mods = still_remaining_mods; } } Ok((translated_onions, mods_env)) }
return Err(format!("Loaded module '{}', but got '{}'", required_name.0, module.name.0)); } loaded_names.insert(required_name);
random_line_split
mods.rs
use std::collections::{HashSet}; use spiral; use spiral::to_spine::{ProgSt, Env, Res}; use spiral::to_spine::decls::{translate_decls}; use spine::onion::{Onion}; pub struct LoadedMod { module: spiral::Mod, required: HashSet<spiral::ModName>, } pub fn load_mods(prog: &spiral::Prog, mod_loader: &mut (FnMut(&spiral::ModName) -> Result<spiral::Mod, String>)) -> Res<Vec<LoadedMod>>
} } if new_mods.is_empty() { break } else { required_names = HashSet::new(); for new_mod in new_mods.into_iter() { required_names.extend(new_mod.required.iter().cloned()); loaded_mods.push(new_mod); } } } Ok(loaded_mods) } pub fn translate_mods(st: &mut ProgSt, env: Env, loaded_mods: Vec<LoadedMod>) -> Res<(Vec<Onion>, Env)> { let mut remaining_mods = loaded_mods; let mut translated_names = HashSet::new(); let mut translated_onions = Vec::new(); let mut mods_env = env; while!remaining_mods.is_empty() { let mut any_translated = false; let mut still_remaining_mods = Vec::new(); for remaining_mod in remaining_mods.into_iter() { if remaining_mod.required.iter().all(|req| translated_names.contains(req)) { let (onion, exports) = try!(translate_decls(st, &mods_env, &remaining_mod.module.decls[..])); let mod_name = remaining_mod.module.name.clone(); translated_names.insert(mod_name.clone()); mods_env = mods_env.bind_mod(mod_name, exports); translated_onions.push(onion); any_translated = true; } else { still_remaining_mods.push(remaining_mod); } } if!any_translated { return Err(format!("some modules are mutually dependent")); } else { remaining_mods = still_remaining_mods; } } Ok((translated_onions, mods_env)) }
{ let mut loaded_mods = Vec::new(); let mut loaded_names = HashSet::new(); let mut required_names = spiral::imported::collect_prog(prog); loop { let mut new_mods = Vec::new(); for required_name in required_names.into_iter() { if !loaded_names.contains(&required_name) { let module = try!(mod_loader(&required_name)); if module.name != required_name { return Err(format!("Loaded module '{}', but got '{}'", required_name.0, module.name.0)); } loaded_names.insert(required_name); new_mods.push(LoadedMod { required: spiral::imported::collect_mod(&module), module: module, });
identifier_body
ring.rs
use super::util::{CacheKeyPath, ConfigOptCacheKeyPath}; use configopt::ConfigOpt; use structopt::StructOpt; #[derive(ConfigOpt, StructOpt)] #[structopt(no_version)] /// Commands relating to Habitat rings pub enum
{ Key(Key), } #[derive(ConfigOpt, StructOpt)] #[structopt(no_version)] /// Commands relating to Habitat ring keys pub enum Key { /// Outputs the latest ring key contents to stdout Export { /// Ring key name #[structopt(name = "RING")] ring: String, #[structopt(flatten)] cache_key_path: CacheKeyPath, }, /// Generates a Habitat ring key Generate { /// Ring key name #[structopt(name = "RING")] ring: String, #[structopt(flatten)] cache_key_path: CacheKeyPath, }, /// Reads a stdin stream containing ring key contents and writes the key to disk Import { #[structopt(flatten)] cache_key_path: CacheKeyPath, }, }
Ring
identifier_name
ring.rs
use super::util::{CacheKeyPath, ConfigOptCacheKeyPath}; use configopt::ConfigOpt; use structopt::StructOpt; #[derive(ConfigOpt, StructOpt)] #[structopt(no_version)] /// Commands relating to Habitat rings pub enum Ring { Key(Key), } #[derive(ConfigOpt, StructOpt)] #[structopt(no_version)] /// Commands relating to Habitat ring keys pub enum Key { /// Outputs the latest ring key contents to stdout Export { /// Ring key name #[structopt(name = "RING")] ring: String,
cache_key_path: CacheKeyPath, }, /// Generates a Habitat ring key Generate { /// Ring key name #[structopt(name = "RING")] ring: String, #[structopt(flatten)] cache_key_path: CacheKeyPath, }, /// Reads a stdin stream containing ring key contents and writes the key to disk Import { #[structopt(flatten)] cache_key_path: CacheKeyPath, }, }
#[structopt(flatten)]
random_line_split
lib.rs
extern crate rl_sys; extern crate lalrpop_util; #[macro_use] extern crate stepper; extern crate unicode_xid; #[macro_use] mod macros; mod ast; mod error; mod eval; mod grammar; mod parser; mod stream; mod token; mod state; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; use std::path::Path; use std::sync::Arc; use std::thread; use error::Result; use parser::{parse_program, parse_stmt}; use state::State; pub use stream::{Event, Stream}; use rl_sys::readline; use rl_sys::history::{histfile, listmgmt}; pub fn run_file(file_name: &str) -> Result<()> { let mut file = File::open(file_name).expect("Unable to open file"); let mut program_str = String::new(); file.read_to_string(&mut program_str).expect("Unable to read file"); run_program(&program_str) } pub fn run_program(program_str: &str) -> Result<()> { let program = parse_program(&program_str).unwrap(); let mut state = State::new(); for stmt in program { try!(stmt.eval(&mut state, None)); } Ok(()) } pub fn run_program_with_stream(program_str: &str) -> Arc<Stream> { let program = parse_program(&program_str).unwrap(); let stream = Arc::new(Stream::new()); let cloned_stream = stream.clone(); let mut state = State::new(); thread::spawn(move || { for stmt in program { if let Err(e) = stmt.eval(&mut state, Some(cloned_stream.clone())) { cloned_stream.write_output(&format!("{}", e)); break; } } cloned_stream.finished(); }); stream
let mut state = State::new(); let mut stderr = io::stderr(); // Create history file if it doesn't already exist. OpenOptions::new().write(true).create(true).truncate(false).open(".history").expect("Unable to create history file"); // Read in history from the file. histfile::read(Some(Path::new(".history"))).expect("Unable to read history file"); while let Some(input) = readline::readline(">> ").unwrap() { if input.is_empty() { continue; } // Add input to both temporary and permanent history. listmgmt::add(&input).unwrap(); let _ = histfile::write(Some(Path::new(".history"))); match parse_stmt(&input) { Ok(stmt) => match stmt.eval(&mut state, None) { Ok(_) => (), Err(e) => writeln!(stderr, "{}", e).unwrap(), }, Err(_) => println!("Sorry! That's an invalid statement"), }; } println!(""); }
} pub fn repl() {
random_line_split
lib.rs
extern crate rl_sys; extern crate lalrpop_util; #[macro_use] extern crate stepper; extern crate unicode_xid; #[macro_use] mod macros; mod ast; mod error; mod eval; mod grammar; mod parser; mod stream; mod token; mod state; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; use std::path::Path; use std::sync::Arc; use std::thread; use error::Result; use parser::{parse_program, parse_stmt}; use state::State; pub use stream::{Event, Stream}; use rl_sys::readline; use rl_sys::history::{histfile, listmgmt}; pub fn
(file_name: &str) -> Result<()> { let mut file = File::open(file_name).expect("Unable to open file"); let mut program_str = String::new(); file.read_to_string(&mut program_str).expect("Unable to read file"); run_program(&program_str) } pub fn run_program(program_str: &str) -> Result<()> { let program = parse_program(&program_str).unwrap(); let mut state = State::new(); for stmt in program { try!(stmt.eval(&mut state, None)); } Ok(()) } pub fn run_program_with_stream(program_str: &str) -> Arc<Stream> { let program = parse_program(&program_str).unwrap(); let stream = Arc::new(Stream::new()); let cloned_stream = stream.clone(); let mut state = State::new(); thread::spawn(move || { for stmt in program { if let Err(e) = stmt.eval(&mut state, Some(cloned_stream.clone())) { cloned_stream.write_output(&format!("{}", e)); break; } } cloned_stream.finished(); }); stream } pub fn repl() { let mut state = State::new(); let mut stderr = io::stderr(); // Create history file if it doesn't already exist. OpenOptions::new().write(true).create(true).truncate(false).open(".history").expect("Unable to create history file"); // Read in history from the file. histfile::read(Some(Path::new(".history"))).expect("Unable to read history file"); while let Some(input) = readline::readline(">> ").unwrap() { if input.is_empty() { continue; } // Add input to both temporary and permanent history. listmgmt::add(&input).unwrap(); let _ = histfile::write(Some(Path::new(".history"))); match parse_stmt(&input) { Ok(stmt) => match stmt.eval(&mut state, None) { Ok(_) => (), Err(e) => writeln!(stderr, "{}", e).unwrap(), }, Err(_) => println!("Sorry! That's an invalid statement"), }; } println!(""); }
run_file
identifier_name
lib.rs
extern crate rl_sys; extern crate lalrpop_util; #[macro_use] extern crate stepper; extern crate unicode_xid; #[macro_use] mod macros; mod ast; mod error; mod eval; mod grammar; mod parser; mod stream; mod token; mod state; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; use std::path::Path; use std::sync::Arc; use std::thread; use error::Result; use parser::{parse_program, parse_stmt}; use state::State; pub use stream::{Event, Stream}; use rl_sys::readline; use rl_sys::history::{histfile, listmgmt}; pub fn run_file(file_name: &str) -> Result<()> { let mut file = File::open(file_name).expect("Unable to open file"); let mut program_str = String::new(); file.read_to_string(&mut program_str).expect("Unable to read file"); run_program(&program_str) } pub fn run_program(program_str: &str) -> Result<()>
pub fn run_program_with_stream(program_str: &str) -> Arc<Stream> { let program = parse_program(&program_str).unwrap(); let stream = Arc::new(Stream::new()); let cloned_stream = stream.clone(); let mut state = State::new(); thread::spawn(move || { for stmt in program { if let Err(e) = stmt.eval(&mut state, Some(cloned_stream.clone())) { cloned_stream.write_output(&format!("{}", e)); break; } } cloned_stream.finished(); }); stream } pub fn repl() { let mut state = State::new(); let mut stderr = io::stderr(); // Create history file if it doesn't already exist. OpenOptions::new().write(true).create(true).truncate(false).open(".history").expect("Unable to create history file"); // Read in history from the file. histfile::read(Some(Path::new(".history"))).expect("Unable to read history file"); while let Some(input) = readline::readline(">> ").unwrap() { if input.is_empty() { continue; } // Add input to both temporary and permanent history. listmgmt::add(&input).unwrap(); let _ = histfile::write(Some(Path::new(".history"))); match parse_stmt(&input) { Ok(stmt) => match stmt.eval(&mut state, None) { Ok(_) => (), Err(e) => writeln!(stderr, "{}", e).unwrap(), }, Err(_) => println!("Sorry! That's an invalid statement"), }; } println!(""); }
{ let program = parse_program(&program_str).unwrap(); let mut state = State::new(); for stmt in program { try!(stmt.eval(&mut state, None)); } Ok(()) }
identifier_body
levenshtein.rs
// Copyright (c) 2016. See AUTHORS file. // // 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 utils; /// Calculates the Levenshtein distance between two strings. /// /// # Levenshtein distance /// The [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) is the number of per-character changes (insertion, deletion & substitution)
/// that are neccessary to convert one string into annother. /// This implementation does fully support unicode strings. /// /// ## Complexity /// m := len(s) + 1 /// n := len(t) + 1 /// /// Time complexity: O(mn) /// Space complexity: O(mn) /// /// ## Examples /// ``` /// use distance::*; /// /// // Levenshtein distance /// let distance = levenshtein("hannah", "hanna"); /// assert_eq!(1, distance); /// ``` /// pub fn levenshtein(s: &str, t: &str) -> usize { // get length of unicode chars let len_s = s.chars().count(); let len_t = t.chars().count(); // initialize the matrix let mut mat: Vec<Vec<usize>> = vec![vec![0; len_t + 1]; len_s + 1]; for i in 1..(len_s + 1) { mat[i][0] = i; } for i in 1..(len_t + 1) { mat[0][i] = i; } // apply edit operations for (i, s_char) in s.chars().enumerate() { for (j, t_char) in t.chars().enumerate() { let substitution = if s_char == t_char {0} else {1}; mat[i+1][j+1] = utils::min3( mat[i][j+1] + 1, // deletion mat[i+1][j] + 1, // insertion mat[i][j] + substitution // substitution ); } } return mat[len_s][len_t]; } #[cfg(test)] mod tests { use super::levenshtein; #[test] fn basic() { assert_eq!(3, levenshtein("kitten", "sitting")); assert_eq!(2, levenshtein("book", "back")); assert_eq!(5, levenshtein("table", "dinner")); assert_eq!(2, levenshtein("person", "pardon")); assert_eq!(1, levenshtein("person", "persons")); } #[test] fn equal() { assert_eq!(0, levenshtein("kitten", "kitten")); assert_eq!(0, levenshtein("a", "a")); } #[test] fn cases() { assert_eq!(1, levenshtein("Hello", "hello")); assert_eq!(1, levenshtein("World", "world")); } #[test] fn empty() { assert_eq!(4, levenshtein("book", "")); assert_eq!(4, levenshtein("", "book")); assert_eq!(0, levenshtein("", "")); } #[test] fn unicode() { assert_eq!(2, levenshtein("SpÀße", "Spaß")); assert_eq!(5, levenshtein("γ•γ‚ˆγ†γͺら", "こんにけは")); assert_eq!(1, levenshtein("γ•γ‚ˆγ†γͺら", "γ•γ‚ˆγ†γͺう")); assert_eq!(4, levenshtein("こんにけは", "こんにけは abc")); assert_eq!(1, levenshtein("ΰΌ†ΰΌƒΚ˜", "ΰΌ†Λ₯ʘ")); } }
random_line_split