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
classes-cross-crate.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. // aux-build:cci_class_4.rs extern crate cci_class_4; use cci_class_4::kitties::cat; pub fn main()
{ let mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
identifier_body
classes-cross-crate.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. // aux-build:cci_class_4.rs extern crate cci_class_4; use cci_class_4::kitties::cat; pub fn
() { let mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
main
identifier_name
classes-cross-crate.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. // aux-build:cci_class_4.rs extern crate cci_class_4; use cci_class_4::kitties::cat;
pub fn main() { let mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
random_line_split
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::net::{TcpListener, TcpStream}; use std::sync::Arc; use threadpool::ThreadPool; use {ApplicationError, ApplicationErrorKind}; use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory}; use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory}; use super::TProcessor; /// Fixed-size thread-pool blocking Thrift server. /// /// A `TServer` listens on a given address and submits accepted connections /// to an **unbounded** queue. Connections from this queue are serviced by /// the first available worker thread from a **fixed-size** thread pool. Each /// accepted connection is handled by that worker thread, and communication /// over this thread occurs sequentially and synchronously (i.e. calls block). /// Accepted connections have an input half and an output half, each of which /// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate /// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol` /// and `TTransport` may be used. /// /// # Examples /// /// Creating and running a `TServer` using Thrift-compiler-generated /// service code. /// /// ```no_run /// use thrift; /// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory}; /// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory}; /// use thrift::protocol::{TInputProtocol, TOutputProtocol}; /// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory, /// TReadTransportFactory, TWriteTransportFactory}; /// use thrift::server::{TProcessor, TServer}; /// /// // /// // auto-generated /// // /// /// // processor for `SimpleService` /// struct SimpleServiceSyncProcessor; /// impl SimpleServiceSyncProcessor { /// fn new<H: SimpleServiceSyncHandler>(processor: H) -> SimpleServiceSyncProcessor { /// unimplemented!(); /// } /// } /// /// // `TProcessor` implementation for `SimpleService` /// impl TProcessor for SimpleServiceSyncProcessor { /// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> { /// unimplemented!(); /// } /// } /// /// // service functions for SimpleService /// trait SimpleServiceSyncHandler { /// fn service_call(&self) -> thrift::Result<()>; /// } /// /// // /// // user-code follows /// // /// /// // define a handler that will be invoked when `service_call` is received /// struct SimpleServiceHandlerImpl; /// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl { /// fn service_call(&self) -> thrift::Result<()> { /// unimplemented!(); /// } /// } /// /// // instantiate the processor /// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {}); /// /// // instantiate the server /// let i_tr_fact: Box<TReadTransportFactory> = Box::new(TBufferedReadTransportFactory::new()); /// let i_pr_fact: Box<TInputProtocolFactory> = Box::new(TBinaryInputProtocolFactory::new()); /// let o_tr_fact: Box<TWriteTransportFactory> = Box::new(TBufferedWriteTransportFactory::new()); /// let o_pr_fact: Box<TOutputProtocolFactory> = Box::new(TBinaryOutputProtocolFactory::new()); /// /// let mut server = TServer::new( /// i_tr_fact, /// i_pr_fact, /// o_tr_fact, /// o_pr_fact, /// processor, /// 10 /// ); /// /// // start listening for incoming connections /// match server.listen("127.0.0.1:8080") { /// Ok(_) => println!("listen completed"), /// Err(e) => println!("listen failed with error {:?}", e), /// } /// ``` #[derive(Debug)] pub struct TServer<PRC, RTF, IPF, WTF, OPF>
RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static, { r_trans_factory: RTF, i_proto_factory: IPF, w_trans_factory: WTF, o_proto_factory: OPF, processor: Arc<PRC>, worker_pool: ThreadPool, } impl<PRC, RTF, IPF, WTF, OPF> TServer<PRC, RTF, IPF, WTF, OPF> where PRC: TProcessor + Send + Sync +'static, RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static { /// Create a `TServer`. /// /// Each accepted connection has an input and output half, each of which /// requires a `TTransport` and `TProtocol`. `TServer` uses /// `read_transport_factory` and `input_protocol_factory` to create /// implementations for the input, and `write_transport_factory` and /// `output_protocol_factory` to create implementations for the output. pub fn new( read_transport_factory: RTF, input_protocol_factory: IPF, write_transport_factory: WTF, output_protocol_factory: OPF, processor: PRC, num_workers: usize, ) -> TServer<PRC, RTF, IPF, WTF, OPF> { TServer { r_trans_factory: read_transport_factory, i_proto_factory: input_protocol_factory, w_trans_factory: write_transport_factory, o_proto_factory: output_protocol_factory, processor: Arc::new(processor), worker_pool: ThreadPool::with_name( "Thrift service processor".to_owned(), num_workers, ), } } /// Listen for incoming connections on `listen_address`. /// /// `listen_address` should be in the form `host:port`, /// for example: `127.0.0.1:8080`. /// /// Return `()` if successful. /// /// Return `Err` when the server cannot bind to `listen_address` or there /// is an unrecoverable error. pub fn listen(&mut self, listen_address: &str) -> ::Result<()> { let listener = TcpListener::bind(listen_address)?; for stream in listener.incoming() { match stream { Ok(s) => { let (i_prot, o_prot) = self.new_protocols_for_connection(s)?; let processor = self.processor.clone(); self.worker_pool .execute(move || handle_incoming_connection(processor, i_prot, o_prot),); } Err(e) => { warn!("failed to accept remote connection with error {:?}", e); } } } Err( ::Error::Application( ApplicationError { kind: ApplicationErrorKind::Unknown, message: "aborted listen loop".into(), }, ), ) } fn new_protocols_for_connection( &mut self, stream: TcpStream, ) -> ::Result<(Box<TInputProtocol + Send>, Box<TOutputProtocol + Send>)> { // create the shared tcp stream let channel = TTcpChannel::with_stream(stream); // split it into two - one to be owned by the // input tran/proto and the other by the output let (r_chan, w_chan) = channel.split()?; // input protocol and transport let r_tran = self.r_trans_factory.create(Box::new(r_chan)); let i_prot = self.i_proto_factory.create(r_tran); // output protocol and transport let w_tran = self.w_trans_factory.create(Box::new(w_chan)); let o_prot = self.o_proto_factory.create(w_tran); Ok((i_prot, o_prot)) } } fn handle_incoming_connection<PRC>( processor: Arc<PRC>, i_prot: Box<TInputProtocol>, o_prot: Box<TOutputProtocol>, ) where PRC: TProcessor, { let mut i_prot = i_prot; let mut o_prot = o_prot; loop { let r = processor.process(&mut *i_prot, &mut *o_prot); if let Err(e) = r { warn!("processor completed with error: {:?}", e); break; } } }
where PRC: TProcessor + Send + Sync + 'static,
random_line_split
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::net::{TcpListener, TcpStream}; use std::sync::Arc; use threadpool::ThreadPool; use {ApplicationError, ApplicationErrorKind}; use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory}; use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory}; use super::TProcessor; /// Fixed-size thread-pool blocking Thrift server. /// /// A `TServer` listens on a given address and submits accepted connections /// to an **unbounded** queue. Connections from this queue are serviced by /// the first available worker thread from a **fixed-size** thread pool. Each /// accepted connection is handled by that worker thread, and communication /// over this thread occurs sequentially and synchronously (i.e. calls block). /// Accepted connections have an input half and an output half, each of which /// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate /// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol` /// and `TTransport` may be used. /// /// # Examples /// /// Creating and running a `TServer` using Thrift-compiler-generated /// service code. /// /// ```no_run /// use thrift; /// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory}; /// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory}; /// use thrift::protocol::{TInputProtocol, TOutputProtocol}; /// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory, /// TReadTransportFactory, TWriteTransportFactory}; /// use thrift::server::{TProcessor, TServer}; /// /// // /// // auto-generated /// // /// /// // processor for `SimpleService` /// struct SimpleServiceSyncProcessor; /// impl SimpleServiceSyncProcessor { /// fn new<H: SimpleServiceSyncHandler>(processor: H) -> SimpleServiceSyncProcessor { /// unimplemented!(); /// } /// } /// /// // `TProcessor` implementation for `SimpleService` /// impl TProcessor for SimpleServiceSyncProcessor { /// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> { /// unimplemented!(); /// } /// } /// /// // service functions for SimpleService /// trait SimpleServiceSyncHandler { /// fn service_call(&self) -> thrift::Result<()>; /// } /// /// // /// // user-code follows /// // /// /// // define a handler that will be invoked when `service_call` is received /// struct SimpleServiceHandlerImpl; /// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl { /// fn service_call(&self) -> thrift::Result<()> { /// unimplemented!(); /// } /// } /// /// // instantiate the processor /// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {}); /// /// // instantiate the server /// let i_tr_fact: Box<TReadTransportFactory> = Box::new(TBufferedReadTransportFactory::new()); /// let i_pr_fact: Box<TInputProtocolFactory> = Box::new(TBinaryInputProtocolFactory::new()); /// let o_tr_fact: Box<TWriteTransportFactory> = Box::new(TBufferedWriteTransportFactory::new()); /// let o_pr_fact: Box<TOutputProtocolFactory> = Box::new(TBinaryOutputProtocolFactory::new()); /// /// let mut server = TServer::new( /// i_tr_fact, /// i_pr_fact, /// o_tr_fact, /// o_pr_fact, /// processor, /// 10 /// ); /// /// // start listening for incoming connections /// match server.listen("127.0.0.1:8080") { /// Ok(_) => println!("listen completed"), /// Err(e) => println!("listen failed with error {:?}", e), /// } /// ``` #[derive(Debug)] pub struct TServer<PRC, RTF, IPF, WTF, OPF> where PRC: TProcessor + Send + Sync +'static, RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static, { r_trans_factory: RTF, i_proto_factory: IPF, w_trans_factory: WTF, o_proto_factory: OPF, processor: Arc<PRC>, worker_pool: ThreadPool, } impl<PRC, RTF, IPF, WTF, OPF> TServer<PRC, RTF, IPF, WTF, OPF> where PRC: TProcessor + Send + Sync +'static, RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static { /// Create a `TServer`. /// /// Each accepted connection has an input and output half, each of which /// requires a `TTransport` and `TProtocol`. `TServer` uses /// `read_transport_factory` and `input_protocol_factory` to create /// implementations for the input, and `write_transport_factory` and /// `output_protocol_factory` to create implementations for the output. pub fn new( read_transport_factory: RTF, input_protocol_factory: IPF, write_transport_factory: WTF, output_protocol_factory: OPF, processor: PRC, num_workers: usize, ) -> TServer<PRC, RTF, IPF, WTF, OPF> { TServer { r_trans_factory: read_transport_factory, i_proto_factory: input_protocol_factory, w_trans_factory: write_transport_factory, o_proto_factory: output_protocol_factory, processor: Arc::new(processor), worker_pool: ThreadPool::with_name( "Thrift service processor".to_owned(), num_workers, ), } } /// Listen for incoming connections on `listen_address`. /// /// `listen_address` should be in the form `host:port`, /// for example: `127.0.0.1:8080`. /// /// Return `()` if successful. /// /// Return `Err` when the server cannot bind to `listen_address` or there /// is an unrecoverable error. pub fn listen(&mut self, listen_address: &str) -> ::Result<()> { let listener = TcpListener::bind(listen_address)?; for stream in listener.incoming() { match stream { Ok(s) => { let (i_prot, o_prot) = self.new_protocols_for_connection(s)?; let processor = self.processor.clone(); self.worker_pool .execute(move || handle_incoming_connection(processor, i_prot, o_prot),); } Err(e) => { warn!("failed to accept remote connection with error {:?}", e); } } } Err( ::Error::Application( ApplicationError { kind: ApplicationErrorKind::Unknown, message: "aborted listen loop".into(), }, ), ) } fn new_protocols_for_connection( &mut self, stream: TcpStream, ) -> ::Result<(Box<TInputProtocol + Send>, Box<TOutputProtocol + Send>)> { // create the shared tcp stream let channel = TTcpChannel::with_stream(stream); // split it into two - one to be owned by the // input tran/proto and the other by the output let (r_chan, w_chan) = channel.split()?; // input protocol and transport let r_tran = self.r_trans_factory.create(Box::new(r_chan)); let i_prot = self.i_proto_factory.create(r_tran); // output protocol and transport let w_tran = self.w_trans_factory.create(Box::new(w_chan)); let o_prot = self.o_proto_factory.create(w_tran); Ok((i_prot, o_prot)) } } fn handle_incoming_connection<PRC>( processor: Arc<PRC>, i_prot: Box<TInputProtocol>, o_prot: Box<TOutputProtocol>, ) where PRC: TProcessor, { let mut i_prot = i_prot; let mut o_prot = o_prot; loop { let r = processor.process(&mut *i_prot, &mut *o_prot); if let Err(e) = r
} }
{ warn!("processor completed with error: {:?}", e); break; }
conditional_block
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::net::{TcpListener, TcpStream}; use std::sync::Arc; use threadpool::ThreadPool; use {ApplicationError, ApplicationErrorKind}; use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory}; use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory}; use super::TProcessor; /// Fixed-size thread-pool blocking Thrift server. /// /// A `TServer` listens on a given address and submits accepted connections /// to an **unbounded** queue. Connections from this queue are serviced by /// the first available worker thread from a **fixed-size** thread pool. Each /// accepted connection is handled by that worker thread, and communication /// over this thread occurs sequentially and synchronously (i.e. calls block). /// Accepted connections have an input half and an output half, each of which /// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate /// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol` /// and `TTransport` may be used. /// /// # Examples /// /// Creating and running a `TServer` using Thrift-compiler-generated /// service code. /// /// ```no_run /// use thrift; /// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory}; /// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory}; /// use thrift::protocol::{TInputProtocol, TOutputProtocol}; /// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory, /// TReadTransportFactory, TWriteTransportFactory}; /// use thrift::server::{TProcessor, TServer}; /// /// // /// // auto-generated /// // /// /// // processor for `SimpleService` /// struct SimpleServiceSyncProcessor; /// impl SimpleServiceSyncProcessor { /// fn new<H: SimpleServiceSyncHandler>(processor: H) -> SimpleServiceSyncProcessor { /// unimplemented!(); /// } /// } /// /// // `TProcessor` implementation for `SimpleService` /// impl TProcessor for SimpleServiceSyncProcessor { /// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> { /// unimplemented!(); /// } /// } /// /// // service functions for SimpleService /// trait SimpleServiceSyncHandler { /// fn service_call(&self) -> thrift::Result<()>; /// } /// /// // /// // user-code follows /// // /// /// // define a handler that will be invoked when `service_call` is received /// struct SimpleServiceHandlerImpl; /// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl { /// fn service_call(&self) -> thrift::Result<()> { /// unimplemented!(); /// } /// } /// /// // instantiate the processor /// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {}); /// /// // instantiate the server /// let i_tr_fact: Box<TReadTransportFactory> = Box::new(TBufferedReadTransportFactory::new()); /// let i_pr_fact: Box<TInputProtocolFactory> = Box::new(TBinaryInputProtocolFactory::new()); /// let o_tr_fact: Box<TWriteTransportFactory> = Box::new(TBufferedWriteTransportFactory::new()); /// let o_pr_fact: Box<TOutputProtocolFactory> = Box::new(TBinaryOutputProtocolFactory::new()); /// /// let mut server = TServer::new( /// i_tr_fact, /// i_pr_fact, /// o_tr_fact, /// o_pr_fact, /// processor, /// 10 /// ); /// /// // start listening for incoming connections /// match server.listen("127.0.0.1:8080") { /// Ok(_) => println!("listen completed"), /// Err(e) => println!("listen failed with error {:?}", e), /// } /// ``` #[derive(Debug)] pub struct TServer<PRC, RTF, IPF, WTF, OPF> where PRC: TProcessor + Send + Sync +'static, RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static, { r_trans_factory: RTF, i_proto_factory: IPF, w_trans_factory: WTF, o_proto_factory: OPF, processor: Arc<PRC>, worker_pool: ThreadPool, } impl<PRC, RTF, IPF, WTF, OPF> TServer<PRC, RTF, IPF, WTF, OPF> where PRC: TProcessor + Send + Sync +'static, RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static { /// Create a `TServer`. /// /// Each accepted connection has an input and output half, each of which /// requires a `TTransport` and `TProtocol`. `TServer` uses /// `read_transport_factory` and `input_protocol_factory` to create /// implementations for the input, and `write_transport_factory` and /// `output_protocol_factory` to create implementations for the output. pub fn new( read_transport_factory: RTF, input_protocol_factory: IPF, write_transport_factory: WTF, output_protocol_factory: OPF, processor: PRC, num_workers: usize, ) -> TServer<PRC, RTF, IPF, WTF, OPF>
/// Listen for incoming connections on `listen_address`. /// /// `listen_address` should be in the form `host:port`, /// for example: `127.0.0.1:8080`. /// /// Return `()` if successful. /// /// Return `Err` when the server cannot bind to `listen_address` or there /// is an unrecoverable error. pub fn listen(&mut self, listen_address: &str) -> ::Result<()> { let listener = TcpListener::bind(listen_address)?; for stream in listener.incoming() { match stream { Ok(s) => { let (i_prot, o_prot) = self.new_protocols_for_connection(s)?; let processor = self.processor.clone(); self.worker_pool .execute(move || handle_incoming_connection(processor, i_prot, o_prot),); } Err(e) => { warn!("failed to accept remote connection with error {:?}", e); } } } Err( ::Error::Application( ApplicationError { kind: ApplicationErrorKind::Unknown, message: "aborted listen loop".into(), }, ), ) } fn new_protocols_for_connection( &mut self, stream: TcpStream, ) -> ::Result<(Box<TInputProtocol + Send>, Box<TOutputProtocol + Send>)> { // create the shared tcp stream let channel = TTcpChannel::with_stream(stream); // split it into two - one to be owned by the // input tran/proto and the other by the output let (r_chan, w_chan) = channel.split()?; // input protocol and transport let r_tran = self.r_trans_factory.create(Box::new(r_chan)); let i_prot = self.i_proto_factory.create(r_tran); // output protocol and transport let w_tran = self.w_trans_factory.create(Box::new(w_chan)); let o_prot = self.o_proto_factory.create(w_tran); Ok((i_prot, o_prot)) } } fn handle_incoming_connection<PRC>( processor: Arc<PRC>, i_prot: Box<TInputProtocol>, o_prot: Box<TOutputProtocol>, ) where PRC: TProcessor, { let mut i_prot = i_prot; let mut o_prot = o_prot; loop { let r = processor.process(&mut *i_prot, &mut *o_prot); if let Err(e) = r { warn!("processor completed with error: {:?}", e); break; } } }
{ TServer { r_trans_factory: read_transport_factory, i_proto_factory: input_protocol_factory, w_trans_factory: write_transport_factory, o_proto_factory: output_protocol_factory, processor: Arc::new(processor), worker_pool: ThreadPool::with_name( "Thrift service processor".to_owned(), num_workers, ), } }
identifier_body
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::net::{TcpListener, TcpStream}; use std::sync::Arc; use threadpool::ThreadPool; use {ApplicationError, ApplicationErrorKind}; use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory}; use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory}; use super::TProcessor; /// Fixed-size thread-pool blocking Thrift server. /// /// A `TServer` listens on a given address and submits accepted connections /// to an **unbounded** queue. Connections from this queue are serviced by /// the first available worker thread from a **fixed-size** thread pool. Each /// accepted connection is handled by that worker thread, and communication /// over this thread occurs sequentially and synchronously (i.e. calls block). /// Accepted connections have an input half and an output half, each of which /// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate /// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol` /// and `TTransport` may be used. /// /// # Examples /// /// Creating and running a `TServer` using Thrift-compiler-generated /// service code. /// /// ```no_run /// use thrift; /// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory}; /// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory}; /// use thrift::protocol::{TInputProtocol, TOutputProtocol}; /// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory, /// TReadTransportFactory, TWriteTransportFactory}; /// use thrift::server::{TProcessor, TServer}; /// /// // /// // auto-generated /// // /// /// // processor for `SimpleService` /// struct SimpleServiceSyncProcessor; /// impl SimpleServiceSyncProcessor { /// fn new<H: SimpleServiceSyncHandler>(processor: H) -> SimpleServiceSyncProcessor { /// unimplemented!(); /// } /// } /// /// // `TProcessor` implementation for `SimpleService` /// impl TProcessor for SimpleServiceSyncProcessor { /// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> { /// unimplemented!(); /// } /// } /// /// // service functions for SimpleService /// trait SimpleServiceSyncHandler { /// fn service_call(&self) -> thrift::Result<()>; /// } /// /// // /// // user-code follows /// // /// /// // define a handler that will be invoked when `service_call` is received /// struct SimpleServiceHandlerImpl; /// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl { /// fn service_call(&self) -> thrift::Result<()> { /// unimplemented!(); /// } /// } /// /// // instantiate the processor /// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {}); /// /// // instantiate the server /// let i_tr_fact: Box<TReadTransportFactory> = Box::new(TBufferedReadTransportFactory::new()); /// let i_pr_fact: Box<TInputProtocolFactory> = Box::new(TBinaryInputProtocolFactory::new()); /// let o_tr_fact: Box<TWriteTransportFactory> = Box::new(TBufferedWriteTransportFactory::new()); /// let o_pr_fact: Box<TOutputProtocolFactory> = Box::new(TBinaryOutputProtocolFactory::new()); /// /// let mut server = TServer::new( /// i_tr_fact, /// i_pr_fact, /// o_tr_fact, /// o_pr_fact, /// processor, /// 10 /// ); /// /// // start listening for incoming connections /// match server.listen("127.0.0.1:8080") { /// Ok(_) => println!("listen completed"), /// Err(e) => println!("listen failed with error {:?}", e), /// } /// ``` #[derive(Debug)] pub struct TServer<PRC, RTF, IPF, WTF, OPF> where PRC: TProcessor + Send + Sync +'static, RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static, { r_trans_factory: RTF, i_proto_factory: IPF, w_trans_factory: WTF, o_proto_factory: OPF, processor: Arc<PRC>, worker_pool: ThreadPool, } impl<PRC, RTF, IPF, WTF, OPF> TServer<PRC, RTF, IPF, WTF, OPF> where PRC: TProcessor + Send + Sync +'static, RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static { /// Create a `TServer`. /// /// Each accepted connection has an input and output half, each of which /// requires a `TTransport` and `TProtocol`. `TServer` uses /// `read_transport_factory` and `input_protocol_factory` to create /// implementations for the input, and `write_transport_factory` and /// `output_protocol_factory` to create implementations for the output. pub fn new( read_transport_factory: RTF, input_protocol_factory: IPF, write_transport_factory: WTF, output_protocol_factory: OPF, processor: PRC, num_workers: usize, ) -> TServer<PRC, RTF, IPF, WTF, OPF> { TServer { r_trans_factory: read_transport_factory, i_proto_factory: input_protocol_factory, w_trans_factory: write_transport_factory, o_proto_factory: output_protocol_factory, processor: Arc::new(processor), worker_pool: ThreadPool::with_name( "Thrift service processor".to_owned(), num_workers, ), } } /// Listen for incoming connections on `listen_address`. /// /// `listen_address` should be in the form `host:port`, /// for example: `127.0.0.1:8080`. /// /// Return `()` if successful. /// /// Return `Err` when the server cannot bind to `listen_address` or there /// is an unrecoverable error. pub fn listen(&mut self, listen_address: &str) -> ::Result<()> { let listener = TcpListener::bind(listen_address)?; for stream in listener.incoming() { match stream { Ok(s) => { let (i_prot, o_prot) = self.new_protocols_for_connection(s)?; let processor = self.processor.clone(); self.worker_pool .execute(move || handle_incoming_connection(processor, i_prot, o_prot),); } Err(e) => { warn!("failed to accept remote connection with error {:?}", e); } } } Err( ::Error::Application( ApplicationError { kind: ApplicationErrorKind::Unknown, message: "aborted listen loop".into(), }, ), ) } fn new_protocols_for_connection( &mut self, stream: TcpStream, ) -> ::Result<(Box<TInputProtocol + Send>, Box<TOutputProtocol + Send>)> { // create the shared tcp stream let channel = TTcpChannel::with_stream(stream); // split it into two - one to be owned by the // input tran/proto and the other by the output let (r_chan, w_chan) = channel.split()?; // input protocol and transport let r_tran = self.r_trans_factory.create(Box::new(r_chan)); let i_prot = self.i_proto_factory.create(r_tran); // output protocol and transport let w_tran = self.w_trans_factory.create(Box::new(w_chan)); let o_prot = self.o_proto_factory.create(w_tran); Ok((i_prot, o_prot)) } } fn
<PRC>( processor: Arc<PRC>, i_prot: Box<TInputProtocol>, o_prot: Box<TOutputProtocol>, ) where PRC: TProcessor, { let mut i_prot = i_prot; let mut o_prot = o_prot; loop { let r = processor.process(&mut *i_prot, &mut *o_prot); if let Err(e) = r { warn!("processor completed with error: {:?}", e); break; } } }
handle_incoming_connection
identifier_name
edit.rs
#![allow(deprecated)] use gpgme; use std::io::prelude::*; use gpgme::{ edit::{self, EditInteractionStatus, Editor}, Error, Result, }; use self::common::passphrase_cb; #[macro_use] mod common; #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum TestEditorState { Start, Fingerprint, Expire, Valid, Uid, Primary, Quit, Save, } impl Default for TestEditorState { fn default() -> Self { TestEditorState::Start } } struct TestEditor; impl Editor for TestEditor { type State = TestEditorState; fn next_state( state: Result<Self::State>, status: EditInteractionStatus<'_>, need_response: bool, ) -> Result<Self::State> { use self::TestEditorState as State; println!("[-- Code: {:?}, {:?} --]", status.code, status.args()); if!need_response { return state; } if status.args() == Ok(edit::PROMPT) { match state {
Ok(State::Quit) => state, Ok(State::Primary) | Err(_) => Ok(State::Quit), _ => Err(Error::GENERAL), } } else if (status.args() == Ok(edit::KEY_VALID)) && (state == Ok(State::Expire)) { Ok(State::Valid) } else if (status.args() == Ok(edit::CONFIRM_SAVE)) && (state == Ok(State::Quit)) { Ok(State::Save) } else { state.and(Err(Error::GENERAL)) } } fn action<W: Write>(&self, state: Self::State, mut out: W) -> Result<()> { use self::TestEditorState as State; match state { State::Fingerprint => out.write_all(b"fpr")?, State::Expire => out.write_all(b"expire")?, State::Valid => out.write_all(b"0")?, State::Uid => out.write_all(b"1")?, State::Primary => out.write_all(b"primary")?, State::Quit => write!(out, "{}", edit::QUIT)?, State::Save => write!(out, "{}", edit::YES)?, _ => return Err(Error::GENERAL), } Ok(()) } } test_case! { test_edit(test) { test.create_context().with_passphrase_provider(passphrase_cb, |ctx| { let key = ctx.find_keys(Some("Alpha")).unwrap().next().unwrap().unwrap(); ctx.edit_key_with(&key, TestEditor, &mut Vec::new()).unwrap(); }); } }
Ok(State::Start) => Ok(State::Fingerprint), Ok(State::Fingerprint) => Ok(State::Expire), Ok(State::Valid) => Ok(State::Uid), Ok(State::Uid) => Ok(State::Primary),
random_line_split
edit.rs
#![allow(deprecated)] use gpgme; use std::io::prelude::*; use gpgme::{ edit::{self, EditInteractionStatus, Editor}, Error, Result, }; use self::common::passphrase_cb; #[macro_use] mod common; #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum TestEditorState { Start, Fingerprint, Expire, Valid, Uid, Primary, Quit, Save, } impl Default for TestEditorState { fn default() -> Self { TestEditorState::Start } } struct TestEditor; impl Editor for TestEditor { type State = TestEditorState; fn
( state: Result<Self::State>, status: EditInteractionStatus<'_>, need_response: bool, ) -> Result<Self::State> { use self::TestEditorState as State; println!("[-- Code: {:?}, {:?} --]", status.code, status.args()); if!need_response { return state; } if status.args() == Ok(edit::PROMPT) { match state { Ok(State::Start) => Ok(State::Fingerprint), Ok(State::Fingerprint) => Ok(State::Expire), Ok(State::Valid) => Ok(State::Uid), Ok(State::Uid) => Ok(State::Primary), Ok(State::Quit) => state, Ok(State::Primary) | Err(_) => Ok(State::Quit), _ => Err(Error::GENERAL), } } else if (status.args() == Ok(edit::KEY_VALID)) && (state == Ok(State::Expire)) { Ok(State::Valid) } else if (status.args() == Ok(edit::CONFIRM_SAVE)) && (state == Ok(State::Quit)) { Ok(State::Save) } else { state.and(Err(Error::GENERAL)) } } fn action<W: Write>(&self, state: Self::State, mut out: W) -> Result<()> { use self::TestEditorState as State; match state { State::Fingerprint => out.write_all(b"fpr")?, State::Expire => out.write_all(b"expire")?, State::Valid => out.write_all(b"0")?, State::Uid => out.write_all(b"1")?, State::Primary => out.write_all(b"primary")?, State::Quit => write!(out, "{}", edit::QUIT)?, State::Save => write!(out, "{}", edit::YES)?, _ => return Err(Error::GENERAL), } Ok(()) } } test_case! { test_edit(test) { test.create_context().with_passphrase_provider(passphrase_cb, |ctx| { let key = ctx.find_keys(Some("Alpha")).unwrap().next().unwrap().unwrap(); ctx.edit_key_with(&key, TestEditor, &mut Vec::new()).unwrap(); }); } }
next_state
identifier_name
derive.rs
use crate::cfg_eval::cfg_eval; use rustc_ast as ast; use rustc_ast::{attr, token, GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind}; use rustc_errors::{struct_span_err, Applicability}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::AttributeTemplate; use rustc_parse::validate_attr; use rustc_session::Session; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; crate struct Expander; impl MultiItemModifier for Expander { fn expand( &self, ecx: &mut ExtCtxt<'_>, span: Span, meta_item: &ast::MetaItem, item: Annotatable, ) -> ExpandResult<Vec<Annotatable>, Annotatable> { let sess = ecx.sess; if report_bad_target(sess, &item, span) { // We don't want to pass inappropriate targets to derive macros to avoid // follow up errors, all other errors below are recoverable. return ExpandResult::Ready(vec![item]); } let (sess, features) = (ecx.sess, ecx.ecfg.features); let result = ecx.resolver.resolve_derives(ecx.current_expansion.id, ecx.force_mode, &|| { let template = AttributeTemplate { list: Some("Trait1, Trait2,..."),..Default::default() }; let attr = attr::mk_attr_outer(meta_item.clone()); validate_attr::check_builtin_attribute( &sess.parse_sess, &attr, sym::derive, template, ); let mut resolutions: Vec<_> = attr .meta_item_list() .unwrap_or_default() .into_iter() .filter_map(|nested_meta| match nested_meta { NestedMetaItem::MetaItem(meta) => Some(meta), NestedMetaItem::Literal(lit) => { // Reject `#[derive("Debug")]`. report_unexpected_literal(sess, &lit); None } }) .map(|meta| { // Reject `#[derive(Debug = "value", Debug(abc))]`, but recover the paths. report_path_args(sess, &meta); meta.path }) .map(|path| (path, dummy_annotatable(), None)) .collect(); // Do not configure or clone items unless necessary. match &mut resolutions[..] { [] => {} [(_, first_item, _), others @..] => { *first_item = cfg_eval(sess, features, item.clone()); for (_, item, _) in others { *item = first_item.clone(); } } } resolutions }); match result { Ok(()) => ExpandResult::Ready(vec![item]), Err(Indeterminate) => ExpandResult::Retry(item), } } } // The cheapest `Annotatable` to construct. fn dummy_annotatable() -> Annotatable { Annotatable::GenericParam(ast::GenericParam { id: ast::DUMMY_NODE_ID, ident: Ident::empty(), attrs: Default::default(), bounds: Default::default(), is_placeholder: false, kind: GenericParamKind::Lifetime, }) } fn report_bad_target(sess: &Session, item: &Annotatable, span: Span) -> bool { let item_kind = match item { Annotatable::Item(item) => Some(&item.kind), Annotatable::Stmt(stmt) => match &stmt.kind { StmtKind::Item(item) => Some(&item.kind), _ => None, }, _ => None, }; let bad_target = !matches!(item_kind, Some(ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..))); if bad_target { struct_span_err!( sess, span, E0774, "`derive` may only be applied to `struct`s, `enum`s and `union`s", ) .span_label(span, "not applicable here") .span_label(item.span(), "not a `struct`, `enum` or `union`") .emit(); } bad_target } fn report_unexpected_literal(sess: &Session, lit: &ast::Lit)
fn report_path_args(sess: &Session, meta: &ast::MetaItem) { let report_error = |title, action| { let span = meta.span.with_lo(meta.path.span.hi()); sess.struct_span_err(span, title) .span_suggestion(span, action, String::new(), Applicability::MachineApplicable) .emit(); }; match meta.kind { MetaItemKind::Word => {} MetaItemKind::List(..) => report_error( "traits in `#[derive(...)]` don't accept arguments", "remove the arguments", ), MetaItemKind::NameValue(..) => { report_error("traits in `#[derive(...)]` don't accept values", "remove the value") } } }
{ let help_msg = match lit.token.kind { token::Str if rustc_lexer::is_ident(&lit.token.symbol.as_str()) => { format!("try using `#[derive({})]`", lit.token.symbol) } _ => "for example, write `#[derive(Debug)]` for `Debug`".to_string(), }; struct_span_err!(sess, lit.span, E0777, "expected path to a trait, found literal",) .span_label(lit.span, "not a trait") .help(&help_msg) .emit(); }
identifier_body
derive.rs
use crate::cfg_eval::cfg_eval; use rustc_ast as ast; use rustc_ast::{attr, token, GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind}; use rustc_errors::{struct_span_err, Applicability}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::AttributeTemplate; use rustc_parse::validate_attr; use rustc_session::Session; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; crate struct Expander; impl MultiItemModifier for Expander { fn
( &self, ecx: &mut ExtCtxt<'_>, span: Span, meta_item: &ast::MetaItem, item: Annotatable, ) -> ExpandResult<Vec<Annotatable>, Annotatable> { let sess = ecx.sess; if report_bad_target(sess, &item, span) { // We don't want to pass inappropriate targets to derive macros to avoid // follow up errors, all other errors below are recoverable. return ExpandResult::Ready(vec![item]); } let (sess, features) = (ecx.sess, ecx.ecfg.features); let result = ecx.resolver.resolve_derives(ecx.current_expansion.id, ecx.force_mode, &|| { let template = AttributeTemplate { list: Some("Trait1, Trait2,..."),..Default::default() }; let attr = attr::mk_attr_outer(meta_item.clone()); validate_attr::check_builtin_attribute( &sess.parse_sess, &attr, sym::derive, template, ); let mut resolutions: Vec<_> = attr .meta_item_list() .unwrap_or_default() .into_iter() .filter_map(|nested_meta| match nested_meta { NestedMetaItem::MetaItem(meta) => Some(meta), NestedMetaItem::Literal(lit) => { // Reject `#[derive("Debug")]`. report_unexpected_literal(sess, &lit); None } }) .map(|meta| { // Reject `#[derive(Debug = "value", Debug(abc))]`, but recover the paths. report_path_args(sess, &meta); meta.path }) .map(|path| (path, dummy_annotatable(), None)) .collect(); // Do not configure or clone items unless necessary. match &mut resolutions[..] { [] => {} [(_, first_item, _), others @..] => { *first_item = cfg_eval(sess, features, item.clone()); for (_, item, _) in others { *item = first_item.clone(); } } } resolutions }); match result { Ok(()) => ExpandResult::Ready(vec![item]), Err(Indeterminate) => ExpandResult::Retry(item), } } } // The cheapest `Annotatable` to construct. fn dummy_annotatable() -> Annotatable { Annotatable::GenericParam(ast::GenericParam { id: ast::DUMMY_NODE_ID, ident: Ident::empty(), attrs: Default::default(), bounds: Default::default(), is_placeholder: false, kind: GenericParamKind::Lifetime, }) } fn report_bad_target(sess: &Session, item: &Annotatable, span: Span) -> bool { let item_kind = match item { Annotatable::Item(item) => Some(&item.kind), Annotatable::Stmt(stmt) => match &stmt.kind { StmtKind::Item(item) => Some(&item.kind), _ => None, }, _ => None, }; let bad_target = !matches!(item_kind, Some(ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..))); if bad_target { struct_span_err!( sess, span, E0774, "`derive` may only be applied to `struct`s, `enum`s and `union`s", ) .span_label(span, "not applicable here") .span_label(item.span(), "not a `struct`, `enum` or `union`") .emit(); } bad_target } fn report_unexpected_literal(sess: &Session, lit: &ast::Lit) { let help_msg = match lit.token.kind { token::Str if rustc_lexer::is_ident(&lit.token.symbol.as_str()) => { format!("try using `#[derive({})]`", lit.token.symbol) } _ => "for example, write `#[derive(Debug)]` for `Debug`".to_string(), }; struct_span_err!(sess, lit.span, E0777, "expected path to a trait, found literal",) .span_label(lit.span, "not a trait") .help(&help_msg) .emit(); } fn report_path_args(sess: &Session, meta: &ast::MetaItem) { let report_error = |title, action| { let span = meta.span.with_lo(meta.path.span.hi()); sess.struct_span_err(span, title) .span_suggestion(span, action, String::new(), Applicability::MachineApplicable) .emit(); }; match meta.kind { MetaItemKind::Word => {} MetaItemKind::List(..) => report_error( "traits in `#[derive(...)]` don't accept arguments", "remove the arguments", ), MetaItemKind::NameValue(..) => { report_error("traits in `#[derive(...)]` don't accept values", "remove the value") } } }
expand
identifier_name
derive.rs
use crate::cfg_eval::cfg_eval; use rustc_ast as ast; use rustc_ast::{attr, token, GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind}; use rustc_errors::{struct_span_err, Applicability}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::AttributeTemplate; use rustc_parse::validate_attr; use rustc_session::Session; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; crate struct Expander; impl MultiItemModifier for Expander { fn expand( &self, ecx: &mut ExtCtxt<'_>, span: Span, meta_item: &ast::MetaItem, item: Annotatable, ) -> ExpandResult<Vec<Annotatable>, Annotatable> { let sess = ecx.sess; if report_bad_target(sess, &item, span) { // We don't want to pass inappropriate targets to derive macros to avoid // follow up errors, all other errors below are recoverable. return ExpandResult::Ready(vec![item]); } let (sess, features) = (ecx.sess, ecx.ecfg.features); let result = ecx.resolver.resolve_derives(ecx.current_expansion.id, ecx.force_mode, &|| { let template = AttributeTemplate { list: Some("Trait1, Trait2,..."),..Default::default() }; let attr = attr::mk_attr_outer(meta_item.clone()); validate_attr::check_builtin_attribute( &sess.parse_sess, &attr, sym::derive, template, ); let mut resolutions: Vec<_> = attr .meta_item_list() .unwrap_or_default() .into_iter() .filter_map(|nested_meta| match nested_meta { NestedMetaItem::MetaItem(meta) => Some(meta), NestedMetaItem::Literal(lit) => { // Reject `#[derive("Debug")]`. report_unexpected_literal(sess, &lit); None } }) .map(|meta| { // Reject `#[derive(Debug = "value", Debug(abc))]`, but recover the paths. report_path_args(sess, &meta); meta.path }) .map(|path| (path, dummy_annotatable(), None)) .collect();
[(_, first_item, _), others @..] => { *first_item = cfg_eval(sess, features, item.clone()); for (_, item, _) in others { *item = first_item.clone(); } } } resolutions }); match result { Ok(()) => ExpandResult::Ready(vec![item]), Err(Indeterminate) => ExpandResult::Retry(item), } } } // The cheapest `Annotatable` to construct. fn dummy_annotatable() -> Annotatable { Annotatable::GenericParam(ast::GenericParam { id: ast::DUMMY_NODE_ID, ident: Ident::empty(), attrs: Default::default(), bounds: Default::default(), is_placeholder: false, kind: GenericParamKind::Lifetime, }) } fn report_bad_target(sess: &Session, item: &Annotatable, span: Span) -> bool { let item_kind = match item { Annotatable::Item(item) => Some(&item.kind), Annotatable::Stmt(stmt) => match &stmt.kind { StmtKind::Item(item) => Some(&item.kind), _ => None, }, _ => None, }; let bad_target = !matches!(item_kind, Some(ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..))); if bad_target { struct_span_err!( sess, span, E0774, "`derive` may only be applied to `struct`s, `enum`s and `union`s", ) .span_label(span, "not applicable here") .span_label(item.span(), "not a `struct`, `enum` or `union`") .emit(); } bad_target } fn report_unexpected_literal(sess: &Session, lit: &ast::Lit) { let help_msg = match lit.token.kind { token::Str if rustc_lexer::is_ident(&lit.token.symbol.as_str()) => { format!("try using `#[derive({})]`", lit.token.symbol) } _ => "for example, write `#[derive(Debug)]` for `Debug`".to_string(), }; struct_span_err!(sess, lit.span, E0777, "expected path to a trait, found literal",) .span_label(lit.span, "not a trait") .help(&help_msg) .emit(); } fn report_path_args(sess: &Session, meta: &ast::MetaItem) { let report_error = |title, action| { let span = meta.span.with_lo(meta.path.span.hi()); sess.struct_span_err(span, title) .span_suggestion(span, action, String::new(), Applicability::MachineApplicable) .emit(); }; match meta.kind { MetaItemKind::Word => {} MetaItemKind::List(..) => report_error( "traits in `#[derive(...)]` don't accept arguments", "remove the arguments", ), MetaItemKind::NameValue(..) => { report_error("traits in `#[derive(...)]` don't accept values", "remove the value") } } }
// Do not configure or clone items unless necessary. match &mut resolutions[..] { [] => {}
random_line_split
mock_engine.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; use crate::storage::kv::{Callback, ExtCallback, Modify, SnapContext, WriteData}; use crate::storage::{Engine, RocksEngine}; use kvproto::kvrpcpb::Context; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; /// A mock engine is a simple wrapper around RocksEngine /// but with the ability to assert the modifies, /// the callback used, and other aspects during interaction with the engine #[derive(Clone)] pub struct MockEngine { base: RocksEngine, expected_modifies: Arc<ExpectedWriteList>, } #[derive(Debug, Clone, Default, PartialEq)] pub struct ExpectedWrite { // if the following `Option`s are None, it means we just don't care modify: Option<Modify>, use_proposed_cb: Option<bool>, use_committed_cb: Option<bool>, } impl ExpectedWrite { pub fn new() -> Self { Default::default() } pub fn expect_modify(self, modify: Modify) -> Self { Self { modify: Some(modify), use_proposed_cb: self.use_proposed_cb, use_committed_cb: self.use_committed_cb, } } pub fn expect_proposed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: Some(true), use_committed_cb: self.use_committed_cb, } } pub fn expect_no_proposed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: Some(false), use_committed_cb: self.use_committed_cb, } } pub fn expect_committed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: self.use_proposed_cb, use_committed_cb: Some(true), } } pub fn expect_no_committed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: self.use_proposed_cb, use_committed_cb: Some(false), } } } /// `ExpectedWriteList` represents a list of writes expected to write to the engine struct ExpectedWriteList(Mutex<LinkedList<ExpectedWrite>>); // We implement drop here instead of on MockEngine // because `MockEngine` can be cloned and dropped everywhere // and we just want to assert every write impl Drop for ExpectedWriteList { fn drop(&mut self) { let expected_modifies = &mut *self.0.lock().unwrap(); assert_eq!( expected_modifies.len(), 0, "not all expected modifies have been written to the engine, {} rest", expected_modifies.len() ) } } impl Engine for MockEngine { type Snap = <RocksEngine as Engine>::Snap; type Local = <RocksEngine as Engine>::Local; fn
(&self) -> Self::Local { self.base.kv_engine() } fn snapshot_on_kv_engine(&self, start_key: &[u8], end_key: &[u8]) -> Result<Self::Snap> { self.base.snapshot_on_kv_engine(start_key, end_key) } fn modify_on_kv_engine(&self, modifies: Vec<Modify>) -> Result<()> { self.base.modify_on_kv_engine(modifies) } fn async_snapshot(&self, ctx: SnapContext<'_>, cb: Callback<Self::Snap>) -> Result<()> { self.base.async_snapshot(ctx, cb) } fn async_write(&self, ctx: &Context, batch: WriteData, write_cb: Callback<()>) -> Result<()> { self.async_write_ext(ctx, batch, write_cb, None, None) } fn async_write_ext( &self, ctx: &Context, batch: WriteData, write_cb: Callback<()>, proposed_cb: Option<ExtCallback>, committed_cb: Option<ExtCallback>, ) -> Result<()> { let mut expected_writes = self.expected_modifies.0.lock().unwrap(); for modify in batch.modifies.iter() { if let Some(expected_write) = expected_writes.pop_front() { // check whether the modify is expected if let Some(expected_modify) = expected_write.modify { assert_eq!( modify, &expected_modify, "modify writing to Engine not match with expected" ) } // check whether use right callback match expected_write.use_proposed_cb { Some(true) => assert!( proposed_cb.is_some(), "this write is supposed to return during the propose stage" ), Some(false) => assert!( proposed_cb.is_none(), "this write is not supposed to return during the propose stage" ), None => {} } match expected_write.use_committed_cb { Some(true) => assert!( committed_cb.is_some(), "this write is supposed to return during the commit stage" ), Some(false) => assert!( committed_cb.is_none(), "this write is not supposed to return during the commit stage" ), None => {} } } else { panic!("unexpected modify {:?} wrote to the Engine", modify) } } drop(expected_writes); self.base .async_write_ext(ctx, batch, write_cb, proposed_cb, committed_cb) } } pub struct MockEngineBuilder { base: RocksEngine, expected_modifies: LinkedList<ExpectedWrite>, } impl MockEngineBuilder { pub fn from_rocks_engine(rocks_engine: RocksEngine) -> Self { Self { base: rocks_engine, expected_modifies: LinkedList::new(), } } pub fn add_expected_write(mut self, write: ExpectedWrite) -> Self { self.expected_modifies.push_back(write); self } pub fn build(self) -> MockEngine { MockEngine { base: self.base, expected_modifies: Arc::new(ExpectedWriteList(Mutex::new(self.expected_modifies))), } } }
kv_engine
identifier_name
mock_engine.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; use crate::storage::kv::{Callback, ExtCallback, Modify, SnapContext, WriteData}; use crate::storage::{Engine, RocksEngine}; use kvproto::kvrpcpb::Context; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; /// A mock engine is a simple wrapper around RocksEngine /// but with the ability to assert the modifies, /// the callback used, and other aspects during interaction with the engine #[derive(Clone)] pub struct MockEngine { base: RocksEngine, expected_modifies: Arc<ExpectedWriteList>, } #[derive(Debug, Clone, Default, PartialEq)] pub struct ExpectedWrite { // if the following `Option`s are None, it means we just don't care modify: Option<Modify>, use_proposed_cb: Option<bool>, use_committed_cb: Option<bool>, } impl ExpectedWrite { pub fn new() -> Self { Default::default() } pub fn expect_modify(self, modify: Modify) -> Self { Self { modify: Some(modify), use_proposed_cb: self.use_proposed_cb, use_committed_cb: self.use_committed_cb, } } pub fn expect_proposed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: Some(true), use_committed_cb: self.use_committed_cb, } } pub fn expect_no_proposed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: Some(false), use_committed_cb: self.use_committed_cb, } } pub fn expect_committed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: self.use_proposed_cb, use_committed_cb: Some(true), } } pub fn expect_no_committed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: self.use_proposed_cb, use_committed_cb: Some(false), } } } /// `ExpectedWriteList` represents a list of writes expected to write to the engine struct ExpectedWriteList(Mutex<LinkedList<ExpectedWrite>>); // We implement drop here instead of on MockEngine // because `MockEngine` can be cloned and dropped everywhere // and we just want to assert every write impl Drop for ExpectedWriteList { fn drop(&mut self) { let expected_modifies = &mut *self.0.lock().unwrap(); assert_eq!( expected_modifies.len(), 0, "not all expected modifies have been written to the engine, {} rest", expected_modifies.len() ) } } impl Engine for MockEngine { type Snap = <RocksEngine as Engine>::Snap; type Local = <RocksEngine as Engine>::Local; fn kv_engine(&self) -> Self::Local { self.base.kv_engine() } fn snapshot_on_kv_engine(&self, start_key: &[u8], end_key: &[u8]) -> Result<Self::Snap> { self.base.snapshot_on_kv_engine(start_key, end_key) } fn modify_on_kv_engine(&self, modifies: Vec<Modify>) -> Result<()> { self.base.modify_on_kv_engine(modifies) } fn async_snapshot(&self, ctx: SnapContext<'_>, cb: Callback<Self::Snap>) -> Result<()> { self.base.async_snapshot(ctx, cb) } fn async_write(&self, ctx: &Context, batch: WriteData, write_cb: Callback<()>) -> Result<()> { self.async_write_ext(ctx, batch, write_cb, None, None) } fn async_write_ext( &self, ctx: &Context, batch: WriteData, write_cb: Callback<()>, proposed_cb: Option<ExtCallback>, committed_cb: Option<ExtCallback>, ) -> Result<()> { let mut expected_writes = self.expected_modifies.0.lock().unwrap(); for modify in batch.modifies.iter() { if let Some(expected_write) = expected_writes.pop_front() { // check whether the modify is expected if let Some(expected_modify) = expected_write.modify { assert_eq!( modify, &expected_modify, "modify writing to Engine not match with expected" ) } // check whether use right callback match expected_write.use_proposed_cb { Some(true) => assert!( proposed_cb.is_some(), "this write is supposed to return during the propose stage" ), Some(false) => assert!( proposed_cb.is_none(), "this write is not supposed to return during the propose stage" ), None => {} } match expected_write.use_committed_cb { Some(true) => assert!( committed_cb.is_some(), "this write is supposed to return during the commit stage" ), Some(false) => assert!( committed_cb.is_none(), "this write is not supposed to return during the commit stage" ), None => {} } } else { panic!("unexpected modify {:?} wrote to the Engine", modify) } } drop(expected_writes); self.base .async_write_ext(ctx, batch, write_cb, proposed_cb, committed_cb) } } pub struct MockEngineBuilder { base: RocksEngine, expected_modifies: LinkedList<ExpectedWrite>, } impl MockEngineBuilder { pub fn from_rocks_engine(rocks_engine: RocksEngine) -> Self { Self { base: rocks_engine, expected_modifies: LinkedList::new(), }
pub fn add_expected_write(mut self, write: ExpectedWrite) -> Self { self.expected_modifies.push_back(write); self } pub fn build(self) -> MockEngine { MockEngine { base: self.base, expected_modifies: Arc::new(ExpectedWriteList(Mutex::new(self.expected_modifies))), } } }
}
random_line_split
mock_engine.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; use crate::storage::kv::{Callback, ExtCallback, Modify, SnapContext, WriteData}; use crate::storage::{Engine, RocksEngine}; use kvproto::kvrpcpb::Context; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; /// A mock engine is a simple wrapper around RocksEngine /// but with the ability to assert the modifies, /// the callback used, and other aspects during interaction with the engine #[derive(Clone)] pub struct MockEngine { base: RocksEngine, expected_modifies: Arc<ExpectedWriteList>, } #[derive(Debug, Clone, Default, PartialEq)] pub struct ExpectedWrite { // if the following `Option`s are None, it means we just don't care modify: Option<Modify>, use_proposed_cb: Option<bool>, use_committed_cb: Option<bool>, } impl ExpectedWrite { pub fn new() -> Self { Default::default() } pub fn expect_modify(self, modify: Modify) -> Self { Self { modify: Some(modify), use_proposed_cb: self.use_proposed_cb, use_committed_cb: self.use_committed_cb, } } pub fn expect_proposed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: Some(true), use_committed_cb: self.use_committed_cb, } } pub fn expect_no_proposed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: Some(false), use_committed_cb: self.use_committed_cb, } } pub fn expect_committed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: self.use_proposed_cb, use_committed_cb: Some(true), } } pub fn expect_no_committed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: self.use_proposed_cb, use_committed_cb: Some(false), } } } /// `ExpectedWriteList` represents a list of writes expected to write to the engine struct ExpectedWriteList(Mutex<LinkedList<ExpectedWrite>>); // We implement drop here instead of on MockEngine // because `MockEngine` can be cloned and dropped everywhere // and we just want to assert every write impl Drop for ExpectedWriteList { fn drop(&mut self) { let expected_modifies = &mut *self.0.lock().unwrap(); assert_eq!( expected_modifies.len(), 0, "not all expected modifies have been written to the engine, {} rest", expected_modifies.len() ) } } impl Engine for MockEngine { type Snap = <RocksEngine as Engine>::Snap; type Local = <RocksEngine as Engine>::Local; fn kv_engine(&self) -> Self::Local { self.base.kv_engine() } fn snapshot_on_kv_engine(&self, start_key: &[u8], end_key: &[u8]) -> Result<Self::Snap> { self.base.snapshot_on_kv_engine(start_key, end_key) } fn modify_on_kv_engine(&self, modifies: Vec<Modify>) -> Result<()> { self.base.modify_on_kv_engine(modifies) } fn async_snapshot(&self, ctx: SnapContext<'_>, cb: Callback<Self::Snap>) -> Result<()> { self.base.async_snapshot(ctx, cb) } fn async_write(&self, ctx: &Context, batch: WriteData, write_cb: Callback<()>) -> Result<()> { self.async_write_ext(ctx, batch, write_cb, None, None) } fn async_write_ext( &self, ctx: &Context, batch: WriteData, write_cb: Callback<()>, proposed_cb: Option<ExtCallback>, committed_cb: Option<ExtCallback>, ) -> Result<()> { let mut expected_writes = self.expected_modifies.0.lock().unwrap(); for modify in batch.modifies.iter() { if let Some(expected_write) = expected_writes.pop_front() { // check whether the modify is expected if let Some(expected_modify) = expected_write.modify
// check whether use right callback match expected_write.use_proposed_cb { Some(true) => assert!( proposed_cb.is_some(), "this write is supposed to return during the propose stage" ), Some(false) => assert!( proposed_cb.is_none(), "this write is not supposed to return during the propose stage" ), None => {} } match expected_write.use_committed_cb { Some(true) => assert!( committed_cb.is_some(), "this write is supposed to return during the commit stage" ), Some(false) => assert!( committed_cb.is_none(), "this write is not supposed to return during the commit stage" ), None => {} } } else { panic!("unexpected modify {:?} wrote to the Engine", modify) } } drop(expected_writes); self.base .async_write_ext(ctx, batch, write_cb, proposed_cb, committed_cb) } } pub struct MockEngineBuilder { base: RocksEngine, expected_modifies: LinkedList<ExpectedWrite>, } impl MockEngineBuilder { pub fn from_rocks_engine(rocks_engine: RocksEngine) -> Self { Self { base: rocks_engine, expected_modifies: LinkedList::new(), } } pub fn add_expected_write(mut self, write: ExpectedWrite) -> Self { self.expected_modifies.push_back(write); self } pub fn build(self) -> MockEngine { MockEngine { base: self.base, expected_modifies: Arc::new(ExpectedWriteList(Mutex::new(self.expected_modifies))), } } }
{ assert_eq!( modify, &expected_modify, "modify writing to Engine not match with expected" ) }
conditional_block
mock_engine.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; use crate::storage::kv::{Callback, ExtCallback, Modify, SnapContext, WriteData}; use crate::storage::{Engine, RocksEngine}; use kvproto::kvrpcpb::Context; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; /// A mock engine is a simple wrapper around RocksEngine /// but with the ability to assert the modifies, /// the callback used, and other aspects during interaction with the engine #[derive(Clone)] pub struct MockEngine { base: RocksEngine, expected_modifies: Arc<ExpectedWriteList>, } #[derive(Debug, Clone, Default, PartialEq)] pub struct ExpectedWrite { // if the following `Option`s are None, it means we just don't care modify: Option<Modify>, use_proposed_cb: Option<bool>, use_committed_cb: Option<bool>, } impl ExpectedWrite { pub fn new() -> Self { Default::default() } pub fn expect_modify(self, modify: Modify) -> Self { Self { modify: Some(modify), use_proposed_cb: self.use_proposed_cb, use_committed_cb: self.use_committed_cb, } } pub fn expect_proposed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: Some(true), use_committed_cb: self.use_committed_cb, } } pub fn expect_no_proposed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: Some(false), use_committed_cb: self.use_committed_cb, } } pub fn expect_committed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: self.use_proposed_cb, use_committed_cb: Some(true), } } pub fn expect_no_committed_cb(self) -> Self { Self { modify: self.modify, use_proposed_cb: self.use_proposed_cb, use_committed_cb: Some(false), } } } /// `ExpectedWriteList` represents a list of writes expected to write to the engine struct ExpectedWriteList(Mutex<LinkedList<ExpectedWrite>>); // We implement drop here instead of on MockEngine // because `MockEngine` can be cloned and dropped everywhere // and we just want to assert every write impl Drop for ExpectedWriteList { fn drop(&mut self) { let expected_modifies = &mut *self.0.lock().unwrap(); assert_eq!( expected_modifies.len(), 0, "not all expected modifies have been written to the engine, {} rest", expected_modifies.len() ) } } impl Engine for MockEngine { type Snap = <RocksEngine as Engine>::Snap; type Local = <RocksEngine as Engine>::Local; fn kv_engine(&self) -> Self::Local { self.base.kv_engine() } fn snapshot_on_kv_engine(&self, start_key: &[u8], end_key: &[u8]) -> Result<Self::Snap> { self.base.snapshot_on_kv_engine(start_key, end_key) } fn modify_on_kv_engine(&self, modifies: Vec<Modify>) -> Result<()> { self.base.modify_on_kv_engine(modifies) } fn async_snapshot(&self, ctx: SnapContext<'_>, cb: Callback<Self::Snap>) -> Result<()> { self.base.async_snapshot(ctx, cb) } fn async_write(&self, ctx: &Context, batch: WriteData, write_cb: Callback<()>) -> Result<()>
fn async_write_ext( &self, ctx: &Context, batch: WriteData, write_cb: Callback<()>, proposed_cb: Option<ExtCallback>, committed_cb: Option<ExtCallback>, ) -> Result<()> { let mut expected_writes = self.expected_modifies.0.lock().unwrap(); for modify in batch.modifies.iter() { if let Some(expected_write) = expected_writes.pop_front() { // check whether the modify is expected if let Some(expected_modify) = expected_write.modify { assert_eq!( modify, &expected_modify, "modify writing to Engine not match with expected" ) } // check whether use right callback match expected_write.use_proposed_cb { Some(true) => assert!( proposed_cb.is_some(), "this write is supposed to return during the propose stage" ), Some(false) => assert!( proposed_cb.is_none(), "this write is not supposed to return during the propose stage" ), None => {} } match expected_write.use_committed_cb { Some(true) => assert!( committed_cb.is_some(), "this write is supposed to return during the commit stage" ), Some(false) => assert!( committed_cb.is_none(), "this write is not supposed to return during the commit stage" ), None => {} } } else { panic!("unexpected modify {:?} wrote to the Engine", modify) } } drop(expected_writes); self.base .async_write_ext(ctx, batch, write_cb, proposed_cb, committed_cb) } } pub struct MockEngineBuilder { base: RocksEngine, expected_modifies: LinkedList<ExpectedWrite>, } impl MockEngineBuilder { pub fn from_rocks_engine(rocks_engine: RocksEngine) -> Self { Self { base: rocks_engine, expected_modifies: LinkedList::new(), } } pub fn add_expected_write(mut self, write: ExpectedWrite) -> Self { self.expected_modifies.push_back(write); self } pub fn build(self) -> MockEngine { MockEngine { base: self.base, expected_modifies: Arc::new(ExpectedWriteList(Mutex::new(self.expected_modifies))), } } }
{ self.async_write_ext(ctx, batch, write_cb, None, None) }
identifier_body
mtwt.rs
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. //! Machinery for hygienic macros, as described in the MTWT[1] paper. //! //! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler. //! 2012. *Macros that work together: Compile-time bindings, partial expansion, //! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216. //! DOI=10.1017/S0956796812000093 http://dx.doi.org/10.1017/S0956796812000093 use ast::{Ident, Mrk, Name, SyntaxContext}; use std::cell::RefCell; use std::rc::Rc; use collections::HashMap; // the SCTable contains a table of SyntaxContext_'s. It // represents a flattened tree structure, to avoid having // managed pointers everywhere (that caused an ICE). // the mark_memo and rename_memo fields are side-tables // that ensure that adding the same mark to the same context // gives you back the same context as before. This shouldn't // change the semantics--everything here is immutable--but // it should cut down on memory use *a lot*; applying a mark // to a tree containing 50 identifiers would otherwise generate pub struct SCTable { table: RefCell<Vec<SyntaxContext_>>, mark_memo: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>, rename_memo: RefCell<HashMap<(SyntaxContext,Ident,Name),SyntaxContext>>, } #[deriving(Eq, Encodable, Decodable, Hash)] pub enum SyntaxContext_ { EmptyCtxt, Mark (Mrk,SyntaxContext), // flattening the name and syntaxcontext into the rename... // HIDDEN INVARIANTS: // 1) the first name in a Rename node // can only be a programmer-supplied name. // 2) Every Rename node with a given Name in the // "to" slot must have the same name and context // in the "from" slot. In essence, they're all // pointers to a single "rename" event node. Rename (Ident,Name,SyntaxContext), // actually, IllegalCtxt may not be necessary. IllegalCtxt } /// Extend a syntax context with a given mark pub fn new_mark(m: Mrk, tail: SyntaxContext) -> SyntaxContext { with_sctable(|table| new_mark_internal(m, tail, table)) } // Extend a syntax context with a given mark and table fn new_mark_internal(m: Mrk, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (tail, m); let new_ctxt = |_: &(SyntaxContext, Mrk)| idx_push(&mut *table.table.borrow_mut(), Mark(m, tail)); *table.mark_memo.borrow_mut().find_or_insert_with(key, new_ctxt) } /// Extend a syntax context with a given rename pub fn new_rename(id: Ident, to:Name, tail: SyntaxContext) -> SyntaxContext { with_sctable(|table| new_rename_internal(id, to, tail, table)) } // Extend a syntax context with a given rename and sctable fn new_rename_internal(id: Ident, to: Name, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (tail,id,to); let new_ctxt = |_: &(SyntaxContext, Ident, Mrk)| idx_push(&mut *table.table.borrow_mut(), Rename(id, to, tail)); *table.rename_memo.borrow_mut().find_or_insert_with(key, new_ctxt) } /// Fetch the SCTable from TLS, create one if it doesn't yet exist. pub fn with_sctable<T>(op: |&SCTable| -> T) -> T { local_data_key!(sctable_key: Rc<SCTable>) match sctable_key.get() { Some(ts) => op(&**ts), None => { let ts = Rc::new(new_sctable_internal()); sctable_key.replace(Some(ts.clone())); op(&*ts) } } } // Make a fresh syntax context table with EmptyCtxt in slot zero // and IllegalCtxt in slot one. fn new_sctable_internal() -> SCTable { SCTable { table: RefCell::new(vec!(EmptyCtxt, IllegalCtxt)), mark_memo: RefCell::new(HashMap::new()), rename_memo: RefCell::new(HashMap::new()), } } /// Print out an SCTable for debugging pub fn display_sctable(table: &SCTable) { error!("SC table:"); for (idx,val) in table.table.borrow().iter().enumerate() { error!("{:4u} : {:?}",idx,val); } } /// Clear the tables from TLD to reclaim memory. pub fn clear_tables() { with_sctable(|table| { *table.table.borrow_mut() = Vec::new(); *table.mark_memo.borrow_mut() = HashMap::new(); *table.rename_memo.borrow_mut() = HashMap::new(); }); with_resolve_table_mut(|table| *table = HashMap::new()); } // Add a value to the end of a vec, return its index fn idx_push<T>(vec: &mut Vec<T>, val: T) -> u32 { vec.push(val); (vec.len() - 1) as u32 } /// Resolve a syntax object to a name, per MTWT. pub fn resolve(id: Ident) -> Name { with_sctable(|sctable| { with_resolve_table_mut(|resolve_table| { resolve_internal(id, sctable, resolve_table) }) }) } type ResolveTable = HashMap<(Name,SyntaxContext),Name>; // okay, I admit, putting this in TLS is not so nice: // fetch the SCTable from TLS, create one if it doesn't yet exist. fn with_resolve_table_mut<T>(op: |&mut ResolveTable| -> T) -> T { local_data_key!(resolve_table_key: Rc<RefCell<ResolveTable>>) match resolve_table_key.get() { Some(ts) => op(&mut *ts.borrow_mut()), None => { let ts = Rc::new(RefCell::new(HashMap::new())); resolve_table_key.replace(Some(ts.clone())); op(&mut *ts.borrow_mut()) } } } // Resolve a syntax object to a name, per MTWT. // adding memorization to possibly resolve 500+ seconds in resolve for librustc (!) fn resolve_internal(id: Ident, table: &SCTable, resolve_table: &mut ResolveTable) -> Name { let key = (id.name, id.ctxt); match resolve_table.find(&key) { Some(&name) => return name, None => {} } let resolved = { let result = *table.table.borrow().get(id.ctxt as uint); match result { EmptyCtxt => id.name, // ignore marks here: Mark(_,subctxt) => resolve_internal(Ident{name:id.name, ctxt: subctxt}, table, resolve_table), // do the rename if necessary: Rename(Ident{name, ctxt}, toname, subctxt) => { let resolvedfrom = resolve_internal(Ident{name:name, ctxt:ctxt}, table, resolve_table); let resolvedthis = resolve_internal(Ident{name:id.name, ctxt:subctxt}, table, resolve_table); if (resolvedthis == resolvedfrom) && (marksof_internal(ctxt, resolvedthis, table) == marksof_internal(subctxt, resolvedthis, table)) { toname } else { resolvedthis } } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } }; resolve_table.insert(key, resolved); resolved } /// Compute the marks associated with a syntax context. pub fn marksof(ctxt: SyntaxContext, stopname: Name) -> Vec<Mrk> { with_sctable(|table| marksof_internal(ctxt, stopname, table)) } // the internal function for computing marks // it's not clear to me whether it's better to use a [] mutable // vector or a cons-list for this. fn marksof_internal(ctxt: SyntaxContext, stopname: Name, table: &SCTable) -> Vec<Mrk> { let mut result = Vec::new(); let mut loopvar = ctxt; loop { let table_entry = *table.table.borrow().get(loopvar as uint); match table_entry { EmptyCtxt => { return result; }, Mark(mark, tl) => { xorPush(&mut result, mark); loopvar = tl; }, Rename(_,name,tl) => { // see MTWT for details on the purpose of the stopname. // short version: it prevents duplication of effort. if name == stopname { return result; } else { loopvar = tl; } } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } } } /// Return the outer mark for a context with a mark at the outside. /// FAILS when outside is not a mark. pub fn outer_mark(ctxt: SyntaxContext) -> Mrk { with_sctable(|sctable| { match *sctable.table.borrow().get(ctxt as uint) { Mark(mrk, _) => mrk, _ => fail!("can't retrieve outer mark when outside is not a mark") } }) } // Push a name... unless it matches the one on top, in which // case pop and discard (so two of the same marks cancel) fn xorPush(marks: &mut Vec<Mrk>, mark: Mrk) { if (marks.len() > 0) && (*marks.last().unwrap() == mark) { marks.pop().unwrap(); } else { marks.push(mark); } } #[cfg(test)] mod tests { use ast::*; use super::{resolve, xorPush, new_mark_internal, new_sctable_internal}; use super::{new_rename_internal, marksof_internal, resolve_internal}; use super::{SCTable, EmptyCtxt, Mark, Rename, IllegalCtxt}; use collections::HashMap; #[test] fn xorpush_test () { let mut s = Vec::new(); xorPush(&mut s, 14); assert_eq!(s.clone(), vec!(14)); xorPush(&mut s, 14); assert_eq!(s.clone(), Vec::new()); xorPush(&mut s, 14); assert_eq!(s.clone(), vec!(14)); xorPush(&mut s, 15); assert_eq!(s.clone(), vec!(14, 15)); xorPush(&mut s, 16); assert_eq!(s.clone(), vec!(14, 15, 16)); xorPush(&mut s, 16); assert_eq!(s.clone(), vec!(14, 15)); xorPush(&mut s, 15); assert_eq!(s.clone(), vec!(14)); } fn id(n: Name, s: SyntaxContext) -> Ident { Ident {name: n, ctxt: s} } // because of the SCTable, I now need a tidy way of // creating syntax objects. Sigh. #[deriving(Clone, Eq, Show)] enum TestSC { M(Mrk), R(Ident,Name) } // unfold a vector of TestSC values into a SCTable, // returning the resulting index fn unfold_test_sc(tscs : Vec<TestSC>, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { tscs.iter().rev().fold(tail, |tail : SyntaxContext, tsc : &TestSC| {match *tsc { M(mrk) => new_mark_internal(mrk,tail,table), R(ident,name) => new_rename_internal(ident,name,tail,table)}}) } // gather a SyntaxContext back into a vector of TestSCs fn refold_test_sc(mut sc: SyntaxContext, table : &SCTable) -> Vec<TestSC> { let mut result = Vec::new(); loop { let table = table.table.borrow(); match *table.get(sc as uint) { EmptyCtxt => {return result;}, Mark(mrk,tail) => { result.push(M(mrk)); sc = tail; continue; }, Rename(id,name,tail) => { result.push(R(id,name)); sc = tail; continue; } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } } } #[test] fn test_unfold_refold(){ let mut t = new_sctable_internal(); let test_sc = vec!(M(3),R(id(101,0),14),M(9)); assert_eq!(unfold_test_sc(test_sc.clone(),EMPTY_CTXT,&mut t),4); { let table = t.table.borrow(); assert!(*table.get(2) == Mark(9,0)); assert!(*table.get(3) == Rename(id(101,0),14,2)); assert!(*table.get(4) == Mark(3,3)); } assert_eq!(refold_test_sc(4,&t),test_sc); }
fn unfold_marks(mrks: Vec<Mrk>, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { mrks.iter().rev().fold(tail, |tail:SyntaxContext, mrk:&Mrk| {new_mark_internal(*mrk,tail,table)}) } #[test] fn unfold_marks_test() { let mut t = new_sctable_internal(); assert_eq!(unfold_marks(vec!(3,7),EMPTY_CTXT,&mut t),3); { let table = t.table.borrow(); assert!(*table.get(2) == Mark(7,0)); assert!(*table.get(3) == Mark(3,2)); } } #[test] fn test_marksof () { let stopname = 242; let name1 = 243; let mut t = new_sctable_internal(); assert_eq!(marksof_internal (EMPTY_CTXT,stopname,&t),Vec::new()); // FIXME #5074: ANF'd to dodge nested calls { let ans = unfold_marks(vec!(4,98),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans,stopname,&t),vec!(4,98));} // does xoring work? { let ans = unfold_marks(vec!(5,5,16),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans,stopname,&t), vec!(16));} // does nested xoring work? { let ans = unfold_marks(vec!(5,10,10,5,16),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname,&t), vec!(16));} // rename where stop doesn't match: { let chain = vec!(M(9), R(id(name1, new_mark_internal (4, EMPTY_CTXT,&mut t)), 100101102), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname, &t), vec!(9,14));} // rename where stop does match { let name1sc = new_mark_internal(4, EMPTY_CTXT, &mut t); let chain = vec!(M(9), R(id(name1, name1sc), stopname), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname, &t), vec!(9)); } } #[test] fn resolve_tests () { let a = 40; let mut t = new_sctable_internal(); let mut rt = HashMap::new(); // - ctxt is MT assert_eq!(resolve_internal(id(a,EMPTY_CTXT),&mut t, &mut rt),a); // - simple ignored marks { let sc = unfold_marks(vec!(1,2,3),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),a);} // - orthogonal rename where names don't match { let sc = unfold_test_sc(vec!(R(id(50,EMPTY_CTXT),51),M(12)),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),a);} // - rename where names do match, but marks don't { let sc1 = new_mark_internal(1,EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50), M(1), M(2)), EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), a);} // - rename where names and marks match { let sc1 = unfold_test_sc(vec!(M(1),M(2)),EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50),M(1),M(2)),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 50); } // - rename where names and marks match by literal sharing { let sc1 = unfold_test_sc(vec!(M(1),M(2)),EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50)),sc1,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 50); } // - two renames of the same var.. can only happen if you use // local-expand to prevent the inner binding from being renamed // during the rename-pass caused by the first: println!("about to run bad test"); { let sc = unfold_test_sc(vec!(R(id(a,EMPTY_CTXT),50), R(id(a,EMPTY_CTXT),51)), EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 51); } // the simplest double-rename: { let a_to_a50 = new_rename_internal(id(a,EMPTY_CTXT),50,EMPTY_CTXT,&mut t); let a50_to_a51 = new_rename_internal(id(a,a_to_a50),51,a_to_a50,&mut t); assert_eq!(resolve_internal(id(a,a50_to_a51),&mut t, &mut rt),51); // mark on the outside doesn't stop rename: let sc = new_mark_internal(9,a50_to_a51,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),51); // but mark on the inside does: let a50_to_a51_b = unfold_test_sc(vec!(R(id(a,a_to_a50),51), M(9)), a_to_a50, &mut t); assert_eq!(resolve_internal(id(a,a50_to_a51_b),&mut t, &mut rt),50);} } #[test] fn mtwt_resolve_test(){ let a = 40; assert_eq!(resolve(id(a,EMPTY_CTXT)),a); } #[test] fn hashing_tests () { let mut t = new_sctable_internal(); assert_eq!(new_mark_internal(12,EMPTY_CTXT,&mut t),2); assert_eq!(new_mark_internal(13,EMPTY_CTXT,&mut t),3); // using the same one again should result in the same index: assert_eq!(new_mark_internal(12,EMPTY_CTXT,&mut t),2); // I'm assuming that the rename table will behave the same.... } #[test] fn resolve_table_hashing_tests() { let mut t = new_sctable_internal(); let
// extend a syntax context with a sequence of marks given // in a vector. v[0] will be the outermost mark.
random_line_split
mtwt.rs
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. //! Machinery for hygienic macros, as described in the MTWT[1] paper. //! //! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler. //! 2012. *Macros that work together: Compile-time bindings, partial expansion, //! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216. //! DOI=10.1017/S0956796812000093 http://dx.doi.org/10.1017/S0956796812000093 use ast::{Ident, Mrk, Name, SyntaxContext}; use std::cell::RefCell; use std::rc::Rc; use collections::HashMap; // the SCTable contains a table of SyntaxContext_'s. It // represents a flattened tree structure, to avoid having // managed pointers everywhere (that caused an ICE). // the mark_memo and rename_memo fields are side-tables // that ensure that adding the same mark to the same context // gives you back the same context as before. This shouldn't // change the semantics--everything here is immutable--but // it should cut down on memory use *a lot*; applying a mark // to a tree containing 50 identifiers would otherwise generate pub struct SCTable { table: RefCell<Vec<SyntaxContext_>>, mark_memo: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>, rename_memo: RefCell<HashMap<(SyntaxContext,Ident,Name),SyntaxContext>>, } #[deriving(Eq, Encodable, Decodable, Hash)] pub enum SyntaxContext_ { EmptyCtxt, Mark (Mrk,SyntaxContext), // flattening the name and syntaxcontext into the rename... // HIDDEN INVARIANTS: // 1) the first name in a Rename node // can only be a programmer-supplied name. // 2) Every Rename node with a given Name in the // "to" slot must have the same name and context // in the "from" slot. In essence, they're all // pointers to a single "rename" event node. Rename (Ident,Name,SyntaxContext), // actually, IllegalCtxt may not be necessary. IllegalCtxt } /// Extend a syntax context with a given mark pub fn new_mark(m: Mrk, tail: SyntaxContext) -> SyntaxContext { with_sctable(|table| new_mark_internal(m, tail, table)) } // Extend a syntax context with a given mark and table fn new_mark_internal(m: Mrk, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (tail, m); let new_ctxt = |_: &(SyntaxContext, Mrk)| idx_push(&mut *table.table.borrow_mut(), Mark(m, tail)); *table.mark_memo.borrow_mut().find_or_insert_with(key, new_ctxt) } /// Extend a syntax context with a given rename pub fn new_rename(id: Ident, to:Name, tail: SyntaxContext) -> SyntaxContext { with_sctable(|table| new_rename_internal(id, to, tail, table)) } // Extend a syntax context with a given rename and sctable fn new_rename_internal(id: Ident, to: Name, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (tail,id,to); let new_ctxt = |_: &(SyntaxContext, Ident, Mrk)| idx_push(&mut *table.table.borrow_mut(), Rename(id, to, tail)); *table.rename_memo.borrow_mut().find_or_insert_with(key, new_ctxt) } /// Fetch the SCTable from TLS, create one if it doesn't yet exist. pub fn with_sctable<T>(op: |&SCTable| -> T) -> T { local_data_key!(sctable_key: Rc<SCTable>) match sctable_key.get() { Some(ts) => op(&**ts), None => { let ts = Rc::new(new_sctable_internal()); sctable_key.replace(Some(ts.clone())); op(&*ts) } } } // Make a fresh syntax context table with EmptyCtxt in slot zero // and IllegalCtxt in slot one. fn new_sctable_internal() -> SCTable { SCTable { table: RefCell::new(vec!(EmptyCtxt, IllegalCtxt)), mark_memo: RefCell::new(HashMap::new()), rename_memo: RefCell::new(HashMap::new()), } } /// Print out an SCTable for debugging pub fn display_sctable(table: &SCTable) { error!("SC table:"); for (idx,val) in table.table.borrow().iter().enumerate() { error!("{:4u} : {:?}",idx,val); } } /// Clear the tables from TLD to reclaim memory. pub fn clear_tables() { with_sctable(|table| { *table.table.borrow_mut() = Vec::new(); *table.mark_memo.borrow_mut() = HashMap::new(); *table.rename_memo.borrow_mut() = HashMap::new(); }); with_resolve_table_mut(|table| *table = HashMap::new()); } // Add a value to the end of a vec, return its index fn idx_push<T>(vec: &mut Vec<T>, val: T) -> u32 { vec.push(val); (vec.len() - 1) as u32 } /// Resolve a syntax object to a name, per MTWT. pub fn resolve(id: Ident) -> Name { with_sctable(|sctable| { with_resolve_table_mut(|resolve_table| { resolve_internal(id, sctable, resolve_table) }) }) } type ResolveTable = HashMap<(Name,SyntaxContext),Name>; // okay, I admit, putting this in TLS is not so nice: // fetch the SCTable from TLS, create one if it doesn't yet exist. fn with_resolve_table_mut<T>(op: |&mut ResolveTable| -> T) -> T { local_data_key!(resolve_table_key: Rc<RefCell<ResolveTable>>) match resolve_table_key.get() { Some(ts) => op(&mut *ts.borrow_mut()), None => { let ts = Rc::new(RefCell::new(HashMap::new())); resolve_table_key.replace(Some(ts.clone())); op(&mut *ts.borrow_mut()) } } } // Resolve a syntax object to a name, per MTWT. // adding memorization to possibly resolve 500+ seconds in resolve for librustc (!) fn resolve_internal(id: Ident, table: &SCTable, resolve_table: &mut ResolveTable) -> Name { let key = (id.name, id.ctxt); match resolve_table.find(&key) { Some(&name) => return name, None => {} } let resolved = { let result = *table.table.borrow().get(id.ctxt as uint); match result { EmptyCtxt => id.name, // ignore marks here: Mark(_,subctxt) => resolve_internal(Ident{name:id.name, ctxt: subctxt}, table, resolve_table), // do the rename if necessary: Rename(Ident{name, ctxt}, toname, subctxt) => { let resolvedfrom = resolve_internal(Ident{name:name, ctxt:ctxt}, table, resolve_table); let resolvedthis = resolve_internal(Ident{name:id.name, ctxt:subctxt}, table, resolve_table); if (resolvedthis == resolvedfrom) && (marksof_internal(ctxt, resolvedthis, table) == marksof_internal(subctxt, resolvedthis, table)) { toname } else { resolvedthis } } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } }; resolve_table.insert(key, resolved); resolved } /// Compute the marks associated with a syntax context. pub fn marksof(ctxt: SyntaxContext, stopname: Name) -> Vec<Mrk> { with_sctable(|table| marksof_internal(ctxt, stopname, table)) } // the internal function for computing marks // it's not clear to me whether it's better to use a [] mutable // vector or a cons-list for this. fn marksof_internal(ctxt: SyntaxContext, stopname: Name, table: &SCTable) -> Vec<Mrk> { let mut result = Vec::new(); let mut loopvar = ctxt; loop { let table_entry = *table.table.borrow().get(loopvar as uint); match table_entry { EmptyCtxt => { return result; }, Mark(mark, tl) => { xorPush(&mut result, mark); loopvar = tl; }, Rename(_,name,tl) => { // see MTWT for details on the purpose of the stopname. // short version: it prevents duplication of effort. if name == stopname { return result; } else { loopvar = tl; } } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } } } /// Return the outer mark for a context with a mark at the outside. /// FAILS when outside is not a mark. pub fn outer_mark(ctxt: SyntaxContext) -> Mrk { with_sctable(|sctable| { match *sctable.table.borrow().get(ctxt as uint) { Mark(mrk, _) => mrk, _ => fail!("can't retrieve outer mark when outside is not a mark") } }) } // Push a name... unless it matches the one on top, in which // case pop and discard (so two of the same marks cancel) fn xorPush(marks: &mut Vec<Mrk>, mark: Mrk) { if (marks.len() > 0) && (*marks.last().unwrap() == mark)
else { marks.push(mark); } } #[cfg(test)] mod tests { use ast::*; use super::{resolve, xorPush, new_mark_internal, new_sctable_internal}; use super::{new_rename_internal, marksof_internal, resolve_internal}; use super::{SCTable, EmptyCtxt, Mark, Rename, IllegalCtxt}; use collections::HashMap; #[test] fn xorpush_test () { let mut s = Vec::new(); xorPush(&mut s, 14); assert_eq!(s.clone(), vec!(14)); xorPush(&mut s, 14); assert_eq!(s.clone(), Vec::new()); xorPush(&mut s, 14); assert_eq!(s.clone(), vec!(14)); xorPush(&mut s, 15); assert_eq!(s.clone(), vec!(14, 15)); xorPush(&mut s, 16); assert_eq!(s.clone(), vec!(14, 15, 16)); xorPush(&mut s, 16); assert_eq!(s.clone(), vec!(14, 15)); xorPush(&mut s, 15); assert_eq!(s.clone(), vec!(14)); } fn id(n: Name, s: SyntaxContext) -> Ident { Ident {name: n, ctxt: s} } // because of the SCTable, I now need a tidy way of // creating syntax objects. Sigh. #[deriving(Clone, Eq, Show)] enum TestSC { M(Mrk), R(Ident,Name) } // unfold a vector of TestSC values into a SCTable, // returning the resulting index fn unfold_test_sc(tscs : Vec<TestSC>, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { tscs.iter().rev().fold(tail, |tail : SyntaxContext, tsc : &TestSC| {match *tsc { M(mrk) => new_mark_internal(mrk,tail,table), R(ident,name) => new_rename_internal(ident,name,tail,table)}}) } // gather a SyntaxContext back into a vector of TestSCs fn refold_test_sc(mut sc: SyntaxContext, table : &SCTable) -> Vec<TestSC> { let mut result = Vec::new(); loop { let table = table.table.borrow(); match *table.get(sc as uint) { EmptyCtxt => {return result;}, Mark(mrk,tail) => { result.push(M(mrk)); sc = tail; continue; }, Rename(id,name,tail) => { result.push(R(id,name)); sc = tail; continue; } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } } } #[test] fn test_unfold_refold(){ let mut t = new_sctable_internal(); let test_sc = vec!(M(3),R(id(101,0),14),M(9)); assert_eq!(unfold_test_sc(test_sc.clone(),EMPTY_CTXT,&mut t),4); { let table = t.table.borrow(); assert!(*table.get(2) == Mark(9,0)); assert!(*table.get(3) == Rename(id(101,0),14,2)); assert!(*table.get(4) == Mark(3,3)); } assert_eq!(refold_test_sc(4,&t),test_sc); } // extend a syntax context with a sequence of marks given // in a vector. v[0] will be the outermost mark. fn unfold_marks(mrks: Vec<Mrk>, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { mrks.iter().rev().fold(tail, |tail:SyntaxContext, mrk:&Mrk| {new_mark_internal(*mrk,tail,table)}) } #[test] fn unfold_marks_test() { let mut t = new_sctable_internal(); assert_eq!(unfold_marks(vec!(3,7),EMPTY_CTXT,&mut t),3); { let table = t.table.borrow(); assert!(*table.get(2) == Mark(7,0)); assert!(*table.get(3) == Mark(3,2)); } } #[test] fn test_marksof () { let stopname = 242; let name1 = 243; let mut t = new_sctable_internal(); assert_eq!(marksof_internal (EMPTY_CTXT,stopname,&t),Vec::new()); // FIXME #5074: ANF'd to dodge nested calls { let ans = unfold_marks(vec!(4,98),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans,stopname,&t),vec!(4,98));} // does xoring work? { let ans = unfold_marks(vec!(5,5,16),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans,stopname,&t), vec!(16));} // does nested xoring work? { let ans = unfold_marks(vec!(5,10,10,5,16),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname,&t), vec!(16));} // rename where stop doesn't match: { let chain = vec!(M(9), R(id(name1, new_mark_internal (4, EMPTY_CTXT,&mut t)), 100101102), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname, &t), vec!(9,14));} // rename where stop does match { let name1sc = new_mark_internal(4, EMPTY_CTXT, &mut t); let chain = vec!(M(9), R(id(name1, name1sc), stopname), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname, &t), vec!(9)); } } #[test] fn resolve_tests () { let a = 40; let mut t = new_sctable_internal(); let mut rt = HashMap::new(); // - ctxt is MT assert_eq!(resolve_internal(id(a,EMPTY_CTXT),&mut t, &mut rt),a); // - simple ignored marks { let sc = unfold_marks(vec!(1,2,3),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),a);} // - orthogonal rename where names don't match { let sc = unfold_test_sc(vec!(R(id(50,EMPTY_CTXT),51),M(12)),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),a);} // - rename where names do match, but marks don't { let sc1 = new_mark_internal(1,EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50), M(1), M(2)), EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), a);} // - rename where names and marks match { let sc1 = unfold_test_sc(vec!(M(1),M(2)),EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50),M(1),M(2)),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 50); } // - rename where names and marks match by literal sharing { let sc1 = unfold_test_sc(vec!(M(1),M(2)),EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50)),sc1,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 50); } // - two renames of the same var.. can only happen if you use // local-expand to prevent the inner binding from being renamed // during the rename-pass caused by the first: println!("about to run bad test"); { let sc = unfold_test_sc(vec!(R(id(a,EMPTY_CTXT),50), R(id(a,EMPTY_CTXT),51)), EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 51); } // the simplest double-rename: { let a_to_a50 = new_rename_internal(id(a,EMPTY_CTXT),50,EMPTY_CTXT,&mut t); let a50_to_a51 = new_rename_internal(id(a,a_to_a50),51,a_to_a50,&mut t); assert_eq!(resolve_internal(id(a,a50_to_a51),&mut t, &mut rt),51); // mark on the outside doesn't stop rename: let sc = new_mark_internal(9,a50_to_a51,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),51); // but mark on the inside does: let a50_to_a51_b = unfold_test_sc(vec!(R(id(a,a_to_a50),51), M(9)), a_to_a50, &mut t); assert_eq!(resolve_internal(id(a,a50_to_a51_b),&mut t, &mut rt),50);} } #[test] fn mtwt_resolve_test(){ let a = 40; assert_eq!(resolve(id(a,EMPTY_CTXT)),a); } #[test] fn hashing_tests () { let mut t = new_sctable_internal(); assert_eq!(new_mark_internal(12,EMPTY_CTXT,&mut t),2); assert_eq!(new_mark_internal(13,EMPTY_CTXT,&mut t),3); // using the same one again should result in the same index: assert_eq!(new_mark_internal(12,EMPTY_CTXT,&mut t),2); // I'm assuming that the rename table will behave the same.... } #[test] fn resolve_table_hashing_tests() { let mut t = new_sctable_internal();
{ marks.pop().unwrap(); }
conditional_block
mtwt.rs
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. //! Machinery for hygienic macros, as described in the MTWT[1] paper. //! //! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler. //! 2012. *Macros that work together: Compile-time bindings, partial expansion, //! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216. //! DOI=10.1017/S0956796812000093 http://dx.doi.org/10.1017/S0956796812000093 use ast::{Ident, Mrk, Name, SyntaxContext}; use std::cell::RefCell; use std::rc::Rc; use collections::HashMap; // the SCTable contains a table of SyntaxContext_'s. It // represents a flattened tree structure, to avoid having // managed pointers everywhere (that caused an ICE). // the mark_memo and rename_memo fields are side-tables // that ensure that adding the same mark to the same context // gives you back the same context as before. This shouldn't // change the semantics--everything here is immutable--but // it should cut down on memory use *a lot*; applying a mark // to a tree containing 50 identifiers would otherwise generate pub struct SCTable { table: RefCell<Vec<SyntaxContext_>>, mark_memo: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>, rename_memo: RefCell<HashMap<(SyntaxContext,Ident,Name),SyntaxContext>>, } #[deriving(Eq, Encodable, Decodable, Hash)] pub enum SyntaxContext_ { EmptyCtxt, Mark (Mrk,SyntaxContext), // flattening the name and syntaxcontext into the rename... // HIDDEN INVARIANTS: // 1) the first name in a Rename node // can only be a programmer-supplied name. // 2) Every Rename node with a given Name in the // "to" slot must have the same name and context // in the "from" slot. In essence, they're all // pointers to a single "rename" event node. Rename (Ident,Name,SyntaxContext), // actually, IllegalCtxt may not be necessary. IllegalCtxt } /// Extend a syntax context with a given mark pub fn new_mark(m: Mrk, tail: SyntaxContext) -> SyntaxContext { with_sctable(|table| new_mark_internal(m, tail, table)) } // Extend a syntax context with a given mark and table fn new_mark_internal(m: Mrk, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (tail, m); let new_ctxt = |_: &(SyntaxContext, Mrk)| idx_push(&mut *table.table.borrow_mut(), Mark(m, tail)); *table.mark_memo.borrow_mut().find_or_insert_with(key, new_ctxt) } /// Extend a syntax context with a given rename pub fn new_rename(id: Ident, to:Name, tail: SyntaxContext) -> SyntaxContext { with_sctable(|table| new_rename_internal(id, to, tail, table)) } // Extend a syntax context with a given rename and sctable fn new_rename_internal(id: Ident, to: Name, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (tail,id,to); let new_ctxt = |_: &(SyntaxContext, Ident, Mrk)| idx_push(&mut *table.table.borrow_mut(), Rename(id, to, tail)); *table.rename_memo.borrow_mut().find_or_insert_with(key, new_ctxt) } /// Fetch the SCTable from TLS, create one if it doesn't yet exist. pub fn with_sctable<T>(op: |&SCTable| -> T) -> T { local_data_key!(sctable_key: Rc<SCTable>) match sctable_key.get() { Some(ts) => op(&**ts), None => { let ts = Rc::new(new_sctable_internal()); sctable_key.replace(Some(ts.clone())); op(&*ts) } } } // Make a fresh syntax context table with EmptyCtxt in slot zero // and IllegalCtxt in slot one. fn new_sctable_internal() -> SCTable { SCTable { table: RefCell::new(vec!(EmptyCtxt, IllegalCtxt)), mark_memo: RefCell::new(HashMap::new()), rename_memo: RefCell::new(HashMap::new()), } } /// Print out an SCTable for debugging pub fn display_sctable(table: &SCTable) { error!("SC table:"); for (idx,val) in table.table.borrow().iter().enumerate() { error!("{:4u} : {:?}",idx,val); } } /// Clear the tables from TLD to reclaim memory. pub fn clear_tables() { with_sctable(|table| { *table.table.borrow_mut() = Vec::new(); *table.mark_memo.borrow_mut() = HashMap::new(); *table.rename_memo.borrow_mut() = HashMap::new(); }); with_resolve_table_mut(|table| *table = HashMap::new()); } // Add a value to the end of a vec, return its index fn idx_push<T>(vec: &mut Vec<T>, val: T) -> u32 { vec.push(val); (vec.len() - 1) as u32 } /// Resolve a syntax object to a name, per MTWT. pub fn resolve(id: Ident) -> Name { with_sctable(|sctable| { with_resolve_table_mut(|resolve_table| { resolve_internal(id, sctable, resolve_table) }) }) } type ResolveTable = HashMap<(Name,SyntaxContext),Name>; // okay, I admit, putting this in TLS is not so nice: // fetch the SCTable from TLS, create one if it doesn't yet exist. fn with_resolve_table_mut<T>(op: |&mut ResolveTable| -> T) -> T { local_data_key!(resolve_table_key: Rc<RefCell<ResolveTable>>) match resolve_table_key.get() { Some(ts) => op(&mut *ts.borrow_mut()), None => { let ts = Rc::new(RefCell::new(HashMap::new())); resolve_table_key.replace(Some(ts.clone())); op(&mut *ts.borrow_mut()) } } } // Resolve a syntax object to a name, per MTWT. // adding memorization to possibly resolve 500+ seconds in resolve for librustc (!) fn resolve_internal(id: Ident, table: &SCTable, resolve_table: &mut ResolveTable) -> Name { let key = (id.name, id.ctxt); match resolve_table.find(&key) { Some(&name) => return name, None => {} } let resolved = { let result = *table.table.borrow().get(id.ctxt as uint); match result { EmptyCtxt => id.name, // ignore marks here: Mark(_,subctxt) => resolve_internal(Ident{name:id.name, ctxt: subctxt}, table, resolve_table), // do the rename if necessary: Rename(Ident{name, ctxt}, toname, subctxt) => { let resolvedfrom = resolve_internal(Ident{name:name, ctxt:ctxt}, table, resolve_table); let resolvedthis = resolve_internal(Ident{name:id.name, ctxt:subctxt}, table, resolve_table); if (resolvedthis == resolvedfrom) && (marksof_internal(ctxt, resolvedthis, table) == marksof_internal(subctxt, resolvedthis, table)) { toname } else { resolvedthis } } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } }; resolve_table.insert(key, resolved); resolved } /// Compute the marks associated with a syntax context. pub fn marksof(ctxt: SyntaxContext, stopname: Name) -> Vec<Mrk> { with_sctable(|table| marksof_internal(ctxt, stopname, table)) } // the internal function for computing marks // it's not clear to me whether it's better to use a [] mutable // vector or a cons-list for this. fn marksof_internal(ctxt: SyntaxContext, stopname: Name, table: &SCTable) -> Vec<Mrk> { let mut result = Vec::new(); let mut loopvar = ctxt; loop { let table_entry = *table.table.borrow().get(loopvar as uint); match table_entry { EmptyCtxt => { return result; }, Mark(mark, tl) => { xorPush(&mut result, mark); loopvar = tl; }, Rename(_,name,tl) => { // see MTWT for details on the purpose of the stopname. // short version: it prevents duplication of effort. if name == stopname { return result; } else { loopvar = tl; } } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } } } /// Return the outer mark for a context with a mark at the outside. /// FAILS when outside is not a mark. pub fn outer_mark(ctxt: SyntaxContext) -> Mrk { with_sctable(|sctable| { match *sctable.table.borrow().get(ctxt as uint) { Mark(mrk, _) => mrk, _ => fail!("can't retrieve outer mark when outside is not a mark") } }) } // Push a name... unless it matches the one on top, in which // case pop and discard (so two of the same marks cancel) fn xorPush(marks: &mut Vec<Mrk>, mark: Mrk) { if (marks.len() > 0) && (*marks.last().unwrap() == mark) { marks.pop().unwrap(); } else { marks.push(mark); } } #[cfg(test)] mod tests { use ast::*; use super::{resolve, xorPush, new_mark_internal, new_sctable_internal}; use super::{new_rename_internal, marksof_internal, resolve_internal}; use super::{SCTable, EmptyCtxt, Mark, Rename, IllegalCtxt}; use collections::HashMap; #[test] fn xorpush_test () { let mut s = Vec::new(); xorPush(&mut s, 14); assert_eq!(s.clone(), vec!(14)); xorPush(&mut s, 14); assert_eq!(s.clone(), Vec::new()); xorPush(&mut s, 14); assert_eq!(s.clone(), vec!(14)); xorPush(&mut s, 15); assert_eq!(s.clone(), vec!(14, 15)); xorPush(&mut s, 16); assert_eq!(s.clone(), vec!(14, 15, 16)); xorPush(&mut s, 16); assert_eq!(s.clone(), vec!(14, 15)); xorPush(&mut s, 15); assert_eq!(s.clone(), vec!(14)); } fn id(n: Name, s: SyntaxContext) -> Ident { Ident {name: n, ctxt: s} } // because of the SCTable, I now need a tidy way of // creating syntax objects. Sigh. #[deriving(Clone, Eq, Show)] enum TestSC { M(Mrk), R(Ident,Name) } // unfold a vector of TestSC values into a SCTable, // returning the resulting index fn unfold_test_sc(tscs : Vec<TestSC>, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { tscs.iter().rev().fold(tail, |tail : SyntaxContext, tsc : &TestSC| {match *tsc { M(mrk) => new_mark_internal(mrk,tail,table), R(ident,name) => new_rename_internal(ident,name,tail,table)}}) } // gather a SyntaxContext back into a vector of TestSCs fn refold_test_sc(mut sc: SyntaxContext, table : &SCTable) -> Vec<TestSC> { let mut result = Vec::new(); loop { let table = table.table.borrow(); match *table.get(sc as uint) { EmptyCtxt => {return result;}, Mark(mrk,tail) => { result.push(M(mrk)); sc = tail; continue; }, Rename(id,name,tail) => { result.push(R(id,name)); sc = tail; continue; } IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } } } #[test] fn test_unfold_refold(){ let mut t = new_sctable_internal(); let test_sc = vec!(M(3),R(id(101,0),14),M(9)); assert_eq!(unfold_test_sc(test_sc.clone(),EMPTY_CTXT,&mut t),4); { let table = t.table.borrow(); assert!(*table.get(2) == Mark(9,0)); assert!(*table.get(3) == Rename(id(101,0),14,2)); assert!(*table.get(4) == Mark(3,3)); } assert_eq!(refold_test_sc(4,&t),test_sc); } // extend a syntax context with a sequence of marks given // in a vector. v[0] will be the outermost mark. fn unfold_marks(mrks: Vec<Mrk>, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { mrks.iter().rev().fold(tail, |tail:SyntaxContext, mrk:&Mrk| {new_mark_internal(*mrk,tail,table)}) } #[test] fn unfold_marks_test() { let mut t = new_sctable_internal(); assert_eq!(unfold_marks(vec!(3,7),EMPTY_CTXT,&mut t),3); { let table = t.table.borrow(); assert!(*table.get(2) == Mark(7,0)); assert!(*table.get(3) == Mark(3,2)); } } #[test] fn
() { let stopname = 242; let name1 = 243; let mut t = new_sctable_internal(); assert_eq!(marksof_internal (EMPTY_CTXT,stopname,&t),Vec::new()); // FIXME #5074: ANF'd to dodge nested calls { let ans = unfold_marks(vec!(4,98),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans,stopname,&t),vec!(4,98));} // does xoring work? { let ans = unfold_marks(vec!(5,5,16),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans,stopname,&t), vec!(16));} // does nested xoring work? { let ans = unfold_marks(vec!(5,10,10,5,16),EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname,&t), vec!(16));} // rename where stop doesn't match: { let chain = vec!(M(9), R(id(name1, new_mark_internal (4, EMPTY_CTXT,&mut t)), 100101102), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname, &t), vec!(9,14));} // rename where stop does match { let name1sc = new_mark_internal(4, EMPTY_CTXT, &mut t); let chain = vec!(M(9), R(id(name1, name1sc), stopname), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname, &t), vec!(9)); } } #[test] fn resolve_tests () { let a = 40; let mut t = new_sctable_internal(); let mut rt = HashMap::new(); // - ctxt is MT assert_eq!(resolve_internal(id(a,EMPTY_CTXT),&mut t, &mut rt),a); // - simple ignored marks { let sc = unfold_marks(vec!(1,2,3),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),a);} // - orthogonal rename where names don't match { let sc = unfold_test_sc(vec!(R(id(50,EMPTY_CTXT),51),M(12)),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),a);} // - rename where names do match, but marks don't { let sc1 = new_mark_internal(1,EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50), M(1), M(2)), EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), a);} // - rename where names and marks match { let sc1 = unfold_test_sc(vec!(M(1),M(2)),EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50),M(1),M(2)),EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 50); } // - rename where names and marks match by literal sharing { let sc1 = unfold_test_sc(vec!(M(1),M(2)),EMPTY_CTXT,&mut t); let sc = unfold_test_sc(vec!(R(id(a,sc1),50)),sc1,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 50); } // - two renames of the same var.. can only happen if you use // local-expand to prevent the inner binding from being renamed // during the rename-pass caused by the first: println!("about to run bad test"); { let sc = unfold_test_sc(vec!(R(id(a,EMPTY_CTXT),50), R(id(a,EMPTY_CTXT),51)), EMPTY_CTXT,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 51); } // the simplest double-rename: { let a_to_a50 = new_rename_internal(id(a,EMPTY_CTXT),50,EMPTY_CTXT,&mut t); let a50_to_a51 = new_rename_internal(id(a,a_to_a50),51,a_to_a50,&mut t); assert_eq!(resolve_internal(id(a,a50_to_a51),&mut t, &mut rt),51); // mark on the outside doesn't stop rename: let sc = new_mark_internal(9,a50_to_a51,&mut t); assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),51); // but mark on the inside does: let a50_to_a51_b = unfold_test_sc(vec!(R(id(a,a_to_a50),51), M(9)), a_to_a50, &mut t); assert_eq!(resolve_internal(id(a,a50_to_a51_b),&mut t, &mut rt),50);} } #[test] fn mtwt_resolve_test(){ let a = 40; assert_eq!(resolve(id(a,EMPTY_CTXT)),a); } #[test] fn hashing_tests () { let mut t = new_sctable_internal(); assert_eq!(new_mark_internal(12,EMPTY_CTXT,&mut t),2); assert_eq!(new_mark_internal(13,EMPTY_CTXT,&mut t),3); // using the same one again should result in the same index: assert_eq!(new_mark_internal(12,EMPTY_CTXT,&mut t),2); // I'm assuming that the rename table will behave the same.... } #[test] fn resolve_table_hashing_tests() { let mut t = new_sctable_internal();
test_marksof
identifier_name
auth.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{sleep_with_handle, FailReasonExt, GMsg, RequestExt, Route, SessionExt}; use futures::channel::oneshot; use iml_wire_types::{EndpointName, Session}; use regex::Regex; use seed::{browser::service::fetch, prelude::*, *}; use std::time::Duration; use wasm_bindgen::JsValue; use web_sys::HtmlDocument; #[derive(Default)] pub struct Model { session: Option<Session>, request_controller: Option<fetch::RequestController>, cancel: Option<oneshot::Sender<()>>, } impl Model { pub(crate) fn get_session(&self) -> Option<&Session> { self.session.as_ref() } } #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug)] pub enum Msg { Fetch, Fetched(fetch::FetchObject<Session>), Logout, LoggedIn, Loop, Noop, } pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) { match msg { Msg::Fetch => { model.cancel = None; let request = fetch_session().controller(|controller| model.request_controller = Some(controller)); orders.skip().perform_cmd(request.fetch_json(Msg::Fetched)); } Msg::Fetched(data) => { match data.response() { Err(fail_reason) => { log!(format!("Error during session poll: {}", fail_reason.message())); orders.skip().send_msg(Msg::Loop); } Ok(resp) => { model.session = Some(resp.data); if model.session.as_ref().unwrap().needs_login() { orders.send_g_msg(GMsg::RouteChange(Route::Login.into())); } else { orders.send_msg(Msg::Loop); } resp.raw .headers() .get("date") .map_err(|j| error!(j)) .ok() .flatten() .and_then(|h| { chrono::DateTime::parse_from_rfc2822(&h) .map_err(|e| error!(e)) .map(|dt| orders.send_g_msg(GMsg::ServerDate(dt))) .ok() }); } }; } Msg::LoggedIn => { orders.skip(); orders.send_msg(Msg::Fetch); orders.send_g_msg(GMsg::RouteChange(Route::Dashboard.into())); } Msg::Logout => { orders.perform_g_cmd( fetch_session() .method(fetch::Method::Delete) .fetch(|_| GMsg::AuthProxy(Box::new(Msg::LoggedIn))), ); } Msg::Loop => { orders.skip(); let (cancel, fut) = sleep_with_handle(Duration::from_secs(10), Msg::Fetch, Msg::Noop); model.cancel = Some(cancel); orders.perform_cmd(fut); } Msg::Noop => {} }; } pub(crate) fn fetch_session() -> fetch::Request { fetch::Request::api_call(Session::endpoint_name()).with_auth() } /// Returns the CSRF token if one exists within the cookie. pub(crate) fn
() -> Option<String> { let html_doc: HtmlDocument = HtmlDocument::from(JsValue::from(document())); let cookie = html_doc.cookie().unwrap(); parse_cookie(&cookie) } /// Parses the CSRF token out of the cookie if one exists. fn parse_cookie(cookie: &str) -> Option<String> { let re = Regex::new(r"csrftoken=([^;|$]+)").unwrap(); let x = re.captures(cookie)?; x.get(1).map(|x| x.as_str().to_string()) }
csrf_token
identifier_name
auth.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{sleep_with_handle, FailReasonExt, GMsg, RequestExt, Route, SessionExt}; use futures::channel::oneshot; use iml_wire_types::{EndpointName, Session}; use regex::Regex; use seed::{browser::service::fetch, prelude::*, *}; use std::time::Duration; use wasm_bindgen::JsValue; use web_sys::HtmlDocument; #[derive(Default)] pub struct Model { session: Option<Session>, request_controller: Option<fetch::RequestController>, cancel: Option<oneshot::Sender<()>>, } impl Model {
#[allow(clippy::large_enum_variant)] #[derive(Clone, Debug)] pub enum Msg { Fetch, Fetched(fetch::FetchObject<Session>), Logout, LoggedIn, Loop, Noop, } pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) { match msg { Msg::Fetch => { model.cancel = None; let request = fetch_session().controller(|controller| model.request_controller = Some(controller)); orders.skip().perform_cmd(request.fetch_json(Msg::Fetched)); } Msg::Fetched(data) => { match data.response() { Err(fail_reason) => { log!(format!("Error during session poll: {}", fail_reason.message())); orders.skip().send_msg(Msg::Loop); } Ok(resp) => { model.session = Some(resp.data); if model.session.as_ref().unwrap().needs_login() { orders.send_g_msg(GMsg::RouteChange(Route::Login.into())); } else { orders.send_msg(Msg::Loop); } resp.raw .headers() .get("date") .map_err(|j| error!(j)) .ok() .flatten() .and_then(|h| { chrono::DateTime::parse_from_rfc2822(&h) .map_err(|e| error!(e)) .map(|dt| orders.send_g_msg(GMsg::ServerDate(dt))) .ok() }); } }; } Msg::LoggedIn => { orders.skip(); orders.send_msg(Msg::Fetch); orders.send_g_msg(GMsg::RouteChange(Route::Dashboard.into())); } Msg::Logout => { orders.perform_g_cmd( fetch_session() .method(fetch::Method::Delete) .fetch(|_| GMsg::AuthProxy(Box::new(Msg::LoggedIn))), ); } Msg::Loop => { orders.skip(); let (cancel, fut) = sleep_with_handle(Duration::from_secs(10), Msg::Fetch, Msg::Noop); model.cancel = Some(cancel); orders.perform_cmd(fut); } Msg::Noop => {} }; } pub(crate) fn fetch_session() -> fetch::Request { fetch::Request::api_call(Session::endpoint_name()).with_auth() } /// Returns the CSRF token if one exists within the cookie. pub(crate) fn csrf_token() -> Option<String> { let html_doc: HtmlDocument = HtmlDocument::from(JsValue::from(document())); let cookie = html_doc.cookie().unwrap(); parse_cookie(&cookie) } /// Parses the CSRF token out of the cookie if one exists. fn parse_cookie(cookie: &str) -> Option<String> { let re = Regex::new(r"csrftoken=([^;|$]+)").unwrap(); let x = re.captures(cookie)?; x.get(1).map(|x| x.as_str().to_string()) }
pub(crate) fn get_session(&self) -> Option<&Session> { self.session.as_ref() } }
random_line_split
auth.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{sleep_with_handle, FailReasonExt, GMsg, RequestExt, Route, SessionExt}; use futures::channel::oneshot; use iml_wire_types::{EndpointName, Session}; use regex::Regex; use seed::{browser::service::fetch, prelude::*, *}; use std::time::Duration; use wasm_bindgen::JsValue; use web_sys::HtmlDocument; #[derive(Default)] pub struct Model { session: Option<Session>, request_controller: Option<fetch::RequestController>, cancel: Option<oneshot::Sender<()>>, } impl Model { pub(crate) fn get_session(&self) -> Option<&Session> { self.session.as_ref() } } #[allow(clippy::large_enum_variant)] #[derive(Clone, Debug)] pub enum Msg { Fetch, Fetched(fetch::FetchObject<Session>), Logout, LoggedIn, Loop, Noop, } pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) { match msg { Msg::Fetch => { model.cancel = None; let request = fetch_session().controller(|controller| model.request_controller = Some(controller)); orders.skip().perform_cmd(request.fetch_json(Msg::Fetched)); } Msg::Fetched(data) => { match data.response() { Err(fail_reason) =>
Ok(resp) => { model.session = Some(resp.data); if model.session.as_ref().unwrap().needs_login() { orders.send_g_msg(GMsg::RouteChange(Route::Login.into())); } else { orders.send_msg(Msg::Loop); } resp.raw .headers() .get("date") .map_err(|j| error!(j)) .ok() .flatten() .and_then(|h| { chrono::DateTime::parse_from_rfc2822(&h) .map_err(|e| error!(e)) .map(|dt| orders.send_g_msg(GMsg::ServerDate(dt))) .ok() }); } }; } Msg::LoggedIn => { orders.skip(); orders.send_msg(Msg::Fetch); orders.send_g_msg(GMsg::RouteChange(Route::Dashboard.into())); } Msg::Logout => { orders.perform_g_cmd( fetch_session() .method(fetch::Method::Delete) .fetch(|_| GMsg::AuthProxy(Box::new(Msg::LoggedIn))), ); } Msg::Loop => { orders.skip(); let (cancel, fut) = sleep_with_handle(Duration::from_secs(10), Msg::Fetch, Msg::Noop); model.cancel = Some(cancel); orders.perform_cmd(fut); } Msg::Noop => {} }; } pub(crate) fn fetch_session() -> fetch::Request { fetch::Request::api_call(Session::endpoint_name()).with_auth() } /// Returns the CSRF token if one exists within the cookie. pub(crate) fn csrf_token() -> Option<String> { let html_doc: HtmlDocument = HtmlDocument::from(JsValue::from(document())); let cookie = html_doc.cookie().unwrap(); parse_cookie(&cookie) } /// Parses the CSRF token out of the cookie if one exists. fn parse_cookie(cookie: &str) -> Option<String> { let re = Regex::new(r"csrftoken=([^;|$]+)").unwrap(); let x = re.captures(cookie)?; x.get(1).map(|x| x.as_str().to_string()) }
{ log!(format!("Error during session poll: {}", fail_reason.message())); orders.skip().send_msg(Msg::Loop); }
conditional_block
generic-function.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-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish
// gdb-check:$3 = {{1, 2.5}, {2.5, 1}} // gdb-command:continue // gdb-command:finish // gdb-command:print *t0 // gdb-check:$4 = 3.5 // gdb-command:print *t1 // gdb-check:$5 = 4 // gdb-command:print ret // gdb-check:$6 = {{3.5, 4}, {4, 3.5}} // gdb-command:continue // gdb-command:finish // gdb-command:print *t0 // gdb-check:$7 = 5 // gdb-command:print *t1 // gdb-check:$8 = {a = 6, b = 7.5} // gdb-command:print ret // gdb-check:$9 = {{5, {a = 6, b = 7.5}}, {{a = 6, b = 7.5}, 5}} // gdb-command:continue #[deriving(Clone)] struct Struct { a: int, b: f64 } fn dup_tup<T0: Clone, T1: Clone>(t0: &T0, t1: &T1) -> ((T0, T1), (T1, T0)) { let ret = ((t0.clone(), t1.clone()), (t1.clone(), t0.clone())); zzz(); ret } fn main() { let _ = dup_tup(&1i, &2.5f64); let _ = dup_tup(&3.5f64, &4_u16); let _ = dup_tup(&5i, &Struct { a: 6, b: 7.5 }); } fn zzz() {()}
// gdb-command:print *t0 // gdb-check:$1 = 1 // gdb-command:print *t1 // gdb-check:$2 = 2.5 // gdb-command:print ret
random_line_split
generic-function.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-android: FIXME(#10381) // compile-flags:-g // gdb-command:rbreak zzz // gdb-command:run // gdb-command:finish // gdb-command:print *t0 // gdb-check:$1 = 1 // gdb-command:print *t1 // gdb-check:$2 = 2.5 // gdb-command:print ret // gdb-check:$3 = {{1, 2.5}, {2.5, 1}} // gdb-command:continue // gdb-command:finish // gdb-command:print *t0 // gdb-check:$4 = 3.5 // gdb-command:print *t1 // gdb-check:$5 = 4 // gdb-command:print ret // gdb-check:$6 = {{3.5, 4}, {4, 3.5}} // gdb-command:continue // gdb-command:finish // gdb-command:print *t0 // gdb-check:$7 = 5 // gdb-command:print *t1 // gdb-check:$8 = {a = 6, b = 7.5} // gdb-command:print ret // gdb-check:$9 = {{5, {a = 6, b = 7.5}}, {{a = 6, b = 7.5}, 5}} // gdb-command:continue #[deriving(Clone)] struct Struct { a: int, b: f64 } fn dup_tup<T0: Clone, T1: Clone>(t0: &T0, t1: &T1) -> ((T0, T1), (T1, T0)) { let ret = ((t0.clone(), t1.clone()), (t1.clone(), t0.clone())); zzz(); ret } fn main() { let _ = dup_tup(&1i, &2.5f64); let _ = dup_tup(&3.5f64, &4_u16); let _ = dup_tup(&5i, &Struct { a: 6, b: 7.5 }); } fn
() {()}
zzz
identifier_name
bin.rs
#[macro_use] extern crate malachite_base_test_util; extern crate malachite_nz; extern crate malachite_nz_test_util; extern crate serde; extern crate serde_json; use demo_and_bench::register; use generate::digits_data::generate_string_data; use malachite_base_test_util::runner::cmd::read_command_line_arguments; use malachite_base_test_util::runner::Runner; // Examples: // // cargo run -- -l 100000 -m special_random -d demo_natural_from_unsigned_u128 -c // "mean_run_length_n 4 mean_run_length_d 1" // // cargo run --release -- -l 100000 -m random -b benchmark_limbs_to_digits_small_base_algorithms // // cargo run -- -g digits_data fn main()
} } mod demo_and_bench; mod generate;
{ let args = read_command_line_arguments("malachite-nz test utils"); let mut runner = Runner::new(); register(&mut runner); if let Some(demo_key) = args.demo_key { runner.run_demo(&demo_key, args.generation_mode, args.config, args.limit); } else if let Some(bench_key) = args.bench_key { runner.run_bench( &bench_key, args.generation_mode, args.config, args.limit, &args.out, ); } else { let codegen_key = args.codegen_key.unwrap(); match codegen_key.as_str() { "digits_data" => generate_string_data(), _ => panic!("Invalid codegen key: {}", codegen_key), }
identifier_body
bin.rs
#[macro_use] extern crate malachite_base_test_util; extern crate malachite_nz; extern crate malachite_nz_test_util; extern crate serde; extern crate serde_json; use demo_and_bench::register; use generate::digits_data::generate_string_data; use malachite_base_test_util::runner::cmd::read_command_line_arguments; use malachite_base_test_util::runner::Runner; // Examples: // // cargo run -- -l 100000 -m special_random -d demo_natural_from_unsigned_u128 -c // "mean_run_length_n 4 mean_run_length_d 1" // // cargo run --release -- -l 100000 -m random -b benchmark_limbs_to_digits_small_base_algorithms // // cargo run -- -g digits_data fn
() { let args = read_command_line_arguments("malachite-nz test utils"); let mut runner = Runner::new(); register(&mut runner); if let Some(demo_key) = args.demo_key { runner.run_demo(&demo_key, args.generation_mode, args.config, args.limit); } else if let Some(bench_key) = args.bench_key { runner.run_bench( &bench_key, args.generation_mode, args.config, args.limit, &args.out, ); } else { let codegen_key = args.codegen_key.unwrap(); match codegen_key.as_str() { "digits_data" => generate_string_data(), _ => panic!("Invalid codegen key: {}", codegen_key), } } } mod demo_and_bench; mod generate;
main
identifier_name
bin.rs
#[macro_use] extern crate malachite_base_test_util; extern crate malachite_nz; extern crate malachite_nz_test_util; extern crate serde; extern crate serde_json; use demo_and_bench::register; use generate::digits_data::generate_string_data; use malachite_base_test_util::runner::cmd::read_command_line_arguments; use malachite_base_test_util::runner::Runner; // Examples: // // cargo run -- -l 100000 -m special_random -d demo_natural_from_unsigned_u128 -c // "mean_run_length_n 4 mean_run_length_d 1" // // cargo run --release -- -l 100000 -m random -b benchmark_limbs_to_digits_small_base_algorithms // // cargo run -- -g digits_data fn main() { let args = read_command_line_arguments("malachite-nz test utils"); let mut runner = Runner::new(); register(&mut runner); if let Some(demo_key) = args.demo_key { runner.run_demo(&demo_key, args.generation_mode, args.config, args.limit); } else if let Some(bench_key) = args.bench_key { runner.run_bench( &bench_key, args.generation_mode, args.config, args.limit, &args.out, ); } else {
let codegen_key = args.codegen_key.unwrap(); match codegen_key.as_str() { "digits_data" => generate_string_data(), _ => panic!("Invalid codegen key: {}", codegen_key), } } } mod demo_and_bench; mod generate;
random_line_split
types.rs
use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::str::SplitWhitespace; pub type Params<'a> = SplitWhitespace<'a>; pub type Flag = Arc<AtomicBool>; pub const BK_CASTLE: u8 = 1; pub const WK_CASTLE: u8 = BK_CASTLE << WHITE; pub const BQ_CASTLE: u8 = 1 << 2; pub const WQ_CASTLE: u8 = BQ_CASTLE << WHITE; pub const KING_CASTLE: u8 = WK_CASTLE | BK_CASTLE; pub const QUEEN_CASTLE: u8 = WQ_CASTLE | BQ_CASTLE; pub const PAWN: u8 = 0; pub const KNIGHT: u8 = 1 << 1; pub const BISHOP: u8 = 2 << 1; pub const ROOK: u8 = 3 << 1; pub const QUEEN: u8 = 4 << 1; pub const KING: u8 = 5 << 1; pub const ALL: u8 = 6 << 1; pub const EMPTY: u8 = 255; pub const COLOR: u8 = 1; pub const WHITE: u8 = COLOR; pub const BLACK: u8 = 0; pub const PIECE: u8 = 0b1110; pub const I_WHITE: usize = WHITE as usize; pub const I_BLACK: usize = BLACK as usize; pub fn flip(c: u8) -> u8
pub const PVALS: [u32; 12] = [1000, 1000, 4126, 4126, 4222, 4222, 6414, 6414, 12730, 12730, 300000, 300000]; pub fn p_val(piece: u8) -> u32 { match piece { EMPTY => 0, _ => PVALS[piece as usize] } } pub const KNIGHT_PROM: u32 = 1; pub const BISHOP_PROM: u32 = 2; pub const ROOK_PROM: u32 = 3; pub const QUEEN_PROM: u32 = 4; pub const CASTLES_KING: u32 = 1 << 3; pub const CASTLES_QUEEN: u32 = 1 << 4; pub const IS_CAPTURE: u32 = 1 << 5; pub const DOUBLE_PAWN_PUSH: u32 = 1 << 6; pub const EN_PASSANT: u32 = 1 << 7;
{ c ^ WHITE }
identifier_body
types.rs
use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::str::SplitWhitespace; pub type Params<'a> = SplitWhitespace<'a>; pub type Flag = Arc<AtomicBool>; pub const BK_CASTLE: u8 = 1; pub const WK_CASTLE: u8 = BK_CASTLE << WHITE; pub const BQ_CASTLE: u8 = 1 << 2; pub const WQ_CASTLE: u8 = BQ_CASTLE << WHITE; pub const KING_CASTLE: u8 = WK_CASTLE | BK_CASTLE; pub const QUEEN_CASTLE: u8 = WQ_CASTLE | BQ_CASTLE; pub const PAWN: u8 = 0; pub const KNIGHT: u8 = 1 << 1; pub const BISHOP: u8 = 2 << 1; pub const ROOK: u8 = 3 << 1; pub const QUEEN: u8 = 4 << 1; pub const KING: u8 = 5 << 1; pub const ALL: u8 = 6 << 1; pub const EMPTY: u8 = 255; pub const COLOR: u8 = 1; pub const WHITE: u8 = COLOR; pub const BLACK: u8 = 0; pub const PIECE: u8 = 0b1110; pub const I_WHITE: usize = WHITE as usize; pub const I_BLACK: usize = BLACK as usize; pub fn
(c: u8) -> u8 { c ^ WHITE } pub const PVALS: [u32; 12] = [1000, 1000, 4126, 4126, 4222, 4222, 6414, 6414, 12730, 12730, 300000, 300000]; pub fn p_val(piece: u8) -> u32 { match piece { EMPTY => 0, _ => PVALS[piece as usize] } } pub const KNIGHT_PROM: u32 = 1; pub const BISHOP_PROM: u32 = 2; pub const ROOK_PROM: u32 = 3; pub const QUEEN_PROM: u32 = 4; pub const CASTLES_KING: u32 = 1 << 3; pub const CASTLES_QUEEN: u32 = 1 << 4; pub const IS_CAPTURE: u32 = 1 << 5; pub const DOUBLE_PAWN_PUSH: u32 = 1 << 6; pub const EN_PASSANT: u32 = 1 << 7;
flip
identifier_name
types.rs
use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::str::SplitWhitespace; pub type Params<'a> = SplitWhitespace<'a>; pub type Flag = Arc<AtomicBool>; pub const BK_CASTLE: u8 = 1; pub const WK_CASTLE: u8 = BK_CASTLE << WHITE; pub const BQ_CASTLE: u8 = 1 << 2; pub const WQ_CASTLE: u8 = BQ_CASTLE << WHITE; pub const KING_CASTLE: u8 = WK_CASTLE | BK_CASTLE; pub const QUEEN_CASTLE: u8 = WQ_CASTLE | BQ_CASTLE; pub const PAWN: u8 = 0; pub const KNIGHT: u8 = 1 << 1; pub const BISHOP: u8 = 2 << 1; pub const ROOK: u8 = 3 << 1; pub const QUEEN: u8 = 4 << 1; pub const KING: u8 = 5 << 1; pub const ALL: u8 = 6 << 1; pub const EMPTY: u8 = 255; pub const COLOR: u8 = 1; pub const WHITE: u8 = COLOR; pub const BLACK: u8 = 0; pub const PIECE: u8 = 0b1110; pub const I_WHITE: usize = WHITE as usize; pub const I_BLACK: usize = BLACK as usize; pub fn flip(c: u8) -> u8 { c ^ WHITE }
pub const PVALS: [u32; 12] = [1000, 1000, 4126, 4126, 4222, 4222, 6414, 6414, 12730, 12730, 300000, 300000]; pub fn p_val(piece: u8) -> u32 { match piece { EMPTY => 0, _ => PVALS[piece as usize] } } pub const KNIGHT_PROM: u32 = 1; pub const BISHOP_PROM: u32 = 2; pub const ROOK_PROM: u32 = 3; pub const QUEEN_PROM: u32 = 4; pub const CASTLES_KING: u32 = 1 << 3; pub const CASTLES_QUEEN: u32 = 1 << 4; pub const IS_CAPTURE: u32 = 1 << 5; pub const DOUBLE_PAWN_PUSH: u32 = 1 << 6; pub const EN_PASSANT: u32 = 1 << 7;
random_line_split
peer.rs
use ::address::PublicKey; use super::{ ffi, error, vars, Group, Status }; use super::status::{ Connection, UserStatus }; /// GropuChat Peer. #[derive(Clone, Debug)] pub struct Peer { pub group: Group, pub number: i32 } impl Peer { pub fn from(group: &Group, number: i32) -> Peer { Peer { group: group.clone(), number: number } } /// Peer is Self? pub fn is_ours(&self) -> bool { unsafe { ffi::tox_group_peernumber_is_ours( self.group.core, self.group.number, self.number )!= 0 } } } impl Status for Peer { fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { let len = unsafe { ffi::tox_group_number_peers( self.group.core, self.group.number ) }; let mut names = unsafe { vec_with!(len as usize) }; let mut lengths = unsafe { vec_with!(len as usize) }; if self.number >= len || unsafe { ffi::tox_group_get_names( self.group.core, self.group.number, names.as_mut_ptr(), lengths.as_mut_ptr(), len as ::libc::uint16_t ) == -1 }
; let name_len = lengths[self.number as usize]; Ok(names[self.number as usize][..name_len as usize].into()) } // fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { // let mut name = unsafe { vec_with!(vars::TOX_MAX_NAME_LENGTH) }; // match unsafe { ffi::tox_group_peername( // self.group.core, // self.group.number, // self.number, // name.as_mut_ptr() // ) } { // -1 => Err(error::GetStatusErr::Group), // _ => Ok(name) // } // } fn publickey(&self) -> Result<PublicKey, error::GetStatusErr> { let mut pk = unsafe { vec_with!(vars::TOX_PUBLIC_KEY_SIZE) }; match unsafe { ffi::tox_group_peer_pubkey( self.group.core, self.group.number, self.number, pk.as_mut_ptr() ) } { -1 => Err(error::GetStatusErr::Group), _ => Ok(pk.into()) } } /// unimplemented, TODO New GroupChat. fn status(&self) -> Result<UserStatus, error::GetStatusErr> { unimplemented!() } /// unimplemented, TODO New GroupChat. fn status_message(&self) -> Result<Vec<u8>, error::GetStatusErr> { unimplemented!() } /// unimplemented, TODO New GroupChat. fn connection_status(&self) -> Result<Connection, error::GetStatusErr> { unimplemented!() } }
{ return Err(error::GetStatusErr::Group); }
conditional_block
peer.rs
use ::address::PublicKey; use super::{ ffi, error, vars, Group, Status }; use super::status::{ Connection, UserStatus }; /// GropuChat Peer. #[derive(Clone, Debug)] pub struct Peer { pub group: Group, pub number: i32 } impl Peer { pub fn from(group: &Group, number: i32) -> Peer { Peer { group: group.clone(), number: number } } /// Peer is Self? pub fn is_ours(&self) -> bool
} impl Status for Peer { fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { let len = unsafe { ffi::tox_group_number_peers( self.group.core, self.group.number ) }; let mut names = unsafe { vec_with!(len as usize) }; let mut lengths = unsafe { vec_with!(len as usize) }; if self.number >= len || unsafe { ffi::tox_group_get_names( self.group.core, self.group.number, names.as_mut_ptr(), lengths.as_mut_ptr(), len as ::libc::uint16_t ) == -1 } { return Err(error::GetStatusErr::Group); }; let name_len = lengths[self.number as usize]; Ok(names[self.number as usize][..name_len as usize].into()) } // fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { // let mut name = unsafe { vec_with!(vars::TOX_MAX_NAME_LENGTH) }; // match unsafe { ffi::tox_group_peername( // self.group.core, // self.group.number, // self.number, // name.as_mut_ptr() // ) } { // -1 => Err(error::GetStatusErr::Group), // _ => Ok(name) // } // } fn publickey(&self) -> Result<PublicKey, error::GetStatusErr> { let mut pk = unsafe { vec_with!(vars::TOX_PUBLIC_KEY_SIZE) }; match unsafe { ffi::tox_group_peer_pubkey( self.group.core, self.group.number, self.number, pk.as_mut_ptr() ) } { -1 => Err(error::GetStatusErr::Group), _ => Ok(pk.into()) } } /// unimplemented, TODO New GroupChat. fn status(&self) -> Result<UserStatus, error::GetStatusErr> { unimplemented!() } /// unimplemented, TODO New GroupChat. fn status_message(&self) -> Result<Vec<u8>, error::GetStatusErr> { unimplemented!() } /// unimplemented, TODO New GroupChat. fn connection_status(&self) -> Result<Connection, error::GetStatusErr> { unimplemented!() } }
{ unsafe { ffi::tox_group_peernumber_is_ours( self.group.core, self.group.number, self.number ) != 0 } }
identifier_body
peer.rs
use ::address::PublicKey; use super::{ ffi, error, vars, Group, Status }; use super::status::{ Connection, UserStatus }; /// GropuChat Peer. #[derive(Clone, Debug)] pub struct Peer { pub group: Group, pub number: i32 } impl Peer { pub fn from(group: &Group, number: i32) -> Peer { Peer { group: group.clone(), number: number } } /// Peer is Self? pub fn is_ours(&self) -> bool { unsafe { ffi::tox_group_peernumber_is_ours( self.group.core, self.group.number, self.number )!= 0 } } } impl Status for Peer { fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { let len = unsafe { ffi::tox_group_number_peers( self.group.core, self.group.number ) }; let mut names = unsafe { vec_with!(len as usize) }; let mut lengths = unsafe { vec_with!(len as usize) }; if self.number >= len || unsafe { ffi::tox_group_get_names( self.group.core, self.group.number, names.as_mut_ptr(), lengths.as_mut_ptr(), len as ::libc::uint16_t ) == -1 } { return Err(error::GetStatusErr::Group); }; let name_len = lengths[self.number as usize]; Ok(names[self.number as usize][..name_len as usize].into()) } // fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { // let mut name = unsafe { vec_with!(vars::TOX_MAX_NAME_LENGTH) }; // match unsafe { ffi::tox_group_peername( // self.group.core, // self.group.number, // self.number, // name.as_mut_ptr() // ) } { // -1 => Err(error::GetStatusErr::Group), // _ => Ok(name) // } // } fn
(&self) -> Result<PublicKey, error::GetStatusErr> { let mut pk = unsafe { vec_with!(vars::TOX_PUBLIC_KEY_SIZE) }; match unsafe { ffi::tox_group_peer_pubkey( self.group.core, self.group.number, self.number, pk.as_mut_ptr() ) } { -1 => Err(error::GetStatusErr::Group), _ => Ok(pk.into()) } } /// unimplemented, TODO New GroupChat. fn status(&self) -> Result<UserStatus, error::GetStatusErr> { unimplemented!() } /// unimplemented, TODO New GroupChat. fn status_message(&self) -> Result<Vec<u8>, error::GetStatusErr> { unimplemented!() } /// unimplemented, TODO New GroupChat. fn connection_status(&self) -> Result<Connection, error::GetStatusErr> { unimplemented!() } }
publickey
identifier_name
peer.rs
use ::address::PublicKey; use super::{ ffi, error, vars, Group, Status }; use super::status::{ Connection, UserStatus }; /// GropuChat Peer. #[derive(Clone, Debug)] pub struct Peer { pub group: Group, pub number: i32 } impl Peer { pub fn from(group: &Group, number: i32) -> Peer { Peer { group: group.clone(), number: number } } /// Peer is Self? pub fn is_ours(&self) -> bool { unsafe { ffi::tox_group_peernumber_is_ours( self.group.core, self.group.number, self.number )!= 0 } } } impl Status for Peer { fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { let len = unsafe { ffi::tox_group_number_peers( self.group.core, self.group.number ) }; let mut names = unsafe { vec_with!(len as usize) }; let mut lengths = unsafe { vec_with!(len as usize) }; if self.number >= len || unsafe { ffi::tox_group_get_names( self.group.core, self.group.number, names.as_mut_ptr(), lengths.as_mut_ptr(), len as ::libc::uint16_t ) == -1 } { return Err(error::GetStatusErr::Group);
}; let name_len = lengths[self.number as usize]; Ok(names[self.number as usize][..name_len as usize].into()) } // fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { // let mut name = unsafe { vec_with!(vars::TOX_MAX_NAME_LENGTH) }; // match unsafe { ffi::tox_group_peername( // self.group.core, // self.group.number, // self.number, // name.as_mut_ptr() // ) } { // -1 => Err(error::GetStatusErr::Group), // _ => Ok(name) // } // } fn publickey(&self) -> Result<PublicKey, error::GetStatusErr> { let mut pk = unsafe { vec_with!(vars::TOX_PUBLIC_KEY_SIZE) }; match unsafe { ffi::tox_group_peer_pubkey( self.group.core, self.group.number, self.number, pk.as_mut_ptr() ) } { -1 => Err(error::GetStatusErr::Group), _ => Ok(pk.into()) } } /// unimplemented, TODO New GroupChat. fn status(&self) -> Result<UserStatus, error::GetStatusErr> { unimplemented!() } /// unimplemented, TODO New GroupChat. fn status_message(&self) -> Result<Vec<u8>, error::GetStatusErr> { unimplemented!() } /// unimplemented, TODO New GroupChat. fn connection_status(&self) -> Result<Connection, error::GetStatusErr> { unimplemented!() } }
random_line_split
underscore.rs
use std::old_io::{stdout, stderr}; use libc::pid_t; use argparse::{ArgumentParser}; use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store}; use config::Config; use config::command::{CommandInfo, Networking}; use container::container::Namespace::{NewUser, NewNet}; use container::nsutil::{set_namespace}; use super::user; use super::network; use super::build::build_container; pub fn run_command(config: &Config, workdir: &Path, cmdname: String, mut args: Vec<String>) -> Result<i32, String> { let mut cmdargs = Vec::<String>::new(); let mut container = "".to_string(); let mut copy = false; { args.insert(0, "vagga ".to_string() + cmdname.as_slice()); let mut ap = ArgumentParser::new(); ap.set_description(" Runs arbitrary command inside the container "); ap.refer(&mut copy) .add_option(&["-W", "--writeable"], StoreTrue, "Create translient writeable container for running the command. Currently we use hard-linked copy of the container, so it's dangerous for some operations. Still it's ok for installing packages or similar tasks"); ap.refer(&mut container) .add_argument("container", Store, "Container to run command in") .required(); ap.refer(&mut cmdargs) .add_argument("command", List, "Command (with arguments) to run inside container") .required(); ap.stop_on_first_argument(true); match ap.parse(args.clone(), &mut stdout(), &mut stderr()) { Ok(()) => {} Err(0) => return Ok(0), Err(_) => { return Ok(122); } } } args.remove(0); try!(build_container(config, &container)); let res = user::run_wrapper(Some(workdir), cmdname, args, true); if copy { match user::run_wrapper(Some(workdir), "_clean".to_string(), vec!("--transient".to_string()), true) { Ok(0) => {} x => warn!( "The `vagga _clean --transient` exited with status: {:?}", x), } } return res; } pub fn run_in_netns(config: &Config, workdir: &Path, cname: String, mut args: Vec<String>) -> Result<i32, String> { let mut cmdargs = vec!(); let mut container = "".to_string(); let mut pid = None; { args.insert(0, "vagga ".to_string() + cname.as_slice()); let mut ap = ArgumentParser::new(); ap.set_description( "Run command (or shell) in one of the vagga's network namespaces"); ap.refer(&mut pid) .add_option(&["--pid"], StoreOption, " Run in the namespace of the process with PID. By default you get shell in the \"gateway\" namespace.
"); ap.refer(&mut container) .add_argument("container", Store, "Container to run command in") .required(); ap.refer(&mut cmdargs) .add_argument("command", List, "Command (with arguments) to run inside container") .required(); ap.stop_on_first_argument(true); match ap.parse(args, &mut stdout(), &mut stderr()) { Ok(()) => {} Err(0) => return Ok(0), Err(_) => { return Ok(122); } } } cmdargs.insert(0, container.clone()); try!(build_container(config, &container)); try!(network::join_gateway_namespaces()); if let Some::<i32>(pid) = pid { try!(set_namespace(&Path::new(format!("/proc/{}/ns/net", pid)), NewNet) .map_err(|e| format!("Error setting networkns: {}", e))); } user::run_wrapper(Some(workdir), cname, cmdargs, false) }
random_line_split
underscore.rs
use std::old_io::{stdout, stderr}; use libc::pid_t; use argparse::{ArgumentParser}; use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store}; use config::Config; use config::command::{CommandInfo, Networking}; use container::container::Namespace::{NewUser, NewNet}; use container::nsutil::{set_namespace}; use super::user; use super::network; use super::build::build_container; pub fn run_command(config: &Config, workdir: &Path, cmdname: String, mut args: Vec<String>) -> Result<i32, String> { let mut cmdargs = Vec::<String>::new(); let mut container = "".to_string(); let mut copy = false; { args.insert(0, "vagga ".to_string() + cmdname.as_slice()); let mut ap = ArgumentParser::new(); ap.set_description(" Runs arbitrary command inside the container "); ap.refer(&mut copy) .add_option(&["-W", "--writeable"], StoreTrue, "Create translient writeable container for running the command. Currently we use hard-linked copy of the container, so it's dangerous for some operations. Still it's ok for installing packages or similar tasks"); ap.refer(&mut container) .add_argument("container", Store, "Container to run command in") .required(); ap.refer(&mut cmdargs) .add_argument("command", List, "Command (with arguments) to run inside container") .required(); ap.stop_on_first_argument(true); match ap.parse(args.clone(), &mut stdout(), &mut stderr()) { Ok(()) => {} Err(0) => return Ok(0), Err(_) => { return Ok(122); } } } args.remove(0); try!(build_container(config, &container)); let res = user::run_wrapper(Some(workdir), cmdname, args, true); if copy { match user::run_wrapper(Some(workdir), "_clean".to_string(), vec!("--transient".to_string()), true) { Ok(0) => {} x => warn!( "The `vagga _clean --transient` exited with status: {:?}", x), } } return res; } pub fn run_in_netns(config: &Config, workdir: &Path, cname: String, mut args: Vec<String>) -> Result<i32, String>
"Command (with arguments) to run inside container") .required(); ap.stop_on_first_argument(true); match ap.parse(args, &mut stdout(), &mut stderr()) { Ok(()) => {} Err(0) => return Ok(0), Err(_) => { return Ok(122); } } } cmdargs.insert(0, container.clone()); try!(build_container(config, &container)); try!(network::join_gateway_namespaces()); if let Some::<i32>(pid) = pid { try!(set_namespace(&Path::new(format!("/proc/{}/ns/net", pid)), NewNet) .map_err(|e| format!("Error setting networkns: {}", e))); } user::run_wrapper(Some(workdir), cname, cmdargs, false) }
{ let mut cmdargs = vec!(); let mut container = "".to_string(); let mut pid = None; { args.insert(0, "vagga ".to_string() + cname.as_slice()); let mut ap = ArgumentParser::new(); ap.set_description( "Run command (or shell) in one of the vagga's network namespaces"); ap.refer(&mut pid) .add_option(&["--pid"], StoreOption, " Run in the namespace of the process with PID. By default you get shell in the \"gateway\" namespace. "); ap.refer(&mut container) .add_argument("container", Store, "Container to run command in") .required(); ap.refer(&mut cmdargs) .add_argument("command", List,
identifier_body
underscore.rs
use std::old_io::{stdout, stderr}; use libc::pid_t; use argparse::{ArgumentParser}; use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store}; use config::Config; use config::command::{CommandInfo, Networking}; use container::container::Namespace::{NewUser, NewNet}; use container::nsutil::{set_namespace}; use super::user; use super::network; use super::build::build_container; pub fn run_command(config: &Config, workdir: &Path, cmdname: String, mut args: Vec<String>) -> Result<i32, String> { let mut cmdargs = Vec::<String>::new(); let mut container = "".to_string(); let mut copy = false; { args.insert(0, "vagga ".to_string() + cmdname.as_slice()); let mut ap = ArgumentParser::new(); ap.set_description(" Runs arbitrary command inside the container "); ap.refer(&mut copy) .add_option(&["-W", "--writeable"], StoreTrue, "Create translient writeable container for running the command. Currently we use hard-linked copy of the container, so it's dangerous for some operations. Still it's ok for installing packages or similar tasks"); ap.refer(&mut container) .add_argument("container", Store, "Container to run command in") .required(); ap.refer(&mut cmdargs) .add_argument("command", List, "Command (with arguments) to run inside container") .required(); ap.stop_on_first_argument(true); match ap.parse(args.clone(), &mut stdout(), &mut stderr()) { Ok(()) => {} Err(0) => return Ok(0), Err(_) => { return Ok(122); } } } args.remove(0); try!(build_container(config, &container)); let res = user::run_wrapper(Some(workdir), cmdname, args, true); if copy { match user::run_wrapper(Some(workdir), "_clean".to_string(), vec!("--transient".to_string()), true) { Ok(0) => {} x => warn!( "The `vagga _clean --transient` exited with status: {:?}", x), } } return res; } pub fn
(config: &Config, workdir: &Path, cname: String, mut args: Vec<String>) -> Result<i32, String> { let mut cmdargs = vec!(); let mut container = "".to_string(); let mut pid = None; { args.insert(0, "vagga ".to_string() + cname.as_slice()); let mut ap = ArgumentParser::new(); ap.set_description( "Run command (or shell) in one of the vagga's network namespaces"); ap.refer(&mut pid) .add_option(&["--pid"], StoreOption, " Run in the namespace of the process with PID. By default you get shell in the \"gateway\" namespace. "); ap.refer(&mut container) .add_argument("container", Store, "Container to run command in") .required(); ap.refer(&mut cmdargs) .add_argument("command", List, "Command (with arguments) to run inside container") .required(); ap.stop_on_first_argument(true); match ap.parse(args, &mut stdout(), &mut stderr()) { Ok(()) => {} Err(0) => return Ok(0), Err(_) => { return Ok(122); } } } cmdargs.insert(0, container.clone()); try!(build_container(config, &container)); try!(network::join_gateway_namespaces()); if let Some::<i32>(pid) = pid { try!(set_namespace(&Path::new(format!("/proc/{}/ns/net", pid)), NewNet) .map_err(|e| format!("Error setting networkns: {}", e))); } user::run_wrapper(Some(workdir), cname, cmdargs, false) }
run_in_netns
identifier_name
issue-5806.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // opyright 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. #[path = "../compile-fail"] mod foo; //~ ERROR: illegal operation on a directory fn main() {}
//
random_line_split
issue-5806.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // opyright 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. #[path = "../compile-fail"] mod foo; //~ ERROR: illegal operation on a directory fn main()
{}
identifier_body
issue-5806.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // opyright 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. #[path = "../compile-fail"] mod foo; //~ ERROR: illegal operation on a directory fn
() {}
main
identifier_name
types.rs
use self::ItemType::*; use std::io; use std::io::Write; use str::GopherStr; use bytes::Bytes; /// A client-to-server message. #[derive(Clone, Debug)] pub struct GopherRequest { /// Identifier of the resource to fetch. May be an empty string. pub selector: GopherStr, /// Search string for a full-text search transaction. pub query: Option<GopherStr> } impl GopherRequest { /// Read a Gopher request from a buffer containing a line *without* the trailing CRLF. pub fn decode(mut line: Bytes) -> Self { // Split on TAB if present. let query = match line.iter().position(|b| *b == b'\t') { Some(i) => { let mut query = line.split_off(i); query.split_to(1); // Consume the TAB. Some(GopherStr::new(query)) } None => None }; GopherRequest { selector: GopherStr::new(line), query: query, } } } /// A server-to-client message. #[derive(Clone, Debug)] pub enum GopherResponse { /// A list of resources. Menu(Vec<DirEntity>), /// A text document. TextFile(Bytes), /// A binary file download. BinaryFile(Bytes), /// A single menu item enclosed in a Gopher+ protocol response. /// /// Useful for redirecting Gopher+ clients to the standard Gopher protocol. GopherPlusRedirect(DirEntity), } impl GopherResponse { /// Construct a menu with a single error line. pub fn error(text: GopherStr) -> Self { GopherResponse::Menu(vec![ DirEntity { item_type: Error, name: text, selector: GopherStr::from_latin1(b"error"), host: GopherStr::from_latin1(b"error.host"), port: 0, } ]) } /// Encode the response into bytes for sending over the wire. pub fn encode<W>(&self, mut buf: W) -> io::Result<()> where W: Write { match *self { GopherResponse::BinaryFile(ref file) => { buf.write_all(&file)?; } GopherResponse::TextFile(ref file) => { // TODO: Escape lines beginning with periods by adding an extra period. buf.write_all(&file)?; buf.write_all(b"\r\n.\r\n")?; } GopherResponse::Menu(ref entities) => { for entity in entities { entity.encode(&mut buf)?; } buf.write_all(b".\r\n")?; } GopherResponse::GopherPlusRedirect(ref entity) => { buf.write_all(b"+-1\r\n+INFO: ")?; entity.encode(buf)?; } } Ok(()) } } /// A list of Gopher resources. pub struct
{ pub entities: Vec<DirEntity>, } /// An menu item in a directory of Gopher resources. #[derive(Clone, Debug)] pub struct DirEntity { /// The type of the resource pub item_type: ItemType, /// String to display to the user. pub name: GopherStr, /// Path or identifier used for requesting this resource. pub selector: GopherStr, /// The hostname of the server hosting this resource. pub host: GopherStr, /// The TCP port of the server hosting this resource. pub port: u16, } impl DirEntity { pub fn encode<W>(&self, mut buf: W) -> io::Result<()> where W: Write { buf.write_all(&[self.item_type.encode()])?; buf.write_all(&self.name)?; buf.write_all(b"\t")?; buf.write_all(&self.selector)?; buf.write_all(b"\t")?; buf.write_all(&self.host)?; write!(buf, "\t{}\r\n", self.port)?; Ok(()) } } /// The type of a resource in a Gopher directory. /// /// For more details, see: https://tools.ietf.org/html/rfc1436 #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)] pub enum ItemType { /// Item is a file File, /// Item is a directory Dir, /// Item is a CSO phone-book server CsoServer, /// Error Error, /// Item is a BinHexed Macintosh file. BinHex, /// Item is DOS binary archive of some sort. /// /// Client must read until the TCP connection closes. Beware. Dos, /// Item is a UNIX uuencoded file. Uuencoded, /// Item is an Index-Search server. IndexServer, /// Item points to a text-based telnet session. Telnet, /// Item is a binary file! Client must read until the TCP connection closes. Beware Binary, /// Item is a redundant server RedundantServer, /// Item points to a text-based tn3270 session. Tn3270, /// Item is a GIF format graphics file. Gif, /// Item is some kind of image file. Client decides how to display. Image, /// Item is a non-standard type Other(u8), } impl ItemType { pub fn decode(b: u8) -> Self { match b { b'0' => File, b'1' => Dir, b'2' => CsoServer, b'3' => Error, b'4' => BinHex, b'5' => Dos, b'6' => Uuencoded, b'7' => IndexServer, b'8' => Telnet, b'9' => Binary, b'+' => RedundantServer, b'T' => Tn3270, b'g' => Gif, b'I' => Image, byte => Other(byte) } } pub fn encode(self) -> u8 { match self { File => b'0', Dir => b'1', CsoServer => b'2', Error => b'3', BinHex => b'4', Dos => b'5', Uuencoded => b'6', IndexServer => b'7', Telnet => b'8', Binary => b'9', RedundantServer => b'+', Tn3270 => b'T', Gif => b'g', Image => b'I', Other(byte) => byte, } } }
Menu
identifier_name
types.rs
use self::ItemType::*; use std::io; use std::io::Write; use str::GopherStr; use bytes::Bytes; /// A client-to-server message. #[derive(Clone, Debug)] pub struct GopherRequest { /// Identifier of the resource to fetch. May be an empty string. pub selector: GopherStr, /// Search string for a full-text search transaction. pub query: Option<GopherStr> } impl GopherRequest { /// Read a Gopher request from a buffer containing a line *without* the trailing CRLF. pub fn decode(mut line: Bytes) -> Self { // Split on TAB if present. let query = match line.iter().position(|b| *b == b'\t') { Some(i) => { let mut query = line.split_off(i); query.split_to(1); // Consume the TAB. Some(GopherStr::new(query)) } None => None }; GopherRequest { selector: GopherStr::new(line), query: query, } }
/// A list of resources. Menu(Vec<DirEntity>), /// A text document. TextFile(Bytes), /// A binary file download. BinaryFile(Bytes), /// A single menu item enclosed in a Gopher+ protocol response. /// /// Useful for redirecting Gopher+ clients to the standard Gopher protocol. GopherPlusRedirect(DirEntity), } impl GopherResponse { /// Construct a menu with a single error line. pub fn error(text: GopherStr) -> Self { GopherResponse::Menu(vec![ DirEntity { item_type: Error, name: text, selector: GopherStr::from_latin1(b"error"), host: GopherStr::from_latin1(b"error.host"), port: 0, } ]) } /// Encode the response into bytes for sending over the wire. pub fn encode<W>(&self, mut buf: W) -> io::Result<()> where W: Write { match *self { GopherResponse::BinaryFile(ref file) => { buf.write_all(&file)?; } GopherResponse::TextFile(ref file) => { // TODO: Escape lines beginning with periods by adding an extra period. buf.write_all(&file)?; buf.write_all(b"\r\n.\r\n")?; } GopherResponse::Menu(ref entities) => { for entity in entities { entity.encode(&mut buf)?; } buf.write_all(b".\r\n")?; } GopherResponse::GopherPlusRedirect(ref entity) => { buf.write_all(b"+-1\r\n+INFO: ")?; entity.encode(buf)?; } } Ok(()) } } /// A list of Gopher resources. pub struct Menu { pub entities: Vec<DirEntity>, } /// An menu item in a directory of Gopher resources. #[derive(Clone, Debug)] pub struct DirEntity { /// The type of the resource pub item_type: ItemType, /// String to display to the user. pub name: GopherStr, /// Path or identifier used for requesting this resource. pub selector: GopherStr, /// The hostname of the server hosting this resource. pub host: GopherStr, /// The TCP port of the server hosting this resource. pub port: u16, } impl DirEntity { pub fn encode<W>(&self, mut buf: W) -> io::Result<()> where W: Write { buf.write_all(&[self.item_type.encode()])?; buf.write_all(&self.name)?; buf.write_all(b"\t")?; buf.write_all(&self.selector)?; buf.write_all(b"\t")?; buf.write_all(&self.host)?; write!(buf, "\t{}\r\n", self.port)?; Ok(()) } } /// The type of a resource in a Gopher directory. /// /// For more details, see: https://tools.ietf.org/html/rfc1436 #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)] pub enum ItemType { /// Item is a file File, /// Item is a directory Dir, /// Item is a CSO phone-book server CsoServer, /// Error Error, /// Item is a BinHexed Macintosh file. BinHex, /// Item is DOS binary archive of some sort. /// /// Client must read until the TCP connection closes. Beware. Dos, /// Item is a UNIX uuencoded file. Uuencoded, /// Item is an Index-Search server. IndexServer, /// Item points to a text-based telnet session. Telnet, /// Item is a binary file! Client must read until the TCP connection closes. Beware Binary, /// Item is a redundant server RedundantServer, /// Item points to a text-based tn3270 session. Tn3270, /// Item is a GIF format graphics file. Gif, /// Item is some kind of image file. Client decides how to display. Image, /// Item is a non-standard type Other(u8), } impl ItemType { pub fn decode(b: u8) -> Self { match b { b'0' => File, b'1' => Dir, b'2' => CsoServer, b'3' => Error, b'4' => BinHex, b'5' => Dos, b'6' => Uuencoded, b'7' => IndexServer, b'8' => Telnet, b'9' => Binary, b'+' => RedundantServer, b'T' => Tn3270, b'g' => Gif, b'I' => Image, byte => Other(byte) } } pub fn encode(self) -> u8 { match self { File => b'0', Dir => b'1', CsoServer => b'2', Error => b'3', BinHex => b'4', Dos => b'5', Uuencoded => b'6', IndexServer => b'7', Telnet => b'8', Binary => b'9', RedundantServer => b'+', Tn3270 => b'T', Gif => b'g', Image => b'I', Other(byte) => byte, } } }
} /// A server-to-client message. #[derive(Clone, Debug)] pub enum GopherResponse {
random_line_split
fps.rs
use time::precise_time_ns; // FPS is smoothed with an exponentially-weighted moving average. // This is the proportion of the old FPS to keep on each step. const SMOOTHING: f32 = 0.9; // How often to output FPS, in milliseconds. const OUTPUT_INTERVAL: u64 = 5_000; pub struct FPSTracker { last_frame_time: u64, last_fps_output_time: u64, smoothed_fps: f32, } impl FPSTracker { pub fn
() -> FPSTracker { let t = precise_time_ns(); FPSTracker { last_frame_time: t, last_fps_output_time: t, smoothed_fps: 0.0, } } pub fn tick(&mut self) { let this_frame_time = precise_time_ns(); let instant_fps = 1e9 / ((this_frame_time - self.last_frame_time) as f32); self.smoothed_fps = SMOOTHING * self.smoothed_fps + (1.0-SMOOTHING) * instant_fps; self.last_frame_time = this_frame_time; if (this_frame_time - self.last_fps_output_time) >= 1_000_000 * OUTPUT_INTERVAL { println!("Frames per second: {:7.2}", self.smoothed_fps); self.last_fps_output_time = this_frame_time; } } }
new
identifier_name
fps.rs
use time::precise_time_ns; // FPS is smoothed with an exponentially-weighted moving average. // This is the proportion of the old FPS to keep on each step. const SMOOTHING: f32 = 0.9; // How often to output FPS, in milliseconds. const OUTPUT_INTERVAL: u64 = 5_000; pub struct FPSTracker { last_frame_time: u64, last_fps_output_time: u64, smoothed_fps: f32, } impl FPSTracker { pub fn new() -> FPSTracker {
} } pub fn tick(&mut self) { let this_frame_time = precise_time_ns(); let instant_fps = 1e9 / ((this_frame_time - self.last_frame_time) as f32); self.smoothed_fps = SMOOTHING * self.smoothed_fps + (1.0-SMOOTHING) * instant_fps; self.last_frame_time = this_frame_time; if (this_frame_time - self.last_fps_output_time) >= 1_000_000 * OUTPUT_INTERVAL { println!("Frames per second: {:7.2}", self.smoothed_fps); self.last_fps_output_time = this_frame_time; } } }
let t = precise_time_ns(); FPSTracker { last_frame_time: t, last_fps_output_time: t, smoothed_fps: 0.0,
random_line_split
fps.rs
use time::precise_time_ns; // FPS is smoothed with an exponentially-weighted moving average. // This is the proportion of the old FPS to keep on each step. const SMOOTHING: f32 = 0.9; // How often to output FPS, in milliseconds. const OUTPUT_INTERVAL: u64 = 5_000; pub struct FPSTracker { last_frame_time: u64, last_fps_output_time: u64, smoothed_fps: f32, } impl FPSTracker { pub fn new() -> FPSTracker { let t = precise_time_ns(); FPSTracker { last_frame_time: t, last_fps_output_time: t, smoothed_fps: 0.0, } } pub fn tick(&mut self) { let this_frame_time = precise_time_ns(); let instant_fps = 1e9 / ((this_frame_time - self.last_frame_time) as f32); self.smoothed_fps = SMOOTHING * self.smoothed_fps + (1.0-SMOOTHING) * instant_fps; self.last_frame_time = this_frame_time; if (this_frame_time - self.last_fps_output_time) >= 1_000_000 * OUTPUT_INTERVAL
} }
{ println!("Frames per second: {:7.2}", self.smoothed_fps); self.last_fps_output_time = this_frame_time; }
conditional_block
lib.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! The library crate that defines common helper functions that are generally used in //! conjunction with seccompiler-bin. mod common; use bincode::Error as BincodeError; use bincode::{DefaultOptions, Options}; use common::BPF_MAX_LEN; use std::collections::HashMap; use std::fmt::{Display, Formatter}; use std::io::Read; use std::sync::Arc; // Re-export the data types needed for calling the helper functions. pub use common::{sock_filter, BpfProgram}; /// Type that associates a thread category to a BPF program. pub type BpfThreadMap = HashMap<String, Arc<BpfProgram>>; // BPF structure definition for filter array. // See /usr/include/linux/filter.h. #[repr(C)] struct sock_fprog { pub len: ::std::os::raw::c_ushort, pub filter: *const sock_filter, } /// Reference to program made up of a sequence of BPF instructions. pub type BpfProgramRef<'a> = &'a [sock_filter]; /// Binary filter deserialization errors. #[derive(Debug)] pub enum DeserializationError { /// Error when doing bincode deserialization. Bincode(BincodeError), } impl Display for DeserializationError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { use self::DeserializationError::*; match *self { Bincode(ref err) => write!(f, "Bincode deserialization failed: {}", err), } } } /// Filter installation errors. #[derive(Debug, PartialEq)] pub enum InstallationError { /// Filter exceeds the maximum number of instructions that a BPF program can have. FilterTooLarge, /// Error returned by `prctl`. Prctl(i32), } impl Display for InstallationError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { use self::InstallationError::*; match *self { FilterTooLarge => write!( f, "Filter length exceeds the maximum size of {} instructions ", BPF_MAX_LEN ), Prctl(ref errno) => write!(f, "`prctl` syscall failed with error code: {}", errno), } } } /// Deserialize a BPF file into a collection of usable BPF filters. /// Has an optional `bytes_limit` that is passed to bincode to constrain the maximum amount of memory /// that we can allocate while performing the deserialization. /// It's recommended that the integrator of the library uses this to prevent memory allocations DOS-es. pub fn deserialize_binary<R: Read>( reader: R, bytes_limit: Option<u64>, ) -> std::result::Result<BpfThreadMap, DeserializationError> { let result = match bytes_limit { // Also add the default options. These are not part of the `DefaultOptions` as per // this issue: https://github.com/servo/bincode/issues/333 Some(limit) => DefaultOptions::new() .with_fixint_encoding() .allow_trailing_bytes() .with_limit(limit) .deserialize_from::<R, HashMap<String, BpfProgram>>(reader), // No limit is the default. None => bincode::deserialize_from::<R, HashMap<String, BpfProgram>>(reader), }; Ok(result .map_err(DeserializationError::Bincode)? .into_iter() .map(|(k, v)| (k.to_lowercase(), Arc::new(v))) .collect()) } /// Helper function for installing a BPF filter. pub fn apply_filter(bpf_filter: BpfProgramRef) -> std::result::Result<(), InstallationError> { // If the program is empty, don't install the filter. if bpf_filter.is_empty() { return Ok(()); } // If the program length is greater than the limit allowed by the kernel, // fail quickly. Otherwise, `prctl` will give a more cryptic error code. if bpf_filter.len() > BPF_MAX_LEN { return Err(InstallationError::FilterTooLarge); } unsafe { { let rc = libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); if rc!= 0 { return Err(InstallationError::Prctl(*libc::__errno_location())); } } let bpf_prog = sock_fprog { len: bpf_filter.len() as u16, filter: bpf_filter.as_ptr(), }; let bpf_prog_ptr = &bpf_prog as *const sock_fprog; { let rc = libc::prctl( libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER, bpf_prog_ptr, ); if rc!= 0 { return Err(InstallationError::Prctl(*libc::__errno_location())); } } } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::common::BpfProgram; use std::collections::HashMap; use std::sync::Arc; use std::thread; #[test] fn
() { // Malformed bincode binary. { let data = "adassafvc".to_string(); assert!(deserialize_binary(data.as_bytes(), None).is_err()); } // Test that the binary deserialization is correct, and that the thread keys // have been lowercased. { let bpf_prog = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, ]; let mut filter_map: HashMap<String, BpfProgram> = HashMap::new(); filter_map.insert("VcpU".to_string(), bpf_prog.clone()); let bytes = bincode::serialize(&filter_map).unwrap(); let mut expected_res = BpfThreadMap::new(); expected_res.insert("vcpu".to_string(), Arc::new(bpf_prog)); assert_eq!(deserialize_binary(&bytes[..], None).unwrap(), expected_res); } // Test deserialization with binary_limit. { let bpf_prog = vec![sock_filter { code: 32, jt: 0, jf: 0, k: 0, }]; let mut filter_map: HashMap<String, BpfProgram> = HashMap::new(); filter_map.insert("t1".to_string(), bpf_prog.clone()); let bytes = bincode::serialize(&filter_map).unwrap(); // Binary limit too low. assert!(matches!( deserialize_binary(&bytes[..], Some(20)).unwrap_err(), DeserializationError::Bincode(error) if error.to_string() == "the size limit has been reached" )); let mut expected_res = BpfThreadMap::new(); expected_res.insert("t1".to_string(), Arc::new(bpf_prog)); // Correct binary limit. assert_eq!( deserialize_binary(&bytes[..], Some(50)).unwrap(), expected_res ); } } #[test] fn test_filter_apply() { // Test filter too large. thread::spawn(|| { let filter: BpfProgram = vec![ sock_filter { code: 6, jt: 0, jf: 0, k: 0, }; 5000 // Limit is 4096 ]; // Apply seccomp filter. assert_eq!( apply_filter(&filter).unwrap_err(), InstallationError::FilterTooLarge ); }) .join() .unwrap(); // Test empty filter. thread::spawn(|| { let filter: BpfProgram = vec![]; assert_eq!(filter.len(), 0); let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); apply_filter(&filter).unwrap(); // test that seccomp level remains 0 on failure. let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); }) .join() .unwrap(); // Test invalid BPF code. thread::spawn(|| { let filter = vec![sock_filter { // invalid opcode code: 9999, jt: 0, jf: 0, k: 0, }]; let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); assert_eq!( apply_filter(&filter).unwrap_err(), InstallationError::Prctl(22) ); // test that seccomp level remains 0 on failure. let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); }) .join() .unwrap(); } }
test_deserialize_binary
identifier_name
lib.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! The library crate that defines common helper functions that are generally used in //! conjunction with seccompiler-bin. mod common; use bincode::Error as BincodeError; use bincode::{DefaultOptions, Options}; use common::BPF_MAX_LEN; use std::collections::HashMap; use std::fmt::{Display, Formatter}; use std::io::Read; use std::sync::Arc; // Re-export the data types needed for calling the helper functions. pub use common::{sock_filter, BpfProgram}; /// Type that associates a thread category to a BPF program. pub type BpfThreadMap = HashMap<String, Arc<BpfProgram>>; // BPF structure definition for filter array. // See /usr/include/linux/filter.h. #[repr(C)] struct sock_fprog { pub len: ::std::os::raw::c_ushort, pub filter: *const sock_filter, } /// Reference to program made up of a sequence of BPF instructions. pub type BpfProgramRef<'a> = &'a [sock_filter]; /// Binary filter deserialization errors. #[derive(Debug)] pub enum DeserializationError { /// Error when doing bincode deserialization. Bincode(BincodeError), } impl Display for DeserializationError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { use self::DeserializationError::*; match *self { Bincode(ref err) => write!(f, "Bincode deserialization failed: {}", err), } } } /// Filter installation errors. #[derive(Debug, PartialEq)] pub enum InstallationError { /// Filter exceeds the maximum number of instructions that a BPF program can have. FilterTooLarge, /// Error returned by `prctl`. Prctl(i32), } impl Display for InstallationError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { use self::InstallationError::*; match *self { FilterTooLarge => write!( f, "Filter length exceeds the maximum size of {} instructions ", BPF_MAX_LEN ), Prctl(ref errno) => write!(f, "`prctl` syscall failed with error code: {}", errno), } } } /// Deserialize a BPF file into a collection of usable BPF filters. /// Has an optional `bytes_limit` that is passed to bincode to constrain the maximum amount of memory /// that we can allocate while performing the deserialization. /// It's recommended that the integrator of the library uses this to prevent memory allocations DOS-es. pub fn deserialize_binary<R: Read>( reader: R, bytes_limit: Option<u64>, ) -> std::result::Result<BpfThreadMap, DeserializationError> { let result = match bytes_limit { // Also add the default options. These are not part of the `DefaultOptions` as per // this issue: https://github.com/servo/bincode/issues/333 Some(limit) => DefaultOptions::new() .with_fixint_encoding() .allow_trailing_bytes() .with_limit(limit) .deserialize_from::<R, HashMap<String, BpfProgram>>(reader), // No limit is the default. None => bincode::deserialize_from::<R, HashMap<String, BpfProgram>>(reader), }; Ok(result .map_err(DeserializationError::Bincode)? .into_iter() .map(|(k, v)| (k.to_lowercase(), Arc::new(v))) .collect()) } /// Helper function for installing a BPF filter. pub fn apply_filter(bpf_filter: BpfProgramRef) -> std::result::Result<(), InstallationError> { // If the program is empty, don't install the filter. if bpf_filter.is_empty() { return Ok(()); } // If the program length is greater than the limit allowed by the kernel, // fail quickly. Otherwise, `prctl` will give a more cryptic error code. if bpf_filter.len() > BPF_MAX_LEN { return Err(InstallationError::FilterTooLarge); } unsafe { { let rc = libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); if rc!= 0 { return Err(InstallationError::Prctl(*libc::__errno_location())); } } let bpf_prog = sock_fprog { len: bpf_filter.len() as u16, filter: bpf_filter.as_ptr(), }; let bpf_prog_ptr = &bpf_prog as *const sock_fprog; { let rc = libc::prctl( libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER, bpf_prog_ptr, ); if rc!= 0 { return Err(InstallationError::Prctl(*libc::__errno_location())); } } } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::common::BpfProgram; use std::collections::HashMap; use std::sync::Arc; use std::thread; #[test] fn test_deserialize_binary() { // Malformed bincode binary. { let data = "adassafvc".to_string(); assert!(deserialize_binary(data.as_bytes(), None).is_err()); } // Test that the binary deserialization is correct, and that the thread keys // have been lowercased. { let bpf_prog = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, ]; let mut filter_map: HashMap<String, BpfProgram> = HashMap::new(); filter_map.insert("VcpU".to_string(), bpf_prog.clone()); let bytes = bincode::serialize(&filter_map).unwrap(); let mut expected_res = BpfThreadMap::new(); expected_res.insert("vcpu".to_string(), Arc::new(bpf_prog)); assert_eq!(deserialize_binary(&bytes[..], None).unwrap(), expected_res); } // Test deserialization with binary_limit. { let bpf_prog = vec![sock_filter { code: 32, jt: 0, jf: 0, k: 0, }]; let mut filter_map: HashMap<String, BpfProgram> = HashMap::new(); filter_map.insert("t1".to_string(), bpf_prog.clone()); let bytes = bincode::serialize(&filter_map).unwrap();
// Binary limit too low. assert!(matches!( deserialize_binary(&bytes[..], Some(20)).unwrap_err(), DeserializationError::Bincode(error) if error.to_string() == "the size limit has been reached" )); let mut expected_res = BpfThreadMap::new(); expected_res.insert("t1".to_string(), Arc::new(bpf_prog)); // Correct binary limit. assert_eq!( deserialize_binary(&bytes[..], Some(50)).unwrap(), expected_res ); } } #[test] fn test_filter_apply() { // Test filter too large. thread::spawn(|| { let filter: BpfProgram = vec![ sock_filter { code: 6, jt: 0, jf: 0, k: 0, }; 5000 // Limit is 4096 ]; // Apply seccomp filter. assert_eq!( apply_filter(&filter).unwrap_err(), InstallationError::FilterTooLarge ); }) .join() .unwrap(); // Test empty filter. thread::spawn(|| { let filter: BpfProgram = vec![]; assert_eq!(filter.len(), 0); let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); apply_filter(&filter).unwrap(); // test that seccomp level remains 0 on failure. let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); }) .join() .unwrap(); // Test invalid BPF code. thread::spawn(|| { let filter = vec![sock_filter { // invalid opcode code: 9999, jt: 0, jf: 0, k: 0, }]; let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); assert_eq!( apply_filter(&filter).unwrap_err(), InstallationError::Prctl(22) ); // test that seccomp level remains 0 on failure. let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); }) .join() .unwrap(); } }
random_line_split
lib.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! The library crate that defines common helper functions that are generally used in //! conjunction with seccompiler-bin. mod common; use bincode::Error as BincodeError; use bincode::{DefaultOptions, Options}; use common::BPF_MAX_LEN; use std::collections::HashMap; use std::fmt::{Display, Formatter}; use std::io::Read; use std::sync::Arc; // Re-export the data types needed for calling the helper functions. pub use common::{sock_filter, BpfProgram}; /// Type that associates a thread category to a BPF program. pub type BpfThreadMap = HashMap<String, Arc<BpfProgram>>; // BPF structure definition for filter array. // See /usr/include/linux/filter.h. #[repr(C)] struct sock_fprog { pub len: ::std::os::raw::c_ushort, pub filter: *const sock_filter, } /// Reference to program made up of a sequence of BPF instructions. pub type BpfProgramRef<'a> = &'a [sock_filter]; /// Binary filter deserialization errors. #[derive(Debug)] pub enum DeserializationError { /// Error when doing bincode deserialization. Bincode(BincodeError), } impl Display for DeserializationError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { use self::DeserializationError::*; match *self { Bincode(ref err) => write!(f, "Bincode deserialization failed: {}", err), } } } /// Filter installation errors. #[derive(Debug, PartialEq)] pub enum InstallationError { /// Filter exceeds the maximum number of instructions that a BPF program can have. FilterTooLarge, /// Error returned by `prctl`. Prctl(i32), } impl Display for InstallationError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { use self::InstallationError::*; match *self { FilterTooLarge => write!( f, "Filter length exceeds the maximum size of {} instructions ", BPF_MAX_LEN ), Prctl(ref errno) => write!(f, "`prctl` syscall failed with error code: {}", errno), } } } /// Deserialize a BPF file into a collection of usable BPF filters. /// Has an optional `bytes_limit` that is passed to bincode to constrain the maximum amount of memory /// that we can allocate while performing the deserialization. /// It's recommended that the integrator of the library uses this to prevent memory allocations DOS-es. pub fn deserialize_binary<R: Read>( reader: R, bytes_limit: Option<u64>, ) -> std::result::Result<BpfThreadMap, DeserializationError> { let result = match bytes_limit { // Also add the default options. These are not part of the `DefaultOptions` as per // this issue: https://github.com/servo/bincode/issues/333 Some(limit) => DefaultOptions::new() .with_fixint_encoding() .allow_trailing_bytes() .with_limit(limit) .deserialize_from::<R, HashMap<String, BpfProgram>>(reader), // No limit is the default. None => bincode::deserialize_from::<R, HashMap<String, BpfProgram>>(reader), }; Ok(result .map_err(DeserializationError::Bincode)? .into_iter() .map(|(k, v)| (k.to_lowercase(), Arc::new(v))) .collect()) } /// Helper function for installing a BPF filter. pub fn apply_filter(bpf_filter: BpfProgramRef) -> std::result::Result<(), InstallationError> { // If the program is empty, don't install the filter. if bpf_filter.is_empty() { return Ok(()); } // If the program length is greater than the limit allowed by the kernel, // fail quickly. Otherwise, `prctl` will give a more cryptic error code. if bpf_filter.len() > BPF_MAX_LEN { return Err(InstallationError::FilterTooLarge); } unsafe { { let rc = libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); if rc!= 0 { return Err(InstallationError::Prctl(*libc::__errno_location())); } } let bpf_prog = sock_fprog { len: bpf_filter.len() as u16, filter: bpf_filter.as_ptr(), }; let bpf_prog_ptr = &bpf_prog as *const sock_fprog; { let rc = libc::prctl( libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER, bpf_prog_ptr, ); if rc!= 0
} } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::common::BpfProgram; use std::collections::HashMap; use std::sync::Arc; use std::thread; #[test] fn test_deserialize_binary() { // Malformed bincode binary. { let data = "adassafvc".to_string(); assert!(deserialize_binary(data.as_bytes(), None).is_err()); } // Test that the binary deserialization is correct, and that the thread keys // have been lowercased. { let bpf_prog = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, ]; let mut filter_map: HashMap<String, BpfProgram> = HashMap::new(); filter_map.insert("VcpU".to_string(), bpf_prog.clone()); let bytes = bincode::serialize(&filter_map).unwrap(); let mut expected_res = BpfThreadMap::new(); expected_res.insert("vcpu".to_string(), Arc::new(bpf_prog)); assert_eq!(deserialize_binary(&bytes[..], None).unwrap(), expected_res); } // Test deserialization with binary_limit. { let bpf_prog = vec![sock_filter { code: 32, jt: 0, jf: 0, k: 0, }]; let mut filter_map: HashMap<String, BpfProgram> = HashMap::new(); filter_map.insert("t1".to_string(), bpf_prog.clone()); let bytes = bincode::serialize(&filter_map).unwrap(); // Binary limit too low. assert!(matches!( deserialize_binary(&bytes[..], Some(20)).unwrap_err(), DeserializationError::Bincode(error) if error.to_string() == "the size limit has been reached" )); let mut expected_res = BpfThreadMap::new(); expected_res.insert("t1".to_string(), Arc::new(bpf_prog)); // Correct binary limit. assert_eq!( deserialize_binary(&bytes[..], Some(50)).unwrap(), expected_res ); } } #[test] fn test_filter_apply() { // Test filter too large. thread::spawn(|| { let filter: BpfProgram = vec![ sock_filter { code: 6, jt: 0, jf: 0, k: 0, }; 5000 // Limit is 4096 ]; // Apply seccomp filter. assert_eq!( apply_filter(&filter).unwrap_err(), InstallationError::FilterTooLarge ); }) .join() .unwrap(); // Test empty filter. thread::spawn(|| { let filter: BpfProgram = vec![]; assert_eq!(filter.len(), 0); let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); apply_filter(&filter).unwrap(); // test that seccomp level remains 0 on failure. let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); }) .join() .unwrap(); // Test invalid BPF code. thread::spawn(|| { let filter = vec![sock_filter { // invalid opcode code: 9999, jt: 0, jf: 0, k: 0, }]; let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); assert_eq!( apply_filter(&filter).unwrap_err(), InstallationError::Prctl(22) ); // test that seccomp level remains 0 on failure. let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); }) .join() .unwrap(); } }
{ return Err(InstallationError::Prctl(*libc::__errno_location())); }
conditional_block
lib.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! The library crate that defines common helper functions that are generally used in //! conjunction with seccompiler-bin. mod common; use bincode::Error as BincodeError; use bincode::{DefaultOptions, Options}; use common::BPF_MAX_LEN; use std::collections::HashMap; use std::fmt::{Display, Formatter}; use std::io::Read; use std::sync::Arc; // Re-export the data types needed for calling the helper functions. pub use common::{sock_filter, BpfProgram}; /// Type that associates a thread category to a BPF program. pub type BpfThreadMap = HashMap<String, Arc<BpfProgram>>; // BPF structure definition for filter array. // See /usr/include/linux/filter.h. #[repr(C)] struct sock_fprog { pub len: ::std::os::raw::c_ushort, pub filter: *const sock_filter, } /// Reference to program made up of a sequence of BPF instructions. pub type BpfProgramRef<'a> = &'a [sock_filter]; /// Binary filter deserialization errors. #[derive(Debug)] pub enum DeserializationError { /// Error when doing bincode deserialization. Bincode(BincodeError), } impl Display for DeserializationError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { use self::DeserializationError::*; match *self { Bincode(ref err) => write!(f, "Bincode deserialization failed: {}", err), } } } /// Filter installation errors. #[derive(Debug, PartialEq)] pub enum InstallationError { /// Filter exceeds the maximum number of instructions that a BPF program can have. FilterTooLarge, /// Error returned by `prctl`. Prctl(i32), } impl Display for InstallationError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { use self::InstallationError::*; match *self { FilterTooLarge => write!( f, "Filter length exceeds the maximum size of {} instructions ", BPF_MAX_LEN ), Prctl(ref errno) => write!(f, "`prctl` syscall failed with error code: {}", errno), } } } /// Deserialize a BPF file into a collection of usable BPF filters. /// Has an optional `bytes_limit` that is passed to bincode to constrain the maximum amount of memory /// that we can allocate while performing the deserialization. /// It's recommended that the integrator of the library uses this to prevent memory allocations DOS-es. pub fn deserialize_binary<R: Read>( reader: R, bytes_limit: Option<u64>, ) -> std::result::Result<BpfThreadMap, DeserializationError> { let result = match bytes_limit { // Also add the default options. These are not part of the `DefaultOptions` as per // this issue: https://github.com/servo/bincode/issues/333 Some(limit) => DefaultOptions::new() .with_fixint_encoding() .allow_trailing_bytes() .with_limit(limit) .deserialize_from::<R, HashMap<String, BpfProgram>>(reader), // No limit is the default. None => bincode::deserialize_from::<R, HashMap<String, BpfProgram>>(reader), }; Ok(result .map_err(DeserializationError::Bincode)? .into_iter() .map(|(k, v)| (k.to_lowercase(), Arc::new(v))) .collect()) } /// Helper function for installing a BPF filter. pub fn apply_filter(bpf_filter: BpfProgramRef) -> std::result::Result<(), InstallationError>
let bpf_prog = sock_fprog { len: bpf_filter.len() as u16, filter: bpf_filter.as_ptr(), }; let bpf_prog_ptr = &bpf_prog as *const sock_fprog; { let rc = libc::prctl( libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER, bpf_prog_ptr, ); if rc!= 0 { return Err(InstallationError::Prctl(*libc::__errno_location())); } } } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::common::BpfProgram; use std::collections::HashMap; use std::sync::Arc; use std::thread; #[test] fn test_deserialize_binary() { // Malformed bincode binary. { let data = "adassafvc".to_string(); assert!(deserialize_binary(data.as_bytes(), None).is_err()); } // Test that the binary deserialization is correct, and that the thread keys // have been lowercased. { let bpf_prog = vec![ sock_filter { code: 32, jt: 0, jf: 0, k: 0, }, sock_filter { code: 32, jt: 0, jf: 0, k: 4, }, ]; let mut filter_map: HashMap<String, BpfProgram> = HashMap::new(); filter_map.insert("VcpU".to_string(), bpf_prog.clone()); let bytes = bincode::serialize(&filter_map).unwrap(); let mut expected_res = BpfThreadMap::new(); expected_res.insert("vcpu".to_string(), Arc::new(bpf_prog)); assert_eq!(deserialize_binary(&bytes[..], None).unwrap(), expected_res); } // Test deserialization with binary_limit. { let bpf_prog = vec![sock_filter { code: 32, jt: 0, jf: 0, k: 0, }]; let mut filter_map: HashMap<String, BpfProgram> = HashMap::new(); filter_map.insert("t1".to_string(), bpf_prog.clone()); let bytes = bincode::serialize(&filter_map).unwrap(); // Binary limit too low. assert!(matches!( deserialize_binary(&bytes[..], Some(20)).unwrap_err(), DeserializationError::Bincode(error) if error.to_string() == "the size limit has been reached" )); let mut expected_res = BpfThreadMap::new(); expected_res.insert("t1".to_string(), Arc::new(bpf_prog)); // Correct binary limit. assert_eq!( deserialize_binary(&bytes[..], Some(50)).unwrap(), expected_res ); } } #[test] fn test_filter_apply() { // Test filter too large. thread::spawn(|| { let filter: BpfProgram = vec![ sock_filter { code: 6, jt: 0, jf: 0, k: 0, }; 5000 // Limit is 4096 ]; // Apply seccomp filter. assert_eq!( apply_filter(&filter).unwrap_err(), InstallationError::FilterTooLarge ); }) .join() .unwrap(); // Test empty filter. thread::spawn(|| { let filter: BpfProgram = vec![]; assert_eq!(filter.len(), 0); let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); apply_filter(&filter).unwrap(); // test that seccomp level remains 0 on failure. let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); }) .join() .unwrap(); // Test invalid BPF code. thread::spawn(|| { let filter = vec![sock_filter { // invalid opcode code: 9999, jt: 0, jf: 0, k: 0, }]; let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); assert_eq!( apply_filter(&filter).unwrap_err(), InstallationError::Prctl(22) ); // test that seccomp level remains 0 on failure. let seccomp_level = unsafe { libc::prctl(libc::PR_GET_SECCOMP) }; assert_eq!(seccomp_level, 0); }) .join() .unwrap(); } }
{ // If the program is empty, don't install the filter. if bpf_filter.is_empty() { return Ok(()); } // If the program length is greater than the limit allowed by the kernel, // fail quickly. Otherwise, `prctl` will give a more cryptic error code. if bpf_filter.len() > BPF_MAX_LEN { return Err(InstallationError::FilterTooLarge); } unsafe { { let rc = libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); if rc != 0 { return Err(InstallationError::Prctl(*libc::__errno_location())); } }
identifier_body
2_13.rs
extern crate cryptopal; extern crate hex; use std::iter::repeat; use std::str; use cryptopal::oracle::{Oracle, ProfileOracle}; use cryptopal::pkcs; use cryptopal::util; fn string_of_n(n: usize) -> String { repeat("B").take(n).collect::<String>() } fn main() { let oracle = ProfileOracle::new(); let block_size = util::calculate_oracle_block_size(&oracle).expect("bad oracle"); let payload_length = util::calculate_total_payload_length(&oracle).expect("bad payload"); let prefix_length = util::calculate_prefix_length(&oracle).expect("bad oracle"); let suffix_length = payload_length - prefix_length; let padding_to_block_edge = block_size - (prefix_length % block_size); // padding bytes necessary to align block edge at role= let role_assign_offset = (padding_to_block_edge + block_size + "user".len()) - suffix_length; // generate the first ciphertext w/ isolated 'user' component let c1 = oracle.encrypt(string_of_n(role_assign_offset).as_bytes()); let c1_chunked: Vec<&[u8]> = c1.chunks(block_size).collect(); // construct a new plaintext w/ (padding_to_block_edge|admin+pkcs) to // produce a ciphertext w/ isolated `admin` component to swap into C1 let mut p2: Vec<u8> = Vec::new();
// create our composite ciphertext using the first two blocks of the C1 // ciphertext (designed to place the role= at the block edge) // append the C2 ciphertext block which contains the isolated `admin` literal let mut f: Vec<u8> = Vec::new(); c1_chunked[0..2].iter().for_each(|c| f.extend_from_slice(c)); f.extend(c2_chunked[1]); // decrypt & verify let d = oracle.decrypt(&f); println!("d: {}", str::from_utf8(&d).unwrap()); assert_eq!(true, oracle.verify(&oracle.decrypt(&f))); }
p2.extend_from_slice(string_of_n(padding_to_block_edge).as_bytes()); p2.extend(pkcs::pad("admin".as_bytes(), block_size)); let c2 = oracle.encrypt(&p2); let c2_chunked: Vec<&[u8]> = c2.chunks(block_size).collect();
random_line_split
2_13.rs
extern crate cryptopal; extern crate hex; use std::iter::repeat; use std::str; use cryptopal::oracle::{Oracle, ProfileOracle}; use cryptopal::pkcs; use cryptopal::util; fn string_of_n(n: usize) -> String { repeat("B").take(n).collect::<String>() } fn
() { let oracle = ProfileOracle::new(); let block_size = util::calculate_oracle_block_size(&oracle).expect("bad oracle"); let payload_length = util::calculate_total_payload_length(&oracle).expect("bad payload"); let prefix_length = util::calculate_prefix_length(&oracle).expect("bad oracle"); let suffix_length = payload_length - prefix_length; let padding_to_block_edge = block_size - (prefix_length % block_size); // padding bytes necessary to align block edge at role= let role_assign_offset = (padding_to_block_edge + block_size + "user".len()) - suffix_length; // generate the first ciphertext w/ isolated 'user' component let c1 = oracle.encrypt(string_of_n(role_assign_offset).as_bytes()); let c1_chunked: Vec<&[u8]> = c1.chunks(block_size).collect(); // construct a new plaintext w/ (padding_to_block_edge|admin+pkcs) to // produce a ciphertext w/ isolated `admin` component to swap into C1 let mut p2: Vec<u8> = Vec::new(); p2.extend_from_slice(string_of_n(padding_to_block_edge).as_bytes()); p2.extend(pkcs::pad("admin".as_bytes(), block_size)); let c2 = oracle.encrypt(&p2); let c2_chunked: Vec<&[u8]> = c2.chunks(block_size).collect(); // create our composite ciphertext using the first two blocks of the C1 // ciphertext (designed to place the role= at the block edge) // append the C2 ciphertext block which contains the isolated `admin` literal let mut f: Vec<u8> = Vec::new(); c1_chunked[0..2].iter().for_each(|c| f.extend_from_slice(c)); f.extend(c2_chunked[1]); // decrypt & verify let d = oracle.decrypt(&f); println!("d: {}", str::from_utf8(&d).unwrap()); assert_eq!(true, oracle.verify(&oracle.decrypt(&f))); }
main
identifier_name
2_13.rs
extern crate cryptopal; extern crate hex; use std::iter::repeat; use std::str; use cryptopal::oracle::{Oracle, ProfileOracle}; use cryptopal::pkcs; use cryptopal::util; fn string_of_n(n: usize) -> String
fn main() { let oracle = ProfileOracle::new(); let block_size = util::calculate_oracle_block_size(&oracle).expect("bad oracle"); let payload_length = util::calculate_total_payload_length(&oracle).expect("bad payload"); let prefix_length = util::calculate_prefix_length(&oracle).expect("bad oracle"); let suffix_length = payload_length - prefix_length; let padding_to_block_edge = block_size - (prefix_length % block_size); // padding bytes necessary to align block edge at role= let role_assign_offset = (padding_to_block_edge + block_size + "user".len()) - suffix_length; // generate the first ciphertext w/ isolated 'user' component let c1 = oracle.encrypt(string_of_n(role_assign_offset).as_bytes()); let c1_chunked: Vec<&[u8]> = c1.chunks(block_size).collect(); // construct a new plaintext w/ (padding_to_block_edge|admin+pkcs) to // produce a ciphertext w/ isolated `admin` component to swap into C1 let mut p2: Vec<u8> = Vec::new(); p2.extend_from_slice(string_of_n(padding_to_block_edge).as_bytes()); p2.extend(pkcs::pad("admin".as_bytes(), block_size)); let c2 = oracle.encrypt(&p2); let c2_chunked: Vec<&[u8]> = c2.chunks(block_size).collect(); // create our composite ciphertext using the first two blocks of the C1 // ciphertext (designed to place the role= at the block edge) // append the C2 ciphertext block which contains the isolated `admin` literal let mut f: Vec<u8> = Vec::new(); c1_chunked[0..2].iter().for_each(|c| f.extend_from_slice(c)); f.extend(c2_chunked[1]); // decrypt & verify let d = oracle.decrypt(&f); println!("d: {}", str::from_utf8(&d).unwrap()); assert_eq!(true, oracle.verify(&oracle.decrypt(&f))); }
{ repeat("B").take(n).collect::<String>() }
identifier_body
scif.rs
//! formatter for %e %E scientific notation subs use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; pub struct Scif { as_num: f64, } impl Scif { pub fn new() -> Scif { Scif { as_num: 0.0 } } } impl Formatter for Scif { fn get_primitive( &self, field: &FormatField, inprefix: &InPrefix, str_in: &str, ) -> Option<FormatPrimitive>
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
{ let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze( str_in, inprefix, Some(second_field as usize + 1), None, false, ); let f = get_primitive_dec( inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, Some(*field.field_char == 'E'), ); Some(f) }
identifier_body
scif.rs
//! formatter for %e %E scientific notation subs use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; pub struct Scif { as_num: f64, } impl Scif {
impl Formatter for Scif { fn get_primitive( &self, field: &FormatField, inprefix: &InPrefix, str_in: &str, ) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze( str_in, inprefix, Some(second_field as usize + 1), None, false, ); let f = get_primitive_dec( inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, Some(*field.field_char == 'E'), ); Some(f) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
pub fn new() -> Scif { Scif { as_num: 0.0 } } }
random_line_split
scif.rs
//! formatter for %e %E scientific notation subs use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; pub struct Scif { as_num: f64, } impl Scif { pub fn new() -> Scif { Scif { as_num: 0.0 } } } impl Formatter for Scif { fn
( &self, field: &FormatField, inprefix: &InPrefix, str_in: &str, ) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze( str_in, inprefix, Some(second_field as usize + 1), None, false, ); let f = get_primitive_dec( inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, Some(*field.field_char == 'E'), ); Some(f) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
get_primitive
identifier_name
const-vecs-and-slices.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. static x : [int; 4] = [1,2,3,4]; static y : &'static [int] = &[1,2,3,4]; static z : &'static [int; 4] = &[1,2,3,4]; static zz : &'static [int] = &[1,2,3,4]; pub fn main() { println!("{}", x[1]); println!("{}", y[1]); println!("{}", z[1]); println!("{}", zz[1]); assert_eq!(x[1], 2); assert_eq!(x[3], 4); assert_eq!(x[3], y[3]); assert_eq!(z[1], 2); assert_eq!(z[3], 4); assert_eq!(z[3], y[3]); assert_eq!(zz[1], 2); assert_eq!(zz[3], 4); assert_eq!(zz[3], y[3]); }
//
random_line_split
const-vecs-and-slices.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. static x : [int; 4] = [1,2,3,4]; static y : &'static [int] = &[1,2,3,4]; static z : &'static [int; 4] = &[1,2,3,4]; static zz : &'static [int] = &[1,2,3,4]; pub fn main()
{ println!("{}", x[1]); println!("{}", y[1]); println!("{}", z[1]); println!("{}", zz[1]); assert_eq!(x[1], 2); assert_eq!(x[3], 4); assert_eq!(x[3], y[3]); assert_eq!(z[1], 2); assert_eq!(z[3], 4); assert_eq!(z[3], y[3]); assert_eq!(zz[1], 2); assert_eq!(zz[3], 4); assert_eq!(zz[3], y[3]); }
identifier_body
const-vecs-and-slices.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. static x : [int; 4] = [1,2,3,4]; static y : &'static [int] = &[1,2,3,4]; static z : &'static [int; 4] = &[1,2,3,4]; static zz : &'static [int] = &[1,2,3,4]; pub fn
() { println!("{}", x[1]); println!("{}", y[1]); println!("{}", z[1]); println!("{}", zz[1]); assert_eq!(x[1], 2); assert_eq!(x[3], 4); assert_eq!(x[3], y[3]); assert_eq!(z[1], 2); assert_eq!(z[3], 4); assert_eq!(z[3], y[3]); assert_eq!(zz[1], 2); assert_eq!(zz[3], 4); assert_eq!(zz[3], y[3]); }
main
identifier_name
lib.rs
//! # Test CLI Applications //! //! This crate's goal is to provide you some very easy tools to test your CLI //! applications. It can currently execute child processes and validate their //! exit status as well as stdout and stderr output against your assertions. //! //! Include the crate like //! //! ```rust //! #[macro_use] // <-- import the convenience macro (optional) //! extern crate assert_cli; //! # fn main() { } //! ``` //! //! ## Basic Examples //! //! Here's a trivial example: //! //! ```rust //! assert_cli::Assert::command(&["echo", "42"]) //! .stdout().contains("42") //! .unwrap(); //! ``` //! //! And here is one that will fail: //! //! ```rust,should_panic //! assert_cli::Assert::command(&["echo", "42"]) //! .stdout().is("1337") //! .unwrap(); //! ``` //! //! this will show a nice, colorful diff in your terminal, like this: //! //! ```diff //! -1337 //! +42 //! ``` //! //! ## `assert_cmd!` Macro //! //! Alternatively, you can use the `assert_cmd!` macro to construct the command more conveniently, //! but please carefully read the limitations below, or this may seriously go wrong. //! //! ```rust //! # #[macro_use] extern crate assert_cli; //! # fn main() { //! assert_cmd!(echo "42").stdout().contains("42").unwrap(); //! # } //! ``` //! //! **Tips** //! //! - Don't forget to import the crate with `#[macro_use]`. ;-) //! - Enclose arguments in the `assert_cmd!` macro in quotes `"`, //! if there are special characters, which the macro doesn't accept, e.g. //! `assert_cmd!(cat "foo.txt")`. //! //! ## Exit Status //! //! All assertion default to checking that the command exited with success. //! //! However, when you expect a command to fail, you can express it like this: //! //! ```rust //! # #[macro_use] extern crate assert_cli; //! # fn main() { //! assert_cmd!(cat "non-existing-file") //! .fails() //! .unwrap(); //! # } //! ``` //! //! Some notes on this: //! //! - Use `fails_with` to assert a specific exit status. //! - There is also a `succeeds` method, but this is already the implicit default //! and can usually be omitted. //! - The `and` method has no effect, other than to make everything more readable. //! Feel free to use it. :-) //! //! ## stdout / stderr //! //! You can add assertions on the content of **stdout** and **stderr**. They //! can be mixed together or even multiple of one stream can be used. //! //! ```rust //! # #[macro_use] extern crate assert_cli; //! # fn main() { //! assert_cmd!(echo "Hello world! The ansswer is 42.") //! .stdout().contains("Hello world") //! .stdout().contains("42") //! .stderr().is("") //! .unwrap(); //! # } //! ``` //! //! ## Assert CLI Crates //! //! If you are testing a Rust binary crate, you can start with //! `Assert::main_binary()` to use `cargo run` as command. Or, if you want to //! run a specific binary (if you have more than one), use //! `Assert::cargo_binary`. //! //! ## Don't Panic! //! //! If you don't want it to panic when the assertions are not met, simply call //! `.execute` instead of `.unwrap` to get a `Result`: //! //! ```rust //! # #[macro_use] extern crate assert_cli; //! # fn main() { //! let x = assert_cmd!(echo "1337").stdout().is("42").execute(); //! assert!(x.is_err()); //! # } //! ``` #![deny(missing_docs)] extern crate colored; extern crate difference; extern crate environment; #[macro_use] extern crate failure; #[macro_use] extern crate failure_derive; extern crate serde_json; mod errors; pub use errors::AssertionError; #[macro_use]
mod assert; mod diff; mod output; pub use assert::Assert; pub use assert::OutputAssertionBuilder; /// Environment is a re-export of the Environment crate /// /// It allow you to define/override environment variables for one or more assertions. pub use environment::Environment;
mod macros; pub use macros::flatten_escaped_string;
random_line_split
main.rs
use byteorder::{BigEndian, ByteOrder}; fn main() { // Exercise external crate, printing to stdout. let buf = &[1,2,3,4]; let n = <BigEndian as ByteOrder>::read_u32(buf); assert_eq!(n, 0x01020304); println!("{:#010x}", n); // Access program arguments, printing to stderr. for arg in std::env::args() { eprintln!("{}", arg); } } #[cfg(test)] mod test { use rand::{Rng, SeedableRng}; // Make sure in-crate tests with dev-dependencies work #[test] fn
() { let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef); let x: u32 = rng.gen(); let y: usize = rng.gen(); let z: u128 = rng.gen(); assert_ne!(x as usize, y); assert_ne!(y as u128, z); } }
rng
identifier_name
main.rs
use byteorder::{BigEndian, ByteOrder}; fn main() { // Exercise external crate, printing to stdout. let buf = &[1,2,3,4]; let n = <BigEndian as ByteOrder>::read_u32(buf); assert_eq!(n, 0x01020304); println!("{:#010x}", n);
eprintln!("{}", arg); } } #[cfg(test)] mod test { use rand::{Rng, SeedableRng}; // Make sure in-crate tests with dev-dependencies work #[test] fn rng() { let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef); let x: u32 = rng.gen(); let y: usize = rng.gen(); let z: u128 = rng.gen(); assert_ne!(x as usize, y); assert_ne!(y as u128, z); } }
// Access program arguments, printing to stderr. for arg in std::env::args() {
random_line_split
main.rs
use byteorder::{BigEndian, ByteOrder}; fn main() { // Exercise external crate, printing to stdout. let buf = &[1,2,3,4]; let n = <BigEndian as ByteOrder>::read_u32(buf); assert_eq!(n, 0x01020304); println!("{:#010x}", n); // Access program arguments, printing to stderr. for arg in std::env::args() { eprintln!("{}", arg); } } #[cfg(test)] mod test { use rand::{Rng, SeedableRng}; // Make sure in-crate tests with dev-dependencies work #[test] fn rng()
}
{ let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef); let x: u32 = rng.gen(); let y: usize = rng.gen(); let z: u128 = rng.gen(); assert_ne!(x as usize, y); assert_ne!(y as u128, z); }
identifier_body
executor.rs
use crossbeam::channel; use scoped_pool::{Pool, ThreadConfig}; use Result; /// Search executor whether search request are single thread or multithread. /// /// We don't expose Rayon thread pool directly here for several reasons. /// /// First dependency hell. It is not a good idea to expose the /// API of a dependency, knowing it might conflict with a different version /// used by the client. Second, we may stop using rayon in the future. pub enum Executor { SingleThread, ThreadPool(Pool), } impl Executor { /// Creates an Executor that performs all task in the caller thread. pub fn single_thread() -> Executor { Executor::SingleThread } // Creates an Executor that dispatches the tasks in a thread pool. pub fn multi_thread(num_threads: usize, prefix: &'static str) -> Executor { let thread_config = ThreadConfig::new().prefix(prefix); let pool = Pool::with_thread_config(num_threads, thread_config); Executor::ThreadPool(pool) } // Perform a map in the thread pool. // // Regardless of the executor (`SingleThread` or `ThreadPool`), panics in the task // will propagate to the caller. pub fn map< A: Send, R: Send, AIterator: Iterator<Item = A>, F: Sized + Sync + Fn(A) -> Result<R>, >( &self, f: F, args: AIterator, ) -> Result<Vec<R>> { match self { Executor::SingleThread => args.map(f).collect::<Result<_>>(), Executor::ThreadPool(pool) => { let args_with_indices: Vec<(usize, A)> = args.enumerate().collect(); let num_fruits = args_with_indices.len(); let fruit_receiver = { let (fruit_sender, fruit_receiver) = channel::unbounded(); pool.scoped(|scope| { for arg_with_idx in args_with_indices { scope.execute(|| { let (idx, arg) = arg_with_idx; let fruit = f(arg); if let Err(err) = fruit_sender.send((idx, fruit)) { error!("Failed to send search task. It probably means all search threads have panicked. {:?}", err); } }); } }); fruit_receiver // This ends the scope of fruit_sender. // This is important as it makes it possible for the fruit_receiver iteration to // terminate. }; // This is lame, but safe. let mut results_with_position = Vec::with_capacity(num_fruits); for (pos, fruit_res) in fruit_receiver { let fruit = fruit_res?; results_with_position.push((pos, fruit)); } results_with_position.sort_by_key(|(pos, _)| *pos); assert_eq!(results_with_position.len(), num_fruits); Ok(results_with_position .into_iter() .map(|(_, fruit)| fruit) .collect::<Vec<_>>()) } } }
} #[cfg(test)] mod tests { use super::Executor; #[test] #[should_panic(expected = "panic should propagate")] fn test_panic_propagates_single_thread() { let _result: Vec<usize> = Executor::single_thread() .map( |_| { panic!("panic should propagate"); }, vec![0].into_iter(), ) .unwrap(); } #[test] #[should_panic] //< unfortunately the panic message is not propagated fn test_panic_propagates_multi_thread() { let _result: Vec<usize> = Executor::multi_thread(1, "search-test") .map( |_| { panic!("panic should propagate"); }, vec![0].into_iter(), ) .unwrap(); } #[test] fn test_map_singlethread() { let result: Vec<usize> = Executor::single_thread() .map(|i| Ok(i * 2), 0..1_000) .unwrap(); assert_eq!(result.len(), 1_000); for i in 0..1_000 { assert_eq!(result[i], i * 2); } } #[test] fn test_map_multithread() { let result: Vec<usize> = Executor::multi_thread(3, "search-test") .map(|i| Ok(i * 2), 0..10) .unwrap(); assert_eq!(result.len(), 10); for i in 0..10 { assert_eq!(result[i], i * 2); } } }
random_line_split
executor.rs
use crossbeam::channel; use scoped_pool::{Pool, ThreadConfig}; use Result; /// Search executor whether search request are single thread or multithread. /// /// We don't expose Rayon thread pool directly here for several reasons. /// /// First dependency hell. It is not a good idea to expose the /// API of a dependency, knowing it might conflict with a different version /// used by the client. Second, we may stop using rayon in the future. pub enum Executor { SingleThread, ThreadPool(Pool), } impl Executor { /// Creates an Executor that performs all task in the caller thread. pub fn single_thread() -> Executor { Executor::SingleThread } // Creates an Executor that dispatches the tasks in a thread pool. pub fn multi_thread(num_threads: usize, prefix: &'static str) -> Executor { let thread_config = ThreadConfig::new().prefix(prefix); let pool = Pool::with_thread_config(num_threads, thread_config); Executor::ThreadPool(pool) } // Perform a map in the thread pool. // // Regardless of the executor (`SingleThread` or `ThreadPool`), panics in the task // will propagate to the caller. pub fn map< A: Send, R: Send, AIterator: Iterator<Item = A>, F: Sized + Sync + Fn(A) -> Result<R>, >( &self, f: F, args: AIterator, ) -> Result<Vec<R>>
// This ends the scope of fruit_sender. // This is important as it makes it possible for the fruit_receiver iteration to // terminate. }; // This is lame, but safe. let mut results_with_position = Vec::with_capacity(num_fruits); for (pos, fruit_res) in fruit_receiver { let fruit = fruit_res?; results_with_position.push((pos, fruit)); } results_with_position.sort_by_key(|(pos, _)| *pos); assert_eq!(results_with_position.len(), num_fruits); Ok(results_with_position .into_iter() .map(|(_, fruit)| fruit) .collect::<Vec<_>>()) } } } } #[cfg(test)] mod tests { use super::Executor; #[test] #[should_panic(expected = "panic should propagate")] fn test_panic_propagates_single_thread() { let _result: Vec<usize> = Executor::single_thread() .map( |_| { panic!("panic should propagate"); }, vec![0].into_iter(), ) .unwrap(); } #[test] #[should_panic] //< unfortunately the panic message is not propagated fn test_panic_propagates_multi_thread() { let _result: Vec<usize> = Executor::multi_thread(1, "search-test") .map( |_| { panic!("panic should propagate"); }, vec![0].into_iter(), ) .unwrap(); } #[test] fn test_map_singlethread() { let result: Vec<usize> = Executor::single_thread() .map(|i| Ok(i * 2), 0..1_000) .unwrap(); assert_eq!(result.len(), 1_000); for i in 0..1_000 { assert_eq!(result[i], i * 2); } } #[test] fn test_map_multithread() { let result: Vec<usize> = Executor::multi_thread(3, "search-test") .map(|i| Ok(i * 2), 0..10) .unwrap(); assert_eq!(result.len(), 10); for i in 0..10 { assert_eq!(result[i], i * 2); } } }
{ match self { Executor::SingleThread => args.map(f).collect::<Result<_>>(), Executor::ThreadPool(pool) => { let args_with_indices: Vec<(usize, A)> = args.enumerate().collect(); let num_fruits = args_with_indices.len(); let fruit_receiver = { let (fruit_sender, fruit_receiver) = channel::unbounded(); pool.scoped(|scope| { for arg_with_idx in args_with_indices { scope.execute(|| { let (idx, arg) = arg_with_idx; let fruit = f(arg); if let Err(err) = fruit_sender.send((idx, fruit)) { error!("Failed to send search task. It probably means all search threads have panicked. {:?}", err); } }); } }); fruit_receiver
identifier_body
executor.rs
use crossbeam::channel; use scoped_pool::{Pool, ThreadConfig}; use Result; /// Search executor whether search request are single thread or multithread. /// /// We don't expose Rayon thread pool directly here for several reasons. /// /// First dependency hell. It is not a good idea to expose the /// API of a dependency, knowing it might conflict with a different version /// used by the client. Second, we may stop using rayon in the future. pub enum
{ SingleThread, ThreadPool(Pool), } impl Executor { /// Creates an Executor that performs all task in the caller thread. pub fn single_thread() -> Executor { Executor::SingleThread } // Creates an Executor that dispatches the tasks in a thread pool. pub fn multi_thread(num_threads: usize, prefix: &'static str) -> Executor { let thread_config = ThreadConfig::new().prefix(prefix); let pool = Pool::with_thread_config(num_threads, thread_config); Executor::ThreadPool(pool) } // Perform a map in the thread pool. // // Regardless of the executor (`SingleThread` or `ThreadPool`), panics in the task // will propagate to the caller. pub fn map< A: Send, R: Send, AIterator: Iterator<Item = A>, F: Sized + Sync + Fn(A) -> Result<R>, >( &self, f: F, args: AIterator, ) -> Result<Vec<R>> { match self { Executor::SingleThread => args.map(f).collect::<Result<_>>(), Executor::ThreadPool(pool) => { let args_with_indices: Vec<(usize, A)> = args.enumerate().collect(); let num_fruits = args_with_indices.len(); let fruit_receiver = { let (fruit_sender, fruit_receiver) = channel::unbounded(); pool.scoped(|scope| { for arg_with_idx in args_with_indices { scope.execute(|| { let (idx, arg) = arg_with_idx; let fruit = f(arg); if let Err(err) = fruit_sender.send((idx, fruit)) { error!("Failed to send search task. It probably means all search threads have panicked. {:?}", err); } }); } }); fruit_receiver // This ends the scope of fruit_sender. // This is important as it makes it possible for the fruit_receiver iteration to // terminate. }; // This is lame, but safe. let mut results_with_position = Vec::with_capacity(num_fruits); for (pos, fruit_res) in fruit_receiver { let fruit = fruit_res?; results_with_position.push((pos, fruit)); } results_with_position.sort_by_key(|(pos, _)| *pos); assert_eq!(results_with_position.len(), num_fruits); Ok(results_with_position .into_iter() .map(|(_, fruit)| fruit) .collect::<Vec<_>>()) } } } } #[cfg(test)] mod tests { use super::Executor; #[test] #[should_panic(expected = "panic should propagate")] fn test_panic_propagates_single_thread() { let _result: Vec<usize> = Executor::single_thread() .map( |_| { panic!("panic should propagate"); }, vec![0].into_iter(), ) .unwrap(); } #[test] #[should_panic] //< unfortunately the panic message is not propagated fn test_panic_propagates_multi_thread() { let _result: Vec<usize> = Executor::multi_thread(1, "search-test") .map( |_| { panic!("panic should propagate"); }, vec![0].into_iter(), ) .unwrap(); } #[test] fn test_map_singlethread() { let result: Vec<usize> = Executor::single_thread() .map(|i| Ok(i * 2), 0..1_000) .unwrap(); assert_eq!(result.len(), 1_000); for i in 0..1_000 { assert_eq!(result[i], i * 2); } } #[test] fn test_map_multithread() { let result: Vec<usize> = Executor::multi_thread(3, "search-test") .map(|i| Ok(i * 2), 0..10) .unwrap(); assert_eq!(result.len(), 10); for i in 0..10 { assert_eq!(result[i], i * 2); } } }
Executor
identifier_name
lib.rs
#![deny(broken_intra_doc_links)] //! Implementation of marshaller for rust-protobuf parameter types. use bytes::Bytes; use grpc::marshall::Marshaller; use protobuf::CodedInputStream; use protobuf::Message; pub struct MarshallerProtobuf; impl<M: Message> Marshaller<M> for MarshallerProtobuf { fn write_size_estimate(&self, _m: &M) -> grpc::Result<u32>
fn write(&self, m: &M, _size_esimate: u32, out: &mut Vec<u8>) -> grpc::Result<()> { m.write_to_vec(out) .map_err(|e| grpc::Error::Marshaller(Box::new(e))) } fn read(&self, buf: Bytes) -> grpc::Result<M> { // TODO: make protobuf simple let mut is = CodedInputStream::from_carllerche_bytes(&buf); let mut r: M = M::new(); r.merge_from(&mut is) .map_err(|e| grpc::Error::Marshaller(Box::new(e)))?; r.check_initialized() .map_err(|e| grpc::Error::Marshaller(Box::new(e)))?; Ok(r) } }
{ // TODO: implement it Ok(0) }
identifier_body
lib.rs
#![deny(broken_intra_doc_links)] //! Implementation of marshaller for rust-protobuf parameter types. use bytes::Bytes; use grpc::marshall::Marshaller; use protobuf::CodedInputStream; use protobuf::Message; pub struct
; impl<M: Message> Marshaller<M> for MarshallerProtobuf { fn write_size_estimate(&self, _m: &M) -> grpc::Result<u32> { // TODO: implement it Ok(0) } fn write(&self, m: &M, _size_esimate: u32, out: &mut Vec<u8>) -> grpc::Result<()> { m.write_to_vec(out) .map_err(|e| grpc::Error::Marshaller(Box::new(e))) } fn read(&self, buf: Bytes) -> grpc::Result<M> { // TODO: make protobuf simple let mut is = CodedInputStream::from_carllerche_bytes(&buf); let mut r: M = M::new(); r.merge_from(&mut is) .map_err(|e| grpc::Error::Marshaller(Box::new(e)))?; r.check_initialized() .map_err(|e| grpc::Error::Marshaller(Box::new(e)))?; Ok(r) } }
MarshallerProtobuf
identifier_name
lib.rs
#![deny(broken_intra_doc_links)] //! Implementation of marshaller for rust-protobuf parameter types. use bytes::Bytes; use grpc::marshall::Marshaller;
use protobuf::CodedInputStream; use protobuf::Message; pub struct MarshallerProtobuf; impl<M: Message> Marshaller<M> for MarshallerProtobuf { fn write_size_estimate(&self, _m: &M) -> grpc::Result<u32> { // TODO: implement it Ok(0) } fn write(&self, m: &M, _size_esimate: u32, out: &mut Vec<u8>) -> grpc::Result<()> { m.write_to_vec(out) .map_err(|e| grpc::Error::Marshaller(Box::new(e))) } fn read(&self, buf: Bytes) -> grpc::Result<M> { // TODO: make protobuf simple let mut is = CodedInputStream::from_carllerche_bytes(&buf); let mut r: M = M::new(); r.merge_from(&mut is) .map_err(|e| grpc::Error::Marshaller(Box::new(e)))?; r.check_initialized() .map_err(|e| grpc::Error::Marshaller(Box::new(e)))?; Ok(r) } }
random_line_split
errors.rs
use std::error; use std::fmt; use std::io; use parsed_class::FieldRef; #[derive(Debug)] pub enum ClassLoadingError { NoClassDefFound(Result<String, io::Error>), ClassFormatError(String), UnsupportedClassVersion, NoSuchFieldError(FieldRef), #[allow(dead_code)] IncompatibleClassChange, #[allow(dead_code)] ClassCircularity, } impl fmt::Display for ClassLoadingError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ClassLoadingError::NoClassDefFound(ref err) => { write!(f, "NoClassDefFound: {}", err.as_ref().map(|o| o.to_owned()).map_err(|e| format!("{}", e)).unwrap_or_else(|e| e)) } ClassLoadingError::ClassFormatError(ref err) => write!(f, "ClassFormatError: {}", err), ClassLoadingError::NoSuchFieldError(ref field) => write!(f, "NoSuchField: {:?}", field), ClassLoadingError::UnsupportedClassVersion => write!(f, "class version not supported"), ClassLoadingError::IncompatibleClassChange => write!(f, "IncompatibleClassChange"), ClassLoadingError::ClassCircularity => write!(f, "ClassCircularity"), } } } impl error::Error for ClassLoadingError { fn description(&self) -> &str { match *self { ClassLoadingError::NoClassDefFound(..) => "NoClassDefFound", ClassLoadingError::ClassFormatError(..) => "ClassFormatError", ClassLoadingError::NoSuchFieldError(..) => "NoSuchFieldError", ClassLoadingError::UnsupportedClassVersion => "UnsupportedClassVersion", ClassLoadingError::IncompatibleClassChange => "IncompatibleClassChange", ClassLoadingError::ClassCircularity => "ClassCircularity", } } fn cause(&self) -> Option<&error::Error> {
}
match *self { ClassLoadingError::NoClassDefFound(ref err) => err.as_ref().err().map(|e| e as &error::Error), _ => None, } }
random_line_split
errors.rs
use std::error; use std::fmt; use std::io; use parsed_class::FieldRef; #[derive(Debug)] pub enum ClassLoadingError { NoClassDefFound(Result<String, io::Error>), ClassFormatError(String), UnsupportedClassVersion, NoSuchFieldError(FieldRef), #[allow(dead_code)] IncompatibleClassChange, #[allow(dead_code)] ClassCircularity, } impl fmt::Display for ClassLoadingError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ClassLoadingError::NoClassDefFound(ref err) => { write!(f, "NoClassDefFound: {}", err.as_ref().map(|o| o.to_owned()).map_err(|e| format!("{}", e)).unwrap_or_else(|e| e)) } ClassLoadingError::ClassFormatError(ref err) => write!(f, "ClassFormatError: {}", err), ClassLoadingError::NoSuchFieldError(ref field) => write!(f, "NoSuchField: {:?}", field), ClassLoadingError::UnsupportedClassVersion => write!(f, "class version not supported"), ClassLoadingError::IncompatibleClassChange => write!(f, "IncompatibleClassChange"), ClassLoadingError::ClassCircularity => write!(f, "ClassCircularity"), } } } impl error::Error for ClassLoadingError { fn description(&self) -> &str
fn cause(&self) -> Option<&error::Error> { match *self { ClassLoadingError::NoClassDefFound(ref err) => err.as_ref().err().map(|e| e as &error::Error), _ => None, } } }
{ match *self { ClassLoadingError::NoClassDefFound(..) => "NoClassDefFound", ClassLoadingError::ClassFormatError(..) => "ClassFormatError", ClassLoadingError::NoSuchFieldError(..) => "NoSuchFieldError", ClassLoadingError::UnsupportedClassVersion => "UnsupportedClassVersion", ClassLoadingError::IncompatibleClassChange => "IncompatibleClassChange", ClassLoadingError::ClassCircularity => "ClassCircularity", } }
identifier_body
errors.rs
use std::error; use std::fmt; use std::io; use parsed_class::FieldRef; #[derive(Debug)] pub enum
{ NoClassDefFound(Result<String, io::Error>), ClassFormatError(String), UnsupportedClassVersion, NoSuchFieldError(FieldRef), #[allow(dead_code)] IncompatibleClassChange, #[allow(dead_code)] ClassCircularity, } impl fmt::Display for ClassLoadingError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ClassLoadingError::NoClassDefFound(ref err) => { write!(f, "NoClassDefFound: {}", err.as_ref().map(|o| o.to_owned()).map_err(|e| format!("{}", e)).unwrap_or_else(|e| e)) } ClassLoadingError::ClassFormatError(ref err) => write!(f, "ClassFormatError: {}", err), ClassLoadingError::NoSuchFieldError(ref field) => write!(f, "NoSuchField: {:?}", field), ClassLoadingError::UnsupportedClassVersion => write!(f, "class version not supported"), ClassLoadingError::IncompatibleClassChange => write!(f, "IncompatibleClassChange"), ClassLoadingError::ClassCircularity => write!(f, "ClassCircularity"), } } } impl error::Error for ClassLoadingError { fn description(&self) -> &str { match *self { ClassLoadingError::NoClassDefFound(..) => "NoClassDefFound", ClassLoadingError::ClassFormatError(..) => "ClassFormatError", ClassLoadingError::NoSuchFieldError(..) => "NoSuchFieldError", ClassLoadingError::UnsupportedClassVersion => "UnsupportedClassVersion", ClassLoadingError::IncompatibleClassChange => "IncompatibleClassChange", ClassLoadingError::ClassCircularity => "ClassCircularity", } } fn cause(&self) -> Option<&error::Error> { match *self { ClassLoadingError::NoClassDefFound(ref err) => err.as_ref().err().map(|e| e as &error::Error), _ => None, } } }
ClassLoadingError
identifier_name
issue-13482.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(slice_patterns)] fn main()
{ let x = [1,2]; let y = match x { [] => None, //~^ ERROR mismatched types //~| expected `[_; 2]` //~| found `[_; 0]` //~| expected array with a fixed size of 2 elements [a,_] => Some(a) }; }
identifier_body
issue-13482.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
let y = match x { [] => None, //~^ ERROR mismatched types //~| expected `[_; 2]` //~| found `[_; 0]` //~| expected array with a fixed size of 2 elements [a,_] => Some(a) }; }
#![feature(slice_patterns)] fn main() { let x = [1,2];
random_line_split
issue-13482.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(slice_patterns)] fn
() { let x = [1,2]; let y = match x { [] => None, //~^ ERROR mismatched types //~| expected `[_; 2]` //~| found `[_; 0]` //~| expected array with a fixed size of 2 elements [a,_] => Some(a) }; }
main
identifier_name
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if!sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); hasher.input_str(&n.to_string()); let result = String::from(hasher.result_str()); sieve.insert(n, result); } return sieve[&n].clone(); } fn contains_3(data: &str) -> Option<char> { let mut cur = 1; let mut prev = '\0'; for c in data.chars() { if c == prev { cur += 1; if cur == 3 { return Some(c); } } else { prev = c; cur = 1; } } return None; } fn get_hash2(n: i32, sieve: &mut HashMap<i32, String>) -> String { if!sieve.contains_key(&n) { let mut cur = String::from(INPUT); cur += &n.to_string(); for _ in 0..2017 { let mut hasher = Md5::new(); hasher.input_str(&cur); cur = String::from(hasher.result_str()); } sieve.insert(n, cur); } return sieve[&n].clone(); } fn part1() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { let opt = get_hash(n + i, &mut sieve); if opt.contains(&search) { found += 1; break; } } if found == 64 { println!("Found 64 keys at index {}", n); return; } }, _ => {}, } n += 1; } } fn part2() { let mut n = 0;
loop { let cur = get_hash2(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { let opt = get_hash2(n + i, &mut sieve); if opt.contains(&search) { found += 1; break; } } if found == 64 { println!("Found 64 keys at index {}", n); return; } }, _ => {}, } n += 1; } } fn main() { part1(); part2(); }
let mut found = 0; let mut sieve = HashMap::new();
random_line_split
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if!sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); hasher.input_str(&n.to_string()); let result = String::from(hasher.result_str()); sieve.insert(n, result); } return sieve[&n].clone(); } fn contains_3(data: &str) -> Option<char> { let mut cur = 1; let mut prev = '\0'; for c in data.chars() { if c == prev { cur += 1; if cur == 3 { return Some(c); } } else { prev = c; cur = 1; } } return None; } fn get_hash2(n: i32, sieve: &mut HashMap<i32, String>) -> String
fn part1() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { let opt = get_hash(n + i, &mut sieve); if opt.contains(&search) { found += 1; break; } } if found == 64 { println!("Found 64 keys at index {}", n); return; } }, _ => {}, } n += 1; } } fn part2() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash2(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { let opt = get_hash2(n + i, &mut sieve); if opt.contains(&search) { found += 1; break; } } if found == 64 { println!("Found 64 keys at index {}", n); return; } }, _ => {}, } n += 1; } } fn main() { part1(); part2(); }
{ if !sieve.contains_key(&n) { let mut cur = String::from(INPUT); cur += &n.to_string(); for _ in 0..2017 { let mut hasher = Md5::new(); hasher.input_str(&cur); cur = String::from(hasher.result_str()); } sieve.insert(n, cur); } return sieve[&n].clone(); }
identifier_body
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if!sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); hasher.input_str(&n.to_string()); let result = String::from(hasher.result_str()); sieve.insert(n, result); } return sieve[&n].clone(); } fn contains_3(data: &str) -> Option<char> { let mut cur = 1; let mut prev = '\0'; for c in data.chars() { if c == prev { cur += 1; if cur == 3 { return Some(c); } } else { prev = c; cur = 1; } } return None; } fn get_hash2(n: i32, sieve: &mut HashMap<i32, String>) -> String { if!sieve.contains_key(&n) { let mut cur = String::from(INPUT); cur += &n.to_string(); for _ in 0..2017 { let mut hasher = Md5::new(); hasher.input_str(&cur); cur = String::from(hasher.result_str()); } sieve.insert(n, cur); } return sieve[&n].clone(); } fn part1() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { let opt = get_hash(n + i, &mut sieve); if opt.contains(&search) { found += 1; break; } } if found == 64 { println!("Found 64 keys at index {}", n); return; } }, _ => {}, } n += 1; } } fn
() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash2(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { let opt = get_hash2(n + i, &mut sieve); if opt.contains(&search) { found += 1; break; } } if found == 64 { println!("Found 64 keys at index {}", n); return; } }, _ => {}, } n += 1; } } fn main() { part1(); part2(); }
part2
identifier_name
font.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 app_units::Au; use euclid::{Point2D, Rect, Size2D}; use font_template::FontTemplateDescriptor; use ordered_float::NotNaN; use platform::font::{FontHandle, FontTable}; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use smallvec::SmallVec; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::str; use std::sync::Arc; use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; use style::computed_values::{font_stretch, font_variant_caps, font_weight}; use text::Shaper; use text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore}; use text::shaping::ShaperMethods; use time; use unicode_script::Script; use webrender_api; macro_rules! ot_tag { ($t1:expr, $t2:expr, $t3:expr, $t4:expr) => ( (($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32) ); } pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S'); pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B'); pub const KERN: u32 = ot_tag!('k', 'e', 'r', 'n'); static TEXT_SHAPING_PERFORMANCE_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods: Sized { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self, ()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> Option<String>; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel; /// Can this font do basic horizontal LTR shaping without Harfbuzz? fn can_do_fast_shaping(&self) -> bool; fn metrics(&self) -> FontMetrics; fn table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { let bytes = [(self >> 24) as u8, (self >> 16) as u8, (self >> 8) as u8, (self >> 0) as u8]; str::from_utf8(&bytes).unwrap().to_owned() } } pub trait FontTableMethods { fn buffer(&self) -> &[u8]; } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } #[derive(Debug)] pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant_caps::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, shaper: Option<Shaper>, shape_cache: RefCell<HashMap<ShapeCacheEntry, Arc<GlyphStore>>>, glyph_advance_cache: RefCell<HashMap<u32, FractionalPixel>>, pub font_key: webrender_api::FontInstanceKey, } impl Font { pub fn new(handle: FontHandle, variant: font_variant_caps::T, descriptor: FontTemplateDescriptor, requested_pt_size: Au, actual_pt_size: Au, font_key: webrender_api::FontInstanceKey) -> Font { let metrics = handle.metrics(); Font { handle: handle, shaper: None, variant: variant, descriptor: descriptor, requested_pt_size: requested_pt_size, actual_pt_size: actual_pt_size, metrics: metrics, shape_cache: RefCell::new(HashMap::new()), glyph_advance_cache: RefCell::new(HashMap::new()), font_key: font_key, } } } bitflags! { pub struct ShapingFlags: u8 { #[doc = "Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01; #[doc = "Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02; #[doc = "Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04; #[doc = "Text direction is right-to-left."] const RTL_FLAG = 0x08; #[doc = "Set if word-break is set to keep-all."] const KEEP_ALL_FLAG = 0x10; } } /// Various options that control text shaping. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: (Au, NotNaN<f32>), /// The Unicode script property of the characters in this run. pub script: Script, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { let this = self as *const Font; let mut shaper = self.shaper.take(); let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: *options, }; let result = self.shape_cache.borrow_mut().entry(lookup_key).or_insert_with(|| { let start_time = time::precise_time_ns(); let mut glyphs = GlyphStore::new(text.len(), options.flags.contains(ShapingFlags::IS_WHITESPACE_SHAPING_FLAG), options.flags.contains(ShapingFlags::RTL_FLAG)); if self.can_do_fast_shaping(text, options) { debug!("shape_text: Using ASCII fast path."); self.shape_text_fast(text, options, &mut glyphs); } else
let end_time = time::precise_time_ns(); TEXT_SHAPING_PERFORMANCE_COUNTER.fetch_add((end_time - start_time) as usize, Ordering::Relaxed); Arc::new(glyphs) }).clone(); self.shaper = shaper; result } fn can_do_fast_shaping(&self, text: &str, options: &ShapingOptions) -> bool { options.script == Script::Latin && !options.flags.contains(ShapingFlags::RTL_FLAG) && self.handle.can_do_fast_shaping() && text.is_ascii() } /// Fast path for ASCII text that only needs simple horizontal LTR kerning. fn shape_text_fast(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) { let mut prev_glyph_id = None; for (i, byte) in text.bytes().enumerate() { let character = byte as char; let glyph_id = match self.glyph_index(character) { Some(id) => id, None => continue, }; let mut advance = Au::from_f64_px(self.glyph_h_advance(glyph_id)); if character =='' { // https://drafts.csswg.org/css-text-3/#word-spacing-property let (length, percent) = options.word_spacing; advance = (advance + length) + Au((advance.0 as f32 * percent.into_inner()) as i32); } if let Some(letter_spacing) = options.letter_spacing { advance += letter_spacing; } let offset = prev_glyph_id.map(|prev| { let h_kerning = Au::from_f64_px(self.glyph_h_kerning(prev, glyph_id)); advance += h_kerning; Point2D::new(h_kerning, Au(0)) }); let glyph = GlyphData::new(glyph_id, advance, offset, true, true); glyphs.add_glyph_for_byte_index(ByteIndex(i as isize), character, &glyph); prev_glyph_id = Some(glyph_id); } glyphs.finalize_changes(); } pub fn table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name().unwrap_or("unavailable".to_owned())); result } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant_caps::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant_caps::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&self, glyph: GlyphId) -> FractionalPixel { *self.glyph_advance_cache.borrow_mut().entry(glyph).or_insert_with(|| { match self.handle.glyph_h_advance(glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } #[derive(Debug)] pub struct FontGroup { pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>, } impl FontGroup { pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect::new(Point2D::new(Au(0), -ascent), Size2D::new(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } } pub fn get_and_reset_text_shaping_performance_counter() -> usize { let value = TEXT_SHAPING_PERFORMANCE_COUNTER.load(Ordering::SeqCst); TEXT_SHAPING_PERFORMANCE_COUNTER.store(0, Ordering::SeqCst); value }
{ debug!("shape_text: Using Harfbuzz."); if shaper.is_none() { shaper = Some(Shaper::new(this)); } shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); }
conditional_block
font.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 app_units::Au; use euclid::{Point2D, Rect, Size2D}; use font_template::FontTemplateDescriptor; use ordered_float::NotNaN; use platform::font::{FontHandle, FontTable}; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use smallvec::SmallVec; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::str; use std::sync::Arc; use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; use style::computed_values::{font_stretch, font_variant_caps, font_weight}; use text::Shaper; use text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore};
use webrender_api; macro_rules! ot_tag { ($t1:expr, $t2:expr, $t3:expr, $t4:expr) => ( (($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32) ); } pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S'); pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B'); pub const KERN: u32 = ot_tag!('k', 'e', 'r', 'n'); static TEXT_SHAPING_PERFORMANCE_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods: Sized { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self, ()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> Option<String>; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel; /// Can this font do basic horizontal LTR shaping without Harfbuzz? fn can_do_fast_shaping(&self) -> bool; fn metrics(&self) -> FontMetrics; fn table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { let bytes = [(self >> 24) as u8, (self >> 16) as u8, (self >> 8) as u8, (self >> 0) as u8]; str::from_utf8(&bytes).unwrap().to_owned() } } pub trait FontTableMethods { fn buffer(&self) -> &[u8]; } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } #[derive(Debug)] pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant_caps::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, shaper: Option<Shaper>, shape_cache: RefCell<HashMap<ShapeCacheEntry, Arc<GlyphStore>>>, glyph_advance_cache: RefCell<HashMap<u32, FractionalPixel>>, pub font_key: webrender_api::FontInstanceKey, } impl Font { pub fn new(handle: FontHandle, variant: font_variant_caps::T, descriptor: FontTemplateDescriptor, requested_pt_size: Au, actual_pt_size: Au, font_key: webrender_api::FontInstanceKey) -> Font { let metrics = handle.metrics(); Font { handle: handle, shaper: None, variant: variant, descriptor: descriptor, requested_pt_size: requested_pt_size, actual_pt_size: actual_pt_size, metrics: metrics, shape_cache: RefCell::new(HashMap::new()), glyph_advance_cache: RefCell::new(HashMap::new()), font_key: font_key, } } } bitflags! { pub struct ShapingFlags: u8 { #[doc = "Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01; #[doc = "Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02; #[doc = "Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04; #[doc = "Text direction is right-to-left."] const RTL_FLAG = 0x08; #[doc = "Set if word-break is set to keep-all."] const KEEP_ALL_FLAG = 0x10; } } /// Various options that control text shaping. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: (Au, NotNaN<f32>), /// The Unicode script property of the characters in this run. pub script: Script, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { let this = self as *const Font; let mut shaper = self.shaper.take(); let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: *options, }; let result = self.shape_cache.borrow_mut().entry(lookup_key).or_insert_with(|| { let start_time = time::precise_time_ns(); let mut glyphs = GlyphStore::new(text.len(), options.flags.contains(ShapingFlags::IS_WHITESPACE_SHAPING_FLAG), options.flags.contains(ShapingFlags::RTL_FLAG)); if self.can_do_fast_shaping(text, options) { debug!("shape_text: Using ASCII fast path."); self.shape_text_fast(text, options, &mut glyphs); } else { debug!("shape_text: Using Harfbuzz."); if shaper.is_none() { shaper = Some(Shaper::new(this)); } shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); } let end_time = time::precise_time_ns(); TEXT_SHAPING_PERFORMANCE_COUNTER.fetch_add((end_time - start_time) as usize, Ordering::Relaxed); Arc::new(glyphs) }).clone(); self.shaper = shaper; result } fn can_do_fast_shaping(&self, text: &str, options: &ShapingOptions) -> bool { options.script == Script::Latin && !options.flags.contains(ShapingFlags::RTL_FLAG) && self.handle.can_do_fast_shaping() && text.is_ascii() } /// Fast path for ASCII text that only needs simple horizontal LTR kerning. fn shape_text_fast(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) { let mut prev_glyph_id = None; for (i, byte) in text.bytes().enumerate() { let character = byte as char; let glyph_id = match self.glyph_index(character) { Some(id) => id, None => continue, }; let mut advance = Au::from_f64_px(self.glyph_h_advance(glyph_id)); if character =='' { // https://drafts.csswg.org/css-text-3/#word-spacing-property let (length, percent) = options.word_spacing; advance = (advance + length) + Au((advance.0 as f32 * percent.into_inner()) as i32); } if let Some(letter_spacing) = options.letter_spacing { advance += letter_spacing; } let offset = prev_glyph_id.map(|prev| { let h_kerning = Au::from_f64_px(self.glyph_h_kerning(prev, glyph_id)); advance += h_kerning; Point2D::new(h_kerning, Au(0)) }); let glyph = GlyphData::new(glyph_id, advance, offset, true, true); glyphs.add_glyph_for_byte_index(ByteIndex(i as isize), character, &glyph); prev_glyph_id = Some(glyph_id); } glyphs.finalize_changes(); } pub fn table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name().unwrap_or("unavailable".to_owned())); result } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant_caps::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant_caps::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&self, glyph: GlyphId) -> FractionalPixel { *self.glyph_advance_cache.borrow_mut().entry(glyph).or_insert_with(|| { match self.handle.glyph_h_advance(glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } #[derive(Debug)] pub struct FontGroup { pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>, } impl FontGroup { pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect::new(Point2D::new(Au(0), -ascent), Size2D::new(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } } pub fn get_and_reset_text_shaping_performance_counter() -> usize { let value = TEXT_SHAPING_PERFORMANCE_COUNTER.load(Ordering::SeqCst); TEXT_SHAPING_PERFORMANCE_COUNTER.store(0, Ordering::SeqCst); value }
use text::shaping::ShaperMethods; use time; use unicode_script::Script;
random_line_split
font.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 app_units::Au; use euclid::{Point2D, Rect, Size2D}; use font_template::FontTemplateDescriptor; use ordered_float::NotNaN; use platform::font::{FontHandle, FontTable}; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use smallvec::SmallVec; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::str; use std::sync::Arc; use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; use style::computed_values::{font_stretch, font_variant_caps, font_weight}; use text::Shaper; use text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore}; use text::shaping::ShaperMethods; use time; use unicode_script::Script; use webrender_api; macro_rules! ot_tag { ($t1:expr, $t2:expr, $t3:expr, $t4:expr) => ( (($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32) ); } pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S'); pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B'); pub const KERN: u32 = ot_tag!('k', 'e', 'r', 'n'); static TEXT_SHAPING_PERFORMANCE_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods: Sized { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<Self, ()>; fn template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> Option<String>; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel; /// Can this font do basic horizontal LTR shaping without Harfbuzz? fn can_do_fast_shaping(&self) -> bool; fn metrics(&self) -> FontMetrics; fn table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { let bytes = [(self >> 24) as u8, (self >> 16) as u8, (self >> 8) as u8, (self >> 0) as u8]; str::from_utf8(&bytes).unwrap().to_owned() } } pub trait FontTableMethods { fn buffer(&self) -> &[u8]; } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub average_advance: Au, pub line_gap: Au, } #[derive(Debug)] pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub variant: font_variant_caps::T, pub descriptor: FontTemplateDescriptor, pub requested_pt_size: Au, pub actual_pt_size: Au, shaper: Option<Shaper>, shape_cache: RefCell<HashMap<ShapeCacheEntry, Arc<GlyphStore>>>, glyph_advance_cache: RefCell<HashMap<u32, FractionalPixel>>, pub font_key: webrender_api::FontInstanceKey, } impl Font { pub fn new(handle: FontHandle, variant: font_variant_caps::T, descriptor: FontTemplateDescriptor, requested_pt_size: Au, actual_pt_size: Au, font_key: webrender_api::FontInstanceKey) -> Font { let metrics = handle.metrics(); Font { handle: handle, shaper: None, variant: variant, descriptor: descriptor, requested_pt_size: requested_pt_size, actual_pt_size: actual_pt_size, metrics: metrics, shape_cache: RefCell::new(HashMap::new()), glyph_advance_cache: RefCell::new(HashMap::new()), font_key: font_key, } } } bitflags! { pub struct ShapingFlags: u8 { #[doc = "Set if the text is entirely whitespace."] const IS_WHITESPACE_SHAPING_FLAG = 0x01; #[doc = "Set if we are to ignore ligatures."] const IGNORE_LIGATURES_SHAPING_FLAG = 0x02; #[doc = "Set if we are to disable kerning."] const DISABLE_KERNING_SHAPING_FLAG = 0x04; #[doc = "Text direction is right-to-left."] const RTL_FLAG = 0x08; #[doc = "Set if word-break is set to keep-all."] const KEEP_ALL_FLAG = 0x10; } } /// Various options that control text shaping. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct ShapingOptions { /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property. /// NB: You will probably want to set the `IGNORE_LIGATURES_SHAPING_FLAG` if this is non-null. pub letter_spacing: Option<Au>, /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property. pub word_spacing: (Au, NotNaN<f32>), /// The Unicode script property of the characters in this run. pub script: Script, /// Various flags. pub flags: ShapingFlags, } /// An entry in the shape cache. #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct ShapeCacheEntry { text: String, options: ShapingOptions, } impl Font { pub fn shape_text(&mut self, text: &str, options: &ShapingOptions) -> Arc<GlyphStore> { let this = self as *const Font; let mut shaper = self.shaper.take(); let lookup_key = ShapeCacheEntry { text: text.to_owned(), options: *options, }; let result = self.shape_cache.borrow_mut().entry(lookup_key).or_insert_with(|| { let start_time = time::precise_time_ns(); let mut glyphs = GlyphStore::new(text.len(), options.flags.contains(ShapingFlags::IS_WHITESPACE_SHAPING_FLAG), options.flags.contains(ShapingFlags::RTL_FLAG)); if self.can_do_fast_shaping(text, options) { debug!("shape_text: Using ASCII fast path."); self.shape_text_fast(text, options, &mut glyphs); } else { debug!("shape_text: Using Harfbuzz."); if shaper.is_none() { shaper = Some(Shaper::new(this)); } shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); } let end_time = time::precise_time_ns(); TEXT_SHAPING_PERFORMANCE_COUNTER.fetch_add((end_time - start_time) as usize, Ordering::Relaxed); Arc::new(glyphs) }).clone(); self.shaper = shaper; result } fn can_do_fast_shaping(&self, text: &str, options: &ShapingOptions) -> bool { options.script == Script::Latin && !options.flags.contains(ShapingFlags::RTL_FLAG) && self.handle.can_do_fast_shaping() && text.is_ascii() } /// Fast path for ASCII text that only needs simple horizontal LTR kerning. fn shape_text_fast(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) { let mut prev_glyph_id = None; for (i, byte) in text.bytes().enumerate() { let character = byte as char; let glyph_id = match self.glyph_index(character) { Some(id) => id, None => continue, }; let mut advance = Au::from_f64_px(self.glyph_h_advance(glyph_id)); if character =='' { // https://drafts.csswg.org/css-text-3/#word-spacing-property let (length, percent) = options.word_spacing; advance = (advance + length) + Au((advance.0 as f32 * percent.into_inner()) as i32); } if let Some(letter_spacing) = options.letter_spacing { advance += letter_spacing; } let offset = prev_glyph_id.map(|prev| { let h_kerning = Au::from_f64_px(self.glyph_h_kerning(prev, glyph_id)); advance += h_kerning; Point2D::new(h_kerning, Au(0)) }); let glyph = GlyphData::new(glyph_id, advance, offset, true, true); glyphs.add_glyph_for_byte_index(ByteIndex(i as isize), character, &glyph); prev_glyph_id = Some(glyph_id); } glyphs.finalize_changes(); } pub fn table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{} font table[{}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name().unwrap_or("unavailable".to_owned())); result } #[inline] pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { let codepoint = match self.variant { font_variant_caps::T::small_caps => codepoint.to_uppercase().next().unwrap(), //FIXME: #5938 font_variant_caps::T::normal => codepoint, }; self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&self, glyph: GlyphId) -> FractionalPixel { *self.glyph_advance_cache.borrow_mut().entry(glyph).or_insert_with(|| { match self.handle.glyph_h_advance(glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } #[derive(Debug)] pub struct
{ pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>, } impl FontGroup { pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect::new(Point2D::new(Au(0), -ascent), Size2D::new(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } } pub fn get_and_reset_text_shaping_performance_counter() -> usize { let value = TEXT_SHAPING_PERFORMANCE_COUNTER.load(Ordering::SeqCst); TEXT_SHAPING_PERFORMANCE_COUNTER.store(0, Ordering::SeqCst); value }
FontGroup
identifier_name
lorenz96.rs
//! Lorenz 96 model //! https://en.wikipedia.org/wiki/Lorenz_96_model use crate::traits::*; use ndarray::*; #[derive(Clone, Copy, Debug)] pub struct Lorenz96 { pub f: f64, pub n: usize, } impl Default for Lorenz96 { fn default() -> Self { Lorenz96 { f: 8.0, n: 40 } } } impl ModelSpec for Lorenz96 { type Scalar = f64; type Dim = Ix1; fn model_size(&self) -> usize { self.n } } impl Explicit for Lorenz96 { fn
<'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1> where S: DataMut<Elem = f64>, { let n = v.len(); let v0 = v.to_owned(); for i in 0..n { let p1 = (i + 1) % n; let m1 = (i + n - 1) % n; let m2 = (i + n - 2) % n; v[i] = (v0[p1] - v0[m2]) * v0[m1] - v0[i] + self.f; } v } }
rhs
identifier_name
lorenz96.rs
//! Lorenz 96 model //! https://en.wikipedia.org/wiki/Lorenz_96_model use crate::traits::*; use ndarray::*; #[derive(Clone, Copy, Debug)] pub struct Lorenz96 { pub f: f64, pub n: usize, } impl Default for Lorenz96 { fn default() -> Self { Lorenz96 { f: 8.0, n: 40 } }
impl ModelSpec for Lorenz96 { type Scalar = f64; type Dim = Ix1; fn model_size(&self) -> usize { self.n } } impl Explicit for Lorenz96 { fn rhs<'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1> where S: DataMut<Elem = f64>, { let n = v.len(); let v0 = v.to_owned(); for i in 0..n { let p1 = (i + 1) % n; let m1 = (i + n - 1) % n; let m2 = (i + n - 2) % n; v[i] = (v0[p1] - v0[m2]) * v0[m1] - v0[i] + self.f; } v } }
}
random_line_split
lorenz96.rs
//! Lorenz 96 model //! https://en.wikipedia.org/wiki/Lorenz_96_model use crate::traits::*; use ndarray::*; #[derive(Clone, Copy, Debug)] pub struct Lorenz96 { pub f: f64, pub n: usize, } impl Default for Lorenz96 { fn default() -> Self
} impl ModelSpec for Lorenz96 { type Scalar = f64; type Dim = Ix1; fn model_size(&self) -> usize { self.n } } impl Explicit for Lorenz96 { fn rhs<'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1> where S: DataMut<Elem = f64>, { let n = v.len(); let v0 = v.to_owned(); for i in 0..n { let p1 = (i + 1) % n; let m1 = (i + n - 1) % n; let m2 = (i + n - 2) % n; v[i] = (v0[p1] - v0[m2]) * v0[m1] - v0[i] + self.f; } v } }
{ Lorenz96 { f: 8.0, n: 40 } }
identifier_body
coulomb.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use toml::Value; use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf}; use lumol_core::System; use log::{info, warn}; use super::read_restriction; use crate::{InteractionsInput, Error, FromToml, FromTomlWithRefData}; impl InteractionsInput { /// Read the "coulomb" section from the potential configuration. pub(crate) fn re
self, system: &mut System) -> Result<(), Error> { let coulomb = match self.config.get("coulomb") { Some(coulomb) => coulomb, None => return Ok(()), }; let coulomb = coulomb.as_table().ok_or(Error::from("the 'coulomb' section must be a table"))?; let solvers = coulomb.keys().cloned().filter(|key| key!= "restriction").collect::<Vec<_>>(); if solvers.len()!= 1 { return Err(Error::from( format!("got more than one coulombic solver: {}", solvers.join(" and ")), )); } let key = &*solvers[0]; if let Value::Table(ref table) = coulomb[key] { let mut potential: Box<dyn CoulombicPotential> = match key { "wolf" => Box::new(Wolf::from_toml(table)?), "ewald" => { let ewald = Ewald::from_toml(table, &system)?; Box::new(SharedEwald::new(ewald)) } other => return Err(Error::from(format!("unknown coulomb solver '{}'", other))), }; if let Some(restriction) = read_restriction(coulomb)? { potential.set_restriction(restriction); } system.set_coulomb_potential(potential); Ok(()) } else { Err(Error::from(format!("coulombic solver '{}' must be a table", key))) } } /// Read the "charges" from the potential configuration. pub(crate) fn read_charges(&self, system: &mut System) -> Result<(), Error> { let charges = match self.config.get("charges") { Some(charges) => charges, None => return Ok(()), }; let charges = charges.as_table().ok_or( Error::from("the 'charges' section must be a table") )?; let mut total_charge = 0.0; for (name, charge) in charges.iter() { let charge = match *charge { Value::Integer(val) => val as f64, Value::Float(val) => val, _ => { return Err(Error::from("charges must be numbers")); } }; let mut nchanged = 0; for particle in system.particles_mut() { if particle.name == name { *particle.charge = charge; nchanged += 1; total_charge += charge; } } if nchanged == 0 { warn!("No particle with name '{}' was found while setting the charges", name); } else { info!("Charge set to {:+} for {} {} particles", charge, nchanged, name); } } if total_charge.abs() > 1e-6 { warn!("System is not neutral and have a net charge of {:+}", total_charge); } Ok(()) } }
ad_coulomb(&
identifier_name
coulomb.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use toml::Value; use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf}; use lumol_core::System; use log::{info, warn}; use super::read_restriction; use crate::{InteractionsInput, Error, FromToml, FromTomlWithRefData}; impl InteractionsInput { /// Read the "coulomb" section from the potential configuration. pub(crate) fn read_coulomb(&self, system: &mut System) -> Result<(), Error> {
let ewald = Ewald::from_toml(table, &system)?; Box::new(SharedEwald::new(ewald)) } other => return Err(Error::from(format!("unknown coulomb solver '{}'", other))), }; if let Some(restriction) = read_restriction(coulomb)? { potential.set_restriction(restriction); } system.set_coulomb_potential(potential); Ok(()) } else { Err(Error::from(format!("coulombic solver '{}' must be a table", key))) } } /// Read the "charges" from the potential configuration. pub(crate) fn read_charges(&self, system: &mut System) -> Result<(), Error> { let charges = match self.config.get("charges") { Some(charges) => charges, None => return Ok(()), }; let charges = charges.as_table().ok_or( Error::from("the 'charges' section must be a table") )?; let mut total_charge = 0.0; for (name, charge) in charges.iter() { let charge = match *charge { Value::Integer(val) => val as f64, Value::Float(val) => val, _ => { return Err(Error::from("charges must be numbers")); } }; let mut nchanged = 0; for particle in system.particles_mut() { if particle.name == name { *particle.charge = charge; nchanged += 1; total_charge += charge; } } if nchanged == 0 { warn!("No particle with name '{}' was found while setting the charges", name); } else { info!("Charge set to {:+} for {} {} particles", charge, nchanged, name); } } if total_charge.abs() > 1e-6 { warn!("System is not neutral and have a net charge of {:+}", total_charge); } Ok(()) } }
let coulomb = match self.config.get("coulomb") { Some(coulomb) => coulomb, None => return Ok(()), }; let coulomb = coulomb.as_table().ok_or(Error::from("the 'coulomb' section must be a table"))?; let solvers = coulomb.keys().cloned().filter(|key| key != "restriction").collect::<Vec<_>>(); if solvers.len() != 1 { return Err(Error::from( format!("got more than one coulombic solver: {}", solvers.join(" and ")), )); } let key = &*solvers[0]; if let Value::Table(ref table) = coulomb[key] { let mut potential: Box<dyn CoulombicPotential> = match key { "wolf" => Box::new(Wolf::from_toml(table)?), "ewald" => {
identifier_body
coulomb.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use toml::Value; use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf}; use lumol_core::System; use log::{info, warn}; use super::read_restriction; use crate::{InteractionsInput, Error, FromToml, FromTomlWithRefData}; impl InteractionsInput { /// Read the "coulomb" section from the potential configuration. pub(crate) fn read_coulomb(&self, system: &mut System) -> Result<(), Error> { let coulomb = match self.config.get("coulomb") { Some(coulomb) => coulomb, None => return Ok(()), }; let coulomb = coulomb.as_table().ok_or(Error::from("the 'coulomb' section must be a table"))?; let solvers = coulomb.keys().cloned().filter(|key| key!= "restriction").collect::<Vec<_>>(); if solvers.len()!= 1 { return Err(Error::from( format!("got more than one coulombic solver: {}", solvers.join(" and ")), )); } let key = &*solvers[0]; if let Value::Table(ref table) = coulomb[key] { let mut potential: Box<dyn CoulombicPotential> = match key { "wolf" => Box::new(Wolf::from_toml(table)?), "ewald" => { let ewald = Ewald::from_toml(table, &system)?; Box::new(SharedEwald::new(ewald)) } other => return Err(Error::from(format!("unknown coulomb solver '{}'", other))), }; if let Some(restriction) = read_restriction(coulomb)? { potential.set_restriction(restriction); } system.set_coulomb_potential(potential); Ok(()) } else { Err(Error::from(format!("coulombic solver '{}' must be a table", key))) } } /// Read the "charges" from the potential configuration. pub(crate) fn read_charges(&self, system: &mut System) -> Result<(), Error> { let charges = match self.config.get("charges") { Some(charges) => charges, None => return Ok(()), }; let charges = charges.as_table().ok_or( Error::from("the 'charges' section must be a table") )?;
let mut total_charge = 0.0; for (name, charge) in charges.iter() { let charge = match *charge { Value::Integer(val) => val as f64, Value::Float(val) => val, _ => { return Err(Error::from("charges must be numbers")); } }; let mut nchanged = 0; for particle in system.particles_mut() { if particle.name == name { *particle.charge = charge; nchanged += 1; total_charge += charge; } } if nchanged == 0 { warn!("No particle with name '{}' was found while setting the charges", name); } else { info!("Charge set to {:+} for {} {} particles", charge, nchanged, name); } } if total_charge.abs() > 1e-6 { warn!("System is not neutral and have a net charge of {:+}", total_charge); } Ok(()) } }
random_line_split
next_back.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } } } } impl DoubleEndedIterator for A<T> { fn next_back(&mut self) -> Option<Self::Item> { if self.begin < self.end { self.end = self.end.wrapping_sub(1); Some::<Self::Item>(self.end) } else { None::<Self::Item> } } } type T = i32; Iterator_impl!(T); // impl<'a, I: DoubleEndedIterator +?Sized> DoubleEndedIterator for &'a mut I { // fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } // } type I = A<T>; #[test] fn
() { let mut a: A<T> = A { begin: 0, end: 10 }; let mut iter: &mut I = &mut a; for x in 0..10 { let y: Option<T> = iter.next_back(); match y { Some(v) => { assert_eq!(v, 9 - x); } None => { assert!(false); } } } assert_eq!(iter.next(), None::<<I as Iterator>::Item>);; } }
next_back_test1
identifier_name
next_back.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } } } } impl DoubleEndedIterator for A<T> { fn next_back(&mut self) -> Option<Self::Item> { if self.begin < self.end { self.end = self.end.wrapping_sub(1); Some::<Self::Item>(self.end) } else { None::<Self::Item> } } } type T = i32; Iterator_impl!(T); // impl<'a, I: DoubleEndedIterator +?Sized> DoubleEndedIterator for &'a mut I { // fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } // } type I = A<T>; #[test] fn next_back_test1()
}
{ let mut a: A<T> = A { begin: 0, end: 10 }; let mut iter: &mut I = &mut a; for x in 0..10 { let y: Option<T> = iter.next_back(); match y { Some(v) => { assert_eq!(v, 9 - x); } None => { assert!(false); } } } assert_eq!(iter.next(), None::<<I as Iterator>::Item>);; }
identifier_body
next_back.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } else { None::<Self::Item> } } } } } impl DoubleEndedIterator for A<T> { fn next_back(&mut self) -> Option<Self::Item> { if self.begin < self.end { self.end = self.end.wrapping_sub(1); Some::<Self::Item>(self.end) } else { None::<Self::Item> } } } type T = i32; Iterator_impl!(T); // impl<'a, I: DoubleEndedIterator +?Sized> DoubleEndedIterator for &'a mut I { // fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } // } type I = A<T>; #[test] fn next_back_test1() { let mut a: A<T> = A { begin: 0, end: 10 }; let mut iter: &mut I = &mut a; for x in 0..10 { let y: Option<T> = iter.next_back(); match y { Some(v) => { assert_eq!(v, 9 - x); } None => { assert!(false); }
}
} } assert_eq!(iter.next(), None::<<I as Iterator>::Item>);; }
random_line_split
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::canvasrenderingcontext2d::parse_color; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[jstraceable] pub enum CanvasGradientStyle { Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(self, offset: Finite<f32>, color: String) { let default_black = RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0, };
self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: parse_color(&color).unwrap_or(default_black), }); } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for JSRef<'a, CanvasGradient> { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }, CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } } }
random_line_split
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::canvasrenderingcontext2d::parse_color; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[jstraceable] pub enum CanvasGradientStyle { Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn new(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(self, offset: Finite<f32>, color: String) { let default_black = RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0, }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: parse_color(&color).unwrap_or(default_black), }); } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for JSRef<'a, CanvasGradient> { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) =>
, CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } } }
{ FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }
conditional_block
canvasgradient.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::num::Finite; use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::canvasrenderingcontext2d::parse_color; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] pub struct CanvasGradient { reflector_: Reflector, style: CanvasGradientStyle, stops: DOMRefCell<Vec<CanvasGradientStop>>, } #[jstraceable] pub enum CanvasGradientStyle { Linear(LinearGradientStyle), Radial(RadialGradientStyle), } impl CanvasGradient { fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient { CanvasGradient { reflector_: Reflector::new(), style: style, stops: DOMRefCell::new(Vec::new()), } } pub fn
(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> { // https://html.spec.whatwg.org/multipage/#dom-canvasgradient-addcolorstop fn AddColorStop(self, offset: Finite<f32>, color: String) { let default_black = RGBA { red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0, }; self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: parse_color(&color).unwrap_or(default_black), }); } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for JSRef<'a, CanvasGradient> { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle { let gradient_stops = self.stops.borrow().clone(); match self.style { CanvasGradientStyle::Linear(ref gradient) => { FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }, CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, gradient_stops)) } } } }
new
identifier_name
viewport.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 app_units::Au; use style::properties::PropertyDeclaration; use style::properties::longhands::border_top_width; use style::values::HasViewportPercentage; use style::values::specified::{AbsoluteLength, Length, NoCalcLength, ViewportPercentageLength}; #[test] fn has_viewport_percentage_for_specified_value() { //TODO: test all specified value with a HasViewportPercentage impl let pvw = PropertyDeclaration::BorderTopWidth( border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(100.)))
border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(Au(100).to_f32_px()))) ) ); assert!(!pabs.has_viewport_percentage()); }
) ); assert!(pvw.has_viewport_percentage()); let pabs = PropertyDeclaration::BorderTopWidth(
random_line_split
viewport.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 app_units::Au; use style::properties::PropertyDeclaration; use style::properties::longhands::border_top_width; use style::values::HasViewportPercentage; use style::values::specified::{AbsoluteLength, Length, NoCalcLength, ViewportPercentageLength}; #[test] fn has_viewport_percentage_for_specified_value()
{ //TODO: test all specified value with a HasViewportPercentage impl let pvw = PropertyDeclaration::BorderTopWidth( border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(100.))) ) ); assert!(pvw.has_viewport_percentage()); let pabs = PropertyDeclaration::BorderTopWidth( border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(Au(100).to_f32_px()))) ) ); assert!(!pabs.has_viewport_percentage()); }
identifier_body
viewport.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 app_units::Au; use style::properties::PropertyDeclaration; use style::properties::longhands::border_top_width; use style::values::HasViewportPercentage; use style::values::specified::{AbsoluteLength, Length, NoCalcLength, ViewportPercentageLength}; #[test] fn
() { //TODO: test all specified value with a HasViewportPercentage impl let pvw = PropertyDeclaration::BorderTopWidth( border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(100.))) ) ); assert!(pvw.has_viewport_percentage()); let pabs = PropertyDeclaration::BorderTopWidth( border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(Au(100).to_f32_px()))) ) ); assert!(!pabs.has_viewport_percentage()); }
has_viewport_percentage_for_specified_value
identifier_name
zero-size-array-align.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub const fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData, []) } #[inline] pub fn as_ptr(&self) -> *const T { self as *const _ as *const T } #[inline] pub fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut T } #[inline] pub unsafe fn as_slice(&self, len: usize) -> &[T] { ::std::slice::from_raw_parts(self.as_ptr(), len) } #[inline] pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
} #[repr(C)] #[derive(Debug, Default)] pub struct dm_deps { pub count: ::std::os::raw::c_uint, pub filler: ::std::os::raw::c_uint, pub device: __IncompleteArrayField<::std::os::raw::c_ulonglong>, } #[test] fn bindgen_test_layout_dm_deps() { assert_eq!( ::std::mem::size_of::<dm_deps>(), 8usize, concat!("Size of: ", stringify!(dm_deps)) ); assert_eq!( ::std::mem::align_of::<dm_deps>(), 8usize, concat!("Alignment of ", stringify!(dm_deps)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).count as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(count) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).filler as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(filler) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).device as *const _ as usize }, 8usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(device) ) ); }
{ fmt.write_str("__IncompleteArrayField") }
identifier_body
zero-size-array-align.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub const fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData, []) } #[inline] pub fn as_ptr(&self) -> *const T { self as *const _ as *const T } #[inline] pub fn
(&mut self) -> *mut T { self as *mut _ as *mut T } #[inline] pub unsafe fn as_slice(&self, len: usize) -> &[T] { ::std::slice::from_raw_parts(self.as_ptr(), len) } #[inline] pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { fmt.write_str("__IncompleteArrayField") } } #[repr(C)] #[derive(Debug, Default)] pub struct dm_deps { pub count: ::std::os::raw::c_uint, pub filler: ::std::os::raw::c_uint, pub device: __IncompleteArrayField<::std::os::raw::c_ulonglong>, } #[test] fn bindgen_test_layout_dm_deps() { assert_eq!( ::std::mem::size_of::<dm_deps>(), 8usize, concat!("Size of: ", stringify!(dm_deps)) ); assert_eq!( ::std::mem::align_of::<dm_deps>(), 8usize, concat!("Alignment of ", stringify!(dm_deps)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).count as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(count) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).filler as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(filler) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).device as *const _ as usize }, 8usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(device) ) ); }
as_mut_ptr
identifier_name
zero-size-array-align.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub const fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData, []) } #[inline] pub fn as_ptr(&self) -> *const T { self as *const _ as *const T } #[inline] pub fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut T } #[inline] pub unsafe fn as_slice(&self, len: usize) -> &[T] { ::std::slice::from_raw_parts(self.as_ptr(), len) } #[inline] pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { fmt.write_str("__IncompleteArrayField") } } #[repr(C)] #[derive(Debug, Default)] pub struct dm_deps { pub count: ::std::os::raw::c_uint, pub filler: ::std::os::raw::c_uint, pub device: __IncompleteArrayField<::std::os::raw::c_ulonglong>, } #[test] fn bindgen_test_layout_dm_deps() { assert_eq!( ::std::mem::size_of::<dm_deps>(), 8usize, concat!("Size of: ", stringify!(dm_deps))
); assert_eq!( ::std::mem::align_of::<dm_deps>(), 8usize, concat!("Alignment of ", stringify!(dm_deps)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).count as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(count) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).filler as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(filler) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).device as *const _ as usize }, 8usize, concat!( "Offset of field: ", stringify!(dm_deps), "::", stringify!(device) ) ); }
random_line_split
issue-2834.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test case for issue #2843. // proto! streamp ( open:send<T:Send> { data(T) -> open<T> } ) fn rendezvous() { let (s, c) = streamp::init(); let streams: ~[streamp::client::open<int>] = ~[c]; error!("%?", streams[0]); }
pub fn main() { //os::getenv("FOO"); rendezvous(); }
random_line_split
issue-2834.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test case for issue #2843. // proto! streamp ( open:send<T:Send> { data(T) -> open<T> } ) fn rendezvous()
pub fn main() { //os::getenv("FOO"); rendezvous(); }
{ let (s, c) = streamp::init(); let streams: ~[streamp::client::open<int>] = ~[c]; error!("%?", streams[0]); }
identifier_body