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
lib.rs
#![feature(plugin)] #![plugin(interpolate_idents)] #[macro_use] extern crate apache2; use apache2::{Request, Status, server_banner, server_description, server_built, show_mpm, apr_version_string, apu_version_string, Cookie, time_now}; apache2_module!(info_rs, b"mod_info_rs\0"); fn unwrap_str<'a>(wrapped: Option<&'a str>) -> &'a str { wrapped.unwrap_or("--") } fn info_rs_handler(r: &mut Request) -> Result<Status, ()>
try!(r.write(format!("<p>Server: {}:{} (via {})</p>", server_name, server_port, local_ip))); let description = unwrap_str(server_description()); let banner = unwrap_str(server_banner()); try!(r.write(format!("<p>Server Description/Banner: {} / {}</p>", description, banner))); let mmp = unwrap_str(show_mpm()); try!(r.write(format!("<p>Server MPM: {}</p>", mmp))); let built = unwrap_str(server_built()); try!(r.write(format!("<p>Server Built: {}</p>", built))); let apr_version = unwrap_str(apr_version_string()); try!(r.write(format!("<p>Server loaded APR Version: {}</p>", apr_version))); let apu_version = unwrap_str(apu_version_string()); try!(r.write(format!("<p>Server loaded APU Version: {}</p>", apu_version))); let document_root = unwrap_str(r.document_root()); try!(r.write(format!("<p>Document Root: {}</p>", document_root))); try!(r.write("<hr />")); try!(r.write("<h2>Current Request Information</h2>")); let client_ip = unwrap_str(get!(r.connection()).client_ip()); try!(r.write(format!("<p>Client IP: {}</p>", client_ip))); let useragent_ip = unwrap_str(r.useragent_ip()); try!(r.write(format!("<p>Useragent IP: {}</p>", useragent_ip))); let hostname = unwrap_str(r.hostname()); try!(r.write(format!("<p>Hostname: {}</p>", hostname))); let the_request = unwrap_str(r.the_request()); try!(r.write(format!("<p>Request: {}</p>", the_request))); let protocol = unwrap_str(r.protocol()); try!(r.write(format!("<p>Protocol: {}</p>", protocol))); let http_scheme = unwrap_str(r.http_scheme()); try!(r.write(format!("<p>HTTP Scheme: {}</p>", http_scheme))); try!(r.write(format!("<p>HTTP/0.9: {:?}</p>", r.assbackwards()))); let method = unwrap_str(r.method()); try!(r.write(format!("<p>Method: {}</p>", method))); let unparsed_uri = unwrap_str(r.unparsed_uri()); try!(r.write(format!("<p>Unparsed URI: {}</p>", unparsed_uri))); let uri = unwrap_str(r.uri()); try!(r.write(format!("<p>URI: {}</p>", uri))); let args = unwrap_str(r.args()); try!(r.write(format!("<p>Request Args: {}</p>", args))); let content_type = unwrap_str(r.content_type()); try!(r.write(format!("<p>Content Type: {}</p>", content_type))); let content_encoding = unwrap_str(r.content_encoding()); try!(r.write(format!("<p>Content Encoding: {}</p>", content_encoding))); try!(r.write(format!("<p>Content Length: {}</p>", r.clength()))); try!(r.write(format!("<p>Is Initial Request: {}</p>", r.is_initial_req()))); let context_document_root = unwrap_str(r.context_document_root()); try!(r.write(format!("<p>Context Document Root: {}</p>", context_document_root))); let context_prefix = unwrap_str(r.context_prefix()); try!(r.write(format!("<p>Context Prefix: {}</p>", context_prefix))); let range = unwrap_str(r.range()); try!(r.write(format!("<p>Range: {}</p>", range))); let handler = unwrap_str(r.handler()); try!(r.write(format!("<p>Handler: {}</p>", handler))); let path_info = unwrap_str(r.path_info()); try!(r.write(format!("<p>Path Info: {}</p>", path_info))); let filename = unwrap_str(r.filename()); try!(r.write(format!("<p>Filename: {}</p>", filename))); let canonical_filename = unwrap_str(r.canonical_filename()); try!(r.write(format!("<p>Canonical Filename: {}</p>", canonical_filename))); let request_time = try!(r.rfc822_date(r.request_time())); try!(r.write(format!("<p>Request Time: {} / {}</p>", request_time, r.request_time()))); let mtime = try!(r.rfc822_date(r.mtime())); try!(r.write(format!("<p>Last modified time: {} / {}</p>", mtime, r.mtime()))); let log_id = unwrap_str(r.log_id()); try!(r.write(format!("<p>Log ID: {}</p>", log_id))); let user = unwrap_str(r.user()); try!(r.write(format!("<p>User: {}</p>", user))); try!(r.write(format!("<p>Some Auth Required: {}</p>", r.some_auth_required()))); let ap_auth_type = unwrap_str(r.ap_auth_type()); try!(r.write(format!("<p>Auth Type: {}</p>", ap_auth_type))); let auth_name = unwrap_str(r.auth_name()); try!(r.write(format!("<p>Auth Name: {}</p>", auth_name))); let basic_auth_pw = unwrap_str(r.basic_auth_pw()); try!(r.write(format!("<p>Basic Auth PW: {}</p>", basic_auth_pw))); try!(r.write(format!("<p>Default Port: {}</p>", r.default_port()))); try!(r.write(format!("<p>ProxyReq: {}</p>", r.proxyreq()))); let key = "sample_cookie"; let val = "info_rs"; match r.cookie(key) { None => { let mut cookie = Cookie::new(key, val); cookie.expires = Some(time_now() + 1000000 * 30); r.set_cookie(cookie); try!(r.write(format!("<p>New Cookie – {}: {}</p>", key, val))); }, Some(stored) => { try!(r.write(format!("<p>Cookie – {}: {}</p>", key, stored))); } }; try!(r.write("<h3>Request Headers</h3>")); let headers_in = get!(r.headers_in()); for (key, val) in headers_in.iter() { try!(r.write(format!("<p>{}: {}</p>", key, unwrap_str(val)))); } try!(r.write("<h3>Headers Out</h3>")); let headers_out = get!(r.headers_out()); for (key, val) in headers_out.iter() { try!(r.write(format!("<p>{}: {}</p>", key, unwrap_str(val)))); } try!(r.write("<h3>Err Headers Out</h3>")); let err_headers_out = get!(r.err_headers_out()); for (key, val) in err_headers_out.iter() { try!(r.write(format!("<p>{}: {}</p>", key, unwrap_str(val)))); } try!(r.write("<h3>Notes</h3>")); let notes = get!(r.notes()); for (key, val) in notes.iter() { try!(r.write(format!("<p>{}: {}</p>", key, unwrap_str(val)))); } try!(r.write("<h3>Subprocess Environment</h3>")); let subprocess_env = get!(r.subprocess_env()); for (key, val) in subprocess_env.iter() { try!(r.write(format!("<p>{}: {}</p>", key, unwrap_str(val)))); } try!(r.write("<h3>Request API check</h3>")); let original = "Բարեւ, Héébee, გამარჯობა, Witôjze, Здраво, Ciao"; let encoded = try!(r.base64_encode(original)); let plain = try!(r.base64_decode(encoded)); try!(r.write(format!("<p>Original Text: {}</p>", original))); try!(r.write(format!("<p>Base64 Encoded: {}</p>", encoded))); try!(r.write(format!("<p>Base64 Decoded: {}</p>", plain))); let original_url = "http://foo.bar/1 2 3 & 4 + 5"; let encoded_url = try!(r.escape_urlencoded(original_url)); let plain_url = try!(r.unescape_urlencoded(encoded_url)); try!(r.write(format!("<p>Original URL: {}</p>", original_url))); try!(r.write(format!("<p>Encoded URL: {}</p>", encoded_url))); try!(r.write(format!("<p>Decoded URL: {}</p>", plain_url))); let date = try!(r.rfc822_date(0)); try!(r.write(format!("<p>RFC 822 Date: {}</p>", date))); try!(r.write("</body></html>")); Ok(Status::OK) }
{ if get!(r.handler()) != "server-info-rs" { return Ok(Status::DECLINED) } r.set_content_type("text/html"); r.set_last_modified(time_now()); try!(r.write("<!doctype html><html><head><meta charset=\"utf-8\"><title>Apache Info</title></head><body>")); try!(r.write("<h1>Apache Server Information</h1>")); let server_name = try!( r.escape_html( unwrap_str(r.server_name()) ) ); let server_port = r.server_port(); let local_ip = unwrap_str(get!(r.connection()).local_ip());
identifier_body
rom_bls461_64.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 bls461::big::NLEN; use super::super::arch::Chunk; use types::{ModType, CurveType, CurvePairingType, SexticTwist, SignOfX}; // Base Bits= 60 // bls461 Modulus pub const MODULUS: [Chunk; NLEN] = [ 0xAAC0000AAAAAAAB, 0x20000555554AAAA, 0x6AA91557F004000, 0xA8DFFA5C1CC00F2, 0xACCA47B14848B42, 0x935FBD6F1E32D8B, 0xD5A555A55D69414, 0x15555545554, ]; pub const R2MODP: [Chunk; NLEN] = [ 0x96D08774614DDA8, 0xCD45F539225D5BD, 0xD712EB760C95AB1, 0xB3B687155F30B55, 0xC4E62A05C3F5B81, 0xBA1151676CA3CD0, 0x7EDD8A958F442BE, 0x12B89DD3F91, ]; pub const MCONST: Chunk = 0xC0005FFFFFFFD; pub const FRA: [Chunk; NLEN] = [ 0xF7117BF9B812A3A, 0xA1C6308A599C400, 0x5A6510E07505BF8, 0xB31ACE4858D45FA, 0xFC61EBC2CB04770, 0x366190D073588E2, 0x69E55E24DFEFA84, 0x12E40504B7F, ]; pub const FRB: [Chunk; NLEN] = [ 0xB3AE8410F298071, 0x7E39D4CAFBAE6A9, 0x104404777AFE407, 0xF5C52C13C3EBAF8, 0xB0685BEE7D443D1, 0x5CFE2C9EAADA4A8, 0x6BBFF7807D79990, 0x27150409D5, ]; // bls461 Curve pub const CURVE_COF_I: isize = 0; pub const CURVE_A: isize = 0; pub const CURVE_B_I: isize = 9; pub const CURVE_B: [Chunk; NLEN] = [0x9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]; pub const CURVE_ORDER: [Chunk; NLEN] = [ 0x1, 0x7FEFFFEFFFFC0, 0xC017FFC80001100, 0x7FE05FD000E801F, 0xFFFF7FFFC018001, 0xFF, 0x0, 0x0, ]; pub const CURVE_GX: [Chunk; NLEN] = [ 0x14D026A8ADEE93D, 0xF2D9C00EE74B741, 0x229C3981B531AC7, 0x6650D3564DC9218, 0x436166F7C292A09, 0x2CF668BE922B197, 0x463B73A0C813271, 0xAD0E74E99B, ]; pub const CURVE_GY: [Chunk; NLEN] = [ 0xF763157AD1D465, 0x5D17884C8C4FF47, 0x9D0A819E66B8D21, 0x910AE5C3245F495, 0x96EECB8BFA40B84, 0x277ACC8BF9F8CBE, 0x5F68C95F1C3F2F, 0x77BCDB14B3, ]; pub const CURVE_BNX: [Chunk; NLEN] = [0xFFBFFFE00000000, 0x1FFFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]; pub const CURVE_COF: [Chunk; NLEN] = [ 0xAA7FFFEAAAAAAAB, 0xFFD55AAAB01556A, 0x1555554FF, 0x0, 0x0, 0x0, 0x0, 0x0, ]; pub const CURVE_CRU: [Chunk; NLEN] = [ 0x40001FFFFFFFE, 0x6FFFE7FFFFE0000, 0x6047200C47F0FFF, 0x777115796DB7BCC, 0x3F0E89875433CF4, 0xBFFF60500050261, 0x1FFFFFE, 0x0, ]; pub const CURVE_PXA: [Chunk; NLEN] = [ 0x65B503186D0A37C, 0xA9C2E492E75DCC4, 0x564E01F919D6878, 0x3F086DB74FF92F, 0xED78D46D581A668, 0x270C892F97C2907, 0x6A50A9AF679453C, 0x10CC54138A0, ]; pub const CURVE_PXB: [Chunk; NLEN] = [ 0x9F85CA8C2C1C0AD, 0x96CD66C425CADE, 0x1AC612951A2896, 0xB17D529ABEBEE24, 0xC5AF5BA09D33F65, 0x6A672E4D4371ED4, 0xACEA37CA279D224, 0x95C1FB4FE5, ]; pub const CURVE_PYA: [Chunk; NLEN] = [ 0x7CCD0C1B02FB006, 0x953D194A4A12A33, 0x68B4960CFCC92C8, 0xBA0F3A9B00F39FC, 0xCDFD8A7DBBC5ED1, 0xE73ED227CC2F7A9, 0xEBA7E676070F4F4, 0x226AC848E7, ]; pub const CURVE_PYB: [Chunk; NLEN] = [ 0x8A506ADFDF1457C, 0xB4D6A31DC04C20A, 0x668EA9A8F136E3F, 0x12973C3BE4492F5, 0xA20BE74BEABA67A, 0x5157F04C42E3856, 0xBB402EA2AB1D004, 0xE38101B4FA, ]; pub const CURVE_W: [[Chunk; NLEN]; 2] = [ [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], ]; pub const CURVE_SB: [[[Chunk; NLEN]; 2]; 2] = [ [ [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], ], [ [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], ], ]; pub const CURVE_WB: [[Chunk; NLEN]; 4] = [ [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], ]; pub const CURVE_BB: [[[Chunk; NLEN]; 4]; 4] = [ [ [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], ], [ [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], ], [ [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], ], [ [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0], ], ]; pub const USE_GLV: bool = true; pub const USE_GS_G2: bool = true; pub const USE_GS_GT: bool = true; pub const GT_STRONG: bool = false; pub const MODBYTES: usize = 58; pub const BASEBITS: usize = 60; pub const MODBITS: usize = 461; pub const MOD8: usize = 3; pub const MODTYPE: ModType = ModType::NOT_SPECIAL; pub const SH: usize = 19; pub const CURVETYPE: CurveType = CurveType::WEIERSTRASS; pub const CURVE_PAIRING_TYPE: CurvePairingType = CurvePairingType::BLS;
pub const HASH_TYPE: usize = 32; pub const AESKEY: usize = 16;
pub const SEXTIC_TWIST: SexticTwist = SexticTwist::M_TYPE; pub const ATE_BITS: usize = 78; pub const SIGN_OF_X: SignOfX = SignOfX::NEGATIVEX;
random_line_split
node.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use elastic_array::ElasticArray36; use nibbleslice::*; use bytes::*; use rlp::*; use super::journal::*; use hashdb::DBValue; /// Partial node key type. pub type NodeKey = ElasticArray36<u8>; /// Type of node in the trie and essential information thereof. #[derive(Eq, PartialEq, Debug)] pub enum Node { /// Null trie node; could be an empty root or an empty branch entry. Empty, /// Leaf node; has key slice and value. Value may not be empty. Leaf(NodeKey, DBValue), /// Extension node; has key slice and node data. Data may not be null. Extension(NodeKey, DBValue), /// Branch node; has array of 16 child nodes (each possibly null) and an optional immediate node data.
fn clone(&self) -> Node { match *self { Node::Empty => Node::Empty, Node::Leaf(ref k, ref v) => Node::Leaf(k.clone(), v.clone()), Node::Extension(ref k, ref v) => Node::Extension(k.clone(), v.clone()), Node::Branch(ref k, ref v) => { let mut branch = [NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new()]; for i in 0.. 16 { branch[i] = k[i].clone(); } Node::Branch(branch, v.clone()) } } } } impl Node { /// Decode the `node_rlp` and return the Node. pub fn decoded(node_rlp: &[u8]) -> Node { let r = Rlp::new(node_rlp); match r.prototype() { // either leaf or extension - decode first item with NibbleSlice::??? // and use is_leaf return to figure out which. // if leaf, second item is a value (is_data()) // if extension, second item is a node (either SHA3 to be looked up and // fed back into this function or inline RLP which can be fed back into this function). Prototype::List(2) => match NibbleSlice::from_encoded(r.at(0).data()) { (slice, true) => Node::Leaf(slice.encoded(true), DBValue::from_slice(r.at(1).data())), (slice, false) => Node::Extension(slice.encoded(false), DBValue::from_slice(r.at(1).as_raw())), }, // branch - first 16 are nodes, 17th is a value (or empty). Prototype::List(17) => { let mut nodes: [NodeKey; 16] = [NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new()]; for i in 0..16 { nodes[i] = NodeKey::from_slice(r.at(i).as_raw()); } Node::Branch(nodes, if r.at(16).is_empty() { None } else { Some(DBValue::from_slice(r.at(16).data())) }) }, // an empty branch index. Prototype::Data(0) => Node::Empty, // something went wrong. _ => panic!("Rlp is not valid.") } } /// Encode the node into RLP. /// /// Will always return the direct node RLP even if it's 32 or more bytes. To get the /// RLP which would be valid for using in another node, use `encoded_and_added()`. pub fn encoded(&self) -> Bytes { match *self { Node::Leaf(ref slice, ref value) => { let mut stream = RlpStream::new_list(2); stream.append(&&**slice); stream.append(&&**value); stream.out() }, Node::Extension(ref slice, ref raw_rlp) => { let mut stream = RlpStream::new_list(2); stream.append(&&**slice); stream.append_raw(&&*raw_rlp, 1); stream.out() }, Node::Branch(ref nodes, ref value) => { let mut stream = RlpStream::new_list(17); for i in 0..16 { stream.append_raw(&*nodes[i], 1); } match *value { Some(ref n) => { stream.append(&&**n); }, None => { stream.append_empty_data(); }, } stream.out() }, Node::Empty => { let mut stream = RlpStream::new(); stream.append_empty_data(); stream.out() } } } /// Encode the node, adding it to `journal` if necessary and return the RLP valid for /// insertion into a parent node. pub fn encoded_and_added(&self, journal: &mut Journal) -> DBValue { let mut stream = RlpStream::new(); match *self { Node::Leaf(ref slice, ref value) => { stream.begin_list(2); stream.append(&&**slice); stream.append(&&**value); }, Node::Extension(ref slice, ref raw_rlp) => { stream.begin_list(2); stream.append(&&**slice); stream.append_raw(&&**raw_rlp, 1); }, Node::Branch(ref nodes, ref value) => { stream.begin_list(17); for i in 0..16 { stream.append_raw(&*nodes[i], 1); } match *value { Some(ref n) => { stream.append(&&**n); }, None => { stream.append_empty_data(); }, } }, Node::Empty => { stream.append_empty_data(); } } let node = DBValue::from_slice(stream.as_raw()); match node.len() { 0... 31 => node, _ => { let mut stream = RlpStream::new(); journal.new_node(node, &mut stream); DBValue::from_slice(stream.as_raw()) } } } }
Branch([NodeKey; 16], Option<DBValue>) } impl Clone for Node {
random_line_split
node.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use elastic_array::ElasticArray36; use nibbleslice::*; use bytes::*; use rlp::*; use super::journal::*; use hashdb::DBValue; /// Partial node key type. pub type NodeKey = ElasticArray36<u8>; /// Type of node in the trie and essential information thereof. #[derive(Eq, PartialEq, Debug)] pub enum Node { /// Null trie node; could be an empty root or an empty branch entry. Empty, /// Leaf node; has key slice and value. Value may not be empty. Leaf(NodeKey, DBValue), /// Extension node; has key slice and node data. Data may not be null. Extension(NodeKey, DBValue), /// Branch node; has array of 16 child nodes (each possibly null) and an optional immediate node data. Branch([NodeKey; 16], Option<DBValue>) } impl Clone for Node { fn clone(&self) -> Node { match *self { Node::Empty => Node::Empty, Node::Leaf(ref k, ref v) => Node::Leaf(k.clone(), v.clone()), Node::Extension(ref k, ref v) => Node::Extension(k.clone(), v.clone()), Node::Branch(ref k, ref v) => { let mut branch = [NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new()]; for i in 0.. 16 { branch[i] = k[i].clone(); } Node::Branch(branch, v.clone()) } } } } impl Node { /// Decode the `node_rlp` and return the Node. pub fn
(node_rlp: &[u8]) -> Node { let r = Rlp::new(node_rlp); match r.prototype() { // either leaf or extension - decode first item with NibbleSlice::??? // and use is_leaf return to figure out which. // if leaf, second item is a value (is_data()) // if extension, second item is a node (either SHA3 to be looked up and // fed back into this function or inline RLP which can be fed back into this function). Prototype::List(2) => match NibbleSlice::from_encoded(r.at(0).data()) { (slice, true) => Node::Leaf(slice.encoded(true), DBValue::from_slice(r.at(1).data())), (slice, false) => Node::Extension(slice.encoded(false), DBValue::from_slice(r.at(1).as_raw())), }, // branch - first 16 are nodes, 17th is a value (or empty). Prototype::List(17) => { let mut nodes: [NodeKey; 16] = [NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new()]; for i in 0..16 { nodes[i] = NodeKey::from_slice(r.at(i).as_raw()); } Node::Branch(nodes, if r.at(16).is_empty() { None } else { Some(DBValue::from_slice(r.at(16).data())) }) }, // an empty branch index. Prototype::Data(0) => Node::Empty, // something went wrong. _ => panic!("Rlp is not valid.") } } /// Encode the node into RLP. /// /// Will always return the direct node RLP even if it's 32 or more bytes. To get the /// RLP which would be valid for using in another node, use `encoded_and_added()`. pub fn encoded(&self) -> Bytes { match *self { Node::Leaf(ref slice, ref value) => { let mut stream = RlpStream::new_list(2); stream.append(&&**slice); stream.append(&&**value); stream.out() }, Node::Extension(ref slice, ref raw_rlp) => { let mut stream = RlpStream::new_list(2); stream.append(&&**slice); stream.append_raw(&&*raw_rlp, 1); stream.out() }, Node::Branch(ref nodes, ref value) => { let mut stream = RlpStream::new_list(17); for i in 0..16 { stream.append_raw(&*nodes[i], 1); } match *value { Some(ref n) => { stream.append(&&**n); }, None => { stream.append_empty_data(); }, } stream.out() }, Node::Empty => { let mut stream = RlpStream::new(); stream.append_empty_data(); stream.out() } } } /// Encode the node, adding it to `journal` if necessary and return the RLP valid for /// insertion into a parent node. pub fn encoded_and_added(&self, journal: &mut Journal) -> DBValue { let mut stream = RlpStream::new(); match *self { Node::Leaf(ref slice, ref value) => { stream.begin_list(2); stream.append(&&**slice); stream.append(&&**value); }, Node::Extension(ref slice, ref raw_rlp) => { stream.begin_list(2); stream.append(&&**slice); stream.append_raw(&&**raw_rlp, 1); }, Node::Branch(ref nodes, ref value) => { stream.begin_list(17); for i in 0..16 { stream.append_raw(&*nodes[i], 1); } match *value { Some(ref n) => { stream.append(&&**n); }, None => { stream.append_empty_data(); }, } }, Node::Empty => { stream.append_empty_data(); } } let node = DBValue::from_slice(stream.as_raw()); match node.len() { 0... 31 => node, _ => { let mut stream = RlpStream::new(); journal.new_node(node, &mut stream); DBValue::from_slice(stream.as_raw()) } } } }
decoded
identifier_name
node.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use elastic_array::ElasticArray36; use nibbleslice::*; use bytes::*; use rlp::*; use super::journal::*; use hashdb::DBValue; /// Partial node key type. pub type NodeKey = ElasticArray36<u8>; /// Type of node in the trie and essential information thereof. #[derive(Eq, PartialEq, Debug)] pub enum Node { /// Null trie node; could be an empty root or an empty branch entry. Empty, /// Leaf node; has key slice and value. Value may not be empty. Leaf(NodeKey, DBValue), /// Extension node; has key slice and node data. Data may not be null. Extension(NodeKey, DBValue), /// Branch node; has array of 16 child nodes (each possibly null) and an optional immediate node data. Branch([NodeKey; 16], Option<DBValue>) } impl Clone for Node { fn clone(&self) -> Node { match *self { Node::Empty => Node::Empty, Node::Leaf(ref k, ref v) => Node::Leaf(k.clone(), v.clone()), Node::Extension(ref k, ref v) => Node::Extension(k.clone(), v.clone()), Node::Branch(ref k, ref v) => { let mut branch = [NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new()]; for i in 0.. 16 { branch[i] = k[i].clone(); } Node::Branch(branch, v.clone()) } } } } impl Node { /// Decode the `node_rlp` and return the Node. pub fn decoded(node_rlp: &[u8]) -> Node { let r = Rlp::new(node_rlp); match r.prototype() { // either leaf or extension - decode first item with NibbleSlice::??? // and use is_leaf return to figure out which. // if leaf, second item is a value (is_data()) // if extension, second item is a node (either SHA3 to be looked up and // fed back into this function or inline RLP which can be fed back into this function). Prototype::List(2) => match NibbleSlice::from_encoded(r.at(0).data()) { (slice, true) => Node::Leaf(slice.encoded(true), DBValue::from_slice(r.at(1).data())), (slice, false) => Node::Extension(slice.encoded(false), DBValue::from_slice(r.at(1).as_raw())), }, // branch - first 16 are nodes, 17th is a value (or empty). Prototype::List(17) => { let mut nodes: [NodeKey; 16] = [NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new(), NodeKey::new()]; for i in 0..16 { nodes[i] = NodeKey::from_slice(r.at(i).as_raw()); } Node::Branch(nodes, if r.at(16).is_empty() { None } else { Some(DBValue::from_slice(r.at(16).data())) }) }, // an empty branch index. Prototype::Data(0) => Node::Empty, // something went wrong. _ => panic!("Rlp is not valid.") } } /// Encode the node into RLP. /// /// Will always return the direct node RLP even if it's 32 or more bytes. To get the /// RLP which would be valid for using in another node, use `encoded_and_added()`. pub fn encoded(&self) -> Bytes
Some(ref n) => { stream.append(&&**n); }, None => { stream.append_empty_data(); }, } stream.out() }, Node::Empty => { let mut stream = RlpStream::new(); stream.append_empty_data(); stream.out() } } } /// Encode the node, adding it to `journal` if necessary and return the RLP valid for /// insertion into a parent node. pub fn encoded_and_added(&self, journal: &mut Journal) -> DBValue { let mut stream = RlpStream::new(); match *self { Node::Leaf(ref slice, ref value) => { stream.begin_list(2); stream.append(&&**slice); stream.append(&&**value); }, Node::Extension(ref slice, ref raw_rlp) => { stream.begin_list(2); stream.append(&&**slice); stream.append_raw(&&**raw_rlp, 1); }, Node::Branch(ref nodes, ref value) => { stream.begin_list(17); for i in 0..16 { stream.append_raw(&*nodes[i], 1); } match *value { Some(ref n) => { stream.append(&&**n); }, None => { stream.append_empty_data(); }, } }, Node::Empty => { stream.append_empty_data(); } } let node = DBValue::from_slice(stream.as_raw()); match node.len() { 0... 31 => node, _ => { let mut stream = RlpStream::new(); journal.new_node(node, &mut stream); DBValue::from_slice(stream.as_raw()) } } } }
{ match *self { Node::Leaf(ref slice, ref value) => { let mut stream = RlpStream::new_list(2); stream.append(&&**slice); stream.append(&&**value); stream.out() }, Node::Extension(ref slice, ref raw_rlp) => { let mut stream = RlpStream::new_list(2); stream.append(&&**slice); stream.append_raw(&&*raw_rlp, 1); stream.out() }, Node::Branch(ref nodes, ref value) => { let mut stream = RlpStream::new_list(17); for i in 0..16 { stream.append_raw(&*nodes[i], 1); } match *value {
identifier_body
errors.rs
//! # Errors //! //! Rust doesn't have exceptions, so errors are expressed as a variant on //! the standard library [`Result`]() type that implements the [`Error`]() //! trait. //! The problem with the `Error` trait is that it can be cumbersome to implement //! manually, and leads to a lot of conversion boiletplate. //! Luckily we have crates like [`error-chain`]() that make it really easy to //! declare error types. use redis; use serde_json; error_chain! { foreign_links { redis::RedisError, RedisError; serde_json::Error, JsonError; } errors { NotAnId { description("the given value isn't a valid id") display("the given value isn't a valid id") } PersonNotFound { description("the requested person doesn't exist") display("the requested person doesn't exist") } } } use iron::IronError; use iron::status::Status; impl From<Error> for IronError { fn
(err: Error) -> IronError { match err { e @ Error { kind: ErrorKind::PersonNotFound, state: _ } => IronError::new(e, Status::NotFound), e => IronError::new(e, Status::InternalServerError), } } }
from
identifier_name
errors.rs
//! # Errors //! //! Rust doesn't have exceptions, so errors are expressed as a variant on //! the standard library [`Result`]() type that implements the [`Error`]() //! trait. //! The problem with the `Error` trait is that it can be cumbersome to implement //! manually, and leads to a lot of conversion boiletplate. //! Luckily we have crates like [`error-chain`]() that make it really easy to //! declare error types.
error_chain! { foreign_links { redis::RedisError, RedisError; serde_json::Error, JsonError; } errors { NotAnId { description("the given value isn't a valid id") display("the given value isn't a valid id") } PersonNotFound { description("the requested person doesn't exist") display("the requested person doesn't exist") } } } use iron::IronError; use iron::status::Status; impl From<Error> for IronError { fn from(err: Error) -> IronError { match err { e @ Error { kind: ErrorKind::PersonNotFound, state: _ } => IronError::new(e, Status::NotFound), e => IronError::new(e, Status::InternalServerError), } } }
use redis; use serde_json;
random_line_split
errors.rs
//! # Errors //! //! Rust doesn't have exceptions, so errors are expressed as a variant on //! the standard library [`Result`]() type that implements the [`Error`]() //! trait. //! The problem with the `Error` trait is that it can be cumbersome to implement //! manually, and leads to a lot of conversion boiletplate. //! Luckily we have crates like [`error-chain`]() that make it really easy to //! declare error types. use redis; use serde_json; error_chain! { foreign_links { redis::RedisError, RedisError; serde_json::Error, JsonError; } errors { NotAnId { description("the given value isn't a valid id") display("the given value isn't a valid id") } PersonNotFound { description("the requested person doesn't exist") display("the requested person doesn't exist") } } } use iron::IronError; use iron::status::Status; impl From<Error> for IronError { fn from(err: Error) -> IronError
}
{ match err { e @ Error { kind: ErrorKind::PersonNotFound, state: _ } => IronError::new(e, Status::NotFound), e => IronError::new(e, Status::InternalServerError), } }
identifier_body
i686_unknown_linux_gnu.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use target::Target; pub fn
() -> Target { let mut base = super::linux_base::opts(); base.pre_link_args.push("-m32".to_string()); Target { data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(), llvm_target: "i686-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "linux".to_string(), options: base, } }
target
identifier_name
i686_unknown_linux_gnu.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use target::Target; pub fn target() -> Target { let mut base = super::linux_base::opts(); base.pre_link_args.push("-m32".to_string()); Target { data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(), llvm_target: "i686-unknown-linux-gnu".to_string(), target_endian: "little".to_string(),
target_os: "linux".to_string(), options: base, } }
target_pointer_width: "32".to_string(), arch: "x86".to_string(),
random_line_split
i686_unknown_linux_gnu.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use target::Target; pub fn target() -> Target
{ let mut base = super::linux_base::opts(); base.pre_link_args.push("-m32".to_string()); Target { data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(), llvm_target: "i686-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "linux".to_string(), options: base, } }
identifier_body
day07.rs
use std::io::Read; use itertools::Itertools; use crate::common::ordered; fn read_input(input: &mut dyn Read) -> Vec<usize> { let mut buf = String::new(); input.read_to_string(&mut buf).unwrap(); let mut crabs: Vec<usize> = buf .trim_end() .split(',') .map(|s| s.parse().unwrap()) .collect(); crabs.sort_unstable(); crabs } fn cost_at(pos: usize, crabs: &[usize]) -> usize { crabs .iter() .map(|&crab_pos| { if crab_pos > pos { crab_pos - pos } else { pos - crab_pos } }) .sum() } pub fn part1(input: &mut dyn Read) -> String { let crabs = read_input(input); let median = crabs[crabs.len() / 2 + (crabs.len() % 2)]; cost_at(median, &crabs).to_string() } pub fn sum_until(end: usize) -> usize { (end * (1 + end)) / 2 } fn cost_at2(pos: usize, groups: &[(usize, usize)]) -> usize { groups .iter() .map(|&(number, new_pos)| { let (first, last) = ordered(pos, new_pos); number * sum_until(last - first) }) .sum() } fn ternary_search(mut min: usize, mut max: usize, callback: impl Fn(usize) -> usize) -> usize { while max - min > 6 { let mid1 = min + (max - min) / 3; let mid2 = max - (max - min) / 3; let cost1 = callback(mid1); let cost2 = callback(mid2); if cost1 < cost2
else { min = mid1 + 1 } } // Ternary search isn't effective at such small intervals so we iterate the remaining part (min..=max).map(callback).min().unwrap() } pub fn part2(input: &mut dyn Read) -> String { let groups: Vec<_> = read_input(input).into_iter().dedup_with_count().collect(); let min = groups.first().unwrap().1; let max = groups.last().unwrap().1; ternary_search(min, max, |pos| cost_at2(pos, &groups)).to_string() } #[cfg(test)] mod tests { use crate::test_implementation; use super::*; const SAMPLE: &[u8] = &*b"16,1,2,0,4,2,7,1,2,14"; #[test] fn sample_part1() { test_implementation(part1, SAMPLE, 37); } #[test] fn sample_part2() { test_implementation(part2, SAMPLE, 168); } #[test] fn test_maths() { assert_eq!(sum_until(1), 1); assert_eq!(sum_until(2), 3); assert_eq!(sum_until(3), 6); assert_eq!(sum_until(4), 10); } }
{ max = mid2 - 1 }
conditional_block
day07.rs
use std::io::Read; use itertools::Itertools; use crate::common::ordered; fn read_input(input: &mut dyn Read) -> Vec<usize> { let mut buf = String::new(); input.read_to_string(&mut buf).unwrap(); let mut crabs: Vec<usize> = buf .trim_end() .split(',') .map(|s| s.parse().unwrap()) .collect(); crabs.sort_unstable(); crabs } fn cost_at(pos: usize, crabs: &[usize]) -> usize { crabs .iter() .map(|&crab_pos| { if crab_pos > pos { crab_pos - pos } else { pos - crab_pos } }) .sum() } pub fn part1(input: &mut dyn Read) -> String { let crabs = read_input(input); let median = crabs[crabs.len() / 2 + (crabs.len() % 2)]; cost_at(median, &crabs).to_string() } pub fn sum_until(end: usize) -> usize { (end * (1 + end)) / 2 } fn cost_at2(pos: usize, groups: &[(usize, usize)]) -> usize { groups .iter() .map(|&(number, new_pos)| { let (first, last) = ordered(pos, new_pos); number * sum_until(last - first) }) .sum() } fn ternary_search(mut min: usize, mut max: usize, callback: impl Fn(usize) -> usize) -> usize { while max - min > 6 { let mid1 = min + (max - min) / 3; let mid2 = max - (max - min) / 3; let cost1 = callback(mid1); let cost2 = callback(mid2); if cost1 < cost2 { max = mid2 - 1 } else { min = mid1 + 1 } } // Ternary search isn't effective at such small intervals so we iterate the remaining part (min..=max).map(callback).min().unwrap() } pub fn part2(input: &mut dyn Read) -> String
#[cfg(test)] mod tests { use crate::test_implementation; use super::*; const SAMPLE: &[u8] = &*b"16,1,2,0,4,2,7,1,2,14"; #[test] fn sample_part1() { test_implementation(part1, SAMPLE, 37); } #[test] fn sample_part2() { test_implementation(part2, SAMPLE, 168); } #[test] fn test_maths() { assert_eq!(sum_until(1), 1); assert_eq!(sum_until(2), 3); assert_eq!(sum_until(3), 6); assert_eq!(sum_until(4), 10); } }
{ let groups: Vec<_> = read_input(input).into_iter().dedup_with_count().collect(); let min = groups.first().unwrap().1; let max = groups.last().unwrap().1; ternary_search(min, max, |pos| cost_at2(pos, &groups)).to_string() }
identifier_body
day07.rs
use std::io::Read; use itertools::Itertools; use crate::common::ordered; fn read_input(input: &mut dyn Read) -> Vec<usize> { let mut buf = String::new(); input.read_to_string(&mut buf).unwrap(); let mut crabs: Vec<usize> = buf .trim_end() .split(',') .map(|s| s.parse().unwrap()) .collect(); crabs.sort_unstable(); crabs } fn cost_at(pos: usize, crabs: &[usize]) -> usize { crabs .iter() .map(|&crab_pos| { if crab_pos > pos { crab_pos - pos } else { pos - crab_pos } }) .sum() } pub fn part1(input: &mut dyn Read) -> String { let crabs = read_input(input); let median = crabs[crabs.len() / 2 + (crabs.len() % 2)]; cost_at(median, &crabs).to_string() } pub fn
(end: usize) -> usize { (end * (1 + end)) / 2 } fn cost_at2(pos: usize, groups: &[(usize, usize)]) -> usize { groups .iter() .map(|&(number, new_pos)| { let (first, last) = ordered(pos, new_pos); number * sum_until(last - first) }) .sum() } fn ternary_search(mut min: usize, mut max: usize, callback: impl Fn(usize) -> usize) -> usize { while max - min > 6 { let mid1 = min + (max - min) / 3; let mid2 = max - (max - min) / 3; let cost1 = callback(mid1); let cost2 = callback(mid2); if cost1 < cost2 { max = mid2 - 1 } else { min = mid1 + 1 } } // Ternary search isn't effective at such small intervals so we iterate the remaining part (min..=max).map(callback).min().unwrap() } pub fn part2(input: &mut dyn Read) -> String { let groups: Vec<_> = read_input(input).into_iter().dedup_with_count().collect(); let min = groups.first().unwrap().1; let max = groups.last().unwrap().1; ternary_search(min, max, |pos| cost_at2(pos, &groups)).to_string() } #[cfg(test)] mod tests { use crate::test_implementation; use super::*; const SAMPLE: &[u8] = &*b"16,1,2,0,4,2,7,1,2,14"; #[test] fn sample_part1() { test_implementation(part1, SAMPLE, 37); } #[test] fn sample_part2() { test_implementation(part2, SAMPLE, 168); } #[test] fn test_maths() { assert_eq!(sum_until(1), 1); assert_eq!(sum_until(2), 3); assert_eq!(sum_until(3), 6); assert_eq!(sum_until(4), 10); } }
sum_until
identifier_name
day07.rs
use std::io::Read; use itertools::Itertools; use crate::common::ordered; fn read_input(input: &mut dyn Read) -> Vec<usize> { let mut buf = String::new(); input.read_to_string(&mut buf).unwrap(); let mut crabs: Vec<usize> = buf .trim_end() .split(',') .map(|s| s.parse().unwrap()) .collect(); crabs.sort_unstable(); crabs } fn cost_at(pos: usize, crabs: &[usize]) -> usize { crabs .iter() .map(|&crab_pos| { if crab_pos > pos { crab_pos - pos } else { pos - crab_pos }
.sum() } pub fn part1(input: &mut dyn Read) -> String { let crabs = read_input(input); let median = crabs[crabs.len() / 2 + (crabs.len() % 2)]; cost_at(median, &crabs).to_string() } pub fn sum_until(end: usize) -> usize { (end * (1 + end)) / 2 } fn cost_at2(pos: usize, groups: &[(usize, usize)]) -> usize { groups .iter() .map(|&(number, new_pos)| { let (first, last) = ordered(pos, new_pos); number * sum_until(last - first) }) .sum() } fn ternary_search(mut min: usize, mut max: usize, callback: impl Fn(usize) -> usize) -> usize { while max - min > 6 { let mid1 = min + (max - min) / 3; let mid2 = max - (max - min) / 3; let cost1 = callback(mid1); let cost2 = callback(mid2); if cost1 < cost2 { max = mid2 - 1 } else { min = mid1 + 1 } } // Ternary search isn't effective at such small intervals so we iterate the remaining part (min..=max).map(callback).min().unwrap() } pub fn part2(input: &mut dyn Read) -> String { let groups: Vec<_> = read_input(input).into_iter().dedup_with_count().collect(); let min = groups.first().unwrap().1; let max = groups.last().unwrap().1; ternary_search(min, max, |pos| cost_at2(pos, &groups)).to_string() } #[cfg(test)] mod tests { use crate::test_implementation; use super::*; const SAMPLE: &[u8] = &*b"16,1,2,0,4,2,7,1,2,14"; #[test] fn sample_part1() { test_implementation(part1, SAMPLE, 37); } #[test] fn sample_part2() { test_implementation(part2, SAMPLE, 168); } #[test] fn test_maths() { assert_eq!(sum_until(1), 1); assert_eq!(sum_until(2), 3); assert_eq!(sum_until(3), 6); assert_eq!(sum_until(4), 10); } }
})
random_line_split
ppm_writer.rs
extern crate ppm; use std::io; use ppm::PPMWriter; fn main() { let width = 200; let height = 100; let image_data = generate_image_data(width, height); let stdout = io::stdout(); let mut out = stdout.lock(); let mut writer = PPMWriter::new(&mut out); writer.write(&image_data[..], width, height).unwrap(); } fn
(width: usize, height: usize) -> Vec<f32> { let mut image_data = Vec::new(); for y in 0..height { for x in 0..width { let r = x as f32 / width as f32; let g = y as f32 / height as f32; let b = 0.2; image_data.push(r); image_data.push(g); image_data.push(b); } } image_data }
generate_image_data
identifier_name
ppm_writer.rs
extern crate ppm; use std::io; use ppm::PPMWriter; fn main() { let width = 200; let height = 100; let image_data = generate_image_data(width, height); let stdout = io::stdout(); let mut out = stdout.lock(); let mut writer = PPMWriter::new(&mut out); writer.write(&image_data[..], width, height).unwrap(); } fn generate_image_data(width: usize, height: usize) -> Vec<f32> { let mut image_data = Vec::new(); for y in 0..height { for x in 0..width { let r = x as f32 / width as f32; let g = y as f32 / height as f32; let b = 0.2;
} image_data }
image_data.push(r); image_data.push(g); image_data.push(b); }
random_line_split
ppm_writer.rs
extern crate ppm; use std::io; use ppm::PPMWriter; fn main() { let width = 200; let height = 100; let image_data = generate_image_data(width, height); let stdout = io::stdout(); let mut out = stdout.lock(); let mut writer = PPMWriter::new(&mut out); writer.write(&image_data[..], width, height).unwrap(); } fn generate_image_data(width: usize, height: usize) -> Vec<f32>
{ let mut image_data = Vec::new(); for y in 0..height { for x in 0..width { let r = x as f32 / width as f32; let g = y as f32 / height as f32; let b = 0.2; image_data.push(r); image_data.push(g); image_data.push(b); } } image_data }
identifier_body
csssupportsrule.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::Parser; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use style::parser::{LengthParsingMode, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylearc::Arc; use style::stylesheets::{CssRuleType, SupportsRule}; use style::supports::SupportsCondition; use style_traits::ToCss; #[dom_struct] pub struct CSSSupportsRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), window, CSSSupportsRuleBinding::Wrap) } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text: DOMString)
} impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
{ let mut input = Parser::new(&text); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), LengthParsingMode::Default, quirks_mode); let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; } }
identifier_body
csssupportsrule.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::Parser; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use style::parser::{LengthParsingMode, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylearc::Arc; use style::stylesheets::{CssRuleType, SupportsRule}; use style::supports::SupportsCondition; use style_traits::ToCss; #[dom_struct] pub struct CSSSupportsRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), window, CSSSupportsRuleBinding::Wrap) } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = Parser::new(&text); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond
} } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
{ let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), LengthParsingMode::Default, quirks_mode); let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; }
conditional_block
csssupportsrule.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::Parser; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use style::parser::{LengthParsingMode, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylearc::Arc; use style::stylesheets::{CssRuleType, SupportsRule}; use style::supports::SupportsCondition; use style_traits::ToCss; #[dom_struct] pub struct CSSSupportsRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), window, CSSSupportsRuleBinding::Wrap) } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn
(&self, text: DOMString) { let mut input = Parser::new(&text); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), LengthParsingMode::Default, quirks_mode); let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; } } } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
set_condition_text
identifier_name
csssupportsrule.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::Parser; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use style::parser::{LengthParsingMode, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylearc::Arc; use style::stylesheets::{CssRuleType, SupportsRule}; use style::supports::SupportsCondition; use style_traits::ToCss; #[dom_struct] pub struct CSSSupportsRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), window, CSSSupportsRuleBinding::Wrap) } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = Parser::new(&text); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), LengthParsingMode::Default, quirks_mode); let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; } } } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
use dom::bindings::js::Root;
random_line_split
tests.rs
use scanner::tokenize; use scanner::tokens::Token; use scanner::tokens::Token::*;
assert_eq!(expected, actual); } #[test] fn scan_base_command() { let expected: Vec<Token> = vec![ Base, Ident("name".to_string()), Lparen, Ident("A50".to_string()), Rparen, Dot]; let actual = tokenize("base name (A50)."); assert_eq!(expected, actual); } #[test] fn scan_end_command() { let expected = vec![End, Dot]; let actual = tokenize("end."); assert_eq!(expected, actual); } #[test] fn scan_unicode_ident() { // todo: add some unicode characters to the test let expected = vec![Lparen, Ident("abc1231".to_string()), Rparen]; let actual = tokenize("(abc1231)"); assert_eq!(expected, actual); } #[test] fn scan_keywords() { let expected = vec![Database, Base, Type, End]; let actual = tokenize("database base type end"); assert_eq!(expected, actual); }
#[test] fn scan_terminals() { let expected = vec![Lparen, Rparen, Dot]; let actual = tokenize("().");
random_line_split
tests.rs
use scanner::tokenize; use scanner::tokens::Token; use scanner::tokens::Token::*; #[test] fn scan_terminals() { let expected = vec![Lparen, Rparen, Dot]; let actual = tokenize("()."); assert_eq!(expected, actual); } #[test] fn
() { let expected: Vec<Token> = vec![ Base, Ident("name".to_string()), Lparen, Ident("A50".to_string()), Rparen, Dot]; let actual = tokenize("base name (A50)."); assert_eq!(expected, actual); } #[test] fn scan_end_command() { let expected = vec![End, Dot]; let actual = tokenize("end."); assert_eq!(expected, actual); } #[test] fn scan_unicode_ident() { // todo: add some unicode characters to the test let expected = vec![Lparen, Ident("abc1231".to_string()), Rparen]; let actual = tokenize("(abc1231)"); assert_eq!(expected, actual); } #[test] fn scan_keywords() { let expected = vec![Database, Base, Type, End]; let actual = tokenize("database base type end"); assert_eq!(expected, actual); }
scan_base_command
identifier_name
tests.rs
use scanner::tokenize; use scanner::tokens::Token; use scanner::tokens::Token::*; #[test] fn scan_terminals()
#[test] fn scan_base_command() { let expected: Vec<Token> = vec![ Base, Ident("name".to_string()), Lparen, Ident("A50".to_string()), Rparen, Dot]; let actual = tokenize("base name (A50)."); assert_eq!(expected, actual); } #[test] fn scan_end_command() { let expected = vec![End, Dot]; let actual = tokenize("end."); assert_eq!(expected, actual); } #[test] fn scan_unicode_ident() { // todo: add some unicode characters to the test let expected = vec![Lparen, Ident("abc1231".to_string()), Rparen]; let actual = tokenize("(abc1231)"); assert_eq!(expected, actual); } #[test] fn scan_keywords() { let expected = vec![Database, Base, Type, End]; let actual = tokenize("database base type end"); assert_eq!(expected, actual); }
{ let expected = vec![Lparen, Rparen, Dot]; let actual = tokenize("()."); assert_eq!(expected, actual); }
identifier_body
input.rs
use std::collections::HashMap; use std::time::Instant; use glium::glutin::{ dpi::PhysicalPosition, event::{ElementState, Event, KeyboardInput, MouseButton, VirtualKeyCode, WindowEvent}, }; pub struct InputState { /// Position of the mouse pub mouse_pos: (f64, f64), /// Previous position of the mouse prev_mouse_pos: (f64, f64), /// Currently pressed mouse buttons with the time of the press pub mouse_presses: HashMap<MouseButton, Instant>, /// Currently pressed keys with the time of the press pub key_presses: HashMap<VirtualKeyCode, Instant>, /// Time of the last reset pub last_reset: Instant, } impl InputState { /// Get a new empty input state pub fn new() -> InputState { InputState { mouse_pos: (0.0, 0.0), prev_mouse_pos: (0.0, 0.0), mouse_presses: HashMap::new(), key_presses: HashMap::new(), last_reset: Instant::now(), } } pub fn
(&self) -> (f64, f64) { let (px, py) = self.prev_mouse_pos; let (x, y) = self.mouse_pos; (x - px, y - py) } /// Update the state with an event pub fn update(&mut self, event: &Event<()>) { if let Event::WindowEvent { ref event,.. } = *event { match *event { WindowEvent::CursorMoved { position: PhysicalPosition { x, y }, .. } => { self.mouse_pos = (x, y); } WindowEvent::MouseInput { state: ElementState::Pressed, button, .. } => { self.mouse_presses .entry(button) .or_insert_with(Instant::now); } WindowEvent::MouseInput { state: ElementState::Released, button, .. } => { self.mouse_presses.remove(&button); } WindowEvent::KeyboardInput { input,.. } => match input { KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(key), .. } => { self.key_presses.entry(key).or_insert_with(Instant::now); } KeyboardInput { state: ElementState::Released, virtual_keycode: Some(key), .. } => { self.key_presses.remove(&key); } _ => (), }, WindowEvent::Focused(false) => { self.mouse_presses.clear(); self.key_presses.clear(); } _ => (), } } } /// Reset the delta values after a loop pub fn reset_deltas(&mut self) { self.prev_mouse_pos = self.mouse_pos; self.last_reset = Instant::now(); } }
d_mouse
identifier_name
input.rs
use std::collections::HashMap; use std::time::Instant; use glium::glutin::{ dpi::PhysicalPosition, event::{ElementState, Event, KeyboardInput, MouseButton, VirtualKeyCode, WindowEvent}, }; pub struct InputState { /// Position of the mouse pub mouse_pos: (f64, f64), /// Previous position of the mouse prev_mouse_pos: (f64, f64), /// Currently pressed mouse buttons with the time of the press pub mouse_presses: HashMap<MouseButton, Instant>, /// Currently pressed keys with the time of the press pub key_presses: HashMap<VirtualKeyCode, Instant>, /// Time of the last reset pub last_reset: Instant, } impl InputState { /// Get a new empty input state pub fn new() -> InputState { InputState { mouse_pos: (0.0, 0.0), prev_mouse_pos: (0.0, 0.0), mouse_presses: HashMap::new(), key_presses: HashMap::new(), last_reset: Instant::now(), } } pub fn d_mouse(&self) -> (f64, f64) { let (px, py) = self.prev_mouse_pos; let (x, y) = self.mouse_pos; (x - px, y - py) }
WindowEvent::CursorMoved { position: PhysicalPosition { x, y }, .. } => { self.mouse_pos = (x, y); } WindowEvent::MouseInput { state: ElementState::Pressed, button, .. } => { self.mouse_presses .entry(button) .or_insert_with(Instant::now); } WindowEvent::MouseInput { state: ElementState::Released, button, .. } => { self.mouse_presses.remove(&button); } WindowEvent::KeyboardInput { input,.. } => match input { KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(key), .. } => { self.key_presses.entry(key).or_insert_with(Instant::now); } KeyboardInput { state: ElementState::Released, virtual_keycode: Some(key), .. } => { self.key_presses.remove(&key); } _ => (), }, WindowEvent::Focused(false) => { self.mouse_presses.clear(); self.key_presses.clear(); } _ => (), } } } /// Reset the delta values after a loop pub fn reset_deltas(&mut self) { self.prev_mouse_pos = self.mouse_pos; self.last_reset = Instant::now(); } }
/// Update the state with an event pub fn update(&mut self, event: &Event<()>) { if let Event::WindowEvent { ref event, .. } = *event { match *event {
random_line_split
usbscan.rs
// Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms use shared::ntdef::{ULONG, USHORT}; use um::winioctl::{FILE_ANY_ACCESS, METHOD_BUFFERED}; //98
usLanguageId: USHORT, }} pub type PDEVICE_DESCRIPTOR = *mut DEVICE_DESCRIPTOR; //132 pub const FILE_DEVICE_USB_SCAN: ULONG = 0x8000; pub const IOCTL_INDEX: ULONG = 0x0800; //143 pub const IOCTL_GET_USB_DESCRIPTOR: ULONG = CTL_CODE!(FILE_DEVICE_USB_SCAN, IOCTL_INDEX + 8, METHOD_BUFFERED, FILE_ANY_ACCESS);
STRUCT!{struct DEVICE_DESCRIPTOR { usVendorId: USHORT, usProductId: USHORT, usBcdDevice: USHORT,
random_line_split
mod.rs
use malachite_base::num::logic::traits::{BitConvertible, BitIterable, SignificantBits}; use malachite_nz::natural::Natural; use malachite_nz::platform::Limb; use std::iter::repeat; pub fn natural_op_bits(bit_fn: &dyn Fn(bool, bool) -> bool, x: &Natural, y: &Natural) -> Natural { let bit_zip: Box<dyn Iterator<Item = (bool, bool)>> = if x.significant_bits() >= y.significant_bits() { Box::new(x.bits().zip(y.bits().chain(repeat(false)))) } else { Box::new(x.bits().chain(repeat(false)).zip(y.bits())) }; Natural::from_bits_asc(bit_zip.map(|(b, c)| bit_fn(b, c))) } pub fn natural_op_limbs(limb_fn: &dyn Fn(Limb, Limb) -> Limb, x: &Natural, y: &Natural) -> Natural { let limb_zip: Box<dyn Iterator<Item = (Limb, Limb)>> = if x.limb_count() >= y.limb_count()
else { Box::new(x.limbs().chain(repeat(0)).zip(y.limbs())) }; let mut and_limbs = Vec::new(); for (x, y) in limb_zip { and_limbs.push(limb_fn(x, y)); } Natural::from_owned_limbs_asc(and_limbs) } pub mod and; pub mod count_ones; pub mod from_bits; pub mod get_bit; pub mod hamming_distance; pub mod index_of_next_false_bit; pub mod index_of_next_true_bit; pub mod or; pub mod set_bit; pub mod to_bits; pub mod trailing_zeros; pub mod xor;
{ Box::new(x.limbs().zip(y.limbs().chain(repeat(0)))) }
conditional_block
mod.rs
use malachite_base::num::logic::traits::{BitConvertible, BitIterable, SignificantBits}; use malachite_nz::natural::Natural; use malachite_nz::platform::Limb; use std::iter::repeat; pub fn natural_op_bits(bit_fn: &dyn Fn(bool, bool) -> bool, x: &Natural, y: &Natural) -> Natural { let bit_zip: Box<dyn Iterator<Item = (bool, bool)>> = if x.significant_bits() >= y.significant_bits() { Box::new(x.bits().zip(y.bits().chain(repeat(false)))) } else { Box::new(x.bits().chain(repeat(false)).zip(y.bits())) }; Natural::from_bits_asc(bit_zip.map(|(b, c)| bit_fn(b, c))) } pub fn natural_op_limbs(limb_fn: &dyn Fn(Limb, Limb) -> Limb, x: &Natural, y: &Natural) -> Natural
pub mod and; pub mod count_ones; pub mod from_bits; pub mod get_bit; pub mod hamming_distance; pub mod index_of_next_false_bit; pub mod index_of_next_true_bit; pub mod or; pub mod set_bit; pub mod to_bits; pub mod trailing_zeros; pub mod xor;
{ let limb_zip: Box<dyn Iterator<Item = (Limb, Limb)>> = if x.limb_count() >= y.limb_count() { Box::new(x.limbs().zip(y.limbs().chain(repeat(0)))) } else { Box::new(x.limbs().chain(repeat(0)).zip(y.limbs())) }; let mut and_limbs = Vec::new(); for (x, y) in limb_zip { and_limbs.push(limb_fn(x, y)); } Natural::from_owned_limbs_asc(and_limbs) }
identifier_body
mod.rs
use malachite_base::num::logic::traits::{BitConvertible, BitIterable, SignificantBits}; use malachite_nz::natural::Natural; use malachite_nz::platform::Limb; use std::iter::repeat; pub fn natural_op_bits(bit_fn: &dyn Fn(bool, bool) -> bool, x: &Natural, y: &Natural) -> Natural { let bit_zip: Box<dyn Iterator<Item = (bool, bool)>> = if x.significant_bits() >= y.significant_bits() { Box::new(x.bits().zip(y.bits().chain(repeat(false)))) } else { Box::new(x.bits().chain(repeat(false)).zip(y.bits())) }; Natural::from_bits_asc(bit_zip.map(|(b, c)| bit_fn(b, c))) } pub fn
(limb_fn: &dyn Fn(Limb, Limb) -> Limb, x: &Natural, y: &Natural) -> Natural { let limb_zip: Box<dyn Iterator<Item = (Limb, Limb)>> = if x.limb_count() >= y.limb_count() { Box::new(x.limbs().zip(y.limbs().chain(repeat(0)))) } else { Box::new(x.limbs().chain(repeat(0)).zip(y.limbs())) }; let mut and_limbs = Vec::new(); for (x, y) in limb_zip { and_limbs.push(limb_fn(x, y)); } Natural::from_owned_limbs_asc(and_limbs) } pub mod and; pub mod count_ones; pub mod from_bits; pub mod get_bit; pub mod hamming_distance; pub mod index_of_next_false_bit; pub mod index_of_next_true_bit; pub mod or; pub mod set_bit; pub mod to_bits; pub mod trailing_zeros; pub mod xor;
natural_op_limbs
identifier_name
mod.rs
use malachite_base::num::logic::traits::{BitConvertible, BitIterable, SignificantBits}; use malachite_nz::natural::Natural; use malachite_nz::platform::Limb; use std::iter::repeat; pub fn natural_op_bits(bit_fn: &dyn Fn(bool, bool) -> bool, x: &Natural, y: &Natural) -> Natural { let bit_zip: Box<dyn Iterator<Item = (bool, bool)>> = if x.significant_bits() >= y.significant_bits() { Box::new(x.bits().zip(y.bits().chain(repeat(false)))) } else { Box::new(x.bits().chain(repeat(false)).zip(y.bits())) }; Natural::from_bits_asc(bit_zip.map(|(b, c)| bit_fn(b, c))) } pub fn natural_op_limbs(limb_fn: &dyn Fn(Limb, Limb) -> Limb, x: &Natural, y: &Natural) -> Natural { let limb_zip: Box<dyn Iterator<Item = (Limb, Limb)>> = if x.limb_count() >= y.limb_count() { Box::new(x.limbs().zip(y.limbs().chain(repeat(0)))) } else { Box::new(x.limbs().chain(repeat(0)).zip(y.limbs())) }; let mut and_limbs = Vec::new();
and_limbs.push(limb_fn(x, y)); } Natural::from_owned_limbs_asc(and_limbs) } pub mod and; pub mod count_ones; pub mod from_bits; pub mod get_bit; pub mod hamming_distance; pub mod index_of_next_false_bit; pub mod index_of_next_true_bit; pub mod or; pub mod set_bit; pub mod to_bits; pub mod trailing_zeros; pub mod xor;
for (x, y) in limb_zip {
random_line_split
directional.rs
use std::f32; use color::Color; use intersection::Intersection; use material::Material; use math::{Vector3, EPSILON}; use ray::Ray; use super::Light; pub struct Directional { pub direction: Vector3, inverse_direction: Vector3, pub color: Color, intensity: f32, diffuse: bool, specular: bool, } impl Directional { pub fn new( direction: Vector3, color: Color, intensity: f32, diffuse: bool, specular: bool, ) -> Self { let normalized_direction = direction.normalize(); Self { direction: normalized_direction, inverse_direction: -normalized_direction, color, intensity, diffuse, specular, } } pub fn intensity(&self, _distance_to_light: f32) -> f32 { self.intensity } } impl Light for Directional { fn create_shadow_ray( &self, intersection: &Intersection, medium_refraction: Option<f32>, ) -> Ray { let direction = self.inverse_direction; Ray::new( (intersection.point + direction * 1e-3).as_point(), direction, medium_refraction, ) } fn distance_to_light(&self, _intersection: &Intersection) -> f32 { f32::INFINITY } fn
( &self, intersection: &Intersection, material: &Material, distance_to_light: f32, ) -> Option<Color> { if!self.diffuse { return None; } let dot = self.inverse_direction.dot(&intersection.normal); if dot > 0.0 { Some( (self.color * material.diffuse_color(intersection.texture_coord)) * dot * self.intensity(distance_to_light), ) } else { None } } fn specular_color( &self, intersection: &Intersection, material: &Material, ray: &Ray, distance_to_light: f32, ) -> Option<Color> { if!self.specular { return None; } let dot = ray .direction .dot(&self.inverse_direction.reflect(&intersection.normal)); if dot > 0.0 { let spec = dot.powf(material.specular_exponent); Some( (self.color * material.specular_color(intersection.texture_coord)) * spec * self.intensity(distance_to_light), ) } else { None } } }
diffuse_color
identifier_name
directional.rs
use std::f32; use color::Color; use intersection::Intersection; use material::Material; use math::{Vector3, EPSILON}; use ray::Ray; use super::Light; pub struct Directional { pub direction: Vector3, inverse_direction: Vector3, pub color: Color, intensity: f32, diffuse: bool, specular: bool, } impl Directional { pub fn new( direction: Vector3, color: Color, intensity: f32, diffuse: bool, specular: bool, ) -> Self { let normalized_direction = direction.normalize(); Self { direction: normalized_direction, inverse_direction: -normalized_direction, color, intensity, diffuse, specular, } } pub fn intensity(&self, _distance_to_light: f32) -> f32 { self.intensity } } impl Light for Directional { fn create_shadow_ray( &self, intersection: &Intersection, medium_refraction: Option<f32>, ) -> Ray { let direction = self.inverse_direction; Ray::new( (intersection.point + direction * 1e-3).as_point(), direction, medium_refraction, ) } fn distance_to_light(&self, _intersection: &Intersection) -> f32 { f32::INFINITY } fn diffuse_color( &self, intersection: &Intersection, material: &Material, distance_to_light: f32, ) -> Option<Color> { if!self.diffuse
let dot = self.inverse_direction.dot(&intersection.normal); if dot > 0.0 { Some( (self.color * material.diffuse_color(intersection.texture_coord)) * dot * self.intensity(distance_to_light), ) } else { None } } fn specular_color( &self, intersection: &Intersection, material: &Material, ray: &Ray, distance_to_light: f32, ) -> Option<Color> { if!self.specular { return None; } let dot = ray .direction .dot(&self.inverse_direction.reflect(&intersection.normal)); if dot > 0.0 { let spec = dot.powf(material.specular_exponent); Some( (self.color * material.specular_color(intersection.texture_coord)) * spec * self.intensity(distance_to_light), ) } else { None } } }
{ return None; }
conditional_block
directional.rs
use std::f32; use color::Color; use intersection::Intersection; use material::Material; use math::{Vector3, EPSILON}; use ray::Ray; use super::Light; pub struct Directional { pub direction: Vector3, inverse_direction: Vector3, pub color: Color, intensity: f32, diffuse: bool, specular: bool, } impl Directional { pub fn new( direction: Vector3, color: Color, intensity: f32, diffuse: bool, specular: bool, ) -> Self { let normalized_direction = direction.normalize(); Self { direction: normalized_direction, inverse_direction: -normalized_direction, color, intensity, diffuse, specular, } } pub fn intensity(&self, _distance_to_light: f32) -> f32 { self.intensity } } impl Light for Directional { fn create_shadow_ray( &self, intersection: &Intersection, medium_refraction: Option<f32>, ) -> Ray { let direction = self.inverse_direction; Ray::new( (intersection.point + direction * 1e-3).as_point(), direction, medium_refraction, ) } fn distance_to_light(&self, _intersection: &Intersection) -> f32 { f32::INFINITY } fn diffuse_color( &self, intersection: &Intersection, material: &Material, distance_to_light: f32, ) -> Option<Color> { if!self.diffuse { return None; } let dot = self.inverse_direction.dot(&intersection.normal); if dot > 0.0 { Some( (self.color * material.diffuse_color(intersection.texture_coord)) * dot * self.intensity(distance_to_light), ) } else { None } } fn specular_color( &self, intersection: &Intersection, material: &Material, ray: &Ray, distance_to_light: f32, ) -> Option<Color>
}
{ if !self.specular { return None; } let dot = ray .direction .dot(&self.inverse_direction.reflect(&intersection.normal)); if dot > 0.0 { let spec = dot.powf(material.specular_exponent); Some( (self.color * material.specular_color(intersection.texture_coord)) * spec * self.intensity(distance_to_light), ) } else { None } }
identifier_body
directional.rs
use std::f32; use color::Color; use intersection::Intersection; use material::Material; use math::{Vector3, EPSILON}; use ray::Ray; use super::Light; pub struct Directional { pub direction: Vector3, inverse_direction: Vector3, pub color: Color,
} impl Directional { pub fn new( direction: Vector3, color: Color, intensity: f32, diffuse: bool, specular: bool, ) -> Self { let normalized_direction = direction.normalize(); Self { direction: normalized_direction, inverse_direction: -normalized_direction, color, intensity, diffuse, specular, } } pub fn intensity(&self, _distance_to_light: f32) -> f32 { self.intensity } } impl Light for Directional { fn create_shadow_ray( &self, intersection: &Intersection, medium_refraction: Option<f32>, ) -> Ray { let direction = self.inverse_direction; Ray::new( (intersection.point + direction * 1e-3).as_point(), direction, medium_refraction, ) } fn distance_to_light(&self, _intersection: &Intersection) -> f32 { f32::INFINITY } fn diffuse_color( &self, intersection: &Intersection, material: &Material, distance_to_light: f32, ) -> Option<Color> { if!self.diffuse { return None; } let dot = self.inverse_direction.dot(&intersection.normal); if dot > 0.0 { Some( (self.color * material.diffuse_color(intersection.texture_coord)) * dot * self.intensity(distance_to_light), ) } else { None } } fn specular_color( &self, intersection: &Intersection, material: &Material, ray: &Ray, distance_to_light: f32, ) -> Option<Color> { if!self.specular { return None; } let dot = ray .direction .dot(&self.inverse_direction.reflect(&intersection.normal)); if dot > 0.0 { let spec = dot.powf(material.specular_exponent); Some( (self.color * material.specular_color(intersection.texture_coord)) * spec * self.intensity(distance_to_light), ) } else { None } } }
intensity: f32, diffuse: bool, specular: bool,
random_line_split
mod.rs
pub mod interval_tree; pub mod plain_tree; pub mod interval; use base::{Node, TreeDeref, TreeRepr}; pub trait AppliedTree<N: Node>: TreeDeref<N> + Sized { /// Constructs a new AppliedTree fn new(items: Vec<(N::K, N::V)>) -> Self { Self::with_repr(TreeRepr::new(items)) } /// Constructs a new IvTree /// Note: the argument must be sorted! fn with_sorted(sorted: Vec<(N::K, N::V)>) -> Self { Self::with_repr(TreeRepr::with_sorted(sorted)) } fn
(nodes: Vec<Option<N>>) -> Self { Self::with_repr(TreeRepr::with_nodes(nodes)) } fn with_repr(repr: TreeRepr<N>) -> Self; unsafe fn with_shape(items: Vec<Option<(N::K, N::V)>>) -> Self; }
with_nodes
identifier_name
mod.rs
pub mod interval_tree; pub mod plain_tree; pub mod interval; use base::{Node, TreeDeref, TreeRepr}; pub trait AppliedTree<N: Node>: TreeDeref<N> + Sized { /// Constructs a new AppliedTree fn new(items: Vec<(N::K, N::V)>) -> Self { Self::with_repr(TreeRepr::new(items)) } /// Constructs a new IvTree /// Note: the argument must be sorted! fn with_sorted(sorted: Vec<(N::K, N::V)>) -> Self { Self::with_repr(TreeRepr::with_sorted(sorted)) } fn with_nodes(nodes: Vec<Option<N>>) -> Self { Self::with_repr(TreeRepr::with_nodes(nodes)) }
fn with_repr(repr: TreeRepr<N>) -> Self; unsafe fn with_shape(items: Vec<Option<(N::K, N::V)>>) -> Self; }
random_line_split
mod.rs
pub mod interval_tree; pub mod plain_tree; pub mod interval; use base::{Node, TreeDeref, TreeRepr}; pub trait AppliedTree<N: Node>: TreeDeref<N> + Sized { /// Constructs a new AppliedTree fn new(items: Vec<(N::K, N::V)>) -> Self { Self::with_repr(TreeRepr::new(items)) } /// Constructs a new IvTree /// Note: the argument must be sorted! fn with_sorted(sorted: Vec<(N::K, N::V)>) -> Self
fn with_nodes(nodes: Vec<Option<N>>) -> Self { Self::with_repr(TreeRepr::with_nodes(nodes)) } fn with_repr(repr: TreeRepr<N>) -> Self; unsafe fn with_shape(items: Vec<Option<(N::K, N::V)>>) -> Self; }
{ Self::with_repr(TreeRepr::with_sorted(sorted)) }
identifier_body
mod.rs
We then try to compile a program for arm-linux-androideabi // 3. The compiler has a host of linux and a target of android, so it loads // macros from the *linux* libstd. // 4. The macro generates a #[thread_local] field, but the android libstd does // not use #[thread_local] // 5. Compile error about structs with wrong fields. // // To get around this, we're forced to inject the #[cfg] logic into the macro // itself. Woohoo. #[macro_export] #[doc(hidden)] #[allow_internal_unstable] macro_rules! __thread_local_inner { (static $name:ident: $t:ty = $init:expr) => ( #[cfg_attr(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")), thread_local)] static $name: ::std::thread_local::__impl::KeyInner<$t> = __thread_local_inner!($init, $t); ); (pub static $name:ident: $t:ty = $init:expr) => ( #[cfg_attr(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")), thread_local)] pub static $name: ::std::thread_local::__impl::KeyInner<$t> = __thread_local_inner!($init, $t); ); ($init:expr, $t:ty) => ({ #[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))] const _INIT: ::std::thread_local::__impl::KeyInner<$t> = { ::std::thread_local::__impl::KeyInner { inner: ::std::cell::UnsafeCell { value: $init }, dtor_registered: ::std::cell::UnsafeCell { value: false }, dtor_running: ::std::cell::UnsafeCell { value: false }, } }; #[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))] const _INIT: ::std::thread_local::__impl::KeyInner<$t> = { unsafe extern fn __destroy(ptr: *mut u8) { ::std::thread_local::__impl::destroy_value::<$t>(ptr); } ::std::thread_local::__impl::KeyInner { inner: ::std::cell::UnsafeCell { value: $init }, os: ::std::thread_local::__impl::OsStaticKey { inner: ::std::thread_local::__impl::OS_INIT_INNER, dtor: ::std::option::Option::Some(__destroy as unsafe extern fn(*mut u8)), }, } }; _INIT }); } /// Indicator of the state of a thread local storage key. #[unstable(feature = "std_misc", reason = "state querying was recently added")] #[derive(Eq, PartialEq, Copy)] pub enum State { /// All keys are in this state whenever a thread starts. Keys will /// transition to the `Valid` state once the first call to `with` happens /// and the initialization expression succeeds. /// /// Keys in the `Uninitialized` state will yield a reference to the closure /// passed to `with` so long as the initialization routine does not panic. Uninitialized, /// Once a key has been accessed successfully, it will enter the `Valid` /// state. Keys in the `Valid` state will remain so until the thread exits, /// at which point the destructor will be run and the key will enter the /// `Destroyed` state. /// /// Keys in the `Valid` state will be guaranteed to yield a reference to the /// closure passed to `with`. Valid, /// When a thread exits, the destructors for keys will be run (if /// necessary). While a destructor is running, and possibly after a /// destructor has run, a key is in the `Destroyed` state. /// /// Keys in the `Destroyed` states will trigger a panic when accessed via /// `with`. Destroyed, } impl<T:'static> Key<T> { /// Acquire a reference to the value in this TLS key. /// /// This will lazily initialize the value if this thread has not referenced /// this key yet. /// /// # Panics /// /// This function will `panic!()` if the key currently has its /// destructor running, and it **may** panic if the destructor has /// previously been run for this thread. #[stable(feature = "rust1", since = "1.0.0")] pub fn with<F, R>(&'static self, f: F) -> R where F: FnOnce(&T) -> R { let slot = (self.inner)(); unsafe { let slot = slot.get().expect("cannot access a TLS value during or \ after it is destroyed"); f(match *slot.get() { Some(ref inner) => inner, None => self.init(slot), }) } } unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T { // Execute the initialization up front, *then* move it into our slot, // just in case initialization fails. let value = (self.init)(); let ptr = slot.get(); *ptr = Some(value); (*ptr).as_ref().unwrap() } /// Query the current state of this key. /// /// A key is initially in the `Uninitialized` state whenever a thread /// starts. It will remain in this state up until the first call to `with` /// within a thread has run the initialization expression successfully. /// /// Once the initialization expression succeeds, the key transitions to the /// `Valid` state which will guarantee that future calls to `with` will /// succeed within the thread. /// /// When a thread exits, each key will be destroyed in turn, and as keys are /// destroyed they will enter the `Destroyed` state just before the /// destructor starts to run. Keys may remain in the `Destroyed` state after /// destruction has completed. Keys without destructors (e.g. with types /// that are `Copy`), may never enter the `Destroyed` state. /// /// Keys in the `Uninitialized` can be accessed so long as the /// initialization does not panic. Keys in the `Valid` state are guaranteed /// to be able to be accessed. Keys in the `Destroyed` state will panic on /// any call to `with`. #[unstable(feature = "std_misc", reason = "state querying was recently added")] pub fn state(&'static self) -> State { unsafe { match (self.inner)().get() { Some(cell) => { match *cell.get() { Some(..) => State::Valid, None => State::Uninitialized, } } None => State::Destroyed, } } } /// Deprecated #[unstable(feature = "std_misc")] #[deprecated(since = "1.0.0", reason = "function renamed to state() and returns more info")] pub fn destroyed(&'static self) -> bool { self.state() == State::Destroyed } } #[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))] mod imp { use prelude::v1::*; use cell::UnsafeCell; use intrinsics; use ptr; #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub struct Key<T> { // Place the inner bits in an `UnsafeCell` to currently get around the // "only Sync statics" restriction. This allows any type to be placed in // the cell. // // Note that all access requires `T:'static` so it can't be a type with // any borrowed pointers still. #[unstable(feature = "thread_local_internals")] pub inner: UnsafeCell<T>, // Metadata to keep track of the state of the destructor. Remember that // these variables are thread-local, not global. #[unstable(feature = "thread_local_internals")] pub dtor_registered: UnsafeCell<bool>, // should be Cell #[unstable(feature = "thread_local_internals")] pub dtor_running: UnsafeCell<bool>, // should be Cell } unsafe impl<T> ::marker::Sync for Key<T> { } #[doc(hidden)] impl<T> Key<T> { pub unsafe fn get(&'static self) -> Option<&'static T> { if intrinsics::needs_drop::<T>() && *self.dtor_running.get() { return None } self.register_dtor(); Some(&*self.inner.get()) } unsafe fn register_dtor(&self) { if!intrinsics::needs_drop::<T>() || *self.dtor_registered.get() { return } register_dtor(self as *const _ as *mut u8, destroy_value::<T>); *self.dtor_registered.get() = true; } } // Since what appears to be glibc 2.18 this symbol has been shipped which // GCC and clang both use to invoke destructors in thread_local globals, so // let's do the same! // // Note, however, that we run on lots older linuxes, as well as cross // compiling from a newer linux to an older linux, so we also have a // fallback implementation to use as well. // // Due to rust-lang/rust#18804, make sure this is not generic! #[cfg(target_os = "linux")] unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { use boxed; use mem; use libc; use sys_common::thread_local as os; extern { static __dso_handle: *mut u8; #[linkage = "extern_weak"] static __cxa_thread_atexit_impl: *const (); } if!__cxa_thread_atexit_impl.is_null() { type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8), arg: *mut u8, dso_handle: *mut u8) -> libc::c_int; mem::transmute::<*const (), F>(__cxa_thread_atexit_impl) (dtor, t, __dso_handle); return } // The fallback implementation uses a vanilla OS-based TLS key to track // the list of destructors that need to be run for this thread. The key // then has its own destructor which runs all the other destructors. // // The destructor for DTORS is a little special in that it has a `while` // loop to continuously drain the list of registered destructors. It // *should* be the case that this loop always terminates because we // provide the guarantee that a TLS key cannot be set after it is // flagged for destruction. static DTORS: os::StaticKey = os::StaticKey { inner: os::INIT_INNER, dtor: Some(run_dtors as unsafe extern "C" fn(*mut u8)), }; type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; if DTORS.get().is_null() { let v: Box<List> = box Vec::new(); DTORS.set(boxed::into_raw(v) as *mut u8); } let list: &mut List = &mut *(DTORS.get() as *mut List); list.push((t, dtor)); unsafe extern fn run_dtors(mut ptr: *mut u8) { while!ptr.is_null() { let list: Box<List> = Box::from_raw(ptr as *mut List); for &(ptr, dtor) in &*list { dtor(ptr); } ptr = DTORS.get(); DTORS.set(ptr::null_mut()); } } } // OSX's analog of the above linux function is this _tlv_atexit function. // The disassembly of thread_local globals in C++ (at least produced by // clang) will have this show up in the output. #[cfg(target_os = "macos")] unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { extern { fn _tlv_atexit(dtor: unsafe extern fn(*mut u8), arg: *mut u8); } _tlv_atexit(dtor, t); } #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { let ptr = ptr as *mut Key<T>; // Right before we run the user destructor be sure to flag the // destructor as running for this thread so calls to `get` will return // `None`. *(*ptr).dtor_running.get() = true; ptr::read((*ptr).inner.get()); } } #[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))] mod imp { use prelude::v1::*; use alloc::boxed; use cell::UnsafeCell; use mem; use ptr; use sys_common::thread_local::StaticKey as OsStaticKey; #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub struct Key<T> { // Statically allocated initialization expression, using an `UnsafeCell` // for the same reasons as above. #[unstable(feature = "thread_local_internals")] pub inner: UnsafeCell<T>, // OS-TLS key that we'll use to key off. #[unstable(feature = "thread_local_internals")] pub os: OsStaticKey, } unsafe impl<T> ::marker::Sync for Key<T> { } struct Value<T:'static> { key: &'static Key<T>, value: T, } #[doc(hidden)] impl<T> Key<T> { pub unsafe fn get(&'static self) -> Option<&'static T> { self.ptr().map(|p| &*p) } unsafe fn ptr(&'static self) -> Option<*mut T> { let ptr = self.os.get() as *mut Value<T>; if!ptr.is_null() { if ptr as usize == 1 { return None } return Some(&mut (*ptr).value as *mut T); } // If the lookup returned null, we haven't initialized our own local // copy, so do that now. // // Also note that this transmute_copy should be ok because the value // `inner` is already validated to be a valid `static` value, so we // should be able to freely copy the bits. let ptr: Box<Value<T>> = box Value { key: self, value: mem::transmute_copy(&self.inner), }; let ptr: *mut Value<T> = boxed::into_raw(ptr); self.os.set(ptr as *mut u8); Some(&mut (*ptr).value as *mut T) } } #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub unsafe extern fn destroy_value<T:'static>(ptr: *mut u8) { // The OS TLS ensures that this key contains a NULL value when this // destructor starts to run. We set it back to a sentinel value of 1 to // ensure that any future calls to `get` for this thread will return // `None`. // // Note that to prevent an infinite loop we reset it back to null right // before we return from the destructor ourselves. let ptr: Box<Value<T>> = Box::from_raw(ptr as *mut Value<T>); let key = ptr.key; key.os.set(1 as *mut u8); drop(ptr); key.os.set(ptr::null_mut()); } } #[cfg(test)] mod tests { use prelude::v1::*; use sync::mpsc::{channel, Sender}; use cell::UnsafeCell; use super::State; use thread; struct Foo(Sender<()>); impl Drop for Foo { fn drop(&mut self) { let Foo(ref s) = *self; s.send(()).unwrap(); } } #[test] fn smoke_no_dtor() { thread_local!(static FOO: UnsafeCell<i32> = UnsafeCell { value: 1 }); FOO.with(|f| unsafe { assert_eq!(*f.get(), 1); *f.get() = 2; }); let (tx, rx) = channel(); let _t = thread::spawn(move|| { FOO.with(|f| unsafe { assert_eq!(*f.get(), 1); }); tx.send(()).unwrap(); }); rx.recv().unwrap(); FOO.with(|f| unsafe { assert_eq!(*f.get(), 2); }); } #[test] fn states() { struct Foo; impl Drop for Foo { fn drop(&mut self) { assert!(FOO.state() == State::Destroyed); } } fn foo() -> Foo { assert!(FOO.state() == State::Uninitialized); Foo } thread_local!(static FOO: Foo = foo()); thread::spawn(|| { assert!(FOO.state() == State::Uninitialized); FOO.with(|_| { assert!(FOO.state() == State::Valid); }); assert!(FOO.state() == State::Valid); }).join().ok().unwrap(); } #[test] fn smoke_dtor() { thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell { value: None }); let (tx, rx) = channel(); let _t = thread::spawn(move|| unsafe { let mut tx = Some(tx); FOO.with(|f| { *f.get() = Some(Foo(tx.take().unwrap())); }); }); rx.recv().unwrap(); } #[test] fn circular() { struct S1; struct S2; thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell { value: None }); thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell { value: None }); static mut HITS: u32 = 0; impl Drop for S1 { fn drop(&mut self) { unsafe { HITS += 1; if K2.state() == State::Destroyed { assert_eq!(HITS, 3); } else { if HITS == 1 { K2.with(|s| *s.get() = Some(S2)); } else { assert_eq!(HITS, 3); } } } } } impl Drop for S2 { fn drop(&mut self) { unsafe { HITS += 1; assert!(K1.state()!= State::Destroyed); assert_eq!(HITS, 2); K1.with(|s| *s.get() = Some(S1)); } } } thread::spawn(move|| { drop(S1); }).join().ok().unwrap(); } #[test] fn self_referential() { struct S1; thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell { value: None }); impl Drop for S1 { fn
drop
identifier_name
mod.rs
= "rust1", since = "1.0.0")] pub struct Key<T> { // The key itself may be tagged with #[thread_local], and this `Key` is // stored as a `static`, and it's not valid for a static to reference the // address of another thread_local static. For this reason we kinda wonkily // work around this by generating a shim function which will give us the // address of the inner TLS key at runtime. // // This is trivially devirtualizable by LLVM because we never store anything // to this field and rustc can declare the `static` as constant as well. #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub inner: fn() -> &'static __impl::KeyInner<UnsafeCell<Option<T>>>, // initialization routine to invoke to create a value #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub init: fn() -> T, } /// Declare a new thread local storage key of type `std::thread_local::Key`. #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] #[allow_internal_unstable] macro_rules! thread_local { (static $name:ident: $t:ty = $init:expr) => ( static $name: ::std::thread_local::Key<$t> = { use std::cell::UnsafeCell as __UnsafeCell; use std::thread_local::__impl::KeyInner as __KeyInner; use std::option::Option as __Option; use std::option::Option::None as __None; __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = { __UnsafeCell { value: __None } }); fn __init() -> $t { $init } fn __getit() -> &'static __KeyInner<__UnsafeCell<__Option<$t>>> { &__KEY } ::std::thread_local::Key { inner: __getit, init: __init } }; ); (pub static $name:ident: $t:ty = $init:expr) => ( pub static $name: ::std::thread_local::Key<$t> = { use std::cell::UnsafeCell as __UnsafeCell; use std::thread_local::__impl::KeyInner as __KeyInner; use std::option::Option as __Option; use std::option::Option::None as __None; __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = { __UnsafeCell { value: __None } }); fn __init() -> $t { $init } fn __getit() -> &'static __KeyInner<__UnsafeCell<__Option<$t>>> { &__KEY } ::std::thread_local::Key { inner: __getit, init: __init } }; ); } // Macro pain #4586: // // When cross compiling, rustc will load plugins and macros from the *host* // platform before search for macros from the target platform. This is primarily // done to detect, for example, plugins. Ideally the macro below would be // defined once per module below, but unfortunately this means we have the // following situation: // // 1. We compile libstd for x86_64-unknown-linux-gnu, this thread_local!() macro // will inject #[thread_local] statics. // 2. We then try to compile a program for arm-linux-androideabi // 3. The compiler has a host of linux and a target of android, so it loads // macros from the *linux* libstd. // 4. The macro generates a #[thread_local] field, but the android libstd does // not use #[thread_local] // 5. Compile error about structs with wrong fields. // // To get around this, we're forced to inject the #[cfg] logic into the macro // itself. Woohoo. #[macro_export] #[doc(hidden)] #[allow_internal_unstable] macro_rules! __thread_local_inner { (static $name:ident: $t:ty = $init:expr) => ( #[cfg_attr(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")), thread_local)] static $name: ::std::thread_local::__impl::KeyInner<$t> = __thread_local_inner!($init, $t);
#[cfg_attr(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")), thread_local)] pub static $name: ::std::thread_local::__impl::KeyInner<$t> = __thread_local_inner!($init, $t); ); ($init:expr, $t:ty) => ({ #[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))] const _INIT: ::std::thread_local::__impl::KeyInner<$t> = { ::std::thread_local::__impl::KeyInner { inner: ::std::cell::UnsafeCell { value: $init }, dtor_registered: ::std::cell::UnsafeCell { value: false }, dtor_running: ::std::cell::UnsafeCell { value: false }, } }; #[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))] const _INIT: ::std::thread_local::__impl::KeyInner<$t> = { unsafe extern fn __destroy(ptr: *mut u8) { ::std::thread_local::__impl::destroy_value::<$t>(ptr); } ::std::thread_local::__impl::KeyInner { inner: ::std::cell::UnsafeCell { value: $init }, os: ::std::thread_local::__impl::OsStaticKey { inner: ::std::thread_local::__impl::OS_INIT_INNER, dtor: ::std::option::Option::Some(__destroy as unsafe extern fn(*mut u8)), }, } }; _INIT }); } /// Indicator of the state of a thread local storage key. #[unstable(feature = "std_misc", reason = "state querying was recently added")] #[derive(Eq, PartialEq, Copy)] pub enum State { /// All keys are in this state whenever a thread starts. Keys will /// transition to the `Valid` state once the first call to `with` happens /// and the initialization expression succeeds. /// /// Keys in the `Uninitialized` state will yield a reference to the closure /// passed to `with` so long as the initialization routine does not panic. Uninitialized, /// Once a key has been accessed successfully, it will enter the `Valid` /// state. Keys in the `Valid` state will remain so until the thread exits, /// at which point the destructor will be run and the key will enter the /// `Destroyed` state. /// /// Keys in the `Valid` state will be guaranteed to yield a reference to the /// closure passed to `with`. Valid, /// When a thread exits, the destructors for keys will be run (if /// necessary). While a destructor is running, and possibly after a /// destructor has run, a key is in the `Destroyed` state. /// /// Keys in the `Destroyed` states will trigger a panic when accessed via /// `with`. Destroyed, } impl<T:'static> Key<T> { /// Acquire a reference to the value in this TLS key. /// /// This will lazily initialize the value if this thread has not referenced /// this key yet. /// /// # Panics /// /// This function will `panic!()` if the key currently has its /// destructor running, and it **may** panic if the destructor has /// previously been run for this thread. #[stable(feature = "rust1", since = "1.0.0")] pub fn with<F, R>(&'static self, f: F) -> R where F: FnOnce(&T) -> R { let slot = (self.inner)(); unsafe { let slot = slot.get().expect("cannot access a TLS value during or \ after it is destroyed"); f(match *slot.get() { Some(ref inner) => inner, None => self.init(slot), }) } } unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T { // Execute the initialization up front, *then* move it into our slot, // just in case initialization fails. let value = (self.init)(); let ptr = slot.get(); *ptr = Some(value); (*ptr).as_ref().unwrap() } /// Query the current state of this key. /// /// A key is initially in the `Uninitialized` state whenever a thread /// starts. It will remain in this state up until the first call to `with` /// within a thread has run the initialization expression successfully. /// /// Once the initialization expression succeeds, the key transitions to the /// `Valid` state which will guarantee that future calls to `with` will /// succeed within the thread. /// /// When a thread exits, each key will be destroyed in turn, and as keys are /// destroyed they will enter the `Destroyed` state just before the /// destructor starts to run. Keys may remain in the `Destroyed` state after /// destruction has completed. Keys without destructors (e.g. with types /// that are `Copy`), may never enter the `Destroyed` state. /// /// Keys in the `Uninitialized` can be accessed so long as the /// initialization does not panic. Keys in the `Valid` state are guaranteed /// to be able to be accessed. Keys in the `Destroyed` state will panic on /// any call to `with`. #[unstable(feature = "std_misc", reason = "state querying was recently added")] pub fn state(&'static self) -> State { unsafe { match (self.inner)().get() { Some(cell) => { match *cell.get() { Some(..) => State::Valid, None => State::Uninitialized, } } None => State::Destroyed, } } } /// Deprecated #[unstable(feature = "std_misc")] #[deprecated(since = "1.0.0", reason = "function renamed to state() and returns more info")] pub fn destroyed(&'static self) -> bool { self.state() == State::Destroyed } } #[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))] mod imp { use prelude::v1::*; use cell::UnsafeCell; use intrinsics; use ptr; #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub struct Key<T> { // Place the inner bits in an `UnsafeCell` to currently get around the // "only Sync statics" restriction. This allows any type to be placed in // the cell. // // Note that all access requires `T:'static` so it can't be a type with // any borrowed pointers still. #[unstable(feature = "thread_local_internals")] pub inner: UnsafeCell<T>, // Metadata to keep track of the state of the destructor. Remember that // these variables are thread-local, not global. #[unstable(feature = "thread_local_internals")] pub dtor_registered: UnsafeCell<bool>, // should be Cell #[unstable(feature = "thread_local_internals")] pub dtor_running: UnsafeCell<bool>, // should be Cell } unsafe impl<T> ::marker::Sync for Key<T> { } #[doc(hidden)] impl<T> Key<T> { pub unsafe fn get(&'static self) -> Option<&'static T> { if intrinsics::needs_drop::<T>() && *self.dtor_running.get() { return None } self.register_dtor(); Some(&*self.inner.get()) } unsafe fn register_dtor(&self) { if!intrinsics::needs_drop::<T>() || *self.dtor_registered.get() { return } register_dtor(self as *const _ as *mut u8, destroy_value::<T>); *self.dtor_registered.get() = true; } } // Since what appears to be glibc 2.18 this symbol has been shipped which // GCC and clang both use to invoke destructors in thread_local globals, so // let's do the same! // // Note, however, that we run on lots older linuxes, as well as cross // compiling from a newer linux to an older linux, so we also have a // fallback implementation to use as well. // // Due to rust-lang/rust#18804, make sure this is not generic! #[cfg(target_os = "linux")] unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { use boxed; use mem; use libc; use sys_common::thread_local as os; extern { static __dso_handle: *mut u8; #[linkage = "extern_weak"] static __cxa_thread_atexit_impl: *const (); } if!__cxa_thread_atexit_impl.is_null() { type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8), arg: *mut u8, dso_handle: *mut u8) -> libc::c_int; mem::transmute::<*const (), F>(__cxa_thread_atexit_impl) (dtor, t, __dso_handle); return } // The fallback implementation uses a vanilla OS-based TLS key to track // the list of destructors that need to be run for this thread. The key // then has its own destructor which runs all the other destructors. // // The destructor for DTORS is a little special in that it has a `while` // loop to continuously drain the list of registered destructors. It // *should* be the case that this loop always terminates because we // provide the guarantee that a TLS key cannot be set after it is // flagged for destruction. static DTORS: os::StaticKey = os::StaticKey { inner: os::INIT_INNER, dtor: Some(run_dtors as unsafe extern "C" fn(*mut u8)), }; type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; if DTORS.get().is_null() { let v: Box<List> = box Vec::new(); DTORS.set(boxed::into_raw(v) as *mut u8); } let list: &mut List = &mut *(DTORS.get() as *mut List); list.push((t, dtor)); unsafe extern fn run_dtors(mut ptr: *mut u8) { while!ptr.is_null() { let list: Box<List> = Box::from_raw(ptr as *mut List); for &(ptr, dtor) in &*list { dtor(ptr); } ptr = DTORS.get(); DTORS.set(ptr::null_mut()); } } } // OSX's analog of the above linux function is this _tlv_atexit function. // The disassembly of thread_local globals in C++ (at least produced by // clang) will have this show up in the output. #[cfg(target_os = "macos")] unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { extern { fn _tlv_atexit(dtor: unsafe extern fn(*mut u8), arg: *mut u8); } _tlv_atexit(dtor, t); } #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { let ptr = ptr as *mut Key<T>; // Right before we run the user destructor be sure to flag the // destructor as running for this thread so calls to `get` will return // `None`. *(*ptr).dtor_running.get() = true; ptr::read((*ptr).inner.get()); } } #[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))] mod imp { use prelude::v1::*; use alloc::boxed; use cell::UnsafeCell; use mem; use ptr; use sys_common::thread_local::StaticKey as OsStaticKey; #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub struct Key<T> { // Statically allocated initialization expression, using an `UnsafeCell` // for the same reasons as above. #[unstable(feature = "thread_local_internals")] pub inner: UnsafeCell<T>, // OS-TLS key that we'll use to key off. #[unstable(feature = "thread_local_internals")] pub os: OsStaticKey, } unsafe impl<T> ::marker::Sync for Key<T> { } struct Value<T:'static> { key: &'static Key<T>, value: T, } #[doc(hidden)] impl<T> Key<T> { pub unsafe fn get(&'static self) -> Option<&'static T> { self.ptr().map(|p| &*p) } unsafe fn ptr(&'static self) -> Option<*mut T> { let ptr = self.os.get() as *mut Value<T>; if!ptr.is_null() { if ptr as usize == 1 { return None } return Some(&mut (*ptr).value as *mut T); } // If the lookup returned null, we haven't initialized our own local // copy, so do that now. // // Also note that this transmute_copy should be ok because the value // `inner` is already validated to be a valid `static` value, so we // should be able to freely copy the bits. let ptr: Box<Value<T>> = box Value { key: self, value: mem::transmute_copy(&self.inner), }; let ptr: *mut Value<T> = boxed::into_raw(ptr); self.os.set(ptr as *mut u8); Some(&mut (*ptr).value as *mut T) } } #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub unsafe extern fn destroy_value<T:'static>(ptr: *mut u8) { // The OS TLS ensures that this key contains a NULL value when this // destructor starts to run. We set it back to a sentinel value of 1 to // ensure that any future calls to `get` for this thread will return // `None`. // // Note that to prevent an infinite loop we reset it back to null right // before we return from the destructor ourselves. let ptr: Box<Value<T>> = Box::from_raw(ptr as *mut Value<T>); let key = ptr.key; key.os.set(1 as *mut u8); drop(ptr); key.os.set(ptr::null_mut()); } } #[cfg(test)] mod tests { use prelude::v1::*; use sync::mpsc::{channel, Sender}; use cell::UnsafeCell; use super::State; use thread; struct Foo(Sender<()>); impl Drop for Foo { fn drop(&mut self) { let Foo(ref s) = *self; s.send(()).unwrap(); } } #[test] fn smoke_no_dtor() { thread_local!(static FOO: UnsafeCell<i32> = UnsafeCell { value: 1 }); FOO.with(|f| unsafe { assert_eq!(*f.get(), 1); *f.get() = 2; }); let (tx, rx) = channel(); let _t = thread::spawn(move|| { FOO.with(|f| unsafe { assert_eq!(*f.get(), 1); }); tx.send(()).unwrap(); }); rx.recv().unwrap(); FOO.with(|f| unsafe { assert_eq!(*f.get(), 2); }); } #[test] fn states() { struct Foo; impl Drop for Foo { fn drop(&mut self) { assert!(FOO.state() == State::Destroyed); } } fn foo() -> Foo { assert!(FOO.state() == State::Uninitialized); Foo } thread_local!(static FOO: Foo = foo()); thread::spawn(|| { assert!(FOO.state() == State::Uninitialized); FOO.with(|_| { assert!(FOO.state() == State::Valid); }); assert!(FOO.state() == State::Valid); }).join().ok().unwrap();
); (pub static $name:ident: $t:ty = $init:expr) => (
random_line_split
mod.rs
"rust1", since = "1.0.0")] pub struct Key<T> { // The key itself may be tagged with #[thread_local], and this `Key` is // stored as a `static`, and it's not valid for a static to reference the // address of another thread_local static. For this reason we kinda wonkily // work around this by generating a shim function which will give us the // address of the inner TLS key at runtime. // // This is trivially devirtualizable by LLVM because we never store anything // to this field and rustc can declare the `static` as constant as well. #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub inner: fn() -> &'static __impl::KeyInner<UnsafeCell<Option<T>>>, // initialization routine to invoke to create a value #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub init: fn() -> T, } /// Declare a new thread local storage key of type `std::thread_local::Key`. #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] #[allow_internal_unstable] macro_rules! thread_local { (static $name:ident: $t:ty = $init:expr) => ( static $name: ::std::thread_local::Key<$t> = { use std::cell::UnsafeCell as __UnsafeCell; use std::thread_local::__impl::KeyInner as __KeyInner; use std::option::Option as __Option; use std::option::Option::None as __None; __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = { __UnsafeCell { value: __None } }); fn __init() -> $t { $init } fn __getit() -> &'static __KeyInner<__UnsafeCell<__Option<$t>>> { &__KEY } ::std::thread_local::Key { inner: __getit, init: __init } }; ); (pub static $name:ident: $t:ty = $init:expr) => ( pub static $name: ::std::thread_local::Key<$t> = { use std::cell::UnsafeCell as __UnsafeCell; use std::thread_local::__impl::KeyInner as __KeyInner; use std::option::Option as __Option; use std::option::Option::None as __None; __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = { __UnsafeCell { value: __None } }); fn __init() -> $t { $init } fn __getit() -> &'static __KeyInner<__UnsafeCell<__Option<$t>>> { &__KEY } ::std::thread_local::Key { inner: __getit, init: __init } }; ); } // Macro pain #4586: // // When cross compiling, rustc will load plugins and macros from the *host* // platform before search for macros from the target platform. This is primarily // done to detect, for example, plugins. Ideally the macro below would be // defined once per module below, but unfortunately this means we have the // following situation: // // 1. We compile libstd for x86_64-unknown-linux-gnu, this thread_local!() macro // will inject #[thread_local] statics. // 2. We then try to compile a program for arm-linux-androideabi // 3. The compiler has a host of linux and a target of android, so it loads // macros from the *linux* libstd. // 4. The macro generates a #[thread_local] field, but the android libstd does // not use #[thread_local] // 5. Compile error about structs with wrong fields. // // To get around this, we're forced to inject the #[cfg] logic into the macro // itself. Woohoo. #[macro_export] #[doc(hidden)] #[allow_internal_unstable] macro_rules! __thread_local_inner { (static $name:ident: $t:ty = $init:expr) => ( #[cfg_attr(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")), thread_local)] static $name: ::std::thread_local::__impl::KeyInner<$t> = __thread_local_inner!($init, $t); ); (pub static $name:ident: $t:ty = $init:expr) => ( #[cfg_attr(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")), thread_local)] pub static $name: ::std::thread_local::__impl::KeyInner<$t> = __thread_local_inner!($init, $t); ); ($init:expr, $t:ty) => ({ #[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))] const _INIT: ::std::thread_local::__impl::KeyInner<$t> = { ::std::thread_local::__impl::KeyInner { inner: ::std::cell::UnsafeCell { value: $init }, dtor_registered: ::std::cell::UnsafeCell { value: false }, dtor_running: ::std::cell::UnsafeCell { value: false }, } }; #[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))] const _INIT: ::std::thread_local::__impl::KeyInner<$t> = { unsafe extern fn __destroy(ptr: *mut u8) { ::std::thread_local::__impl::destroy_value::<$t>(ptr); } ::std::thread_local::__impl::KeyInner { inner: ::std::cell::UnsafeCell { value: $init }, os: ::std::thread_local::__impl::OsStaticKey { inner: ::std::thread_local::__impl::OS_INIT_INNER, dtor: ::std::option::Option::Some(__destroy as unsafe extern fn(*mut u8)), }, } }; _INIT }); } /// Indicator of the state of a thread local storage key. #[unstable(feature = "std_misc", reason = "state querying was recently added")] #[derive(Eq, PartialEq, Copy)] pub enum State { /// All keys are in this state whenever a thread starts. Keys will /// transition to the `Valid` state once the first call to `with` happens /// and the initialization expression succeeds. /// /// Keys in the `Uninitialized` state will yield a reference to the closure /// passed to `with` so long as the initialization routine does not panic. Uninitialized, /// Once a key has been accessed successfully, it will enter the `Valid` /// state. Keys in the `Valid` state will remain so until the thread exits, /// at which point the destructor will be run and the key will enter the /// `Destroyed` state. /// /// Keys in the `Valid` state will be guaranteed to yield a reference to the /// closure passed to `with`. Valid, /// When a thread exits, the destructors for keys will be run (if /// necessary). While a destructor is running, and possibly after a /// destructor has run, a key is in the `Destroyed` state. /// /// Keys in the `Destroyed` states will trigger a panic when accessed via /// `with`. Destroyed, } impl<T:'static> Key<T> { /// Acquire a reference to the value in this TLS key. /// /// This will lazily initialize the value if this thread has not referenced /// this key yet. /// /// # Panics /// /// This function will `panic!()` if the key currently has its /// destructor running, and it **may** panic if the destructor has /// previously been run for this thread. #[stable(feature = "rust1", since = "1.0.0")] pub fn with<F, R>(&'static self, f: F) -> R where F: FnOnce(&T) -> R { let slot = (self.inner)(); unsafe { let slot = slot.get().expect("cannot access a TLS value during or \ after it is destroyed"); f(match *slot.get() { Some(ref inner) => inner, None => self.init(slot), }) } } unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T { // Execute the initialization up front, *then* move it into our slot, // just in case initialization fails. let value = (self.init)(); let ptr = slot.get(); *ptr = Some(value); (*ptr).as_ref().unwrap() } /// Query the current state of this key. /// /// A key is initially in the `Uninitialized` state whenever a thread /// starts. It will remain in this state up until the first call to `with` /// within a thread has run the initialization expression successfully. /// /// Once the initialization expression succeeds, the key transitions to the /// `Valid` state which will guarantee that future calls to `with` will /// succeed within the thread. /// /// When a thread exits, each key will be destroyed in turn, and as keys are /// destroyed they will enter the `Destroyed` state just before the /// destructor starts to run. Keys may remain in the `Destroyed` state after /// destruction has completed. Keys without destructors (e.g. with types /// that are `Copy`), may never enter the `Destroyed` state. /// /// Keys in the `Uninitialized` can be accessed so long as the /// initialization does not panic. Keys in the `Valid` state are guaranteed /// to be able to be accessed. Keys in the `Destroyed` state will panic on /// any call to `with`. #[unstable(feature = "std_misc", reason = "state querying was recently added")] pub fn state(&'static self) -> State { unsafe { match (self.inner)().get() { Some(cell) =>
None => State::Destroyed, } } } /// Deprecated #[unstable(feature = "std_misc")] #[deprecated(since = "1.0.0", reason = "function renamed to state() and returns more info")] pub fn destroyed(&'static self) -> bool { self.state() == State::Destroyed } } #[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))] mod imp { use prelude::v1::*; use cell::UnsafeCell; use intrinsics; use ptr; #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub struct Key<T> { // Place the inner bits in an `UnsafeCell` to currently get around the // "only Sync statics" restriction. This allows any type to be placed in // the cell. // // Note that all access requires `T:'static` so it can't be a type with // any borrowed pointers still. #[unstable(feature = "thread_local_internals")] pub inner: UnsafeCell<T>, // Metadata to keep track of the state of the destructor. Remember that // these variables are thread-local, not global. #[unstable(feature = "thread_local_internals")] pub dtor_registered: UnsafeCell<bool>, // should be Cell #[unstable(feature = "thread_local_internals")] pub dtor_running: UnsafeCell<bool>, // should be Cell } unsafe impl<T> ::marker::Sync for Key<T> { } #[doc(hidden)] impl<T> Key<T> { pub unsafe fn get(&'static self) -> Option<&'static T> { if intrinsics::needs_drop::<T>() && *self.dtor_running.get() { return None } self.register_dtor(); Some(&*self.inner.get()) } unsafe fn register_dtor(&self) { if!intrinsics::needs_drop::<T>() || *self.dtor_registered.get() { return } register_dtor(self as *const _ as *mut u8, destroy_value::<T>); *self.dtor_registered.get() = true; } } // Since what appears to be glibc 2.18 this symbol has been shipped which // GCC and clang both use to invoke destructors in thread_local globals, so // let's do the same! // // Note, however, that we run on lots older linuxes, as well as cross // compiling from a newer linux to an older linux, so we also have a // fallback implementation to use as well. // // Due to rust-lang/rust#18804, make sure this is not generic! #[cfg(target_os = "linux")] unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { use boxed; use mem; use libc; use sys_common::thread_local as os; extern { static __dso_handle: *mut u8; #[linkage = "extern_weak"] static __cxa_thread_atexit_impl: *const (); } if!__cxa_thread_atexit_impl.is_null() { type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8), arg: *mut u8, dso_handle: *mut u8) -> libc::c_int; mem::transmute::<*const (), F>(__cxa_thread_atexit_impl) (dtor, t, __dso_handle); return } // The fallback implementation uses a vanilla OS-based TLS key to track // the list of destructors that need to be run for this thread. The key // then has its own destructor which runs all the other destructors. // // The destructor for DTORS is a little special in that it has a `while` // loop to continuously drain the list of registered destructors. It // *should* be the case that this loop always terminates because we // provide the guarantee that a TLS key cannot be set after it is // flagged for destruction. static DTORS: os::StaticKey = os::StaticKey { inner: os::INIT_INNER, dtor: Some(run_dtors as unsafe extern "C" fn(*mut u8)), }; type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; if DTORS.get().is_null() { let v: Box<List> = box Vec::new(); DTORS.set(boxed::into_raw(v) as *mut u8); } let list: &mut List = &mut *(DTORS.get() as *mut List); list.push((t, dtor)); unsafe extern fn run_dtors(mut ptr: *mut u8) { while!ptr.is_null() { let list: Box<List> = Box::from_raw(ptr as *mut List); for &(ptr, dtor) in &*list { dtor(ptr); } ptr = DTORS.get(); DTORS.set(ptr::null_mut()); } } } // OSX's analog of the above linux function is this _tlv_atexit function. // The disassembly of thread_local globals in C++ (at least produced by // clang) will have this show up in the output. #[cfg(target_os = "macos")] unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { extern { fn _tlv_atexit(dtor: unsafe extern fn(*mut u8), arg: *mut u8); } _tlv_atexit(dtor, t); } #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub unsafe extern fn destroy_value<T>(ptr: *mut u8) { let ptr = ptr as *mut Key<T>; // Right before we run the user destructor be sure to flag the // destructor as running for this thread so calls to `get` will return // `None`. *(*ptr).dtor_running.get() = true; ptr::read((*ptr).inner.get()); } } #[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))] mod imp { use prelude::v1::*; use alloc::boxed; use cell::UnsafeCell; use mem; use ptr; use sys_common::thread_local::StaticKey as OsStaticKey; #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub struct Key<T> { // Statically allocated initialization expression, using an `UnsafeCell` // for the same reasons as above. #[unstable(feature = "thread_local_internals")] pub inner: UnsafeCell<T>, // OS-TLS key that we'll use to key off. #[unstable(feature = "thread_local_internals")] pub os: OsStaticKey, } unsafe impl<T> ::marker::Sync for Key<T> { } struct Value<T:'static> { key: &'static Key<T>, value: T, } #[doc(hidden)] impl<T> Key<T> { pub unsafe fn get(&'static self) -> Option<&'static T> { self.ptr().map(|p| &*p) } unsafe fn ptr(&'static self) -> Option<*mut T> { let ptr = self.os.get() as *mut Value<T>; if!ptr.is_null() { if ptr as usize == 1 { return None } return Some(&mut (*ptr).value as *mut T); } // If the lookup returned null, we haven't initialized our own local // copy, so do that now. // // Also note that this transmute_copy should be ok because the value // `inner` is already validated to be a valid `static` value, so we // should be able to freely copy the bits. let ptr: Box<Value<T>> = box Value { key: self, value: mem::transmute_copy(&self.inner), }; let ptr: *mut Value<T> = boxed::into_raw(ptr); self.os.set(ptr as *mut u8); Some(&mut (*ptr).value as *mut T) } } #[doc(hidden)] #[unstable(feature = "thread_local_internals")] pub unsafe extern fn destroy_value<T:'static>(ptr: *mut u8) { // The OS TLS ensures that this key contains a NULL value when this // destructor starts to run. We set it back to a sentinel value of 1 to // ensure that any future calls to `get` for this thread will return // `None`. // // Note that to prevent an infinite loop we reset it back to null right // before we return from the destructor ourselves. let ptr: Box<Value<T>> = Box::from_raw(ptr as *mut Value<T>); let key = ptr.key; key.os.set(1 as *mut u8); drop(ptr); key.os.set(ptr::null_mut()); } } #[cfg(test)] mod tests { use prelude::v1::*; use sync::mpsc::{channel, Sender}; use cell::UnsafeCell; use super::State; use thread; struct Foo(Sender<()>); impl Drop for Foo { fn drop(&mut self) { let Foo(ref s) = *self; s.send(()).unwrap(); } } #[test] fn smoke_no_dtor() { thread_local!(static FOO: UnsafeCell<i32> = UnsafeCell { value: 1 }); FOO.with(|f| unsafe { assert_eq!(*f.get(), 1); *f.get() = 2; }); let (tx, rx) = channel(); let _t = thread::spawn(move|| { FOO.with(|f| unsafe { assert_eq!(*f.get(), 1); }); tx.send(()).unwrap(); }); rx.recv().unwrap(); FOO.with(|f| unsafe { assert_eq!(*f.get(), 2); }); } #[test] fn states() { struct Foo; impl Drop for Foo { fn drop(&mut self) { assert!(FOO.state() == State::Destroyed); } } fn foo() -> Foo { assert!(FOO.state() == State::Uninitialized); Foo } thread_local!(static FOO: Foo = foo()); thread::spawn(|| { assert!(FOO.state() == State::Uninitialized); FOO.with(|_| { assert!(FOO.state() == State::Valid); }); assert!(FOO.state() == State::Valid); }).join().ok().unwrap();
{ match *cell.get() { Some(..) => State::Valid, None => State::Uninitialized, } }
conditional_block
main.rs
_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(unboxed_closures)] #![feature(unsafe_no_drop_flag)] #![feature(unwind_attributes)] #![feature(vec_push_all)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use core::{ptr, mem, usize}; use core::slice::SliceExt; use common::event::{self, EVENT_KEY, EventOption}; use common::memory; use common::paging::Page; use common::time::Duration; use drivers::pci::*; use drivers::pio::*; use drivers::ps2::*; use drivers::rtc::*; use drivers::serial::*; use env::Environment; pub use externs::*; use graphics::display; use programs::executor::execute; use programs::scheme::*; use scheduler::{Context, Regs, TSS}; use scheduler::context::context_switch; use schemes::Url; use schemes::arp::*; use schemes::context::*; use schemes::debug::*; use schemes::ethernet::*; use schemes::icmp::*; use schemes::ip::*; use schemes::memory::*; // use schemes::display::*; use syscall::handle::*; /// Common std-like functionality #[macro_use] pub mod common; /// Allocation pub mod alloc_system; /// Audio pub mod audio; /// Various drivers /// TODO: Move out of kernel space (like other microkernels) pub mod drivers; /// Environment pub mod env; /// Externs pub mod externs; /// Various graphical methods pub mod graphics; /// Network pub mod network; /// Panic pub mod panic; /// Programs pub mod programs; /// Schemes pub mod schemes; /// Scheduling pub mod scheduler; /// Sync primatives pub mod sync; /// System calls pub mod syscall; /// USB input/output pub mod usb; pub static mut TSS_PTR: Option<&'static mut TSS> = None; pub static mut ENV_PTR: Option<&'static mut Environment> = None; pub fn env() -> &'static Environment { unsafe { match ENV_PTR { Some(&mut ref p) => p, None => unreachable!(), } } } /// Pit duration static PIT_DURATION: Duration = Duration { secs: 0, nanos: 2250286, }; /// Idle loop (active while idle) unsafe fn idle_loop() ->! { loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; { let contexts = ::env().contexts.lock(); for i in 1..contexts.len() { if let Some(context) = contexts.get(i) { if context.interrupted { halt = false; break; } } } } if halt { asm!("sti" : : : : "intel", "volatile"); asm!("hlt" : : : : "intel", "volatile"); } else { asm!("sti" : : : : "intel", "volatile"); } context_switch(false); } } /// Event poll loop fn poll_loop() ->! { loop { env().on_poll(); unsafe { context_switch(false) }; } } /// Event loop fn event_loop() ->! { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String::new(); loop { loop { let mut console = env().console.lock(); match env().events.lock().pop_front() { Some(event) => { if console.draw { match event.to_option() { EventOption::Key(key_event) => { if key_event.pressed { match key_event.scancode { event::K_F2 => { console.draw = false; } event::K_BKSP => if!cmd.is_empty() { console.write(&[8]); cmd.pop(); }, _ => match key_event.character { '\0' => (), '\n' => { console.command = Some(cmd.clone()); cmd.clear(); console.write(&[10]); } _ => { cmd.push(key_event.character); console.write(&[key_event.character as u8]); } }, } } } _ => (), } } else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack unsafe { for scheme in env().schemes.iter() { if (*scheme.get()).scheme() == "orbital" { (*scheme.get()).event(&event); break; } } } } } } None => break, } } { let mut console = env().console.lock(); console.instant = false; if console.draw && console.redraw { console.redraw = false; console.display.flip(); } } unsafe { context_switch(false) }; } } /// Initialize kernel unsafe fn init(font_data: usize, tss_data: usize) { //Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr: *mut u8 = &mut __bss_start; let end_ptr: *mut u8 = &mut __bss_end; if start_ptr as usize <= end_ptr as usize { let size = end_ptr as usize - start_ptr as usize; memset(start_ptr, 0, size); } } //Setup paging, this allows for memory allocation Page::init(); memory::cluster_init(); // Unmap first page to catch null pointer errors (after reading memory map) Page::new(0).unmap(); display::fonts = font_data; TSS_PTR = Some(&mut *(tss_data as *mut TSS)); ENV_PTR = Some(&mut *Box::into_raw(Environment::new())); match ENV_PTR { Some(ref mut env) => { env.contexts.lock().push(Context::root()); env.console.lock().draw = true; debug!("Redox {} bits\n", mem::size_of::<usize>() * 8); *(env.clock_realtime.lock()) = Rtc::new().time(); env.schemes.push(UnsafeCell::new(Ps2::new())); env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4))); pci_init(env); env.schemes.push(UnsafeCell::new(DebugScheme::new())); env.schemes.push(UnsafeCell::new(box ContextScheme)); env.schemes.push(UnsafeCell::new(box MemoryScheme)); // session.items.push(box RandomScheme); // session.items.push(box TimeScheme); env.schemes.push(UnsafeCell::new(box EthernetScheme)); env.schemes.push(UnsafeCell::new(box ArpScheme)); env.schemes.push(UnsafeCell::new(box IcmpScheme)); env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() })); // session.items.push(box DisplayScheme); Context::spawn("kpoll".to_string(), box move || { poll_loop(); }); Context::spawn("kevent".to_string(), box move || { event_loop(); }); Context::spawn("karp".to_string(), box move || { ArpScheme::reply_loop(); }); Context::spawn("kicmp".to_string(), box move || { IcmpScheme::reply_loop(); }); env.contexts.lock().enabled = true; if let Ok(mut resource) = Url::from_str("file:/schemes/").open() { let mut vec: Vec<u8> = Vec::new(); resource.read_to_end(&mut vec); for folder in String::from_utf8_unchecked(vec).lines() { if folder.ends_with('/') { let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/" .to_string() + &folder)); env.schemes.push(UnsafeCell::new(scheme_item)); } } } Context::spawn("kinit".to_string(), box move || { { let wd_c = "file:/\0"; do_sys_chdir(wd_c.as_ptr()); let stdio_c = "debug:\0"; do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); } execute(Url::from_str("file:/apps/login/main.bin"), Vec::new()); debug!("INIT: Failed to execute\n"); loop { context_switch(false); } }); }, None => unreachable!(), } } #[cold] #[inline(never)] #[no_mangle] /// Take regs for kernel calls and exceptions pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) { macro_rules! exception_inner { ($name:expr) => ({ { let contexts = ::env().contexts.lock(); if let Some(context) = contexts.current() { debugln!("PID {}: {}", context.pid, context.name); } } debugln!(" INT {:X}: {}", interrupt, $name); debugln!(" CS: {:08X} IP: {:08X} FLG: {:08X}", regs.cs, regs.ip, regs.flags); debugln!(" SS: {:08X} SP: {:08X} BP: {:08X}", regs.ss, regs.sp, regs.bp); debugln!(" AX: {:08X} BX: {:08X} CX: {:08X} DX: {:08X}", regs.ax, regs.bx, regs.cx, regs.dx); debugln!(" DI: {:08X} SI: {:08X}", regs.di, regs.di); let cr0: usize; let cr2: usize; let cr3: usize; let cr4: usize; unsafe { asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile"); asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile"); asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile"); asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile"); } debugln!(" CR0: {:08X} CR2: {:08X} CR3: {:08X} CR4: {:08X}", cr0, cr2, cr3, cr4); let sp = regs.sp as *const u32; for y in -15..16 { debug!(" {:>3}:", y * 8 * 4); for x in 0..8 {
}; macro_rules! exception { ($name:expr) => ({ exception_inner!($name); loop { do_sys_exit(usize::MAX); } }) }; macro_rules! exception_error { ($name:expr) => ({ let error = regs.ip; regs.ip = regs.cs; regs.cs = regs.flags; regs.flags = regs.sp; regs.sp = regs.ss; regs.ss = 0; //regs.ss = regs.error; exception_inner!($name); debugln!(" ERR: {:08X}", error); loop { do_sys_exit(usize::MAX); } }) }; if interrupt >= 0x20 && interrupt < 0x30 { if interrupt >= 0x28 { unsafe { Pio8::new(0xA0).write(0x20) }; } unsafe { Pio8::new(0x20).write(0x20) }; } match interrupt { 0x20 => { { let mut clock_monotonic = env().clock_monotonic.lock(); *clock_monotonic = *clock_monotonic + PIT_DURATION; } { let mut clock_realtime = env().clock_realtime.lock(); *clock_realtime = *clock_realtime + PIT_DURATION; } let switch = { let mut contexts = ::env().contexts.lock(); if let Some(mut context) = contexts.current_mut() { context.slices -= 1; context.slice_total += 1; context.slices == 0 } else { false } }; if switch { unsafe { context_switch(true) }; } } 0x21 => env().on_irq(0x1), // keyboard 0x22 => env().on_irq(0x2), // cascade 0x23 => env().on_irq(0x3), // serial 2 and 4 0x24 => env().on_irq(0x4), // serial 1 and 3 0x25 => env().on_irq(0x5), //parallel 2 0x26 => env().on_irq(0x6), //floppy 0x27 => env().on_irq(0x7), //parallel 1 or spurious 0x28 => env().on_irq(0x8), //RTC 0x29 => env().on_irq(0x9), //pci 0x2A => env().on_irq(0xA), //pci 0x2B => env().on_irq(0xB), //pci 0x2C => env().on_irq(0xC), //mouse 0x2D => env().on_irq(0xD), //coprocessor 0x2E => env().on_irq(0xE), //disk 0x2F => env().on_irq(0xF), //disk 0x80 => if! syscall_handle(regs) { exception!("Unknown Syscall"); }, 0xFF => { unsafe { init(regs.ax, regs.bx); idle_loop(); } }, 0x0 => exception!("Divide by zero exception"), 0x1 => exception!("Debug exception"), 0x2 => exception!("Non-maskable interrupt"), 0x3 => exception!("Breakpoint exception"), 0x4 => exception!("Overflow exception"), 0x5 => exception!("Bound range exceeded exception"), 0x6 => exception!("Invalid opcode exception"), 0x7 => exception!("Device not available exception"), 0x8 => exception_error!("Double fault"), 0xA => exception_error!("Invalid TSS exception"), 0xB => exception_error!("Segment not present exception"),
debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) }); } debug!("\n"); } })
random_line_split
main.rs
slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(unboxed_closures)] #![feature(unsafe_no_drop_flag)] #![feature(unwind_attributes)] #![feature(vec_push_all)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use core::{ptr, mem, usize}; use core::slice::SliceExt; use common::event::{self, EVENT_KEY, EventOption}; use common::memory; use common::paging::Page; use common::time::Duration; use drivers::pci::*; use drivers::pio::*; use drivers::ps2::*; use drivers::rtc::*; use drivers::serial::*; use env::Environment; pub use externs::*; use graphics::display; use programs::executor::execute; use programs::scheme::*; use scheduler::{Context, Regs, TSS}; use scheduler::context::context_switch; use schemes::Url; use schemes::arp::*; use schemes::context::*; use schemes::debug::*; use schemes::ethernet::*; use schemes::icmp::*; use schemes::ip::*; use schemes::memory::*; // use schemes::display::*; use syscall::handle::*; /// Common std-like functionality #[macro_use] pub mod common; /// Allocation pub mod alloc_system; /// Audio pub mod audio; /// Various drivers /// TODO: Move out of kernel space (like other microkernels) pub mod drivers; /// Environment pub mod env; /// Externs pub mod externs; /// Various graphical methods pub mod graphics; /// Network pub mod network; /// Panic pub mod panic; /// Programs pub mod programs; /// Schemes pub mod schemes; /// Scheduling pub mod scheduler; /// Sync primatives pub mod sync; /// System calls pub mod syscall; /// USB input/output pub mod usb; pub static mut TSS_PTR: Option<&'static mut TSS> = None; pub static mut ENV_PTR: Option<&'static mut Environment> = None; pub fn env() -> &'static Environment { unsafe { match ENV_PTR { Some(&mut ref p) => p, None => unreachable!(), } } } /// Pit duration static PIT_DURATION: Duration = Duration { secs: 0, nanos: 2250286, }; /// Idle loop (active while idle) unsafe fn
() ->! { loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; { let contexts = ::env().contexts.lock(); for i in 1..contexts.len() { if let Some(context) = contexts.get(i) { if context.interrupted { halt = false; break; } } } } if halt { asm!("sti" : : : : "intel", "volatile"); asm!("hlt" : : : : "intel", "volatile"); } else { asm!("sti" : : : : "intel", "volatile"); } context_switch(false); } } /// Event poll loop fn poll_loop() ->! { loop { env().on_poll(); unsafe { context_switch(false) }; } } /// Event loop fn event_loop() ->! { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String::new(); loop { loop { let mut console = env().console.lock(); match env().events.lock().pop_front() { Some(event) => { if console.draw { match event.to_option() { EventOption::Key(key_event) => { if key_event.pressed { match key_event.scancode { event::K_F2 => { console.draw = false; } event::K_BKSP => if!cmd.is_empty() { console.write(&[8]); cmd.pop(); }, _ => match key_event.character { '\0' => (), '\n' => { console.command = Some(cmd.clone()); cmd.clear(); console.write(&[10]); } _ => { cmd.push(key_event.character); console.write(&[key_event.character as u8]); } }, } } } _ => (), } } else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack unsafe { for scheme in env().schemes.iter() { if (*scheme.get()).scheme() == "orbital" { (*scheme.get()).event(&event); break; } } } } } } None => break, } } { let mut console = env().console.lock(); console.instant = false; if console.draw && console.redraw { console.redraw = false; console.display.flip(); } } unsafe { context_switch(false) }; } } /// Initialize kernel unsafe fn init(font_data: usize, tss_data: usize) { //Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr: *mut u8 = &mut __bss_start; let end_ptr: *mut u8 = &mut __bss_end; if start_ptr as usize <= end_ptr as usize { let size = end_ptr as usize - start_ptr as usize; memset(start_ptr, 0, size); } } //Setup paging, this allows for memory allocation Page::init(); memory::cluster_init(); // Unmap first page to catch null pointer errors (after reading memory map) Page::new(0).unmap(); display::fonts = font_data; TSS_PTR = Some(&mut *(tss_data as *mut TSS)); ENV_PTR = Some(&mut *Box::into_raw(Environment::new())); match ENV_PTR { Some(ref mut env) => { env.contexts.lock().push(Context::root()); env.console.lock().draw = true; debug!("Redox {} bits\n", mem::size_of::<usize>() * 8); *(env.clock_realtime.lock()) = Rtc::new().time(); env.schemes.push(UnsafeCell::new(Ps2::new())); env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4))); pci_init(env); env.schemes.push(UnsafeCell::new(DebugScheme::new())); env.schemes.push(UnsafeCell::new(box ContextScheme)); env.schemes.push(UnsafeCell::new(box MemoryScheme)); // session.items.push(box RandomScheme); // session.items.push(box TimeScheme); env.schemes.push(UnsafeCell::new(box EthernetScheme)); env.schemes.push(UnsafeCell::new(box ArpScheme)); env.schemes.push(UnsafeCell::new(box IcmpScheme)); env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() })); // session.items.push(box DisplayScheme); Context::spawn("kpoll".to_string(), box move || { poll_loop(); }); Context::spawn("kevent".to_string(), box move || { event_loop(); }); Context::spawn("karp".to_string(), box move || { ArpScheme::reply_loop(); }); Context::spawn("kicmp".to_string(), box move || { IcmpScheme::reply_loop(); }); env.contexts.lock().enabled = true; if let Ok(mut resource) = Url::from_str("file:/schemes/").open() { let mut vec: Vec<u8> = Vec::new(); resource.read_to_end(&mut vec); for folder in String::from_utf8_unchecked(vec).lines() { if folder.ends_with('/') { let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/" .to_string() + &folder)); env.schemes.push(UnsafeCell::new(scheme_item)); } } } Context::spawn("kinit".to_string(), box move || { { let wd_c = "file:/\0"; do_sys_chdir(wd_c.as_ptr()); let stdio_c = "debug:\0"; do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); } execute(Url::from_str("file:/apps/login/main.bin"), Vec::new()); debug!("INIT: Failed to execute\n"); loop { context_switch(false); } }); }, None => unreachable!(), } } #[cold] #[inline(never)] #[no_mangle] /// Take regs for kernel calls and exceptions pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) { macro_rules! exception_inner { ($name:expr) => ({ { let contexts = ::env().contexts.lock(); if let Some(context) = contexts.current() { debugln!("PID {}: {}", context.pid, context.name); } } debugln!(" INT {:X}: {}", interrupt, $name); debugln!(" CS: {:08X} IP: {:08X} FLG: {:08X}", regs.cs, regs.ip, regs.flags); debugln!(" SS: {:08X} SP: {:08X} BP: {:08X}", regs.ss, regs.sp, regs.bp); debugln!(" AX: {:08X} BX: {:08X} CX: {:08X} DX: {:08X}", regs.ax, regs.bx, regs.cx, regs.dx); debugln!(" DI: {:08X} SI: {:08X}", regs.di, regs.di); let cr0: usize; let cr2: usize; let cr3: usize; let cr4: usize; unsafe { asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile"); asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile"); asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile"); asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile"); } debugln!(" CR0: {:08X} CR2: {:08X} CR3: {:08X} CR4: {:08X}", cr0, cr2, cr3, cr4); let sp = regs.sp as *const u32; for y in -15..16 { debug!(" {:>3}:", y * 8 * 4); for x in 0..8 { debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) }); } debug!("\n"); } }) }; macro_rules! exception { ($name:expr) => ({ exception_inner!($name); loop { do_sys_exit(usize::MAX); } }) }; macro_rules! exception_error { ($name:expr) => ({ let error = regs.ip; regs.ip = regs.cs; regs.cs = regs.flags; regs.flags = regs.sp; regs.sp = regs.ss; regs.ss = 0; //regs.ss = regs.error; exception_inner!($name); debugln!(" ERR: {:08X}", error); loop { do_sys_exit(usize::MAX); } }) }; if interrupt >= 0x20 && interrupt < 0x30 { if interrupt >= 0x28 { unsafe { Pio8::new(0xA0).write(0x20) }; } unsafe { Pio8::new(0x20).write(0x20) }; } match interrupt { 0x20 => { { let mut clock_monotonic = env().clock_monotonic.lock(); *clock_monotonic = *clock_monotonic + PIT_DURATION; } { let mut clock_realtime = env().clock_realtime.lock(); *clock_realtime = *clock_realtime + PIT_DURATION; } let switch = { let mut contexts = ::env().contexts.lock(); if let Some(mut context) = contexts.current_mut() { context.slices -= 1; context.slice_total += 1; context.slices == 0 } else { false } }; if switch { unsafe { context_switch(true) }; } } 0x21 => env().on_irq(0x1), // keyboard 0x22 => env().on_irq(0x2), // cascade 0x23 => env().on_irq(0x3), // serial 2 and 4 0x24 => env().on_irq(0x4), // serial 1 and 3 0x25 => env().on_irq(0x5), //parallel 2 0x26 => env().on_irq(0x6), //floppy 0x27 => env().on_irq(0x7), //parallel 1 or spurious 0x28 => env().on_irq(0x8), //RTC 0x29 => env().on_irq(0x9), //pci 0x2A => env().on_irq(0xA), //pci 0x2B => env().on_irq(0xB), //pci 0x2C => env().on_irq(0xC), //mouse 0x2D => env().on_irq(0xD), //coprocessor 0x2E => env().on_irq(0xE), //disk 0x2F => env().on_irq(0xF), //disk 0x80 => if! syscall_handle(regs) { exception!("Unknown Syscall"); }, 0xFF => { unsafe { init(regs.ax, regs.bx); idle_loop(); } }, 0x0 => exception!("Divide by zero exception"), 0x1 => exception!("Debug exception"), 0x2 => exception!("Non-maskable interrupt"), 0x3 => exception!("Breakpoint exception"), 0x4 => exception!("Overflow exception"), 0x5 => exception!("Bound range exceeded exception"), 0x6 => exception!("Invalid opcode exception"), 0x7 => exception!("Device not available exception"), 0x8 => exception_error!("Double fault"), 0xA => exception_error!("Invalid TSS exception"), 0xB => exception_error!("Segment not present exception"),
idle_loop
identifier_name
main.rs
slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(unboxed_closures)] #![feature(unsafe_no_drop_flag)] #![feature(unwind_attributes)] #![feature(vec_push_all)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use core::{ptr, mem, usize}; use core::slice::SliceExt; use common::event::{self, EVENT_KEY, EventOption}; use common::memory; use common::paging::Page; use common::time::Duration; use drivers::pci::*; use drivers::pio::*; use drivers::ps2::*; use drivers::rtc::*; use drivers::serial::*; use env::Environment; pub use externs::*; use graphics::display; use programs::executor::execute; use programs::scheme::*; use scheduler::{Context, Regs, TSS}; use scheduler::context::context_switch; use schemes::Url; use schemes::arp::*; use schemes::context::*; use schemes::debug::*; use schemes::ethernet::*; use schemes::icmp::*; use schemes::ip::*; use schemes::memory::*; // use schemes::display::*; use syscall::handle::*; /// Common std-like functionality #[macro_use] pub mod common; /// Allocation pub mod alloc_system; /// Audio pub mod audio; /// Various drivers /// TODO: Move out of kernel space (like other microkernels) pub mod drivers; /// Environment pub mod env; /// Externs pub mod externs; /// Various graphical methods pub mod graphics; /// Network pub mod network; /// Panic pub mod panic; /// Programs pub mod programs; /// Schemes pub mod schemes; /// Scheduling pub mod scheduler; /// Sync primatives pub mod sync; /// System calls pub mod syscall; /// USB input/output pub mod usb; pub static mut TSS_PTR: Option<&'static mut TSS> = None; pub static mut ENV_PTR: Option<&'static mut Environment> = None; pub fn env() -> &'static Environment { unsafe { match ENV_PTR { Some(&mut ref p) => p, None => unreachable!(), } } } /// Pit duration static PIT_DURATION: Duration = Duration { secs: 0, nanos: 2250286, }; /// Idle loop (active while idle) unsafe fn idle_loop() ->! { loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; { let contexts = ::env().contexts.lock(); for i in 1..contexts.len() { if let Some(context) = contexts.get(i) { if context.interrupted { halt = false; break; } } } } if halt { asm!("sti" : : : : "intel", "volatile"); asm!("hlt" : : : : "intel", "volatile"); } else { asm!("sti" : : : : "intel", "volatile"); } context_switch(false); } } /// Event poll loop fn poll_loop() ->! { loop { env().on_poll(); unsafe { context_switch(false) }; } } /// Event loop fn event_loop() ->! { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String::new(); loop { loop { let mut console = env().console.lock(); match env().events.lock().pop_front() { Some(event) => { if console.draw { match event.to_option() { EventOption::Key(key_event) => { if key_event.pressed { match key_event.scancode { event::K_F2 => { console.draw = false; } event::K_BKSP => if!cmd.is_empty() { console.write(&[8]); cmd.pop(); }, _ => match key_event.character { '\0' => (), '\n' =>
_ => { cmd.push(key_event.character); console.write(&[key_event.character as u8]); } }, } } } _ => (), } } else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack unsafe { for scheme in env().schemes.iter() { if (*scheme.get()).scheme() == "orbital" { (*scheme.get()).event(&event); break; } } } } } } None => break, } } { let mut console = env().console.lock(); console.instant = false; if console.draw && console.redraw { console.redraw = false; console.display.flip(); } } unsafe { context_switch(false) }; } } /// Initialize kernel unsafe fn init(font_data: usize, tss_data: usize) { //Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr: *mut u8 = &mut __bss_start; let end_ptr: *mut u8 = &mut __bss_end; if start_ptr as usize <= end_ptr as usize { let size = end_ptr as usize - start_ptr as usize; memset(start_ptr, 0, size); } } //Setup paging, this allows for memory allocation Page::init(); memory::cluster_init(); // Unmap first page to catch null pointer errors (after reading memory map) Page::new(0).unmap(); display::fonts = font_data; TSS_PTR = Some(&mut *(tss_data as *mut TSS)); ENV_PTR = Some(&mut *Box::into_raw(Environment::new())); match ENV_PTR { Some(ref mut env) => { env.contexts.lock().push(Context::root()); env.console.lock().draw = true; debug!("Redox {} bits\n", mem::size_of::<usize>() * 8); *(env.clock_realtime.lock()) = Rtc::new().time(); env.schemes.push(UnsafeCell::new(Ps2::new())); env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4))); pci_init(env); env.schemes.push(UnsafeCell::new(DebugScheme::new())); env.schemes.push(UnsafeCell::new(box ContextScheme)); env.schemes.push(UnsafeCell::new(box MemoryScheme)); // session.items.push(box RandomScheme); // session.items.push(box TimeScheme); env.schemes.push(UnsafeCell::new(box EthernetScheme)); env.schemes.push(UnsafeCell::new(box ArpScheme)); env.schemes.push(UnsafeCell::new(box IcmpScheme)); env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() })); // session.items.push(box DisplayScheme); Context::spawn("kpoll".to_string(), box move || { poll_loop(); }); Context::spawn("kevent".to_string(), box move || { event_loop(); }); Context::spawn("karp".to_string(), box move || { ArpScheme::reply_loop(); }); Context::spawn("kicmp".to_string(), box move || { IcmpScheme::reply_loop(); }); env.contexts.lock().enabled = true; if let Ok(mut resource) = Url::from_str("file:/schemes/").open() { let mut vec: Vec<u8> = Vec::new(); resource.read_to_end(&mut vec); for folder in String::from_utf8_unchecked(vec).lines() { if folder.ends_with('/') { let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/" .to_string() + &folder)); env.schemes.push(UnsafeCell::new(scheme_item)); } } } Context::spawn("kinit".to_string(), box move || { { let wd_c = "file:/\0"; do_sys_chdir(wd_c.as_ptr()); let stdio_c = "debug:\0"; do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); } execute(Url::from_str("file:/apps/login/main.bin"), Vec::new()); debug!("INIT: Failed to execute\n"); loop { context_switch(false); } }); }, None => unreachable!(), } } #[cold] #[inline(never)] #[no_mangle] /// Take regs for kernel calls and exceptions pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) { macro_rules! exception_inner { ($name:expr) => ({ { let contexts = ::env().contexts.lock(); if let Some(context) = contexts.current() { debugln!("PID {}: {}", context.pid, context.name); } } debugln!(" INT {:X}: {}", interrupt, $name); debugln!(" CS: {:08X} IP: {:08X} FLG: {:08X}", regs.cs, regs.ip, regs.flags); debugln!(" SS: {:08X} SP: {:08X} BP: {:08X}", regs.ss, regs.sp, regs.bp); debugln!(" AX: {:08X} BX: {:08X} CX: {:08X} DX: {:08X}", regs.ax, regs.bx, regs.cx, regs.dx); debugln!(" DI: {:08X} SI: {:08X}", regs.di, regs.di); let cr0: usize; let cr2: usize; let cr3: usize; let cr4: usize; unsafe { asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile"); asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile"); asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile"); asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile"); } debugln!(" CR0: {:08X} CR2: {:08X} CR3: {:08X} CR4: {:08X}", cr0, cr2, cr3, cr4); let sp = regs.sp as *const u32; for y in -15..16 { debug!(" {:>3}:", y * 8 * 4); for x in 0..8 { debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) }); } debug!("\n"); } }) }; macro_rules! exception { ($name:expr) => ({ exception_inner!($name); loop { do_sys_exit(usize::MAX); } }) }; macro_rules! exception_error { ($name:expr) => ({ let error = regs.ip; regs.ip = regs.cs; regs.cs = regs.flags; regs.flags = regs.sp; regs.sp = regs.ss; regs.ss = 0; //regs.ss = regs.error; exception_inner!($name); debugln!(" ERR: {:08X}", error); loop { do_sys_exit(usize::MAX); } }) }; if interrupt >= 0x20 && interrupt < 0x30 { if interrupt >= 0x28 { unsafe { Pio8::new(0xA0).write(0x20) }; } unsafe { Pio8::new(0x20).write(0x20) }; } match interrupt { 0x20 => { { let mut clock_monotonic = env().clock_monotonic.lock(); *clock_monotonic = *clock_monotonic + PIT_DURATION; } { let mut clock_realtime = env().clock_realtime.lock(); *clock_realtime = *clock_realtime + PIT_DURATION; } let switch = { let mut contexts = ::env().contexts.lock(); if let Some(mut context) = contexts.current_mut() { context.slices -= 1; context.slice_total += 1; context.slices == 0 } else { false } }; if switch { unsafe { context_switch(true) }; } } 0x21 => env().on_irq(0x1), // keyboard 0x22 => env().on_irq(0x2), // cascade 0x23 => env().on_irq(0x3), // serial 2 and 4 0x24 => env().on_irq(0x4), // serial 1 and 3 0x25 => env().on_irq(0x5), //parallel 2 0x26 => env().on_irq(0x6), //floppy 0x27 => env().on_irq(0x7), //parallel 1 or spurious 0x28 => env().on_irq(0x8), //RTC 0x29 => env().on_irq(0x9), //pci 0x2A => env().on_irq(0xA), //pci 0x2B => env().on_irq(0xB), //pci 0x2C => env().on_irq(0xC), //mouse 0x2D => env().on_irq(0xD), //coprocessor 0x2E => env().on_irq(0xE), //disk 0x2F => env().on_irq(0xF), //disk 0x80 => if! syscall_handle(regs) { exception!("Unknown Syscall"); }, 0xFF => { unsafe { init(regs.ax, regs.bx); idle_loop(); } }, 0x0 => exception!("Divide by zero exception"), 0x1 => exception!("Debug exception"), 0x2 => exception!("Non-maskable interrupt"), 0x3 => exception!("Breakpoint exception"), 0x4 => exception!("Overflow exception"), 0x5 => exception!("Bound range exceeded exception"), 0x6 => exception!("Invalid opcode exception"), 0x7 => exception!("Device not available exception"), 0x8 => exception_error!("Double fault"), 0xA => exception_error!("Invalid TSS exception"), 0xB => exception_error!("Segment not present exception"),
{ console.command = Some(cmd.clone()); cmd.clear(); console.write(&[10]); }
conditional_block
main.rs
slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(unboxed_closures)] #![feature(unsafe_no_drop_flag)] #![feature(unwind_attributes)] #![feature(vec_push_all)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use core::{ptr, mem, usize}; use core::slice::SliceExt; use common::event::{self, EVENT_KEY, EventOption}; use common::memory; use common::paging::Page; use common::time::Duration; use drivers::pci::*; use drivers::pio::*; use drivers::ps2::*; use drivers::rtc::*; use drivers::serial::*; use env::Environment; pub use externs::*; use graphics::display; use programs::executor::execute; use programs::scheme::*; use scheduler::{Context, Regs, TSS}; use scheduler::context::context_switch; use schemes::Url; use schemes::arp::*; use schemes::context::*; use schemes::debug::*; use schemes::ethernet::*; use schemes::icmp::*; use schemes::ip::*; use schemes::memory::*; // use schemes::display::*; use syscall::handle::*; /// Common std-like functionality #[macro_use] pub mod common; /// Allocation pub mod alloc_system; /// Audio pub mod audio; /// Various drivers /// TODO: Move out of kernel space (like other microkernels) pub mod drivers; /// Environment pub mod env; /// Externs pub mod externs; /// Various graphical methods pub mod graphics; /// Network pub mod network; /// Panic pub mod panic; /// Programs pub mod programs; /// Schemes pub mod schemes; /// Scheduling pub mod scheduler; /// Sync primatives pub mod sync; /// System calls pub mod syscall; /// USB input/output pub mod usb; pub static mut TSS_PTR: Option<&'static mut TSS> = None; pub static mut ENV_PTR: Option<&'static mut Environment> = None; pub fn env() -> &'static Environment { unsafe { match ENV_PTR { Some(&mut ref p) => p, None => unreachable!(), } } } /// Pit duration static PIT_DURATION: Duration = Duration { secs: 0, nanos: 2250286, }; /// Idle loop (active while idle) unsafe fn idle_loop() ->! { loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; { let contexts = ::env().contexts.lock(); for i in 1..contexts.len() { if let Some(context) = contexts.get(i) { if context.interrupted { halt = false; break; } } } } if halt { asm!("sti" : : : : "intel", "volatile"); asm!("hlt" : : : : "intel", "volatile"); } else { asm!("sti" : : : : "intel", "volatile"); } context_switch(false); } } /// Event poll loop fn poll_loop() ->!
/// Event loop fn event_loop() ->! { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String::new(); loop { loop { let mut console = env().console.lock(); match env().events.lock().pop_front() { Some(event) => { if console.draw { match event.to_option() { EventOption::Key(key_event) => { if key_event.pressed { match key_event.scancode { event::K_F2 => { console.draw = false; } event::K_BKSP => if!cmd.is_empty() { console.write(&[8]); cmd.pop(); }, _ => match key_event.character { '\0' => (), '\n' => { console.command = Some(cmd.clone()); cmd.clear(); console.write(&[10]); } _ => { cmd.push(key_event.character); console.write(&[key_event.character as u8]); } }, } } } _ => (), } } else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack unsafe { for scheme in env().schemes.iter() { if (*scheme.get()).scheme() == "orbital" { (*scheme.get()).event(&event); break; } } } } } } None => break, } } { let mut console = env().console.lock(); console.instant = false; if console.draw && console.redraw { console.redraw = false; console.display.flip(); } } unsafe { context_switch(false) }; } } /// Initialize kernel unsafe fn init(font_data: usize, tss_data: usize) { //Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr: *mut u8 = &mut __bss_start; let end_ptr: *mut u8 = &mut __bss_end; if start_ptr as usize <= end_ptr as usize { let size = end_ptr as usize - start_ptr as usize; memset(start_ptr, 0, size); } } //Setup paging, this allows for memory allocation Page::init(); memory::cluster_init(); // Unmap first page to catch null pointer errors (after reading memory map) Page::new(0).unmap(); display::fonts = font_data; TSS_PTR = Some(&mut *(tss_data as *mut TSS)); ENV_PTR = Some(&mut *Box::into_raw(Environment::new())); match ENV_PTR { Some(ref mut env) => { env.contexts.lock().push(Context::root()); env.console.lock().draw = true; debug!("Redox {} bits\n", mem::size_of::<usize>() * 8); *(env.clock_realtime.lock()) = Rtc::new().time(); env.schemes.push(UnsafeCell::new(Ps2::new())); env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4))); pci_init(env); env.schemes.push(UnsafeCell::new(DebugScheme::new())); env.schemes.push(UnsafeCell::new(box ContextScheme)); env.schemes.push(UnsafeCell::new(box MemoryScheme)); // session.items.push(box RandomScheme); // session.items.push(box TimeScheme); env.schemes.push(UnsafeCell::new(box EthernetScheme)); env.schemes.push(UnsafeCell::new(box ArpScheme)); env.schemes.push(UnsafeCell::new(box IcmpScheme)); env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() })); // session.items.push(box DisplayScheme); Context::spawn("kpoll".to_string(), box move || { poll_loop(); }); Context::spawn("kevent".to_string(), box move || { event_loop(); }); Context::spawn("karp".to_string(), box move || { ArpScheme::reply_loop(); }); Context::spawn("kicmp".to_string(), box move || { IcmpScheme::reply_loop(); }); env.contexts.lock().enabled = true; if let Ok(mut resource) = Url::from_str("file:/schemes/").open() { let mut vec: Vec<u8> = Vec::new(); resource.read_to_end(&mut vec); for folder in String::from_utf8_unchecked(vec).lines() { if folder.ends_with('/') { let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/" .to_string() + &folder)); env.schemes.push(UnsafeCell::new(scheme_item)); } } } Context::spawn("kinit".to_string(), box move || { { let wd_c = "file:/\0"; do_sys_chdir(wd_c.as_ptr()); let stdio_c = "debug:\0"; do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); } execute(Url::from_str("file:/apps/login/main.bin"), Vec::new()); debug!("INIT: Failed to execute\n"); loop { context_switch(false); } }); }, None => unreachable!(), } } #[cold] #[inline(never)] #[no_mangle] /// Take regs for kernel calls and exceptions pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) { macro_rules! exception_inner { ($name:expr) => ({ { let contexts = ::env().contexts.lock(); if let Some(context) = contexts.current() { debugln!("PID {}: {}", context.pid, context.name); } } debugln!(" INT {:X}: {}", interrupt, $name); debugln!(" CS: {:08X} IP: {:08X} FLG: {:08X}", regs.cs, regs.ip, regs.flags); debugln!(" SS: {:08X} SP: {:08X} BP: {:08X}", regs.ss, regs.sp, regs.bp); debugln!(" AX: {:08X} BX: {:08X} CX: {:08X} DX: {:08X}", regs.ax, regs.bx, regs.cx, regs.dx); debugln!(" DI: {:08X} SI: {:08X}", regs.di, regs.di); let cr0: usize; let cr2: usize; let cr3: usize; let cr4: usize; unsafe { asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile"); asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile"); asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile"); asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile"); } debugln!(" CR0: {:08X} CR2: {:08X} CR3: {:08X} CR4: {:08X}", cr0, cr2, cr3, cr4); let sp = regs.sp as *const u32; for y in -15..16 { debug!(" {:>3}:", y * 8 * 4); for x in 0..8 { debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) }); } debug!("\n"); } }) }; macro_rules! exception { ($name:expr) => ({ exception_inner!($name); loop { do_sys_exit(usize::MAX); } }) }; macro_rules! exception_error { ($name:expr) => ({ let error = regs.ip; regs.ip = regs.cs; regs.cs = regs.flags; regs.flags = regs.sp; regs.sp = regs.ss; regs.ss = 0; //regs.ss = regs.error; exception_inner!($name); debugln!(" ERR: {:08X}", error); loop { do_sys_exit(usize::MAX); } }) }; if interrupt >= 0x20 && interrupt < 0x30 { if interrupt >= 0x28 { unsafe { Pio8::new(0xA0).write(0x20) }; } unsafe { Pio8::new(0x20).write(0x20) }; } match interrupt { 0x20 => { { let mut clock_monotonic = env().clock_monotonic.lock(); *clock_monotonic = *clock_monotonic + PIT_DURATION; } { let mut clock_realtime = env().clock_realtime.lock(); *clock_realtime = *clock_realtime + PIT_DURATION; } let switch = { let mut contexts = ::env().contexts.lock(); if let Some(mut context) = contexts.current_mut() { context.slices -= 1; context.slice_total += 1; context.slices == 0 } else { false } }; if switch { unsafe { context_switch(true) }; } } 0x21 => env().on_irq(0x1), // keyboard 0x22 => env().on_irq(0x2), // cascade 0x23 => env().on_irq(0x3), // serial 2 and 4 0x24 => env().on_irq(0x4), // serial 1 and 3 0x25 => env().on_irq(0x5), //parallel 2 0x26 => env().on_irq(0x6), //floppy 0x27 => env().on_irq(0x7), //parallel 1 or spurious 0x28 => env().on_irq(0x8), //RTC 0x29 => env().on_irq(0x9), //pci 0x2A => env().on_irq(0xA), //pci 0x2B => env().on_irq(0xB), //pci 0x2C => env().on_irq(0xC), //mouse 0x2D => env().on_irq(0xD), //coprocessor 0x2E => env().on_irq(0xE), //disk 0x2F => env().on_irq(0xF), //disk 0x80 => if! syscall_handle(regs) { exception!("Unknown Syscall"); }, 0xFF => { unsafe { init(regs.ax, regs.bx); idle_loop(); } }, 0x0 => exception!("Divide by zero exception"), 0x1 => exception!("Debug exception"), 0x2 => exception!("Non-maskable interrupt"), 0x3 => exception!("Breakpoint exception"), 0x4 => exception!("Overflow exception"), 0x5 => exception!("Bound range exceeded exception"), 0x6 => exception!("Invalid opcode exception"), 0x7 => exception!("Device not available exception"), 0x8 => exception_error!("Double fault"), 0xA => exception_error!("Invalid TSS exception"), 0xB => exception_error!("Segment not present exception"),
{ loop { env().on_poll(); unsafe { context_switch(false) }; } }
identifier_body
main.rs
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; fn
() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); print!("secret_number is {}\n", secret_number); loop { // 为什么必须在loop里面做new let mut guess = String::new(); println!("Please input your number:"); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("your guess : {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("less"), Ordering::Equal => { println!("you win"); break; } Ordering::Greater => println!("big"), } } }
main
identifier_name
main.rs
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); print!("secret_number is {}\n", secret_number); loop { // 为什么必须在loop里面做new let mut guess = String::new(); println!("Please input your number:"); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("your guess : {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("less"), Ordering::Equal => { println!("you win"); break; } Ordering::Greater => println!("big"), }
} }
random_line_split
main.rs
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; fn main()
println!("your guess : {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("less"), Ordering::Equal => { println!("you win"); break; } Ordering::Greater => println!("big"), } } }
{ println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); print!("secret_number is {}\n", secret_number); loop { // 为什么必须在loop里面做new let mut guess = String::new(); println!("Please input your number:"); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, };
identifier_body
main.rs
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); print!("secret_number is {}\n", secret_number); loop { // 为什么必须在loop里面做new let mut guess = String::new(); println!("Please input your number:"); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("your guess : {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("less"), Ordering::Equal => {
ing::Greater => println!("big"), } } }
println!("you win"); break; } Order
conditional_block
opts.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/. */ //! Configuration options for a single run of the servo application. Created //! from command line arguments. use geometry::ScreenPx; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use layers::geometry::DevicePixel; use getopts; use std::collections::HashSet; use std::cmp; use std::env; use std::io::{self, Write}; use std::mem; use std::ptr; use std::rt; /// Global flags for Servo, currently set on the command line. #[derive(Clone)] pub struct Opts { /// The initial URL to load. pub url: String, /// How many threads to use for CPU painting (`-t`). /// /// Note that painting is sequentialized when using GPU painting. pub paint_threads: usize, /// True to use GPU painting via Skia-GL, false to use CPU painting via Skia (`-g`). Note that /// compositing is always done on the GPU. pub gpu_painting: bool, /// The maximum size of each tile in pixels (`-s`). pub tile_size: usize, /// The ratio of device pixels per px at the default scale. If unspecified, will use the /// platform default setting. pub device_pixels_per_px: Option<ScaleFactor<ScreenPx, DevicePixel, f32>>, /// `None` to disable the time profiler or `Some` with an interval in seconds to enable it and /// cause it to produce output on that interval (`-p`). pub time_profiler_period: Option<f64>, /// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option<f64>, /// Enable experimental web features (`-e`). pub enable_experimental: bool, /// The number of threads to use for layout (`-y`). Defaults to 1, which results in a recursive /// sequential algorithm. pub layout_threads: usize, pub nonincremental_layout: bool, pub nossl: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded pub userscripts: Option<String>, pub output_file: Option<String>, pub headless: bool, pub hard_fail: bool, /// True if we should bubble intrinsic widths sequentially (`-b`). If this is true, then /// intrinsic widths are computed as a separate pass instead of during flow construction. You /// may wish to turn this flag on in order to benchmark style recalculation against other /// browser engines. pub bubble_inline_sizes_separately: bool, /// True if we should show borders on all layers and tiles for /// debugging purposes (`--show-debug-borders`). pub show_debug_borders: bool, /// True if we should show borders on all fragments for debugging purposes /// (`--show-debug-fragment-borders`). pub show_debug_fragment_borders: bool, /// True if we should paint tiles with overlays based on which thread painted them. pub show_debug_parallel_paint: bool, /// True if we should paint borders around flows based on which thread painted them. pub show_debug_parallel_layout: bool, /// If set with --disable-text-aa, disable antialiasing on fonts. This is primarily useful for reftests /// where pixel perfect results are required when using fonts such as the Ahem /// font for layout tests. pub enable_text_antialiasing: bool, /// True if each step of layout is traced to an external JSON file /// for debugging purposes. Settings this implies sequential layout /// and paint. pub trace_layout: bool, /// If true, instrument the runtime for each task created and dump /// that information to a JSON file that can be viewed in the task /// profile viewer. pub profile_tasks: bool, /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option<u16>, /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to /// remote WebDriver commands. pub webdriver_port: Option<u16>, /// The initial requested size of the window. pub initial_window_size: TypedSize2D<ScreenPx, u32>, /// An optional string allowing the user agent to be set for testing. pub user_agent: Option<String>, /// Dumps the flow tree after a layout. pub dump_flow_tree: bool, /// Dumps the display list after a layout. pub dump_display_list: bool, /// Dumps the display list after optimization (post layout, at painting time). pub dump_display_list_optimized: bool, /// Emits notifications when there is a relayout. pub relayout_event: bool, /// Whether to show an error when display list geometry escapes flow overflow regions. pub validate_display_list_geometry: bool, /// A specific path to find required resources (such as user-agent.css). pub resources_path: Option<String>, /// Whether MIME sniffing should be used pub sniff_mime_types: bool, /// Whether Style Sharing Cache is used pub disable_share_style_cache: bool, } fn print_usage(app: &str, opts: &[getopts::OptGroup]) { let message = format!("Usage: {} [ options... ] [URL]\n\twhere options include", app); println!("{}", getopts::usage(&message, opts)); } pub fn print_debug_usage(app: &str) { fn
(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths separately like other engines."); print_option("disable-text-aa", "Disable antialiasing of rendered text."); print_option("dump-flow-tree", "Print the flow tree after each layout."); print_option("dump-display-list", "Print the display list after each layout."); print_option("dump-display-list-optimized", "Print optimized display list (at paint time)."); print_option("relayout-event", "Print notifications when there is a relayout."); print_option("profile-tasks", "Instrument each task, writing the output to a file."); print_option("show-compositor-borders", "Paint borders along layer and tile boundaries."); print_option("show-fragment-borders", "Paint borders along fragment boundaries."); print_option("show-parallel-paint", "Overlay tiles with colors showing which thread painted them."); print_option("show-parallel-layout", "Mark which thread laid each flow out with colors."); print_option("trace-layout", "Write layout trace to an external file for debugging."); print_option("validate-display-list-geometry", "Display an error when display list geometry escapes overflow region."); print_option("disable-share-style-cache", "Disable the style sharing cache."); println!(""); } fn args_fail(msg: &str) { let mut stderr = io::stderr(); stderr.write_all(msg.as_bytes()).unwrap(); stderr.write_all(b"\n").unwrap(); env::set_exit_status(1); } // Always use CPU painting on android. #[cfg(target_os="android")] static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; pub fn default_opts() -> Opts { Opts { url: String::new(), paint_threads: 1, gpu_painting: false, tile_size: 512, device_pixels_per_px: None, time_profiler_period: None, mem_profiler_period: None, enable_experimental: false, layout_threads: 1, nonincremental_layout: false, nossl: false, userscripts: None, output_file: None, headless: true, hard_fail: true, bubble_inline_sizes_separately: false, show_debug_borders: false, show_debug_fragment_borders: false, show_debug_parallel_paint: false, show_debug_parallel_layout: false, enable_text_antialiasing: false, trace_layout: false, devtools_port: None, webdriver_port: None, initial_window_size: TypedSize2D(800, 600), user_agent: None, dump_flow_tree: false, dump_display_list: false, dump_display_list_optimized: false, relayout_event: false, validate_display_list_geometry: false, profile_tasks: false, resources_path: None, sniff_mime_types: false, disable_share_style_cache: false, } } pub fn from_cmdline_args(args: &[String]) -> bool { let app_name = args[0].to_string(); let args = args.tail(); let opts = vec!( getopts::optflag("c", "cpu", "CPU painting (default)"), getopts::optflag("g", "gpu", "GPU painting"), getopts::optopt("o", "output", "Output file", "output.png"), getopts::optopt("s", "size", "Size of tiles", "512"), getopts::optopt("", "device-pixel-ratio", "Device pixels per px", ""), getopts::optflag("e", "experimental", "Enable experimental web features"), getopts::optopt("t", "threads", "Number of paint threads", "1"), getopts::optflagopt("p", "profile", "Profiler flag and output interval", "10"), getopts::optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"), getopts::optflag("x", "exit", "Exit after load flag"), getopts::optopt("y", "layout-threads", "Number of threads to use for layout", "1"), getopts::optflag("i", "nonincremental-layout", "Enable to turn off incremental layout."), getopts::optflag("", "no-ssl", "Disables ssl certificate verification."), getopts::optflagopt("", "userscripts", "Uses userscripts in resources/user-agent-js, or a specified full path",""), getopts::optflag("z", "headless", "Headless mode"), getopts::optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure"), getopts::optflagopt("", "devtools", "Start remote devtools server on port", "6000"), getopts::optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"), getopts::optopt("", "resolution", "Set window resolution.", "800x600"), getopts::optopt("u", "user-agent", "Set custom user agent string", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"), getopts::optopt("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""), getopts::optflag("h", "help", "Print this message"), getopts::optopt("r", "render-api", "Set the rendering API to use", "gl|mesa"), getopts::optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"), getopts::optflag("", "sniff-mime-types", "Enable MIME sniffing"), ); let opt_match = match getopts::getopts(args, &opts) { Ok(m) => m, Err(f) => { args_fail(&f.to_string()); return false; } }; if opt_match.opt_present("h") || opt_match.opt_present("help") { print_usage(&app_name, &opts); return false; }; let debug_string = match opt_match.opt_str("Z") { Some(string) => string, None => String::new() }; let mut debug_options = HashSet::new(); for split in debug_string.split(',') { debug_options.insert(split.clone()); } if debug_options.contains(&"help") { print_debug_usage(&app_name); return false; } let url = if opt_match.free.is_empty() { print_usage(&app_name, &opts); args_fail("servo asks that you provide a URL"); return false; } else { opt_match.free[0].clone() }; let tile_size: usize = match opt_match.opt_str("s") { Some(tile_size_str) => tile_size_str.parse().unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| ScaleFactor::new(dppx_str.parse().unwrap()) ); let mut paint_threads: usize = match opt_match.opt_str("t") { Some(paint_threads_str) => paint_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; // If only the flag is present, default to a 5 second period for both profilers. let time_profiler_period = opt_match.opt_default("p", "5").map(|period| { period.parse().unwrap() }); let mem_profiler_period = opt_match.opt_default("m", "5").map(|period| { period.parse().unwrap() }); let gpu_painting =!FORCE_CPU_PAINTING && opt_match.opt_present("g"); let mut layout_threads: usize = match opt_match.opt_str("y") { Some(layout_threads_str) => layout_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; let nonincremental_layout = opt_match.opt_present("i"); let nossl = opt_match.opt_present("no-ssl"); let mut bubble_inline_sizes_separately = debug_options.contains(&"bubble-widths"); let trace_layout = debug_options.contains(&"trace-layout"); if trace_layout { paint_threads = 1; layout_threads = 1; bubble_inline_sizes_separately = true; } let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { port.parse().unwrap() }); let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| { port.parse().unwrap() }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { let res: Vec<u32> = res_string.split('x').map(|r| r.parse().unwrap()).collect(); TypedSize2D(res[0], res[1]) } None => { TypedSize2D(800, 600) } }; let opts = Opts { url: url, paint_threads: paint_threads, gpu_painting: gpu_painting, tile_size: tile_size, device_pixels_per_px: device_pixels_per_px, time_profiler_period: time_profiler_period, mem_profiler_period: mem_profiler_period, enable_experimental: opt_match.opt_present("e"), layout_threads: layout_threads, nonincremental_layout: nonincremental_layout, nossl: nossl, userscripts: opt_match.opt_default("userscripts", ""), output_file: opt_match.opt_str("o"), headless: opt_match.opt_present("z"), hard_fail: opt_match.opt_present("f"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_tasks: debug_options.contains(&"profile-tasks"), trace_layout: trace_layout, devtools_port: devtools_port, webdriver_port: webdriver_port, initial_window_size: initial_window_size, user_agent: opt_match.opt_str("u"), show_debug_borders: debug_options.contains(&"show-compositor-borders"), show_debug_fragment_borders: debug_options.contains(&"show-fragment-borders"), show_debug_parallel_paint: debug_options.contains(&"show-parallel-paint"), show_debug_parallel_layout: debug_options.contains(&"show-parallel-layout"), enable_text_antialiasing:!debug_options.contains(&"disable-text-aa"), dump_flow_tree: debug_options.contains(&"dump-flow-tree"), dump_display_list: debug_options.contains(&"dump-display-list"), dump_display_list_optimized: debug_options.contains(&"dump-display-list-optimized"), relayout_event: debug_options.contains(&"relayout-event"), validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"), resources_path: opt_match.opt_str("resources-path"), sniff_mime_types: opt_match.opt_present("sniff-mime-types"), disable_share_style_cache: debug_options.contains(&"disable-share-style-cache"), }; set_opts(opts); true } static mut EXPERIMENTAL_ENABLED: bool = false; pub fn set_experimental_enabled(new_value: bool) { unsafe { EXPERIMENTAL_ENABLED = new_value; } } pub fn experimental_enabled() -> bool { unsafe { EXPERIMENTAL_ENABLED } } // Make Opts available globally. This saves having to clone and pass // opts everywhere it is used, which gets particularly cumbersome // when passing through the DOM structures. static mut OPTIONS: *mut Opts = 0 as *mut Opts; pub fn set_opts(opts: Opts) { unsafe { let box_opts = box opts; OPTIONS = mem::transmute(box_opts); } } #[inline] pub fn get<'a>() -> &'a Opts { unsafe { // If code attempts to retrieve the options and they haven't // been set by the platform init code, just return a default // set of options. This is mostly useful for unit tests that // run through a code path which queries the cmd line options. if OPTIONS == ptr::null_mut() { set_opts(default_opts()); } mem::transmute(OPTIONS) } }
print_option
identifier_name
opts.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/. */ //! Configuration options for a single run of the servo application. Created //! from command line arguments. use geometry::ScreenPx; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use layers::geometry::DevicePixel; use getopts; use std::collections::HashSet; use std::cmp; use std::env; use std::io::{self, Write}; use std::mem; use std::ptr; use std::rt; /// Global flags for Servo, currently set on the command line. #[derive(Clone)] pub struct Opts { /// The initial URL to load. pub url: String, /// How many threads to use for CPU painting (`-t`). /// /// Note that painting is sequentialized when using GPU painting. pub paint_threads: usize, /// True to use GPU painting via Skia-GL, false to use CPU painting via Skia (`-g`). Note that /// compositing is always done on the GPU. pub gpu_painting: bool, /// The maximum size of each tile in pixels (`-s`). pub tile_size: usize, /// The ratio of device pixels per px at the default scale. If unspecified, will use the /// platform default setting. pub device_pixels_per_px: Option<ScaleFactor<ScreenPx, DevicePixel, f32>>, /// `None` to disable the time profiler or `Some` with an interval in seconds to enable it and /// cause it to produce output on that interval (`-p`). pub time_profiler_period: Option<f64>, /// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option<f64>, /// Enable experimental web features (`-e`). pub enable_experimental: bool, /// The number of threads to use for layout (`-y`). Defaults to 1, which results in a recursive /// sequential algorithm. pub layout_threads: usize, pub nonincremental_layout: bool, pub nossl: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded pub userscripts: Option<String>, pub output_file: Option<String>, pub headless: bool, pub hard_fail: bool, /// True if we should bubble intrinsic widths sequentially (`-b`). If this is true, then /// intrinsic widths are computed as a separate pass instead of during flow construction. You /// may wish to turn this flag on in order to benchmark style recalculation against other /// browser engines. pub bubble_inline_sizes_separately: bool, /// True if we should show borders on all layers and tiles for /// debugging purposes (`--show-debug-borders`). pub show_debug_borders: bool, /// True if we should show borders on all fragments for debugging purposes /// (`--show-debug-fragment-borders`). pub show_debug_fragment_borders: bool, /// True if we should paint tiles with overlays based on which thread painted them. pub show_debug_parallel_paint: bool, /// True if we should paint borders around flows based on which thread painted them. pub show_debug_parallel_layout: bool, /// If set with --disable-text-aa, disable antialiasing on fonts. This is primarily useful for reftests /// where pixel perfect results are required when using fonts such as the Ahem /// font for layout tests. pub enable_text_antialiasing: bool, /// True if each step of layout is traced to an external JSON file /// for debugging purposes. Settings this implies sequential layout /// and paint. pub trace_layout: bool, /// If true, instrument the runtime for each task created and dump /// that information to a JSON file that can be viewed in the task /// profile viewer. pub profile_tasks: bool, /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option<u16>, /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to /// remote WebDriver commands. pub webdriver_port: Option<u16>, /// The initial requested size of the window. pub initial_window_size: TypedSize2D<ScreenPx, u32>, /// An optional string allowing the user agent to be set for testing. pub user_agent: Option<String>, /// Dumps the flow tree after a layout. pub dump_flow_tree: bool, /// Dumps the display list after a layout. pub dump_display_list: bool, /// Dumps the display list after optimization (post layout, at painting time). pub dump_display_list_optimized: bool, /// Emits notifications when there is a relayout. pub relayout_event: bool, /// Whether to show an error when display list geometry escapes flow overflow regions. pub validate_display_list_geometry: bool, /// A specific path to find required resources (such as user-agent.css). pub resources_path: Option<String>, /// Whether MIME sniffing should be used pub sniff_mime_types: bool, /// Whether Style Sharing Cache is used pub disable_share_style_cache: bool, } fn print_usage(app: &str, opts: &[getopts::OptGroup]) { let message = format!("Usage: {} [ options... ] [URL]\n\twhere options include", app); println!("{}", getopts::usage(&message, opts)); } pub fn print_debug_usage(app: &str) { fn print_option(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths separately like other engines."); print_option("disable-text-aa", "Disable antialiasing of rendered text."); print_option("dump-flow-tree", "Print the flow tree after each layout."); print_option("dump-display-list", "Print the display list after each layout."); print_option("dump-display-list-optimized", "Print optimized display list (at paint time)."); print_option("relayout-event", "Print notifications when there is a relayout."); print_option("profile-tasks", "Instrument each task, writing the output to a file."); print_option("show-compositor-borders", "Paint borders along layer and tile boundaries."); print_option("show-fragment-borders", "Paint borders along fragment boundaries."); print_option("show-parallel-paint", "Overlay tiles with colors showing which thread painted them."); print_option("show-parallel-layout", "Mark which thread laid each flow out with colors."); print_option("trace-layout", "Write layout trace to an external file for debugging."); print_option("validate-display-list-geometry", "Display an error when display list geometry escapes overflow region."); print_option("disable-share-style-cache", "Disable the style sharing cache."); println!(""); } fn args_fail(msg: &str) { let mut stderr = io::stderr(); stderr.write_all(msg.as_bytes()).unwrap(); stderr.write_all(b"\n").unwrap(); env::set_exit_status(1); } // Always use CPU painting on android. #[cfg(target_os="android")] static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; pub fn default_opts() -> Opts { Opts { url: String::new(), paint_threads: 1, gpu_painting: false, tile_size: 512, device_pixels_per_px: None, time_profiler_period: None, mem_profiler_period: None, enable_experimental: false, layout_threads: 1, nonincremental_layout: false, nossl: false, userscripts: None, output_file: None, headless: true, hard_fail: true, bubble_inline_sizes_separately: false, show_debug_borders: false, show_debug_fragment_borders: false, show_debug_parallel_paint: false, show_debug_parallel_layout: false, enable_text_antialiasing: false, trace_layout: false, devtools_port: None, webdriver_port: None, initial_window_size: TypedSize2D(800, 600), user_agent: None, dump_flow_tree: false, dump_display_list: false, dump_display_list_optimized: false, relayout_event: false, validate_display_list_geometry: false, profile_tasks: false, resources_path: None, sniff_mime_types: false, disable_share_style_cache: false, } } pub fn from_cmdline_args(args: &[String]) -> bool { let app_name = args[0].to_string(); let args = args.tail(); let opts = vec!( getopts::optflag("c", "cpu", "CPU painting (default)"), getopts::optflag("g", "gpu", "GPU painting"), getopts::optopt("o", "output", "Output file", "output.png"), getopts::optopt("s", "size", "Size of tiles", "512"), getopts::optopt("", "device-pixel-ratio", "Device pixels per px", ""), getopts::optflag("e", "experimental", "Enable experimental web features"), getopts::optopt("t", "threads", "Number of paint threads", "1"), getopts::optflagopt("p", "profile", "Profiler flag and output interval", "10"), getopts::optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"), getopts::optflag("x", "exit", "Exit after load flag"), getopts::optopt("y", "layout-threads", "Number of threads to use for layout", "1"), getopts::optflag("i", "nonincremental-layout", "Enable to turn off incremental layout."), getopts::optflag("", "no-ssl", "Disables ssl certificate verification."), getopts::optflagopt("", "userscripts", "Uses userscripts in resources/user-agent-js, or a specified full path",""), getopts::optflag("z", "headless", "Headless mode"), getopts::optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure"), getopts::optflagopt("", "devtools", "Start remote devtools server on port", "6000"), getopts::optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"), getopts::optopt("", "resolution", "Set window resolution.", "800x600"), getopts::optopt("u", "user-agent", "Set custom user agent string", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"), getopts::optopt("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""), getopts::optflag("h", "help", "Print this message"), getopts::optopt("r", "render-api", "Set the rendering API to use", "gl|mesa"), getopts::optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"), getopts::optflag("", "sniff-mime-types", "Enable MIME sniffing"), ); let opt_match = match getopts::getopts(args, &opts) { Ok(m) => m, Err(f) => { args_fail(&f.to_string()); return false; } }; if opt_match.opt_present("h") || opt_match.opt_present("help") { print_usage(&app_name, &opts); return false; }; let debug_string = match opt_match.opt_str("Z") { Some(string) => string, None => String::new() }; let mut debug_options = HashSet::new(); for split in debug_string.split(',') { debug_options.insert(split.clone()); } if debug_options.contains(&"help") { print_debug_usage(&app_name); return false; } let url = if opt_match.free.is_empty() { print_usage(&app_name, &opts); args_fail("servo asks that you provide a URL"); return false; } else { opt_match.free[0].clone() }; let tile_size: usize = match opt_match.opt_str("s") { Some(tile_size_str) => tile_size_str.parse().unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| ScaleFactor::new(dppx_str.parse().unwrap()) ); let mut paint_threads: usize = match opt_match.opt_str("t") { Some(paint_threads_str) => paint_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; // If only the flag is present, default to a 5 second period for both profilers. let time_profiler_period = opt_match.opt_default("p", "5").map(|period| { period.parse().unwrap() }); let mem_profiler_period = opt_match.opt_default("m", "5").map(|period| { period.parse().unwrap() }); let gpu_painting =!FORCE_CPU_PAINTING && opt_match.opt_present("g"); let mut layout_threads: usize = match opt_match.opt_str("y") { Some(layout_threads_str) => layout_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; let nonincremental_layout = opt_match.opt_present("i"); let nossl = opt_match.opt_present("no-ssl"); let mut bubble_inline_sizes_separately = debug_options.contains(&"bubble-widths"); let trace_layout = debug_options.contains(&"trace-layout"); if trace_layout { paint_threads = 1; layout_threads = 1; bubble_inline_sizes_separately = true; } let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { port.parse().unwrap() }); let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| { port.parse().unwrap() }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { let res: Vec<u32> = res_string.split('x').map(|r| r.parse().unwrap()).collect(); TypedSize2D(res[0], res[1]) } None => { TypedSize2D(800, 600) } }; let opts = Opts { url: url, paint_threads: paint_threads, gpu_painting: gpu_painting, tile_size: tile_size, device_pixels_per_px: device_pixels_per_px, time_profiler_period: time_profiler_period, mem_profiler_period: mem_profiler_period, enable_experimental: opt_match.opt_present("e"), layout_threads: layout_threads, nonincremental_layout: nonincremental_layout, nossl: nossl, userscripts: opt_match.opt_default("userscripts", ""), output_file: opt_match.opt_str("o"), headless: opt_match.opt_present("z"), hard_fail: opt_match.opt_present("f"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_tasks: debug_options.contains(&"profile-tasks"), trace_layout: trace_layout, devtools_port: devtools_port, webdriver_port: webdriver_port, initial_window_size: initial_window_size, user_agent: opt_match.opt_str("u"), show_debug_borders: debug_options.contains(&"show-compositor-borders"), show_debug_fragment_borders: debug_options.contains(&"show-fragment-borders"), show_debug_parallel_paint: debug_options.contains(&"show-parallel-paint"), show_debug_parallel_layout: debug_options.contains(&"show-parallel-layout"), enable_text_antialiasing:!debug_options.contains(&"disable-text-aa"), dump_flow_tree: debug_options.contains(&"dump-flow-tree"), dump_display_list: debug_options.contains(&"dump-display-list"), dump_display_list_optimized: debug_options.contains(&"dump-display-list-optimized"), relayout_event: debug_options.contains(&"relayout-event"), validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"), resources_path: opt_match.opt_str("resources-path"), sniff_mime_types: opt_match.opt_present("sniff-mime-types"), disable_share_style_cache: debug_options.contains(&"disable-share-style-cache"), }; set_opts(opts); true } static mut EXPERIMENTAL_ENABLED: bool = false; pub fn set_experimental_enabled(new_value: bool) { unsafe { EXPERIMENTAL_ENABLED = new_value; } } pub fn experimental_enabled() -> bool { unsafe { EXPERIMENTAL_ENABLED } } // Make Opts available globally. This saves having to clone and pass // opts everywhere it is used, which gets particularly cumbersome // when passing through the DOM structures. static mut OPTIONS: *mut Opts = 0 as *mut Opts; pub fn set_opts(opts: Opts) { unsafe { let box_opts = box opts; OPTIONS = mem::transmute(box_opts); } }
// set of options. This is mostly useful for unit tests that // run through a code path which queries the cmd line options. if OPTIONS == ptr::null_mut() { set_opts(default_opts()); } mem::transmute(OPTIONS) } }
#[inline] pub fn get<'a>() -> &'a Opts { unsafe { // If code attempts to retrieve the options and they haven't // been set by the platform init code, just return a default
random_line_split
opts.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/. */ //! Configuration options for a single run of the servo application. Created //! from command line arguments. use geometry::ScreenPx; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use layers::geometry::DevicePixel; use getopts; use std::collections::HashSet; use std::cmp; use std::env; use std::io::{self, Write}; use std::mem; use std::ptr; use std::rt; /// Global flags for Servo, currently set on the command line. #[derive(Clone)] pub struct Opts { /// The initial URL to load. pub url: String, /// How many threads to use for CPU painting (`-t`). /// /// Note that painting is sequentialized when using GPU painting. pub paint_threads: usize, /// True to use GPU painting via Skia-GL, false to use CPU painting via Skia (`-g`). Note that /// compositing is always done on the GPU. pub gpu_painting: bool, /// The maximum size of each tile in pixels (`-s`). pub tile_size: usize, /// The ratio of device pixels per px at the default scale. If unspecified, will use the /// platform default setting. pub device_pixels_per_px: Option<ScaleFactor<ScreenPx, DevicePixel, f32>>, /// `None` to disable the time profiler or `Some` with an interval in seconds to enable it and /// cause it to produce output on that interval (`-p`). pub time_profiler_period: Option<f64>, /// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option<f64>, /// Enable experimental web features (`-e`). pub enable_experimental: bool, /// The number of threads to use for layout (`-y`). Defaults to 1, which results in a recursive /// sequential algorithm. pub layout_threads: usize, pub nonincremental_layout: bool, pub nossl: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded pub userscripts: Option<String>, pub output_file: Option<String>, pub headless: bool, pub hard_fail: bool, /// True if we should bubble intrinsic widths sequentially (`-b`). If this is true, then /// intrinsic widths are computed as a separate pass instead of during flow construction. You /// may wish to turn this flag on in order to benchmark style recalculation against other /// browser engines. pub bubble_inline_sizes_separately: bool, /// True if we should show borders on all layers and tiles for /// debugging purposes (`--show-debug-borders`). pub show_debug_borders: bool, /// True if we should show borders on all fragments for debugging purposes /// (`--show-debug-fragment-borders`). pub show_debug_fragment_borders: bool, /// True if we should paint tiles with overlays based on which thread painted them. pub show_debug_parallel_paint: bool, /// True if we should paint borders around flows based on which thread painted them. pub show_debug_parallel_layout: bool, /// If set with --disable-text-aa, disable antialiasing on fonts. This is primarily useful for reftests /// where pixel perfect results are required when using fonts such as the Ahem /// font for layout tests. pub enable_text_antialiasing: bool, /// True if each step of layout is traced to an external JSON file /// for debugging purposes. Settings this implies sequential layout /// and paint. pub trace_layout: bool, /// If true, instrument the runtime for each task created and dump /// that information to a JSON file that can be viewed in the task /// profile viewer. pub profile_tasks: bool, /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option<u16>, /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to /// remote WebDriver commands. pub webdriver_port: Option<u16>, /// The initial requested size of the window. pub initial_window_size: TypedSize2D<ScreenPx, u32>, /// An optional string allowing the user agent to be set for testing. pub user_agent: Option<String>, /// Dumps the flow tree after a layout. pub dump_flow_tree: bool, /// Dumps the display list after a layout. pub dump_display_list: bool, /// Dumps the display list after optimization (post layout, at painting time). pub dump_display_list_optimized: bool, /// Emits notifications when there is a relayout. pub relayout_event: bool, /// Whether to show an error when display list geometry escapes flow overflow regions. pub validate_display_list_geometry: bool, /// A specific path to find required resources (such as user-agent.css). pub resources_path: Option<String>, /// Whether MIME sniffing should be used pub sniff_mime_types: bool, /// Whether Style Sharing Cache is used pub disable_share_style_cache: bool, } fn print_usage(app: &str, opts: &[getopts::OptGroup]) { let message = format!("Usage: {} [ options... ] [URL]\n\twhere options include", app); println!("{}", getopts::usage(&message, opts)); } pub fn print_debug_usage(app: &str) { fn print_option(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths separately like other engines."); print_option("disable-text-aa", "Disable antialiasing of rendered text."); print_option("dump-flow-tree", "Print the flow tree after each layout."); print_option("dump-display-list", "Print the display list after each layout."); print_option("dump-display-list-optimized", "Print optimized display list (at paint time)."); print_option("relayout-event", "Print notifications when there is a relayout."); print_option("profile-tasks", "Instrument each task, writing the output to a file."); print_option("show-compositor-borders", "Paint borders along layer and tile boundaries."); print_option("show-fragment-borders", "Paint borders along fragment boundaries."); print_option("show-parallel-paint", "Overlay tiles with colors showing which thread painted them."); print_option("show-parallel-layout", "Mark which thread laid each flow out with colors."); print_option("trace-layout", "Write layout trace to an external file for debugging."); print_option("validate-display-list-geometry", "Display an error when display list geometry escapes overflow region."); print_option("disable-share-style-cache", "Disable the style sharing cache."); println!(""); } fn args_fail(msg: &str)
// Always use CPU painting on android. #[cfg(target_os="android")] static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; pub fn default_opts() -> Opts { Opts { url: String::new(), paint_threads: 1, gpu_painting: false, tile_size: 512, device_pixels_per_px: None, time_profiler_period: None, mem_profiler_period: None, enable_experimental: false, layout_threads: 1, nonincremental_layout: false, nossl: false, userscripts: None, output_file: None, headless: true, hard_fail: true, bubble_inline_sizes_separately: false, show_debug_borders: false, show_debug_fragment_borders: false, show_debug_parallel_paint: false, show_debug_parallel_layout: false, enable_text_antialiasing: false, trace_layout: false, devtools_port: None, webdriver_port: None, initial_window_size: TypedSize2D(800, 600), user_agent: None, dump_flow_tree: false, dump_display_list: false, dump_display_list_optimized: false, relayout_event: false, validate_display_list_geometry: false, profile_tasks: false, resources_path: None, sniff_mime_types: false, disable_share_style_cache: false, } } pub fn from_cmdline_args(args: &[String]) -> bool { let app_name = args[0].to_string(); let args = args.tail(); let opts = vec!( getopts::optflag("c", "cpu", "CPU painting (default)"), getopts::optflag("g", "gpu", "GPU painting"), getopts::optopt("o", "output", "Output file", "output.png"), getopts::optopt("s", "size", "Size of tiles", "512"), getopts::optopt("", "device-pixel-ratio", "Device pixels per px", ""), getopts::optflag("e", "experimental", "Enable experimental web features"), getopts::optopt("t", "threads", "Number of paint threads", "1"), getopts::optflagopt("p", "profile", "Profiler flag and output interval", "10"), getopts::optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"), getopts::optflag("x", "exit", "Exit after load flag"), getopts::optopt("y", "layout-threads", "Number of threads to use for layout", "1"), getopts::optflag("i", "nonincremental-layout", "Enable to turn off incremental layout."), getopts::optflag("", "no-ssl", "Disables ssl certificate verification."), getopts::optflagopt("", "userscripts", "Uses userscripts in resources/user-agent-js, or a specified full path",""), getopts::optflag("z", "headless", "Headless mode"), getopts::optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure"), getopts::optflagopt("", "devtools", "Start remote devtools server on port", "6000"), getopts::optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"), getopts::optopt("", "resolution", "Set window resolution.", "800x600"), getopts::optopt("u", "user-agent", "Set custom user agent string", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"), getopts::optopt("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""), getopts::optflag("h", "help", "Print this message"), getopts::optopt("r", "render-api", "Set the rendering API to use", "gl|mesa"), getopts::optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"), getopts::optflag("", "sniff-mime-types", "Enable MIME sniffing"), ); let opt_match = match getopts::getopts(args, &opts) { Ok(m) => m, Err(f) => { args_fail(&f.to_string()); return false; } }; if opt_match.opt_present("h") || opt_match.opt_present("help") { print_usage(&app_name, &opts); return false; }; let debug_string = match opt_match.opt_str("Z") { Some(string) => string, None => String::new() }; let mut debug_options = HashSet::new(); for split in debug_string.split(',') { debug_options.insert(split.clone()); } if debug_options.contains(&"help") { print_debug_usage(&app_name); return false; } let url = if opt_match.free.is_empty() { print_usage(&app_name, &opts); args_fail("servo asks that you provide a URL"); return false; } else { opt_match.free[0].clone() }; let tile_size: usize = match opt_match.opt_str("s") { Some(tile_size_str) => tile_size_str.parse().unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| ScaleFactor::new(dppx_str.parse().unwrap()) ); let mut paint_threads: usize = match opt_match.opt_str("t") { Some(paint_threads_str) => paint_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; // If only the flag is present, default to a 5 second period for both profilers. let time_profiler_period = opt_match.opt_default("p", "5").map(|period| { period.parse().unwrap() }); let mem_profiler_period = opt_match.opt_default("m", "5").map(|period| { period.parse().unwrap() }); let gpu_painting =!FORCE_CPU_PAINTING && opt_match.opt_present("g"); let mut layout_threads: usize = match opt_match.opt_str("y") { Some(layout_threads_str) => layout_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; let nonincremental_layout = opt_match.opt_present("i"); let nossl = opt_match.opt_present("no-ssl"); let mut bubble_inline_sizes_separately = debug_options.contains(&"bubble-widths"); let trace_layout = debug_options.contains(&"trace-layout"); if trace_layout { paint_threads = 1; layout_threads = 1; bubble_inline_sizes_separately = true; } let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { port.parse().unwrap() }); let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| { port.parse().unwrap() }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { let res: Vec<u32> = res_string.split('x').map(|r| r.parse().unwrap()).collect(); TypedSize2D(res[0], res[1]) } None => { TypedSize2D(800, 600) } }; let opts = Opts { url: url, paint_threads: paint_threads, gpu_painting: gpu_painting, tile_size: tile_size, device_pixels_per_px: device_pixels_per_px, time_profiler_period: time_profiler_period, mem_profiler_period: mem_profiler_period, enable_experimental: opt_match.opt_present("e"), layout_threads: layout_threads, nonincremental_layout: nonincremental_layout, nossl: nossl, userscripts: opt_match.opt_default("userscripts", ""), output_file: opt_match.opt_str("o"), headless: opt_match.opt_present("z"), hard_fail: opt_match.opt_present("f"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_tasks: debug_options.contains(&"profile-tasks"), trace_layout: trace_layout, devtools_port: devtools_port, webdriver_port: webdriver_port, initial_window_size: initial_window_size, user_agent: opt_match.opt_str("u"), show_debug_borders: debug_options.contains(&"show-compositor-borders"), show_debug_fragment_borders: debug_options.contains(&"show-fragment-borders"), show_debug_parallel_paint: debug_options.contains(&"show-parallel-paint"), show_debug_parallel_layout: debug_options.contains(&"show-parallel-layout"), enable_text_antialiasing:!debug_options.contains(&"disable-text-aa"), dump_flow_tree: debug_options.contains(&"dump-flow-tree"), dump_display_list: debug_options.contains(&"dump-display-list"), dump_display_list_optimized: debug_options.contains(&"dump-display-list-optimized"), relayout_event: debug_options.contains(&"relayout-event"), validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"), resources_path: opt_match.opt_str("resources-path"), sniff_mime_types: opt_match.opt_present("sniff-mime-types"), disable_share_style_cache: debug_options.contains(&"disable-share-style-cache"), }; set_opts(opts); true } static mut EXPERIMENTAL_ENABLED: bool = false; pub fn set_experimental_enabled(new_value: bool) { unsafe { EXPERIMENTAL_ENABLED = new_value; } } pub fn experimental_enabled() -> bool { unsafe { EXPERIMENTAL_ENABLED } } // Make Opts available globally. This saves having to clone and pass // opts everywhere it is used, which gets particularly cumbersome // when passing through the DOM structures. static mut OPTIONS: *mut Opts = 0 as *mut Opts; pub fn set_opts(opts: Opts) { unsafe { let box_opts = box opts; OPTIONS = mem::transmute(box_opts); } } #[inline] pub fn get<'a>() -> &'a Opts { unsafe { // If code attempts to retrieve the options and they haven't // been set by the platform init code, just return a default // set of options. This is mostly useful for unit tests that // run through a code path which queries the cmd line options. if OPTIONS == ptr::null_mut() { set_opts(default_opts()); } mem::transmute(OPTIONS) } }
{ let mut stderr = io::stderr(); stderr.write_all(msg.as_bytes()).unwrap(); stderr.write_all(b"\n").unwrap(); env::set_exit_status(1); }
identifier_body
opts.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/. */ //! Configuration options for a single run of the servo application. Created //! from command line arguments. use geometry::ScreenPx; use geom::scale_factor::ScaleFactor; use geom::size::TypedSize2D; use layers::geometry::DevicePixel; use getopts; use std::collections::HashSet; use std::cmp; use std::env; use std::io::{self, Write}; use std::mem; use std::ptr; use std::rt; /// Global flags for Servo, currently set on the command line. #[derive(Clone)] pub struct Opts { /// The initial URL to load. pub url: String, /// How many threads to use for CPU painting (`-t`). /// /// Note that painting is sequentialized when using GPU painting. pub paint_threads: usize, /// True to use GPU painting via Skia-GL, false to use CPU painting via Skia (`-g`). Note that /// compositing is always done on the GPU. pub gpu_painting: bool, /// The maximum size of each tile in pixels (`-s`). pub tile_size: usize, /// The ratio of device pixels per px at the default scale. If unspecified, will use the /// platform default setting. pub device_pixels_per_px: Option<ScaleFactor<ScreenPx, DevicePixel, f32>>, /// `None` to disable the time profiler or `Some` with an interval in seconds to enable it and /// cause it to produce output on that interval (`-p`). pub time_profiler_period: Option<f64>, /// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option<f64>, /// Enable experimental web features (`-e`). pub enable_experimental: bool, /// The number of threads to use for layout (`-y`). Defaults to 1, which results in a recursive /// sequential algorithm. pub layout_threads: usize, pub nonincremental_layout: bool, pub nossl: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded pub userscripts: Option<String>, pub output_file: Option<String>, pub headless: bool, pub hard_fail: bool, /// True if we should bubble intrinsic widths sequentially (`-b`). If this is true, then /// intrinsic widths are computed as a separate pass instead of during flow construction. You /// may wish to turn this flag on in order to benchmark style recalculation against other /// browser engines. pub bubble_inline_sizes_separately: bool, /// True if we should show borders on all layers and tiles for /// debugging purposes (`--show-debug-borders`). pub show_debug_borders: bool, /// True if we should show borders on all fragments for debugging purposes /// (`--show-debug-fragment-borders`). pub show_debug_fragment_borders: bool, /// True if we should paint tiles with overlays based on which thread painted them. pub show_debug_parallel_paint: bool, /// True if we should paint borders around flows based on which thread painted them. pub show_debug_parallel_layout: bool, /// If set with --disable-text-aa, disable antialiasing on fonts. This is primarily useful for reftests /// where pixel perfect results are required when using fonts such as the Ahem /// font for layout tests. pub enable_text_antialiasing: bool, /// True if each step of layout is traced to an external JSON file /// for debugging purposes. Settings this implies sequential layout /// and paint. pub trace_layout: bool, /// If true, instrument the runtime for each task created and dump /// that information to a JSON file that can be viewed in the task /// profile viewer. pub profile_tasks: bool, /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option<u16>, /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to /// remote WebDriver commands. pub webdriver_port: Option<u16>, /// The initial requested size of the window. pub initial_window_size: TypedSize2D<ScreenPx, u32>, /// An optional string allowing the user agent to be set for testing. pub user_agent: Option<String>, /// Dumps the flow tree after a layout. pub dump_flow_tree: bool, /// Dumps the display list after a layout. pub dump_display_list: bool, /// Dumps the display list after optimization (post layout, at painting time). pub dump_display_list_optimized: bool, /// Emits notifications when there is a relayout. pub relayout_event: bool, /// Whether to show an error when display list geometry escapes flow overflow regions. pub validate_display_list_geometry: bool, /// A specific path to find required resources (such as user-agent.css). pub resources_path: Option<String>, /// Whether MIME sniffing should be used pub sniff_mime_types: bool, /// Whether Style Sharing Cache is used pub disable_share_style_cache: bool, } fn print_usage(app: &str, opts: &[getopts::OptGroup]) { let message = format!("Usage: {} [ options... ] [URL]\n\twhere options include", app); println!("{}", getopts::usage(&message, opts)); } pub fn print_debug_usage(app: &str) { fn print_option(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths separately like other engines."); print_option("disable-text-aa", "Disable antialiasing of rendered text."); print_option("dump-flow-tree", "Print the flow tree after each layout."); print_option("dump-display-list", "Print the display list after each layout."); print_option("dump-display-list-optimized", "Print optimized display list (at paint time)."); print_option("relayout-event", "Print notifications when there is a relayout."); print_option("profile-tasks", "Instrument each task, writing the output to a file."); print_option("show-compositor-borders", "Paint borders along layer and tile boundaries."); print_option("show-fragment-borders", "Paint borders along fragment boundaries."); print_option("show-parallel-paint", "Overlay tiles with colors showing which thread painted them."); print_option("show-parallel-layout", "Mark which thread laid each flow out with colors."); print_option("trace-layout", "Write layout trace to an external file for debugging."); print_option("validate-display-list-geometry", "Display an error when display list geometry escapes overflow region."); print_option("disable-share-style-cache", "Disable the style sharing cache."); println!(""); } fn args_fail(msg: &str) { let mut stderr = io::stderr(); stderr.write_all(msg.as_bytes()).unwrap(); stderr.write_all(b"\n").unwrap(); env::set_exit_status(1); } // Always use CPU painting on android. #[cfg(target_os="android")] static FORCE_CPU_PAINTING: bool = true; #[cfg(not(target_os="android"))] static FORCE_CPU_PAINTING: bool = false; pub fn default_opts() -> Opts { Opts { url: String::new(), paint_threads: 1, gpu_painting: false, tile_size: 512, device_pixels_per_px: None, time_profiler_period: None, mem_profiler_period: None, enable_experimental: false, layout_threads: 1, nonincremental_layout: false, nossl: false, userscripts: None, output_file: None, headless: true, hard_fail: true, bubble_inline_sizes_separately: false, show_debug_borders: false, show_debug_fragment_borders: false, show_debug_parallel_paint: false, show_debug_parallel_layout: false, enable_text_antialiasing: false, trace_layout: false, devtools_port: None, webdriver_port: None, initial_window_size: TypedSize2D(800, 600), user_agent: None, dump_flow_tree: false, dump_display_list: false, dump_display_list_optimized: false, relayout_event: false, validate_display_list_geometry: false, profile_tasks: false, resources_path: None, sniff_mime_types: false, disable_share_style_cache: false, } } pub fn from_cmdline_args(args: &[String]) -> bool { let app_name = args[0].to_string(); let args = args.tail(); let opts = vec!( getopts::optflag("c", "cpu", "CPU painting (default)"), getopts::optflag("g", "gpu", "GPU painting"), getopts::optopt("o", "output", "Output file", "output.png"), getopts::optopt("s", "size", "Size of tiles", "512"), getopts::optopt("", "device-pixel-ratio", "Device pixels per px", ""), getopts::optflag("e", "experimental", "Enable experimental web features"), getopts::optopt("t", "threads", "Number of paint threads", "1"), getopts::optflagopt("p", "profile", "Profiler flag and output interval", "10"), getopts::optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"), getopts::optflag("x", "exit", "Exit after load flag"), getopts::optopt("y", "layout-threads", "Number of threads to use for layout", "1"), getopts::optflag("i", "nonincremental-layout", "Enable to turn off incremental layout."), getopts::optflag("", "no-ssl", "Disables ssl certificate verification."), getopts::optflagopt("", "userscripts", "Uses userscripts in resources/user-agent-js, or a specified full path",""), getopts::optflag("z", "headless", "Headless mode"), getopts::optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure"), getopts::optflagopt("", "devtools", "Start remote devtools server on port", "6000"), getopts::optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"), getopts::optopt("", "resolution", "Set window resolution.", "800x600"), getopts::optopt("u", "user-agent", "Set custom user agent string", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"), getopts::optopt("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""), getopts::optflag("h", "help", "Print this message"), getopts::optopt("r", "render-api", "Set the rendering API to use", "gl|mesa"), getopts::optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"), getopts::optflag("", "sniff-mime-types", "Enable MIME sniffing"), ); let opt_match = match getopts::getopts(args, &opts) { Ok(m) => m, Err(f) => { args_fail(&f.to_string()); return false; } }; if opt_match.opt_present("h") || opt_match.opt_present("help") { print_usage(&app_name, &opts); return false; }; let debug_string = match opt_match.opt_str("Z") { Some(string) => string, None => String::new() }; let mut debug_options = HashSet::new(); for split in debug_string.split(',') { debug_options.insert(split.clone()); } if debug_options.contains(&"help") { print_debug_usage(&app_name); return false; } let url = if opt_match.free.is_empty() { print_usage(&app_name, &opts); args_fail("servo asks that you provide a URL"); return false; } else { opt_match.free[0].clone() }; let tile_size: usize = match opt_match.opt_str("s") { Some(tile_size_str) => tile_size_str.parse().unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| ScaleFactor::new(dppx_str.parse().unwrap()) ); let mut paint_threads: usize = match opt_match.opt_str("t") { Some(paint_threads_str) => paint_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; // If only the flag is present, default to a 5 second period for both profilers. let time_profiler_period = opt_match.opt_default("p", "5").map(|period| { period.parse().unwrap() }); let mem_profiler_period = opt_match.opt_default("m", "5").map(|period| { period.parse().unwrap() }); let gpu_painting =!FORCE_CPU_PAINTING && opt_match.opt_present("g"); let mut layout_threads: usize = match opt_match.opt_str("y") { Some(layout_threads_str) => layout_threads_str.parse().unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; let nonincremental_layout = opt_match.opt_present("i"); let nossl = opt_match.opt_present("no-ssl"); let mut bubble_inline_sizes_separately = debug_options.contains(&"bubble-widths"); let trace_layout = debug_options.contains(&"trace-layout"); if trace_layout
let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { port.parse().unwrap() }); let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| { port.parse().unwrap() }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { let res: Vec<u32> = res_string.split('x').map(|r| r.parse().unwrap()).collect(); TypedSize2D(res[0], res[1]) } None => { TypedSize2D(800, 600) } }; let opts = Opts { url: url, paint_threads: paint_threads, gpu_painting: gpu_painting, tile_size: tile_size, device_pixels_per_px: device_pixels_per_px, time_profiler_period: time_profiler_period, mem_profiler_period: mem_profiler_period, enable_experimental: opt_match.opt_present("e"), layout_threads: layout_threads, nonincremental_layout: nonincremental_layout, nossl: nossl, userscripts: opt_match.opt_default("userscripts", ""), output_file: opt_match.opt_str("o"), headless: opt_match.opt_present("z"), hard_fail: opt_match.opt_present("f"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_tasks: debug_options.contains(&"profile-tasks"), trace_layout: trace_layout, devtools_port: devtools_port, webdriver_port: webdriver_port, initial_window_size: initial_window_size, user_agent: opt_match.opt_str("u"), show_debug_borders: debug_options.contains(&"show-compositor-borders"), show_debug_fragment_borders: debug_options.contains(&"show-fragment-borders"), show_debug_parallel_paint: debug_options.contains(&"show-parallel-paint"), show_debug_parallel_layout: debug_options.contains(&"show-parallel-layout"), enable_text_antialiasing:!debug_options.contains(&"disable-text-aa"), dump_flow_tree: debug_options.contains(&"dump-flow-tree"), dump_display_list: debug_options.contains(&"dump-display-list"), dump_display_list_optimized: debug_options.contains(&"dump-display-list-optimized"), relayout_event: debug_options.contains(&"relayout-event"), validate_display_list_geometry: debug_options.contains(&"validate-display-list-geometry"), resources_path: opt_match.opt_str("resources-path"), sniff_mime_types: opt_match.opt_present("sniff-mime-types"), disable_share_style_cache: debug_options.contains(&"disable-share-style-cache"), }; set_opts(opts); true } static mut EXPERIMENTAL_ENABLED: bool = false; pub fn set_experimental_enabled(new_value: bool) { unsafe { EXPERIMENTAL_ENABLED = new_value; } } pub fn experimental_enabled() -> bool { unsafe { EXPERIMENTAL_ENABLED } } // Make Opts available globally. This saves having to clone and pass // opts everywhere it is used, which gets particularly cumbersome // when passing through the DOM structures. static mut OPTIONS: *mut Opts = 0 as *mut Opts; pub fn set_opts(opts: Opts) { unsafe { let box_opts = box opts; OPTIONS = mem::transmute(box_opts); } } #[inline] pub fn get<'a>() -> &'a Opts { unsafe { // If code attempts to retrieve the options and they haven't // been set by the platform init code, just return a default // set of options. This is mostly useful for unit tests that // run through a code path which queries the cmd line options. if OPTIONS == ptr::null_mut() { set_opts(default_opts()); } mem::transmute(OPTIONS) } }
{ paint_threads = 1; layout_threads = 1; bubble_inline_sizes_separately = true; }
conditional_block
build.rs
use std::io::Error; // Grpc related files used by tonic are generated here. Those files re-generate for each build // so it's up to date. // // Grpc related files used by grpcio are maintained at src/proto/grpcio. tests/grpc_build.rs makes // sure they are up to date. fn main() -> Result<(), Error>
Ok(()) }
{ #[cfg(feature = "gen-tonic")] tonic_build::configure() .build_server(cfg!(feature = "build-server")) .build_client(cfg!(feature = "build-client")) .format(false) .compile( &[ "src/proto/opentelemetry-proto/opentelemetry/proto/common/v1/common.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/resource/v1/resource.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/trace/v1/trace.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/trace/v1/trace_config.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/trace/v1/trace_service.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/metrics/v1/metrics.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/logs/v1/logs.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/logs/v1/logs_service.proto", ], &["src/proto/opentelemetry-proto"], )?;
identifier_body
build.rs
use std::io::Error; // Grpc related files used by tonic are generated here. Those files re-generate for each build // so it's up to date. // // Grpc related files used by grpcio are maintained at src/proto/grpcio. tests/grpc_build.rs makes // sure they are up to date. fn
() -> Result<(), Error> { #[cfg(feature = "gen-tonic")] tonic_build::configure() .build_server(cfg!(feature = "build-server")) .build_client(cfg!(feature = "build-client")) .format(false) .compile( &[ "src/proto/opentelemetry-proto/opentelemetry/proto/common/v1/common.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/resource/v1/resource.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/trace/v1/trace.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/trace/v1/trace_config.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/trace/v1/trace_service.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/metrics/v1/metrics.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/logs/v1/logs.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/logs/v1/logs_service.proto", ], &["src/proto/opentelemetry-proto"], )?; Ok(()) }
main
identifier_name
build.rs
// Grpc related files used by tonic are generated here. Those files re-generate for each build // so it's up to date. // // Grpc related files used by grpcio are maintained at src/proto/grpcio. tests/grpc_build.rs makes // sure they are up to date. fn main() -> Result<(), Error> { #[cfg(feature = "gen-tonic")] tonic_build::configure() .build_server(cfg!(feature = "build-server")) .build_client(cfg!(feature = "build-client")) .format(false) .compile( &[ "src/proto/opentelemetry-proto/opentelemetry/proto/common/v1/common.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/resource/v1/resource.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/trace/v1/trace.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/trace/v1/trace_config.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/trace/v1/trace_service.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/metrics/v1/metrics.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/metrics/v1/metrics_service.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/logs/v1/logs.proto", "src/proto/opentelemetry-proto/opentelemetry/proto/collector/logs/v1/logs_service.proto", ], &["src/proto/opentelemetry-proto"], )?; Ok(()) }
use std::io::Error;
random_line_split
docopt_macro_use_case.rs
// stolen from here: https://github.com/docopt/docopt.rs #![feature(plugin)] #![plugin(docopt_macros)] extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; docopt!(Args derive Debug, " Naval Fate. Usage: naval_fate.py ship new <name>... naval_fate.py ship <name> move <x> <y> [--speed=<kn>] naval_fate.py ship shoot <x> <y> naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting] naval_fate.py (-h | --help) naval_fate.py --version Options: -h --help Show this screen. --version Show version. --speed=<kn> Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. "); fn
() { let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit()); println!("{:?}", args); }
main
identifier_name
docopt_macro_use_case.rs
// stolen from here: https://github.com/docopt/docopt.rs #![feature(plugin)] #![plugin(docopt_macros)] extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; docopt!(Args derive Debug, " Naval Fate. Usage: naval_fate.py ship new <name>... naval_fate.py ship <name> move <x> <y> [--speed=<kn>] naval_fate.py ship shoot <x> <y> naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting] naval_fate.py (-h | --help) naval_fate.py --version Options: -h --help Show this screen. --version Show version. --speed=<kn> Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. "); fn main()
{ let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit()); println!("{:?}", args); }
identifier_body
docopt_macro_use_case.rs
// stolen from here: https://github.com/docopt/docopt.rs #![feature(plugin)] #![plugin(docopt_macros)] extern crate rustc_serialize; extern crate docopt; use docopt::Docopt; docopt!(Args derive Debug, " Naval Fate. Usage: naval_fate.py ship new <name>... naval_fate.py ship <name> move <x> <y> [--speed=<kn>] naval_fate.py ship shoot <x> <y> naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.py (-h | --help) naval_fate.py --version Options: -h --help Show this screen. --version Show version. --speed=<kn> Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. "); fn main() { let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit()); println!("{:?}", args); }
random_line_split
lib.rs
//! A simple crate for executing work on a thread pool, and getting back a //! future. //! //! This crate provides a simple thread pool abstraction for running work //! externally from the current thread that's running. An instance of `Future` //! is handed back to represent that the work may be done later, and further //! computations can be chained along with it as well. //! //! ```rust //! extern crate futures; //! extern crate futures_cpupool; //! //! use futures::Future; //! use futures_cpupool::CpuPool; //! //! # fn long_running_future(a: u32) -> futures::future::BoxFuture<u32, ()> { //! # futures::future::result(Ok(a)).boxed() //! # } //! # fn main() { //! //! // Create a worker thread pool with four threads //! let pool = CpuPool::new(4); //! //! // Execute some work on the thread pool, optionally closing over data. //! let a = pool.spawn(long_running_future(2)); //! let b = pool.spawn(long_running_future(100)); //! //! // Express some further computation once the work is completed on the thread //! // pool. //! let c = a.join(b).map(|(a, b)| a + b).wait().unwrap(); //! //! // Print out the result //! println!("{:?}", c); //! # } //! ``` #![deny(missing_docs)] extern crate crossbeam; #[macro_use] extern crate futures; extern crate num_cpus; use std::panic::{self, AssertUnwindSafe}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::thread; use crossbeam::sync::MsQueue; use futures::{IntoFuture, Future, Poll, Async}; use futures::future::lazy;
/// This thread pool will hand out futures representing the completed work /// that happens on the thread pool itself, and the futures can then be later /// composed with other work as part of an overall computation. /// /// The worker threads associated with a thread pool are kept alive so long as /// there is an open handle to the `CpuPool` or there is work running on them. Once /// all work has been drained and all references have gone away the worker /// threads will be shut down. /// /// Currently `CpuPool` implements `Clone` which just clones a new reference to /// the underlying thread pool. /// /// **Note:** if you use CpuPool inside a library it's better accept a /// `Builder` object for thread configuration rather than configuring just /// pool size. This not only future proof for other settings but also allows /// user to attach monitoring tools to lifecycle hooks. pub struct CpuPool { inner: Arc<Inner>, } /// Thread pool configuration object /// /// Builder starts with a number of workers equal to the number /// of CPUs on the host. But you can change it until you call `create()`. pub struct Builder { pool_size: usize, name_prefix: Option<String>, after_start: Option<Arc<Fn() + Send + Sync>>, before_stop: Option<Arc<Fn() + Send + Sync>>, } struct MySender<F, T> { fut: F, tx: Option<Sender<T>>, keep_running_flag: Arc<AtomicBool>, } fn _assert() { fn _assert_send<T: Send>() {} fn _assert_sync<T: Sync>() {} _assert_send::<CpuPool>(); _assert_sync::<CpuPool>(); } struct Inner { queue: MsQueue<Message>, cnt: AtomicUsize, size: usize, after_start: Option<Arc<Fn() + Send + Sync>>, before_stop: Option<Arc<Fn() + Send + Sync>>, } /// The type of future returned from the `CpuPool::spawn` function, which /// proxies the futures running on the thread pool. /// /// This future will resolve in the same way as the underlying future, and it /// will propagate panics. #[must_use] pub struct CpuFuture<T, E> { inner: Receiver<thread::Result<Result<T, E>>>, keep_running_flag: Arc<AtomicBool>, } enum Message { Run(Run), Close, } impl CpuPool { /// Creates a new thread pool with `size` worker threads associated with it. /// /// The returned handle can use `execute` to run work on this thread pool, /// and clones can be made of it to get multiple references to the same /// thread pool. /// /// This is a shortcut for: /// ```rust /// Builder::new().pool_size(size).create() /// ``` pub fn new(size: usize) -> CpuPool { Builder::new().pool_size(size).create() } /// Creates a new thread pool with a number of workers equal to the number /// of CPUs on the host. /// /// This is a shortcut for: /// ```rust /// Builder::new().create() /// ``` pub fn new_num_cpus() -> CpuPool { Builder::new().create() } /// Spawns a future to run on this thread pool, returning a future /// representing the produced value. /// /// This function will execute the future `f` on the associated thread /// pool, and return a future representing the finished computation. The /// returned future serves as a proxy to the computation that `F` is /// running. /// /// To simply run an arbitrary closure on a thread pool and extract the /// result, you can use the `future::lazy` combinator to defer work to /// executing on the thread pool itself. /// /// Note that if the future `f` panics it will be caught by default and the /// returned future will propagate the panic. That is, panics will not tear /// down the thread pool and will be propagated to the returned future's /// `poll` method if queried. /// /// If the returned future is dropped then this `CpuPool` will attempt to /// cancel the computation, if possible. That is, if the computation is in /// the middle of working, it will be interrupted when possible. pub fn spawn<F>(&self, f: F) -> CpuFuture<F::Item, F::Error> where F: Future + Send +'static, F::Item: Send +'static, F::Error: Send +'static, { let (tx, rx) = channel(); let keep_running_flag = Arc::new(AtomicBool::new(false)); // AssertUnwindSafe is used here becuase `Send +'static` is basically // an alias for an implementation of the `UnwindSafe` trait but we can't // express that in the standard library right now. let sender = MySender { fut: AssertUnwindSafe(f).catch_unwind(), tx: Some(tx), keep_running_flag: keep_running_flag.clone(), }; executor::spawn(sender).execute(self.inner.clone()); CpuFuture { inner: rx, keep_running_flag: keep_running_flag.clone() } } /// Spawns a closure on this thread pool. /// /// This function is a convenience wrapper around the `spawn` function above /// for running a closure wrapped in `future::lazy`. It will spawn the /// function `f` provided onto the thread pool, and continue to run the /// future returned by `f` on the thread pool as well. /// /// The returned future will be a handle to the result produced by the /// future that `f` returns. pub fn spawn_fn<F, R>(&self, f: F) -> CpuFuture<R::Item, R::Error> where F: FnOnce() -> R + Send +'static, R: IntoFuture +'static, R::Future: Send +'static, R::Item: Send +'static, R::Error: Send +'static, { self.spawn(lazy(f)) } } fn work(inner: &Inner) { inner.after_start.as_ref().map(|fun| fun()); loop { match inner.queue.pop() { Message::Run(r) => r.run(), Message::Close => break, } } inner.before_stop.as_ref().map(|fun| fun()); } impl Clone for CpuPool { fn clone(&self) -> CpuPool { self.inner.cnt.fetch_add(1, Ordering::Relaxed); CpuPool { inner: self.inner.clone() } } } impl Drop for CpuPool { fn drop(&mut self) { if self.inner.cnt.fetch_sub(1, Ordering::Relaxed) == 1 { for _ in 0..self.inner.size { self.inner.queue.push(Message::Close); } } } } impl Executor for Inner { fn execute(&self, run: Run) { self.queue.push(Message::Run(run)) } } impl<T, E> CpuFuture<T, E> { /// Drop this future without canceling the underlying future. /// /// When `CpuFuture` is dropped, `CpuPool` will try to abort the underlying /// future. This function can be used when user wants to drop but keep /// executing the underlying future. pub fn forget(self) { self.keep_running_flag.store(true, Ordering::SeqCst); } } impl<T: Send +'static, E: Send +'static> Future for CpuFuture<T, E> { type Item = T; type Error = E; fn poll(&mut self) -> Poll<T, E> { match self.inner.poll().expect("shouldn't be canceled") { Async::Ready(Ok(Ok(e))) => Ok(e.into()), Async::Ready(Ok(Err(e))) => Err(e), Async::Ready(Err(e)) => panic::resume_unwind(e), Async::NotReady => Ok(Async::NotReady), } } } impl<F: Future> Future for MySender<F, Result<F::Item, F::Error>> { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { if let Ok(Async::Ready(_)) = self.tx.as_mut().unwrap().poll_cancel() { if!self.keep_running_flag.load(Ordering::SeqCst) { // Cancelled, bail out return Ok(().into()) } } let res = match self.fut.poll() { Ok(Async::Ready(e)) => Ok(e), Ok(Async::NotReady) => return Ok(Async::NotReady), Err(e) => Err(e), }; self.tx.take().unwrap().complete(res); Ok(Async::Ready(())) } } impl Builder { /// Create a builder a number of workers equal to the number /// of CPUs on the host. pub fn new() -> Builder { Builder { pool_size: num_cpus::get(), name_prefix: None, after_start: None, before_stop: None, } } /// Set size of a future CpuPool /// /// The size of a thread pool is the number of worker threads spawned pub fn pool_size(&mut self, size: usize) -> &mut Self { self.pool_size = size; self } /// Set thread name prefix of a future CpuPool /// /// Thread name prefix is used for generating thread names. For example, if prefix is /// `my-pool-`, then threads in the pool will get names like `my-pool-1` etc. pub fn name_prefix<S: Into<String>>(&mut self, name_prefix: S) -> &mut Self { self.name_prefix = Some(name_prefix.into()); self } /// Execute function `f` right after each thread is started but before /// running any jobs on it /// /// This is initially intended for bookkeeping and monitoring uses pub fn after_start<F>(&mut self, f: F) -> &mut Self where F: Fn() + Send + Sync +'static { self.after_start = Some(Arc::new(f)); self } /// Execute function `f` before each worker thread stops /// /// This is initially intended for bookkeeping and monitoring uses pub fn before_stop<F>(&mut self, f: F) -> &mut Self where F: Fn() + Send + Sync +'static { self.before_stop = Some(Arc::new(f)); self } /// Create CpuPool with configured parameters pub fn create(&mut self) -> CpuPool { let pool = CpuPool { inner: Arc::new(Inner { queue: MsQueue::new(), cnt: AtomicUsize::new(1), size: self.pool_size, after_start: self.after_start.clone(), before_stop: self.before_stop.clone(), }), }; assert!(self.pool_size > 0); for counter in 0..self.pool_size { let inner = pool.inner.clone(); let mut thread_builder = thread::Builder::new(); if let Some(ref name_prefix) = self.name_prefix { thread_builder = thread_builder.name(format!("{}{}", name_prefix, counter)); } thread_builder.spawn(move || work(&inner)).unwrap(); } return pool } }
use futures::sync::oneshot::{channel, Sender, Receiver}; use futures::executor::{self, Run, Executor}; /// A thread pool intended to run CPU intensive work. ///
random_line_split
lib.rs
//! A simple crate for executing work on a thread pool, and getting back a //! future. //! //! This crate provides a simple thread pool abstraction for running work //! externally from the current thread that's running. An instance of `Future` //! is handed back to represent that the work may be done later, and further //! computations can be chained along with it as well. //! //! ```rust //! extern crate futures; //! extern crate futures_cpupool; //! //! use futures::Future; //! use futures_cpupool::CpuPool; //! //! # fn long_running_future(a: u32) -> futures::future::BoxFuture<u32, ()> { //! # futures::future::result(Ok(a)).boxed() //! # } //! # fn main() { //! //! // Create a worker thread pool with four threads //! let pool = CpuPool::new(4); //! //! // Execute some work on the thread pool, optionally closing over data. //! let a = pool.spawn(long_running_future(2)); //! let b = pool.spawn(long_running_future(100)); //! //! // Express some further computation once the work is completed on the thread //! // pool. //! let c = a.join(b).map(|(a, b)| a + b).wait().unwrap(); //! //! // Print out the result //! println!("{:?}", c); //! # } //! ``` #![deny(missing_docs)] extern crate crossbeam; #[macro_use] extern crate futures; extern crate num_cpus; use std::panic::{self, AssertUnwindSafe}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::thread; use crossbeam::sync::MsQueue; use futures::{IntoFuture, Future, Poll, Async}; use futures::future::lazy; use futures::sync::oneshot::{channel, Sender, Receiver}; use futures::executor::{self, Run, Executor}; /// A thread pool intended to run CPU intensive work. /// /// This thread pool will hand out futures representing the completed work /// that happens on the thread pool itself, and the futures can then be later /// composed with other work as part of an overall computation. /// /// The worker threads associated with a thread pool are kept alive so long as /// there is an open handle to the `CpuPool` or there is work running on them. Once /// all work has been drained and all references have gone away the worker /// threads will be shut down. /// /// Currently `CpuPool` implements `Clone` which just clones a new reference to /// the underlying thread pool. /// /// **Note:** if you use CpuPool inside a library it's better accept a /// `Builder` object for thread configuration rather than configuring just /// pool size. This not only future proof for other settings but also allows /// user to attach monitoring tools to lifecycle hooks. pub struct CpuPool { inner: Arc<Inner>, } /// Thread pool configuration object /// /// Builder starts with a number of workers equal to the number /// of CPUs on the host. But you can change it until you call `create()`. pub struct Builder { pool_size: usize, name_prefix: Option<String>, after_start: Option<Arc<Fn() + Send + Sync>>, before_stop: Option<Arc<Fn() + Send + Sync>>, } struct MySender<F, T> { fut: F, tx: Option<Sender<T>>, keep_running_flag: Arc<AtomicBool>, } fn _assert() { fn _assert_send<T: Send>() {} fn _assert_sync<T: Sync>() {} _assert_send::<CpuPool>(); _assert_sync::<CpuPool>(); } struct Inner { queue: MsQueue<Message>, cnt: AtomicUsize, size: usize, after_start: Option<Arc<Fn() + Send + Sync>>, before_stop: Option<Arc<Fn() + Send + Sync>>, } /// The type of future returned from the `CpuPool::spawn` function, which /// proxies the futures running on the thread pool. /// /// This future will resolve in the same way as the underlying future, and it /// will propagate panics. #[must_use] pub struct CpuFuture<T, E> { inner: Receiver<thread::Result<Result<T, E>>>, keep_running_flag: Arc<AtomicBool>, } enum Message { Run(Run), Close, } impl CpuPool { /// Creates a new thread pool with `size` worker threads associated with it. /// /// The returned handle can use `execute` to run work on this thread pool, /// and clones can be made of it to get multiple references to the same /// thread pool. /// /// This is a shortcut for: /// ```rust /// Builder::new().pool_size(size).create() /// ``` pub fn new(size: usize) -> CpuPool { Builder::new().pool_size(size).create() } /// Creates a new thread pool with a number of workers equal to the number /// of CPUs on the host. /// /// This is a shortcut for: /// ```rust /// Builder::new().create() /// ``` pub fn new_num_cpus() -> CpuPool { Builder::new().create() } /// Spawns a future to run on this thread pool, returning a future /// representing the produced value. /// /// This function will execute the future `f` on the associated thread /// pool, and return a future representing the finished computation. The /// returned future serves as a proxy to the computation that `F` is /// running. /// /// To simply run an arbitrary closure on a thread pool and extract the /// result, you can use the `future::lazy` combinator to defer work to /// executing on the thread pool itself. /// /// Note that if the future `f` panics it will be caught by default and the /// returned future will propagate the panic. That is, panics will not tear /// down the thread pool and will be propagated to the returned future's /// `poll` method if queried. /// /// If the returned future is dropped then this `CpuPool` will attempt to /// cancel the computation, if possible. That is, if the computation is in /// the middle of working, it will be interrupted when possible. pub fn spawn<F>(&self, f: F) -> CpuFuture<F::Item, F::Error> where F: Future + Send +'static, F::Item: Send +'static, F::Error: Send +'static, { let (tx, rx) = channel(); let keep_running_flag = Arc::new(AtomicBool::new(false)); // AssertUnwindSafe is used here becuase `Send +'static` is basically // an alias for an implementation of the `UnwindSafe` trait but we can't // express that in the standard library right now. let sender = MySender { fut: AssertUnwindSafe(f).catch_unwind(), tx: Some(tx), keep_running_flag: keep_running_flag.clone(), }; executor::spawn(sender).execute(self.inner.clone()); CpuFuture { inner: rx, keep_running_flag: keep_running_flag.clone() } } /// Spawns a closure on this thread pool. /// /// This function is a convenience wrapper around the `spawn` function above /// for running a closure wrapped in `future::lazy`. It will spawn the /// function `f` provided onto the thread pool, and continue to run the /// future returned by `f` on the thread pool as well. /// /// The returned future will be a handle to the result produced by the /// future that `f` returns. pub fn spawn_fn<F, R>(&self, f: F) -> CpuFuture<R::Item, R::Error> where F: FnOnce() -> R + Send +'static, R: IntoFuture +'static, R::Future: Send +'static, R::Item: Send +'static, R::Error: Send +'static, { self.spawn(lazy(f)) } } fn work(inner: &Inner) { inner.after_start.as_ref().map(|fun| fun()); loop { match inner.queue.pop() { Message::Run(r) => r.run(), Message::Close => break, } } inner.before_stop.as_ref().map(|fun| fun()); } impl Clone for CpuPool { fn clone(&self) -> CpuPool { self.inner.cnt.fetch_add(1, Ordering::Relaxed); CpuPool { inner: self.inner.clone() } } } impl Drop for CpuPool { fn drop(&mut self) { if self.inner.cnt.fetch_sub(1, Ordering::Relaxed) == 1 { for _ in 0..self.inner.size { self.inner.queue.push(Message::Close); } } } } impl Executor for Inner { fn execute(&self, run: Run) { self.queue.push(Message::Run(run)) } } impl<T, E> CpuFuture<T, E> { /// Drop this future without canceling the underlying future. /// /// When `CpuFuture` is dropped, `CpuPool` will try to abort the underlying /// future. This function can be used when user wants to drop but keep /// executing the underlying future. pub fn forget(self) { self.keep_running_flag.store(true, Ordering::SeqCst); } } impl<T: Send +'static, E: Send +'static> Future for CpuFuture<T, E> { type Item = T; type Error = E; fn poll(&mut self) -> Poll<T, E> { match self.inner.poll().expect("shouldn't be canceled") { Async::Ready(Ok(Ok(e))) => Ok(e.into()), Async::Ready(Ok(Err(e))) => Err(e), Async::Ready(Err(e)) => panic::resume_unwind(e), Async::NotReady => Ok(Async::NotReady), } } } impl<F: Future> Future for MySender<F, Result<F::Item, F::Error>> { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { if let Ok(Async::Ready(_)) = self.tx.as_mut().unwrap().poll_cancel() { if!self.keep_running_flag.load(Ordering::SeqCst) { // Cancelled, bail out return Ok(().into()) } } let res = match self.fut.poll() { Ok(Async::Ready(e)) => Ok(e), Ok(Async::NotReady) => return Ok(Async::NotReady), Err(e) => Err(e), }; self.tx.take().unwrap().complete(res); Ok(Async::Ready(())) } } impl Builder { /// Create a builder a number of workers equal to the number /// of CPUs on the host. pub fn new() -> Builder { Builder { pool_size: num_cpus::get(), name_prefix: None, after_start: None, before_stop: None, } } /// Set size of a future CpuPool /// /// The size of a thread pool is the number of worker threads spawned pub fn pool_size(&mut self, size: usize) -> &mut Self { self.pool_size = size; self } /// Set thread name prefix of a future CpuPool /// /// Thread name prefix is used for generating thread names. For example, if prefix is /// `my-pool-`, then threads in the pool will get names like `my-pool-1` etc. pub fn name_prefix<S: Into<String>>(&mut self, name_prefix: S) -> &mut Self { self.name_prefix = Some(name_prefix.into()); self } /// Execute function `f` right after each thread is started but before /// running any jobs on it /// /// This is initially intended for bookkeeping and monitoring uses pub fn after_start<F>(&mut self, f: F) -> &mut Self where F: Fn() + Send + Sync +'static { self.after_start = Some(Arc::new(f)); self } /// Execute function `f` before each worker thread stops /// /// This is initially intended for bookkeeping and monitoring uses pub fn before_stop<F>(&mut self, f: F) -> &mut Self where F: Fn() + Send + Sync +'static
/// Create CpuPool with configured parameters pub fn create(&mut self) -> CpuPool { let pool = CpuPool { inner: Arc::new(Inner { queue: MsQueue::new(), cnt: AtomicUsize::new(1), size: self.pool_size, after_start: self.after_start.clone(), before_stop: self.before_stop.clone(), }), }; assert!(self.pool_size > 0); for counter in 0..self.pool_size { let inner = pool.inner.clone(); let mut thread_builder = thread::Builder::new(); if let Some(ref name_prefix) = self.name_prefix { thread_builder = thread_builder.name(format!("{}{}", name_prefix, counter)); } thread_builder.spawn(move || work(&inner)).unwrap(); } return pool } }
{ self.before_stop = Some(Arc::new(f)); self }
identifier_body
lib.rs
//! A simple crate for executing work on a thread pool, and getting back a //! future. //! //! This crate provides a simple thread pool abstraction for running work //! externally from the current thread that's running. An instance of `Future` //! is handed back to represent that the work may be done later, and further //! computations can be chained along with it as well. //! //! ```rust //! extern crate futures; //! extern crate futures_cpupool; //! //! use futures::Future; //! use futures_cpupool::CpuPool; //! //! # fn long_running_future(a: u32) -> futures::future::BoxFuture<u32, ()> { //! # futures::future::result(Ok(a)).boxed() //! # } //! # fn main() { //! //! // Create a worker thread pool with four threads //! let pool = CpuPool::new(4); //! //! // Execute some work on the thread pool, optionally closing over data. //! let a = pool.spawn(long_running_future(2)); //! let b = pool.spawn(long_running_future(100)); //! //! // Express some further computation once the work is completed on the thread //! // pool. //! let c = a.join(b).map(|(a, b)| a + b).wait().unwrap(); //! //! // Print out the result //! println!("{:?}", c); //! # } //! ``` #![deny(missing_docs)] extern crate crossbeam; #[macro_use] extern crate futures; extern crate num_cpus; use std::panic::{self, AssertUnwindSafe}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::thread; use crossbeam::sync::MsQueue; use futures::{IntoFuture, Future, Poll, Async}; use futures::future::lazy; use futures::sync::oneshot::{channel, Sender, Receiver}; use futures::executor::{self, Run, Executor}; /// A thread pool intended to run CPU intensive work. /// /// This thread pool will hand out futures representing the completed work /// that happens on the thread pool itself, and the futures can then be later /// composed with other work as part of an overall computation. /// /// The worker threads associated with a thread pool are kept alive so long as /// there is an open handle to the `CpuPool` or there is work running on them. Once /// all work has been drained and all references have gone away the worker /// threads will be shut down. /// /// Currently `CpuPool` implements `Clone` which just clones a new reference to /// the underlying thread pool. /// /// **Note:** if you use CpuPool inside a library it's better accept a /// `Builder` object for thread configuration rather than configuring just /// pool size. This not only future proof for other settings but also allows /// user to attach monitoring tools to lifecycle hooks. pub struct CpuPool { inner: Arc<Inner>, } /// Thread pool configuration object /// /// Builder starts with a number of workers equal to the number /// of CPUs on the host. But you can change it until you call `create()`. pub struct Builder { pool_size: usize, name_prefix: Option<String>, after_start: Option<Arc<Fn() + Send + Sync>>, before_stop: Option<Arc<Fn() + Send + Sync>>, } struct MySender<F, T> { fut: F, tx: Option<Sender<T>>, keep_running_flag: Arc<AtomicBool>, } fn _assert() { fn _assert_send<T: Send>() {} fn _assert_sync<T: Sync>() {} _assert_send::<CpuPool>(); _assert_sync::<CpuPool>(); } struct Inner { queue: MsQueue<Message>, cnt: AtomicUsize, size: usize, after_start: Option<Arc<Fn() + Send + Sync>>, before_stop: Option<Arc<Fn() + Send + Sync>>, } /// The type of future returned from the `CpuPool::spawn` function, which /// proxies the futures running on the thread pool. /// /// This future will resolve in the same way as the underlying future, and it /// will propagate panics. #[must_use] pub struct CpuFuture<T, E> { inner: Receiver<thread::Result<Result<T, E>>>, keep_running_flag: Arc<AtomicBool>, } enum
{ Run(Run), Close, } impl CpuPool { /// Creates a new thread pool with `size` worker threads associated with it. /// /// The returned handle can use `execute` to run work on this thread pool, /// and clones can be made of it to get multiple references to the same /// thread pool. /// /// This is a shortcut for: /// ```rust /// Builder::new().pool_size(size).create() /// ``` pub fn new(size: usize) -> CpuPool { Builder::new().pool_size(size).create() } /// Creates a new thread pool with a number of workers equal to the number /// of CPUs on the host. /// /// This is a shortcut for: /// ```rust /// Builder::new().create() /// ``` pub fn new_num_cpus() -> CpuPool { Builder::new().create() } /// Spawns a future to run on this thread pool, returning a future /// representing the produced value. /// /// This function will execute the future `f` on the associated thread /// pool, and return a future representing the finished computation. The /// returned future serves as a proxy to the computation that `F` is /// running. /// /// To simply run an arbitrary closure on a thread pool and extract the /// result, you can use the `future::lazy` combinator to defer work to /// executing on the thread pool itself. /// /// Note that if the future `f` panics it will be caught by default and the /// returned future will propagate the panic. That is, panics will not tear /// down the thread pool and will be propagated to the returned future's /// `poll` method if queried. /// /// If the returned future is dropped then this `CpuPool` will attempt to /// cancel the computation, if possible. That is, if the computation is in /// the middle of working, it will be interrupted when possible. pub fn spawn<F>(&self, f: F) -> CpuFuture<F::Item, F::Error> where F: Future + Send +'static, F::Item: Send +'static, F::Error: Send +'static, { let (tx, rx) = channel(); let keep_running_flag = Arc::new(AtomicBool::new(false)); // AssertUnwindSafe is used here becuase `Send +'static` is basically // an alias for an implementation of the `UnwindSafe` trait but we can't // express that in the standard library right now. let sender = MySender { fut: AssertUnwindSafe(f).catch_unwind(), tx: Some(tx), keep_running_flag: keep_running_flag.clone(), }; executor::spawn(sender).execute(self.inner.clone()); CpuFuture { inner: rx, keep_running_flag: keep_running_flag.clone() } } /// Spawns a closure on this thread pool. /// /// This function is a convenience wrapper around the `spawn` function above /// for running a closure wrapped in `future::lazy`. It will spawn the /// function `f` provided onto the thread pool, and continue to run the /// future returned by `f` on the thread pool as well. /// /// The returned future will be a handle to the result produced by the /// future that `f` returns. pub fn spawn_fn<F, R>(&self, f: F) -> CpuFuture<R::Item, R::Error> where F: FnOnce() -> R + Send +'static, R: IntoFuture +'static, R::Future: Send +'static, R::Item: Send +'static, R::Error: Send +'static, { self.spawn(lazy(f)) } } fn work(inner: &Inner) { inner.after_start.as_ref().map(|fun| fun()); loop { match inner.queue.pop() { Message::Run(r) => r.run(), Message::Close => break, } } inner.before_stop.as_ref().map(|fun| fun()); } impl Clone for CpuPool { fn clone(&self) -> CpuPool { self.inner.cnt.fetch_add(1, Ordering::Relaxed); CpuPool { inner: self.inner.clone() } } } impl Drop for CpuPool { fn drop(&mut self) { if self.inner.cnt.fetch_sub(1, Ordering::Relaxed) == 1 { for _ in 0..self.inner.size { self.inner.queue.push(Message::Close); } } } } impl Executor for Inner { fn execute(&self, run: Run) { self.queue.push(Message::Run(run)) } } impl<T, E> CpuFuture<T, E> { /// Drop this future without canceling the underlying future. /// /// When `CpuFuture` is dropped, `CpuPool` will try to abort the underlying /// future. This function can be used when user wants to drop but keep /// executing the underlying future. pub fn forget(self) { self.keep_running_flag.store(true, Ordering::SeqCst); } } impl<T: Send +'static, E: Send +'static> Future for CpuFuture<T, E> { type Item = T; type Error = E; fn poll(&mut self) -> Poll<T, E> { match self.inner.poll().expect("shouldn't be canceled") { Async::Ready(Ok(Ok(e))) => Ok(e.into()), Async::Ready(Ok(Err(e))) => Err(e), Async::Ready(Err(e)) => panic::resume_unwind(e), Async::NotReady => Ok(Async::NotReady), } } } impl<F: Future> Future for MySender<F, Result<F::Item, F::Error>> { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { if let Ok(Async::Ready(_)) = self.tx.as_mut().unwrap().poll_cancel() { if!self.keep_running_flag.load(Ordering::SeqCst) { // Cancelled, bail out return Ok(().into()) } } let res = match self.fut.poll() { Ok(Async::Ready(e)) => Ok(e), Ok(Async::NotReady) => return Ok(Async::NotReady), Err(e) => Err(e), }; self.tx.take().unwrap().complete(res); Ok(Async::Ready(())) } } impl Builder { /// Create a builder a number of workers equal to the number /// of CPUs on the host. pub fn new() -> Builder { Builder { pool_size: num_cpus::get(), name_prefix: None, after_start: None, before_stop: None, } } /// Set size of a future CpuPool /// /// The size of a thread pool is the number of worker threads spawned pub fn pool_size(&mut self, size: usize) -> &mut Self { self.pool_size = size; self } /// Set thread name prefix of a future CpuPool /// /// Thread name prefix is used for generating thread names. For example, if prefix is /// `my-pool-`, then threads in the pool will get names like `my-pool-1` etc. pub fn name_prefix<S: Into<String>>(&mut self, name_prefix: S) -> &mut Self { self.name_prefix = Some(name_prefix.into()); self } /// Execute function `f` right after each thread is started but before /// running any jobs on it /// /// This is initially intended for bookkeeping and monitoring uses pub fn after_start<F>(&mut self, f: F) -> &mut Self where F: Fn() + Send + Sync +'static { self.after_start = Some(Arc::new(f)); self } /// Execute function `f` before each worker thread stops /// /// This is initially intended for bookkeeping and monitoring uses pub fn before_stop<F>(&mut self, f: F) -> &mut Self where F: Fn() + Send + Sync +'static { self.before_stop = Some(Arc::new(f)); self } /// Create CpuPool with configured parameters pub fn create(&mut self) -> CpuPool { let pool = CpuPool { inner: Arc::new(Inner { queue: MsQueue::new(), cnt: AtomicUsize::new(1), size: self.pool_size, after_start: self.after_start.clone(), before_stop: self.before_stop.clone(), }), }; assert!(self.pool_size > 0); for counter in 0..self.pool_size { let inner = pool.inner.clone(); let mut thread_builder = thread::Builder::new(); if let Some(ref name_prefix) = self.name_prefix { thread_builder = thread_builder.name(format!("{}{}", name_prefix, counter)); } thread_builder.spawn(move || work(&inner)).unwrap(); } return pool } }
Message
identifier_name
url.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Cross-platform open url in default browser #[cfg(windows)] mod shell { extern crate winapi; use self::winapi::*; extern "system" { pub fn ShellExecuteA( hwnd: HWND, lpOperation: LPCSTR, lpFile: LPCSTR, lpParameters: LPCSTR, lpDirectory: LPCSTR, nShowCmd: c_int ) -> HINSTANCE; } pub use self::winapi::SW_SHOWNORMAL as Normal; } #[cfg(windows)] pub fn open(url: &str) { use std::ffi::CString; use std::ptr; unsafe { shell::ShellExecuteA(ptr::null_mut(), CString::new("open").unwrap().as_ptr(), CString::new(url.to_owned().replace("\n", "%0A")).unwrap().as_ptr(), ptr::null(), ptr::null(), shell::Normal); } } #[cfg(any(target_os="macos", target_os="freebsd"))] pub fn open(url: &str) { use std; let _ = std::process::Command::new("open").arg(url).spawn(); } #[cfg(target_os="linux")] pub fn
(url: &str) { use std; let _ = std::process::Command::new("xdg-open").arg(url).spawn(); }
open
identifier_name
url.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Cross-platform open url in default browser #[cfg(windows)] mod shell { extern crate winapi; use self::winapi::*; extern "system" { pub fn ShellExecuteA( hwnd: HWND, lpOperation: LPCSTR, lpFile: LPCSTR, lpParameters: LPCSTR, lpDirectory: LPCSTR, nShowCmd: c_int ) -> HINSTANCE; } pub use self::winapi::SW_SHOWNORMAL as Normal; } #[cfg(windows)] pub fn open(url: &str) { use std::ffi::CString; use std::ptr;
unsafe { shell::ShellExecuteA(ptr::null_mut(), CString::new("open").unwrap().as_ptr(), CString::new(url.to_owned().replace("\n", "%0A")).unwrap().as_ptr(), ptr::null(), ptr::null(), shell::Normal); } } #[cfg(any(target_os="macos", target_os="freebsd"))] pub fn open(url: &str) { use std; let _ = std::process::Command::new("open").arg(url).spawn(); } #[cfg(target_os="linux")] pub fn open(url: &str) { use std; let _ = std::process::Command::new("xdg-open").arg(url).spawn(); }
random_line_split
url.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Cross-platform open url in default browser #[cfg(windows)] mod shell { extern crate winapi; use self::winapi::*; extern "system" { pub fn ShellExecuteA( hwnd: HWND, lpOperation: LPCSTR, lpFile: LPCSTR, lpParameters: LPCSTR, lpDirectory: LPCSTR, nShowCmd: c_int ) -> HINSTANCE; } pub use self::winapi::SW_SHOWNORMAL as Normal; } #[cfg(windows)] pub fn open(url: &str) { use std::ffi::CString; use std::ptr; unsafe { shell::ShellExecuteA(ptr::null_mut(), CString::new("open").unwrap().as_ptr(), CString::new(url.to_owned().replace("\n", "%0A")).unwrap().as_ptr(), ptr::null(), ptr::null(), shell::Normal); } } #[cfg(any(target_os="macos", target_os="freebsd"))] pub fn open(url: &str) { use std; let _ = std::process::Command::new("open").arg(url).spawn(); } #[cfg(target_os="linux")] pub fn open(url: &str)
{ use std; let _ = std::process::Command::new("xdg-open").arg(url).spawn(); }
identifier_body
issue-7573.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct CrateId { local_path: ~str, junk: ~str } impl CrateId { fn new(s: &str) -> CrateId { CrateId { local_path: s.to_owned(), junk: ~"wutevs" } } } pub fn remove_package_from_database() { let mut lines_to_use: ~[&CrateId] = ~[]; //~ ERROR cannot infer an appropriate lifetime let push_id = |installed_id: &CrateId| { lines_to_use.push(installed_id); }; list_database(push_id); for l in lines_to_use.iter() { println!("{}", l.local_path); } } pub fn list_database(f: |&CrateId|) { let stuff = ["foo", "bar"]; for l in stuff.iter() { f(&CrateId::new(*l)); } } pub fn
() { remove_package_from_database(); }
main
identifier_name
issue-7573.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct CrateId {
local_path: ~str, junk: ~str } impl CrateId { fn new(s: &str) -> CrateId { CrateId { local_path: s.to_owned(), junk: ~"wutevs" } } } pub fn remove_package_from_database() { let mut lines_to_use: ~[&CrateId] = ~[]; //~ ERROR cannot infer an appropriate lifetime let push_id = |installed_id: &CrateId| { lines_to_use.push(installed_id); }; list_database(push_id); for l in lines_to_use.iter() { println!("{}", l.local_path); } } pub fn list_database(f: |&CrateId|) { let stuff = ["foo", "bar"]; for l in stuff.iter() { f(&CrateId::new(*l)); } } pub fn main() { remove_package_from_database(); }
random_line_split
issue-7573.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct CrateId { local_path: ~str, junk: ~str } impl CrateId { fn new(s: &str) -> CrateId { CrateId { local_path: s.to_owned(), junk: ~"wutevs" } } } pub fn remove_package_from_database() { let mut lines_to_use: ~[&CrateId] = ~[]; //~ ERROR cannot infer an appropriate lifetime let push_id = |installed_id: &CrateId| { lines_to_use.push(installed_id); }; list_database(push_id); for l in lines_to_use.iter() { println!("{}", l.local_path); } } pub fn list_database(f: |&CrateId|) { let stuff = ["foo", "bar"]; for l in stuff.iter() { f(&CrateId::new(*l)); } } pub fn main()
{ remove_package_from_database(); }
identifier_body
json_merge.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use super::{Json, JsonRef, JsonType}; use crate::codec::{Error, Result}; use std::collections::BTreeMap; impl Json { /// `merge` is the implementation for JSON_MERGE in mysql /// <https://dev.mysql.com/doc/refman/5.7/en/json-modification-functions.html#function_json-merge> /// /// The merge rules are listed as following: /// 1. adjacent arrays are merged to a single array; /// 2. adjacent object are merged to a single object; /// 3. a scalar value is autowrapped as an array before merge; /// 4. an adjacent array and object are merged by autowrapping the object as an array. /// /// See `MergeBinary()` in TiDB `json/binary_function.go` #[allow(clippy::comparison_chain)] pub fn merge(bjs: Vec<JsonRef>) -> Result<Json> { let mut result = vec![]; let mut objects = vec![]; for j in bjs { if j.get_type()!= JsonType::Object { if objects.len() == 1 { let o = objects.pop().unwrap(); result.push(MergeUnit::Ref(o)); } else if objects.len() > 1 { // We have adjacent JSON objects, merge them into a single object result.push(MergeUnit::Owned(merge_binary_object(&mut objects)?)); } result.push(MergeUnit::Ref(j)); } else { objects.push(j); } } // Resolve the possibly remained objects if!objects.is_empty() { result.push(MergeUnit::Owned(merge_binary_object(&mut objects)?)); } if result.len() == 1 { return Ok(result.pop().unwrap().into_owned()); } merge_binary_array(&result) } } enum
<'a> { Ref(JsonRef<'a>), Owned(Json), } impl<'a> MergeUnit<'a> { fn as_ref(&self) -> JsonRef<'_> { match self { MergeUnit::Ref(r) => *r, MergeUnit::Owned(o) => o.as_ref(), } } fn into_owned(self) -> Json { match self { MergeUnit::Ref(r) => r.to_owned(), MergeUnit::Owned(o) => o, } } } // See `mergeBinaryArray()` in TiDB `json/binary_function.go` fn merge_binary_array(elems: &[MergeUnit]) -> Result<Json> { let mut buf = vec![]; for j in elems.iter() { let j = j.as_ref(); if j.get_type()!= JsonType::Array { buf.push(j) } else { let child_count = j.get_elem_count(); for i in 0..child_count { buf.push(j.array_get_elem(i)?); } } } Json::from_ref_array(buf) } // See `mergeBinaryObject()` in TiDB `json/binary_function.go` fn merge_binary_object(objects: &mut Vec<JsonRef>) -> Result<Json> { let mut kv_map: BTreeMap<String, Json> = BTreeMap::new(); for j in objects.drain(..) { let elem_count = j.get_elem_count(); for i in 0..elem_count { let key = j.object_get_key(i); let val = j.object_get_val(i)?; let key = String::from_utf8(key.to_owned()).map_err(Error::from)?; if let Some(old) = kv_map.remove(&key) { let new = Json::merge(vec![old.as_ref(), val])?; kv_map.insert(key, new); } else { kv_map.insert(key, val.to_owned()); } } } Json::from_object(kv_map) } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let test_cases = vec![ vec![r#"{"a": 1}"#, r#"{"b": 2}"#, r#"{"a": 1, "b": 2}"#], vec![r#"{"a": 1}"#, r#"{"a": 2}"#, r#"{"a": [1, 2]}"#], vec![r#"{"a": 1}"#, r#"{"a": [2, 3]}"#, r#"{"a": [1, 2, 3]}"#], vec![ r#"{"a": 1}"#, r#"{"a": {"b": [2, 3]}}"#, r#"{"a": [1, {"b": [2, 3]}]}"#, ], vec![ r#"{"a": {"b": [2, 3]}}"#, r#"{"a": 1}"#, r#"{"a": [{"b": [2, 3]}, 1]}"#, ], vec![ r#"{"a": [1, 2]}"#, r#"{"a": {"b": [3, 4]}}"#, r#"{"a": [1, 2, {"b": [3, 4]}]}"#, ], vec![ r#"{"b": {"c": 2}}"#, r#"{"a": 1, "b": {"d": 1}}"#, r#"{"a": 1, "b": {"c": 2, "d": 1}}"#, ], vec![r#"[1]"#, r#"[2]"#, r#"[1, 2]"#], vec![r#"{"a": 1}"#, r#"[1]"#, r#"[{"a": 1}, 1]"#], vec![r#"[1]"#, r#"{"a": 1}"#, r#"[1, {"a": 1}]"#], vec![r#"{"a": 1}"#, r#"4"#, r#"[{"a": 1}, 4]"#], vec![r#"[1]"#, r#"4"#, r#"[1, 4]"#], vec![r#"4"#, r#"{"a": 1}"#, r#"[4, {"a": 1}]"#], vec![r#"1"#, r#"[4]"#, r#"[1, 4]"#], vec![r#"4"#, r#"1"#, r#"[4, 1]"#], vec!["1", "2", "3", "[1, 2, 3]"], vec!["[1, 2]", "3", "[4, 5, 6]", "[1, 2, 3, 4, 5, 6]"], vec![ r#"{"a": 1, "b": {"c": 3, "d": 4}, "e": [5, 6]}"#, r#"{"c": 7, "b": {"a": 8, "c": 9}, "f": [1, 2]}"#, r#"{"d": 9, "b": {"b": 10, "c": 11}, "e": 8}"#, r#"{ "a": 1, "b": {"a": 8, "b": 10, "c": [3, 9, 11], "d": 4}, "c": 7, "d": 9, "e": [5, 6, 8], "f": [1, 2] }"#, ], ]; for case in test_cases { let (to_be_merged, expect) = case.split_at(case.len() - 1); let jsons = to_be_merged .iter() .map(|s| s.parse::<Json>().unwrap()) .collect::<Vec<Json>>(); let refs = jsons.iter().map(|j| j.as_ref()).collect::<Vec<_>>(); let res = Json::merge(refs).unwrap(); let expect: Json = expect[0].parse().unwrap(); assert_eq!(res, expect); } } }
MergeUnit
identifier_name
json_merge.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use super::{Json, JsonRef, JsonType}; use crate::codec::{Error, Result}; use std::collections::BTreeMap; impl Json { /// `merge` is the implementation for JSON_MERGE in mysql /// <https://dev.mysql.com/doc/refman/5.7/en/json-modification-functions.html#function_json-merge> /// /// The merge rules are listed as following: /// 1. adjacent arrays are merged to a single array; /// 2. adjacent object are merged to a single object; /// 3. a scalar value is autowrapped as an array before merge; /// 4. an adjacent array and object are merged by autowrapping the object as an array. /// /// See `MergeBinary()` in TiDB `json/binary_function.go` #[allow(clippy::comparison_chain)] pub fn merge(bjs: Vec<JsonRef>) -> Result<Json> { let mut result = vec![]; let mut objects = vec![]; for j in bjs { if j.get_type()!= JsonType::Object { if objects.len() == 1 { let o = objects.pop().unwrap(); result.push(MergeUnit::Ref(o)); } else if objects.len() > 1 { // We have adjacent JSON objects, merge them into a single object result.push(MergeUnit::Owned(merge_binary_object(&mut objects)?)); } result.push(MergeUnit::Ref(j)); } else { objects.push(j); } } // Resolve the possibly remained objects if!objects.is_empty() { result.push(MergeUnit::Owned(merge_binary_object(&mut objects)?)); } if result.len() == 1 { return Ok(result.pop().unwrap().into_owned()); } merge_binary_array(&result) } } enum MergeUnit<'a> { Ref(JsonRef<'a>), Owned(Json), } impl<'a> MergeUnit<'a> { fn as_ref(&self) -> JsonRef<'_> { match self { MergeUnit::Ref(r) => *r, MergeUnit::Owned(o) => o.as_ref(), } } fn into_owned(self) -> Json { match self { MergeUnit::Ref(r) => r.to_owned(), MergeUnit::Owned(o) => o, } } } // See `mergeBinaryArray()` in TiDB `json/binary_function.go` fn merge_binary_array(elems: &[MergeUnit]) -> Result<Json> { let mut buf = vec![]; for j in elems.iter() { let j = j.as_ref(); if j.get_type()!= JsonType::Array { buf.push(j) } else
} Json::from_ref_array(buf) } // See `mergeBinaryObject()` in TiDB `json/binary_function.go` fn merge_binary_object(objects: &mut Vec<JsonRef>) -> Result<Json> { let mut kv_map: BTreeMap<String, Json> = BTreeMap::new(); for j in objects.drain(..) { let elem_count = j.get_elem_count(); for i in 0..elem_count { let key = j.object_get_key(i); let val = j.object_get_val(i)?; let key = String::from_utf8(key.to_owned()).map_err(Error::from)?; if let Some(old) = kv_map.remove(&key) { let new = Json::merge(vec![old.as_ref(), val])?; kv_map.insert(key, new); } else { kv_map.insert(key, val.to_owned()); } } } Json::from_object(kv_map) } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let test_cases = vec![ vec![r#"{"a": 1}"#, r#"{"b": 2}"#, r#"{"a": 1, "b": 2}"#], vec![r#"{"a": 1}"#, r#"{"a": 2}"#, r#"{"a": [1, 2]}"#], vec![r#"{"a": 1}"#, r#"{"a": [2, 3]}"#, r#"{"a": [1, 2, 3]}"#], vec![ r#"{"a": 1}"#, r#"{"a": {"b": [2, 3]}}"#, r#"{"a": [1, {"b": [2, 3]}]}"#, ], vec![ r#"{"a": {"b": [2, 3]}}"#, r#"{"a": 1}"#, r#"{"a": [{"b": [2, 3]}, 1]}"#, ], vec![ r#"{"a": [1, 2]}"#, r#"{"a": {"b": [3, 4]}}"#, r#"{"a": [1, 2, {"b": [3, 4]}]}"#, ], vec![ r#"{"b": {"c": 2}}"#, r#"{"a": 1, "b": {"d": 1}}"#, r#"{"a": 1, "b": {"c": 2, "d": 1}}"#, ], vec![r#"[1]"#, r#"[2]"#, r#"[1, 2]"#], vec![r#"{"a": 1}"#, r#"[1]"#, r#"[{"a": 1}, 1]"#], vec![r#"[1]"#, r#"{"a": 1}"#, r#"[1, {"a": 1}]"#], vec![r#"{"a": 1}"#, r#"4"#, r#"[{"a": 1}, 4]"#], vec![r#"[1]"#, r#"4"#, r#"[1, 4]"#], vec![r#"4"#, r#"{"a": 1}"#, r#"[4, {"a": 1}]"#], vec![r#"1"#, r#"[4]"#, r#"[1, 4]"#], vec![r#"4"#, r#"1"#, r#"[4, 1]"#], vec!["1", "2", "3", "[1, 2, 3]"], vec!["[1, 2]", "3", "[4, 5, 6]", "[1, 2, 3, 4, 5, 6]"], vec![ r#"{"a": 1, "b": {"c": 3, "d": 4}, "e": [5, 6]}"#, r#"{"c": 7, "b": {"a": 8, "c": 9}, "f": [1, 2]}"#, r#"{"d": 9, "b": {"b": 10, "c": 11}, "e": 8}"#, r#"{ "a": 1, "b": {"a": 8, "b": 10, "c": [3, 9, 11], "d": 4}, "c": 7, "d": 9, "e": [5, 6, 8], "f": [1, 2] }"#, ], ]; for case in test_cases { let (to_be_merged, expect) = case.split_at(case.len() - 1); let jsons = to_be_merged .iter() .map(|s| s.parse::<Json>().unwrap()) .collect::<Vec<Json>>(); let refs = jsons.iter().map(|j| j.as_ref()).collect::<Vec<_>>(); let res = Json::merge(refs).unwrap(); let expect: Json = expect[0].parse().unwrap(); assert_eq!(res, expect); } } }
{ let child_count = j.get_elem_count(); for i in 0..child_count { buf.push(j.array_get_elem(i)?); } }
conditional_block
json_merge.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use super::{Json, JsonRef, JsonType}; use crate::codec::{Error, Result}; use std::collections::BTreeMap; impl Json { /// `merge` is the implementation for JSON_MERGE in mysql /// <https://dev.mysql.com/doc/refman/5.7/en/json-modification-functions.html#function_json-merge> /// /// The merge rules are listed as following: /// 1. adjacent arrays are merged to a single array; /// 2. adjacent object are merged to a single object; /// 3. a scalar value is autowrapped as an array before merge; /// 4. an adjacent array and object are merged by autowrapping the object as an array. /// /// See `MergeBinary()` in TiDB `json/binary_function.go` #[allow(clippy::comparison_chain)] pub fn merge(bjs: Vec<JsonRef>) -> Result<Json> { let mut result = vec![]; let mut objects = vec![]; for j in bjs { if j.get_type()!= JsonType::Object { if objects.len() == 1 { let o = objects.pop().unwrap(); result.push(MergeUnit::Ref(o)); } else if objects.len() > 1 { // We have adjacent JSON objects, merge them into a single object result.push(MergeUnit::Owned(merge_binary_object(&mut objects)?)); } result.push(MergeUnit::Ref(j)); } else { objects.push(j); } } // Resolve the possibly remained objects if!objects.is_empty() { result.push(MergeUnit::Owned(merge_binary_object(&mut objects)?)); } if result.len() == 1 { return Ok(result.pop().unwrap().into_owned()); } merge_binary_array(&result) } } enum MergeUnit<'a> { Ref(JsonRef<'a>), Owned(Json), } impl<'a> MergeUnit<'a> { fn as_ref(&self) -> JsonRef<'_> { match self { MergeUnit::Ref(r) => *r, MergeUnit::Owned(o) => o.as_ref(), } } fn into_owned(self) -> Json { match self { MergeUnit::Ref(r) => r.to_owned(), MergeUnit::Owned(o) => o, } } } // See `mergeBinaryArray()` in TiDB `json/binary_function.go` fn merge_binary_array(elems: &[MergeUnit]) -> Result<Json> { let mut buf = vec![]; for j in elems.iter() { let j = j.as_ref(); if j.get_type()!= JsonType::Array { buf.push(j) } else { let child_count = j.get_elem_count(); for i in 0..child_count { buf.push(j.array_get_elem(i)?); } } } Json::from_ref_array(buf) } // See `mergeBinaryObject()` in TiDB `json/binary_function.go` fn merge_binary_object(objects: &mut Vec<JsonRef>) -> Result<Json> { let mut kv_map: BTreeMap<String, Json> = BTreeMap::new(); for j in objects.drain(..) { let elem_count = j.get_elem_count(); for i in 0..elem_count { let key = j.object_get_key(i); let val = j.object_get_val(i)?; let key = String::from_utf8(key.to_owned()).map_err(Error::from)?; if let Some(old) = kv_map.remove(&key) { let new = Json::merge(vec![old.as_ref(), val])?; kv_map.insert(key, new); } else { kv_map.insert(key, val.to_owned()); } } } Json::from_object(kv_map) }
#[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let test_cases = vec![ vec![r#"{"a": 1}"#, r#"{"b": 2}"#, r#"{"a": 1, "b": 2}"#], vec![r#"{"a": 1}"#, r#"{"a": 2}"#, r#"{"a": [1, 2]}"#], vec![r#"{"a": 1}"#, r#"{"a": [2, 3]}"#, r#"{"a": [1, 2, 3]}"#], vec![ r#"{"a": 1}"#, r#"{"a": {"b": [2, 3]}}"#, r#"{"a": [1, {"b": [2, 3]}]}"#, ], vec![ r#"{"a": {"b": [2, 3]}}"#, r#"{"a": 1}"#, r#"{"a": [{"b": [2, 3]}, 1]}"#, ], vec![ r#"{"a": [1, 2]}"#, r#"{"a": {"b": [3, 4]}}"#, r#"{"a": [1, 2, {"b": [3, 4]}]}"#, ], vec![ r#"{"b": {"c": 2}}"#, r#"{"a": 1, "b": {"d": 1}}"#, r#"{"a": 1, "b": {"c": 2, "d": 1}}"#, ], vec![r#"[1]"#, r#"[2]"#, r#"[1, 2]"#], vec![r#"{"a": 1}"#, r#"[1]"#, r#"[{"a": 1}, 1]"#], vec![r#"[1]"#, r#"{"a": 1}"#, r#"[1, {"a": 1}]"#], vec![r#"{"a": 1}"#, r#"4"#, r#"[{"a": 1}, 4]"#], vec![r#"[1]"#, r#"4"#, r#"[1, 4]"#], vec![r#"4"#, r#"{"a": 1}"#, r#"[4, {"a": 1}]"#], vec![r#"1"#, r#"[4]"#, r#"[1, 4]"#], vec![r#"4"#, r#"1"#, r#"[4, 1]"#], vec!["1", "2", "3", "[1, 2, 3]"], vec!["[1, 2]", "3", "[4, 5, 6]", "[1, 2, 3, 4, 5, 6]"], vec![ r#"{"a": 1, "b": {"c": 3, "d": 4}, "e": [5, 6]}"#, r#"{"c": 7, "b": {"a": 8, "c": 9}, "f": [1, 2]}"#, r#"{"d": 9, "b": {"b": 10, "c": 11}, "e": 8}"#, r#"{ "a": 1, "b": {"a": 8, "b": 10, "c": [3, 9, 11], "d": 4}, "c": 7, "d": 9, "e": [5, 6, 8], "f": [1, 2] }"#, ], ]; for case in test_cases { let (to_be_merged, expect) = case.split_at(case.len() - 1); let jsons = to_be_merged .iter() .map(|s| s.parse::<Json>().unwrap()) .collect::<Vec<Json>>(); let refs = jsons.iter().map(|j| j.as_ref()).collect::<Vec<_>>(); let res = Json::merge(refs).unwrap(); let expect: Json = expect[0].parse().unwrap(); assert_eq!(res, expect); } } }
random_line_split
json_merge.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use super::{Json, JsonRef, JsonType}; use crate::codec::{Error, Result}; use std::collections::BTreeMap; impl Json { /// `merge` is the implementation for JSON_MERGE in mysql /// <https://dev.mysql.com/doc/refman/5.7/en/json-modification-functions.html#function_json-merge> /// /// The merge rules are listed as following: /// 1. adjacent arrays are merged to a single array; /// 2. adjacent object are merged to a single object; /// 3. a scalar value is autowrapped as an array before merge; /// 4. an adjacent array and object are merged by autowrapping the object as an array. /// /// See `MergeBinary()` in TiDB `json/binary_function.go` #[allow(clippy::comparison_chain)] pub fn merge(bjs: Vec<JsonRef>) -> Result<Json> { let mut result = vec![]; let mut objects = vec![]; for j in bjs { if j.get_type()!= JsonType::Object { if objects.len() == 1 { let o = objects.pop().unwrap(); result.push(MergeUnit::Ref(o)); } else if objects.len() > 1 { // We have adjacent JSON objects, merge them into a single object result.push(MergeUnit::Owned(merge_binary_object(&mut objects)?)); } result.push(MergeUnit::Ref(j)); } else { objects.push(j); } } // Resolve the possibly remained objects if!objects.is_empty() { result.push(MergeUnit::Owned(merge_binary_object(&mut objects)?)); } if result.len() == 1 { return Ok(result.pop().unwrap().into_owned()); } merge_binary_array(&result) } } enum MergeUnit<'a> { Ref(JsonRef<'a>), Owned(Json), } impl<'a> MergeUnit<'a> { fn as_ref(&self) -> JsonRef<'_> { match self { MergeUnit::Ref(r) => *r, MergeUnit::Owned(o) => o.as_ref(), } } fn into_owned(self) -> Json { match self { MergeUnit::Ref(r) => r.to_owned(), MergeUnit::Owned(o) => o, } } } // See `mergeBinaryArray()` in TiDB `json/binary_function.go` fn merge_binary_array(elems: &[MergeUnit]) -> Result<Json> { let mut buf = vec![]; for j in elems.iter() { let j = j.as_ref(); if j.get_type()!= JsonType::Array { buf.push(j) } else { let child_count = j.get_elem_count(); for i in 0..child_count { buf.push(j.array_get_elem(i)?); } } } Json::from_ref_array(buf) } // See `mergeBinaryObject()` in TiDB `json/binary_function.go` fn merge_binary_object(objects: &mut Vec<JsonRef>) -> Result<Json>
#[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let test_cases = vec![ vec![r#"{"a": 1}"#, r#"{"b": 2}"#, r#"{"a": 1, "b": 2}"#], vec![r#"{"a": 1}"#, r#"{"a": 2}"#, r#"{"a": [1, 2]}"#], vec![r#"{"a": 1}"#, r#"{"a": [2, 3]}"#, r#"{"a": [1, 2, 3]}"#], vec![ r#"{"a": 1}"#, r#"{"a": {"b": [2, 3]}}"#, r#"{"a": [1, {"b": [2, 3]}]}"#, ], vec![ r#"{"a": {"b": [2, 3]}}"#, r#"{"a": 1}"#, r#"{"a": [{"b": [2, 3]}, 1]}"#, ], vec![ r#"{"a": [1, 2]}"#, r#"{"a": {"b": [3, 4]}}"#, r#"{"a": [1, 2, {"b": [3, 4]}]}"#, ], vec![ r#"{"b": {"c": 2}}"#, r#"{"a": 1, "b": {"d": 1}}"#, r#"{"a": 1, "b": {"c": 2, "d": 1}}"#, ], vec![r#"[1]"#, r#"[2]"#, r#"[1, 2]"#], vec![r#"{"a": 1}"#, r#"[1]"#, r#"[{"a": 1}, 1]"#], vec![r#"[1]"#, r#"{"a": 1}"#, r#"[1, {"a": 1}]"#], vec![r#"{"a": 1}"#, r#"4"#, r#"[{"a": 1}, 4]"#], vec![r#"[1]"#, r#"4"#, r#"[1, 4]"#], vec![r#"4"#, r#"{"a": 1}"#, r#"[4, {"a": 1}]"#], vec![r#"1"#, r#"[4]"#, r#"[1, 4]"#], vec![r#"4"#, r#"1"#, r#"[4, 1]"#], vec!["1", "2", "3", "[1, 2, 3]"], vec!["[1, 2]", "3", "[4, 5, 6]", "[1, 2, 3, 4, 5, 6]"], vec![ r#"{"a": 1, "b": {"c": 3, "d": 4}, "e": [5, 6]}"#, r#"{"c": 7, "b": {"a": 8, "c": 9}, "f": [1, 2]}"#, r#"{"d": 9, "b": {"b": 10, "c": 11}, "e": 8}"#, r#"{ "a": 1, "b": {"a": 8, "b": 10, "c": [3, 9, 11], "d": 4}, "c": 7, "d": 9, "e": [5, 6, 8], "f": [1, 2] }"#, ], ]; for case in test_cases { let (to_be_merged, expect) = case.split_at(case.len() - 1); let jsons = to_be_merged .iter() .map(|s| s.parse::<Json>().unwrap()) .collect::<Vec<Json>>(); let refs = jsons.iter().map(|j| j.as_ref()).collect::<Vec<_>>(); let res = Json::merge(refs).unwrap(); let expect: Json = expect[0].parse().unwrap(); assert_eq!(res, expect); } } }
{ let mut kv_map: BTreeMap<String, Json> = BTreeMap::new(); for j in objects.drain(..) { let elem_count = j.get_elem_count(); for i in 0..elem_count { let key = j.object_get_key(i); let val = j.object_get_val(i)?; let key = String::from_utf8(key.to_owned()).map_err(Error::from)?; if let Some(old) = kv_map.remove(&key) { let new = Json::merge(vec![old.as_ref(), val])?; kv_map.insert(key, new); } else { kv_map.insert(key, val.to_owned()); } } } Json::from_object(kv_map) }
identifier_body
text.rs
, and nothing else can. /// /// The flow keeps track of the fragments contained by all non-leaf DOM nodes. This is necessary /// for correct painting order. Since we compress several leaf fragments here, the mapping must /// be adjusted. fn flush_clump_to_list(&mut self, mut font_context: &mut LayoutFontContext, out_fragments: &mut Vec<Fragment>, paragraph_bytes_processed: &mut usize, bidi_levels: Option<&[bidi::Level]>, mut last_whitespace: bool, linebreaker: &mut Option<LineBreakLeafIter>) -> bool
let letter_spacing; let word_spacing; let text_rendering; let word_break; { let in_fragment = self.clump.front().unwrap(); let font_style = in_fragment.style().clone_font(); let inherited_text_style = in_fragment.style().get_inheritedtext(); font_group = font_context.font_group(font_style); compression = match in_fragment.white_space() { WhiteSpace::Normal | WhiteSpace::Nowrap => CompressionMode::CompressWhitespaceNewline, WhiteSpace::Pre | WhiteSpace::PreWrap => CompressionMode::CompressNone, WhiteSpace::PreLine => CompressionMode::CompressWhitespace, }; text_transform = inherited_text_style.text_transform; letter_spacing = inherited_text_style.letter_spacing; word_spacing = inherited_text_style.word_spacing.value() .map(|lop| lop.to_hash_key()) .unwrap_or((Au(0), NotNaN::new(0.0).unwrap())); text_rendering = inherited_text_style.text_rendering; word_break = inherited_text_style.word_break; } // First, transform/compress text of all the nodes. let (mut run_info_list, mut run_info) = (Vec::new(), RunInfo::new()); let mut insertion_point = None; for (fragment_index, in_fragment) in self.clump.iter().enumerate() { debug!(" flushing {:?}", in_fragment); let mut mapping = RunMapping::new(&run_info_list[..], fragment_index); let text; let selection; match in_fragment.specific { SpecificFragmentInfo::UnscannedText(ref text_fragment_info) => { text = &text_fragment_info.text; selection = text_fragment_info.selection; } _ => panic!("Expected an unscanned text fragment!"), }; insertion_point = match selection { Some(range) if range.is_empty() => { // `range` is the range within the current fragment. To get the range // within the text run, offset it by the length of the preceding fragments. Some(range.begin() + ByteIndex(run_info.text.len() as isize)) } _ => None }; let (mut start_position, mut end_position) = (0, 0); for (byte_index, character) in text.char_indices() { if!character.is_control() { let font = font_group.borrow_mut().find_by_codepoint(&mut font_context, character); let bidi_level = match bidi_levels { Some(levels) => levels[*paragraph_bytes_processed], None => bidi::Level::ltr(), }; // Break the run if the new character has a different explicit script than the // previous characters. // // TODO: Special handling of paired punctuation characters. // http://www.unicode.org/reports/tr24/#Common let script = get_script(character); let compatible_script = is_compatible(script, run_info.script); if compatible_script &&!is_specific(run_info.script) && is_specific(script) { run_info.script = script; } let selected = match selection { Some(range) => range.contains(ByteIndex(byte_index as isize)), None => false }; // Now, if necessary, flush the mapping we were building up. let flush_run =!run_info.has_font(&font) || run_info.bidi_level!= bidi_level || !compatible_script; let new_mapping_needed = flush_run || mapping.selected!= selected; if new_mapping_needed { // We ignore empty mappings at the very start of a fragment. // The run info values are uninitialized at this point so // flushing an empty mapping is pointless. if end_position > 0 { mapping.flush(&mut mappings, &mut run_info, &**text, compression, text_transform, &mut last_whitespace, &mut start_position, end_position); } if run_info.text.len() > 0 { if flush_run { run_info.flush(&mut run_info_list, &mut insertion_point); run_info = RunInfo::new(); } mapping = RunMapping::new(&run_info_list[..], fragment_index); } run_info.font = font; run_info.bidi_level = bidi_level; run_info.script = script; mapping.selected = selected; } } // Consume this character. end_position += character.len_utf8(); *paragraph_bytes_processed += character.len_utf8(); } // Flush the last mapping we created for this fragment to the list. mapping.flush(&mut mappings, &mut run_info, &**text, compression, text_transform, &mut last_whitespace, &mut start_position, end_position); } // Push the final run info. run_info.flush(&mut run_info_list, &mut insertion_point); // Per CSS 2.1 § 16.4, "when the resultant space between two characters is not the same // as the default space, user agents should not use ligatures." This ensures that, for // example, `finally` with a wide `letter-spacing` renders as `f i n a l l y` and not // `fi n a l l y`. let mut flags = ShapingFlags::empty(); if let Some(v) = letter_spacing.value() { if v.px()!= 0. { flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG); } } if text_rendering == TextRendering::Optimizespeed { flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG); flags.insert(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG) } if word_break == WordBreak::KeepAll { flags.insert(ShapingFlags::KEEP_ALL_FLAG); } let options = ShapingOptions { letter_spacing: letter_spacing.value().cloned().map(Au::from), word_spacing: word_spacing, script: Script::Common, flags: flags, }; let mut result = Vec::with_capacity(run_info_list.len()); for run_info in run_info_list { let mut options = options; options.script = run_info.script; if run_info.bidi_level.is_rtl() { options.flags.insert(ShapingFlags::RTL_FLAG); } // If no font is found (including fallbacks), there's no way we can render. let font = run_info.font .or_else(|| font_group.borrow_mut().first(&mut font_context)) .expect("No font found for text run!"); let (run, break_at_zero) = TextRun::new(&mut *font.borrow_mut(), run_info.text, &options, run_info.bidi_level, linebreaker); result.push((ScannedTextRun { run: Arc::new(run), insertion_point: run_info.insertion_point, }, break_at_zero)) } result }; // Make new fragments with the runs and adjusted text indices. debug!("TextRunScanner: pushing {} fragment(s)", self.clump.len()); let mut mappings = mappings.into_iter().peekable(); let mut prev_fragments_to_meld = Vec::new(); for (logical_offset, old_fragment) in mem::replace(&mut self.clump, LinkedList::new()).into_iter().enumerate() { let mut is_first_mapping_of_this_old_fragment = true; loop { match mappings.peek() { Some(mapping) if mapping.old_fragment_index == logical_offset => {} Some(_) | None => { if is_first_mapping_of_this_old_fragment { // There were no mappings for this unscanned fragment. Transfer its // flags to the previous/next sibling elements instead. if let Some(ref mut last_fragment) = out_fragments.last_mut() { last_fragment.meld_with_next_inline_fragment(&old_fragment); } prev_fragments_to_meld.push(old_fragment); } break; } }; let mapping = mappings.next().unwrap(); let (scanned_run, break_at_zero) = runs[mapping.text_run_index].clone(); let mut byte_range = Range::new(ByteIndex(mapping.byte_range.begin() as isize), ByteIndex(mapping.byte_range.length() as isize)); let mut flags = ScannedTextFlags::empty(); if!break_at_zero && mapping.byte_range.begin() == 0 { // If this is the first segment of the text run, // and the text run doesn't break at zero, suppress line breaks flags.insert(ScannedTextFlags::SUPPRESS_LINE_BREAK_BEFORE) } let text_size = old_fragment.border_box.size; let requires_line_break_afterward_if_wrapping_on_newlines = scanned_run.run.text[mapping.byte_range.begin()..mapping.byte_range.end()] .ends_with('\n'); if requires_line_break_afterward_if_wrapping_on_newlines { byte_range.extend_by(ByteIndex(-1)); // Trim the '\n' flags.insert(ScannedTextFlags::REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES); } if mapping.selected { flags.insert(ScannedTextFlags::SELECTED); } let insertion_point = if mapping.contains_insertion_point(scanned_run.insertion_point) { scanned_run.insertion_point } else { None }; let mut new_text_fragment_info = Box::new(ScannedTextFragmentInfo::new( scanned_run.run, byte_range, text_size, insertion_point, flags )); let new_metrics = new_text_fragment_info.run.metrics_for_range(&byte_range); let writing_mode = old_fragment.style.writing_mode; let bounding_box_size = bounding_box_for_run_metrics(&new_metrics, writing_mode); new_text_fragment_info.content_size = bounding_box_size; let mut new_fragment = old_fragment.transform( bounding_box_size, SpecificFragmentInfo::ScannedText(new_text_fragment_info)); let is_last_mapping_of_this_old_fragment = match mappings.peek() { Some(mapping) if mapping.old_fragment_index == logical_offset => false, _ => true }; if let Some(ref mut context) = new_fragment.inline_context { for node in &mut context.nodes { if!is_last_mapping_of_this_old_fragment { node.flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT); }
{ debug!("TextRunScanner: flushing {} fragments in range", self.clump.len()); debug_assert!(!self.clump.is_empty()); match self.clump.front().unwrap().specific { SpecificFragmentInfo::UnscannedText(_) => {} _ => { debug_assert!(self.clump.len() == 1, "WAT: can't coalesce non-text nodes in flush_clump_to_list()!"); out_fragments.push(self.clump.pop_front().unwrap()); return false } } // Concatenate all of the transformed strings together, saving the new character indices. let mut mappings: Vec<RunMapping> = Vec::new(); let runs = { let font_group; let compression; let text_transform;
identifier_body
text.rs
Some(range.begin() + ByteIndex(run_info.text.len() as isize)) } _ => None }; let (mut start_position, mut end_position) = (0, 0); for (byte_index, character) in text.char_indices() { if!character.is_control() { let font = font_group.borrow_mut().find_by_codepoint(&mut font_context, character); let bidi_level = match bidi_levels { Some(levels) => levels[*paragraph_bytes_processed], None => bidi::Level::ltr(), }; // Break the run if the new character has a different explicit script than the // previous characters. // // TODO: Special handling of paired punctuation characters. // http://www.unicode.org/reports/tr24/#Common let script = get_script(character); let compatible_script = is_compatible(script, run_info.script); if compatible_script &&!is_specific(run_info.script) && is_specific(script) { run_info.script = script; } let selected = match selection { Some(range) => range.contains(ByteIndex(byte_index as isize)), None => false }; // Now, if necessary, flush the mapping we were building up. let flush_run =!run_info.has_font(&font) || run_info.bidi_level!= bidi_level || !compatible_script; let new_mapping_needed = flush_run || mapping.selected!= selected; if new_mapping_needed { // We ignore empty mappings at the very start of a fragment. // The run info values are uninitialized at this point so // flushing an empty mapping is pointless. if end_position > 0 { mapping.flush(&mut mappings, &mut run_info, &**text, compression, text_transform, &mut last_whitespace, &mut start_position, end_position); } if run_info.text.len() > 0 { if flush_run { run_info.flush(&mut run_info_list, &mut insertion_point); run_info = RunInfo::new(); } mapping = RunMapping::new(&run_info_list[..], fragment_index); } run_info.font = font; run_info.bidi_level = bidi_level; run_info.script = script; mapping.selected = selected; } } // Consume this character. end_position += character.len_utf8(); *paragraph_bytes_processed += character.len_utf8(); } // Flush the last mapping we created for this fragment to the list. mapping.flush(&mut mappings, &mut run_info, &**text, compression, text_transform, &mut last_whitespace, &mut start_position, end_position); } // Push the final run info. run_info.flush(&mut run_info_list, &mut insertion_point); // Per CSS 2.1 § 16.4, "when the resultant space between two characters is not the same // as the default space, user agents should not use ligatures." This ensures that, for // example, `finally` with a wide `letter-spacing` renders as `f i n a l l y` and not // `fi n a l l y`. let mut flags = ShapingFlags::empty(); if let Some(v) = letter_spacing.value() { if v.px()!= 0. { flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG); } } if text_rendering == TextRendering::Optimizespeed { flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG); flags.insert(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG) } if word_break == WordBreak::KeepAll { flags.insert(ShapingFlags::KEEP_ALL_FLAG); } let options = ShapingOptions { letter_spacing: letter_spacing.value().cloned().map(Au::from), word_spacing: word_spacing, script: Script::Common, flags: flags, }; let mut result = Vec::with_capacity(run_info_list.len()); for run_info in run_info_list { let mut options = options; options.script = run_info.script; if run_info.bidi_level.is_rtl() { options.flags.insert(ShapingFlags::RTL_FLAG); } // If no font is found (including fallbacks), there's no way we can render. let font = run_info.font .or_else(|| font_group.borrow_mut().first(&mut font_context)) .expect("No font found for text run!"); let (run, break_at_zero) = TextRun::new(&mut *font.borrow_mut(), run_info.text, &options, run_info.bidi_level, linebreaker); result.push((ScannedTextRun { run: Arc::new(run), insertion_point: run_info.insertion_point, }, break_at_zero)) } result }; // Make new fragments with the runs and adjusted text indices. debug!("TextRunScanner: pushing {} fragment(s)", self.clump.len()); let mut mappings = mappings.into_iter().peekable(); let mut prev_fragments_to_meld = Vec::new(); for (logical_offset, old_fragment) in mem::replace(&mut self.clump, LinkedList::new()).into_iter().enumerate() { let mut is_first_mapping_of_this_old_fragment = true; loop { match mappings.peek() { Some(mapping) if mapping.old_fragment_index == logical_offset => {} Some(_) | None => { if is_first_mapping_of_this_old_fragment { // There were no mappings for this unscanned fragment. Transfer its // flags to the previous/next sibling elements instead. if let Some(ref mut last_fragment) = out_fragments.last_mut() { last_fragment.meld_with_next_inline_fragment(&old_fragment); } prev_fragments_to_meld.push(old_fragment); } break; } }; let mapping = mappings.next().unwrap(); let (scanned_run, break_at_zero) = runs[mapping.text_run_index].clone(); let mut byte_range = Range::new(ByteIndex(mapping.byte_range.begin() as isize), ByteIndex(mapping.byte_range.length() as isize)); let mut flags = ScannedTextFlags::empty(); if!break_at_zero && mapping.byte_range.begin() == 0 { // If this is the first segment of the text run, // and the text run doesn't break at zero, suppress line breaks flags.insert(ScannedTextFlags::SUPPRESS_LINE_BREAK_BEFORE) } let text_size = old_fragment.border_box.size; let requires_line_break_afterward_if_wrapping_on_newlines = scanned_run.run.text[mapping.byte_range.begin()..mapping.byte_range.end()] .ends_with('\n'); if requires_line_break_afterward_if_wrapping_on_newlines { byte_range.extend_by(ByteIndex(-1)); // Trim the '\n' flags.insert(ScannedTextFlags::REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES); } if mapping.selected { flags.insert(ScannedTextFlags::SELECTED); } let insertion_point = if mapping.contains_insertion_point(scanned_run.insertion_point) { scanned_run.insertion_point } else { None }; let mut new_text_fragment_info = Box::new(ScannedTextFragmentInfo::new( scanned_run.run, byte_range, text_size, insertion_point, flags )); let new_metrics = new_text_fragment_info.run.metrics_for_range(&byte_range); let writing_mode = old_fragment.style.writing_mode; let bounding_box_size = bounding_box_for_run_metrics(&new_metrics, writing_mode); new_text_fragment_info.content_size = bounding_box_size; let mut new_fragment = old_fragment.transform( bounding_box_size, SpecificFragmentInfo::ScannedText(new_text_fragment_info)); let is_last_mapping_of_this_old_fragment = match mappings.peek() { Some(mapping) if mapping.old_fragment_index == logical_offset => false, _ => true }; if let Some(ref mut context) = new_fragment.inline_context { for node in &mut context.nodes { if!is_last_mapping_of_this_old_fragment { node.flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT); } if!is_first_mapping_of_this_old_fragment { node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT); } } } for prev_fragment in prev_fragments_to_meld.drain(..) { new_fragment.meld_with_prev_inline_fragment(&prev_fragment); } is_first_mapping_of_this_old_fragment = false; out_fragments.push(new_fragment) } } last_whitespace } } #[inline] fn bounding_box_for_run_metrics(metrics: &RunMetrics, writing_mode: WritingMode) -> LogicalSize<Au> { // TODO: When the text-orientation property is supported, the block and inline directions may // be swapped for horizontal glyphs in vertical lines. LogicalSize::new( writing_mode, metrics.bounding_box.size.width, metrics.bounding_box.size.height) } /// Returns the metrics of the font represented by the given `FontStyleStruct`. /// /// `#[inline]` because often the caller only needs a few fields from the font metrics. /// /// # Panics /// /// Panics if no font can be found for the given font style. #[inline] pub fn font_metrics_for_style(mut font_context: &mut LayoutFontContext, style: ::ServoArc<FontStyleStruct>) -> FontMetrics { let font_group = font_context.font_group(style); let font = font_group.borrow_mut().first(&mut font_context); let font = font.as_ref().unwrap().borrow(); font.metrics.clone() } /// Returns the line block-size needed by the given computed style and font size. pub fn line_height_from_style(style: &ComputedValues, metrics: &FontMetrics) -> Au { let font_size = style.get_font().font_size.size(); match style.get_inheritedtext().line_height { LineHeight::Normal => Au::from(metrics.line_gap), LineHeight::Number(l) => font_size.scale_by(l.0), LineHeight::Length(l) => Au::from(l) } } fn split_first_fragment_at_newline_if_necessary(fragments: &mut LinkedList<Fragment>) { if fragments.is_empty() { return } let new_fragment = { let first_fragment = fragments.front_mut().unwrap(); let string_before; let selection_before; { if!first_fragment.white_space().preserve_newlines() { return; } let unscanned_text_fragment_info = match first_fragment.specific { SpecificFragmentInfo::UnscannedText(ref mut unscanned_text_fragment_info) => { unscanned_text_fragment_info } _ => return, }; let position = match unscanned_text_fragment_info.text.find('\n') { Some(position) if position < unscanned_text_fragment_info.text.len() - 1 => { position } Some(_) | None => return, }; string_before = unscanned_text_fragment_info.text[..(position + 1)].to_owned(); unscanned_text_fragment_info.text = unscanned_text_fragment_info.text[(position + 1)..].to_owned().into_boxed_str(); let offset = ByteIndex(string_before.len() as isize); match unscanned_text_fragment_info.selection { Some(ref mut selection) if selection.begin() >= offset => { // Selection is entirely in the second fragment. selection_before = None; selection.shift_by(-offset); } Some(ref mut selection) if selection.end() > offset => { // Selection is split across two fragments. selection_before = Some(Range::new(selection.begin(), offset)); *selection = Range::new(ByteIndex(0), selection.end() - offset); } _ => { // Selection is entirely in the first fragment. selection_before = unscanned_text_fragment_info.selection;
unscanned_text_fragment_info.selection = None; }
random_line_split
text.rs
None => bidi::Level::ltr(), }; // Break the run if the new character has a different explicit script than the // previous characters. // // TODO: Special handling of paired punctuation characters. // http://www.unicode.org/reports/tr24/#Common let script = get_script(character); let compatible_script = is_compatible(script, run_info.script); if compatible_script &&!is_specific(run_info.script) && is_specific(script) { run_info.script = script; } let selected = match selection { Some(range) => range.contains(ByteIndex(byte_index as isize)), None => false }; // Now, if necessary, flush the mapping we were building up. let flush_run =!run_info.has_font(&font) || run_info.bidi_level!= bidi_level || !compatible_script; let new_mapping_needed = flush_run || mapping.selected!= selected; if new_mapping_needed { // We ignore empty mappings at the very start of a fragment. // The run info values are uninitialized at this point so // flushing an empty mapping is pointless. if end_position > 0 { mapping.flush(&mut mappings, &mut run_info, &**text, compression, text_transform, &mut last_whitespace, &mut start_position, end_position); } if run_info.text.len() > 0 { if flush_run { run_info.flush(&mut run_info_list, &mut insertion_point); run_info = RunInfo::new(); } mapping = RunMapping::new(&run_info_list[..], fragment_index); } run_info.font = font; run_info.bidi_level = bidi_level; run_info.script = script; mapping.selected = selected; } } // Consume this character. end_position += character.len_utf8(); *paragraph_bytes_processed += character.len_utf8(); } // Flush the last mapping we created for this fragment to the list. mapping.flush(&mut mappings, &mut run_info, &**text, compression, text_transform, &mut last_whitespace, &mut start_position, end_position); } // Push the final run info. run_info.flush(&mut run_info_list, &mut insertion_point); // Per CSS 2.1 § 16.4, "when the resultant space between two characters is not the same // as the default space, user agents should not use ligatures." This ensures that, for // example, `finally` with a wide `letter-spacing` renders as `f i n a l l y` and not // `fi n a l l y`. let mut flags = ShapingFlags::empty(); if let Some(v) = letter_spacing.value() { if v.px()!= 0. { flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG); } } if text_rendering == TextRendering::Optimizespeed { flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG); flags.insert(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG) } if word_break == WordBreak::KeepAll { flags.insert(ShapingFlags::KEEP_ALL_FLAG); } let options = ShapingOptions { letter_spacing: letter_spacing.value().cloned().map(Au::from), word_spacing: word_spacing, script: Script::Common, flags: flags, }; let mut result = Vec::with_capacity(run_info_list.len()); for run_info in run_info_list { let mut options = options; options.script = run_info.script; if run_info.bidi_level.is_rtl() { options.flags.insert(ShapingFlags::RTL_FLAG); } // If no font is found (including fallbacks), there's no way we can render. let font = run_info.font .or_else(|| font_group.borrow_mut().first(&mut font_context)) .expect("No font found for text run!"); let (run, break_at_zero) = TextRun::new(&mut *font.borrow_mut(), run_info.text, &options, run_info.bidi_level, linebreaker); result.push((ScannedTextRun { run: Arc::new(run), insertion_point: run_info.insertion_point, }, break_at_zero)) } result }; // Make new fragments with the runs and adjusted text indices. debug!("TextRunScanner: pushing {} fragment(s)", self.clump.len()); let mut mappings = mappings.into_iter().peekable(); let mut prev_fragments_to_meld = Vec::new(); for (logical_offset, old_fragment) in mem::replace(&mut self.clump, LinkedList::new()).into_iter().enumerate() { let mut is_first_mapping_of_this_old_fragment = true; loop { match mappings.peek() { Some(mapping) if mapping.old_fragment_index == logical_offset => {} Some(_) | None => { if is_first_mapping_of_this_old_fragment { // There were no mappings for this unscanned fragment. Transfer its // flags to the previous/next sibling elements instead. if let Some(ref mut last_fragment) = out_fragments.last_mut() { last_fragment.meld_with_next_inline_fragment(&old_fragment); } prev_fragments_to_meld.push(old_fragment); } break; } }; let mapping = mappings.next().unwrap(); let (scanned_run, break_at_zero) = runs[mapping.text_run_index].clone(); let mut byte_range = Range::new(ByteIndex(mapping.byte_range.begin() as isize), ByteIndex(mapping.byte_range.length() as isize)); let mut flags = ScannedTextFlags::empty(); if!break_at_zero && mapping.byte_range.begin() == 0 { // If this is the first segment of the text run, // and the text run doesn't break at zero, suppress line breaks flags.insert(ScannedTextFlags::SUPPRESS_LINE_BREAK_BEFORE) } let text_size = old_fragment.border_box.size; let requires_line_break_afterward_if_wrapping_on_newlines = scanned_run.run.text[mapping.byte_range.begin()..mapping.byte_range.end()] .ends_with('\n'); if requires_line_break_afterward_if_wrapping_on_newlines { byte_range.extend_by(ByteIndex(-1)); // Trim the '\n' flags.insert(ScannedTextFlags::REQUIRES_LINE_BREAK_AFTERWARD_IF_WRAPPING_ON_NEWLINES); } if mapping.selected { flags.insert(ScannedTextFlags::SELECTED); } let insertion_point = if mapping.contains_insertion_point(scanned_run.insertion_point) { scanned_run.insertion_point } else { None }; let mut new_text_fragment_info = Box::new(ScannedTextFragmentInfo::new( scanned_run.run, byte_range, text_size, insertion_point, flags )); let new_metrics = new_text_fragment_info.run.metrics_for_range(&byte_range); let writing_mode = old_fragment.style.writing_mode; let bounding_box_size = bounding_box_for_run_metrics(&new_metrics, writing_mode); new_text_fragment_info.content_size = bounding_box_size; let mut new_fragment = old_fragment.transform( bounding_box_size, SpecificFragmentInfo::ScannedText(new_text_fragment_info)); let is_last_mapping_of_this_old_fragment = match mappings.peek() { Some(mapping) if mapping.old_fragment_index == logical_offset => false, _ => true }; if let Some(ref mut context) = new_fragment.inline_context { for node in &mut context.nodes { if!is_last_mapping_of_this_old_fragment { node.flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT); } if!is_first_mapping_of_this_old_fragment { node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT); } } } for prev_fragment in prev_fragments_to_meld.drain(..) { new_fragment.meld_with_prev_inline_fragment(&prev_fragment); } is_first_mapping_of_this_old_fragment = false; out_fragments.push(new_fragment) } } last_whitespace } } #[inline] fn bounding_box_for_run_metrics(metrics: &RunMetrics, writing_mode: WritingMode) -> LogicalSize<Au> { // TODO: When the text-orientation property is supported, the block and inline directions may // be swapped for horizontal glyphs in vertical lines. LogicalSize::new( writing_mode, metrics.bounding_box.size.width, metrics.bounding_box.size.height) } /// Returns the metrics of the font represented by the given `FontStyleStruct`. /// /// `#[inline]` because often the caller only needs a few fields from the font metrics. /// /// # Panics /// /// Panics if no font can be found for the given font style. #[inline] pub fn font_metrics_for_style(mut font_context: &mut LayoutFontContext, style: ::ServoArc<FontStyleStruct>) -> FontMetrics { let font_group = font_context.font_group(style); let font = font_group.borrow_mut().first(&mut font_context); let font = font.as_ref().unwrap().borrow(); font.metrics.clone() } /// Returns the line block-size needed by the given computed style and font size. pub fn line_height_from_style(style: &ComputedValues, metrics: &FontMetrics) -> Au { let font_size = style.get_font().font_size.size(); match style.get_inheritedtext().line_height { LineHeight::Normal => Au::from(metrics.line_gap), LineHeight::Number(l) => font_size.scale_by(l.0), LineHeight::Length(l) => Au::from(l) } } fn split_first_fragment_at_newline_if_necessary(fragments: &mut LinkedList<Fragment>) { if fragments.is_empty() { return } let new_fragment = { let first_fragment = fragments.front_mut().unwrap(); let string_before; let selection_before; { if!first_fragment.white_space().preserve_newlines() { return; } let unscanned_text_fragment_info = match first_fragment.specific { SpecificFragmentInfo::UnscannedText(ref mut unscanned_text_fragment_info) => { unscanned_text_fragment_info } _ => return, }; let position = match unscanned_text_fragment_info.text.find('\n') { Some(position) if position < unscanned_text_fragment_info.text.len() - 1 => { position } Some(_) | None => return, }; string_before = unscanned_text_fragment_info.text[..(position + 1)].to_owned(); unscanned_text_fragment_info.text = unscanned_text_fragment_info.text[(position + 1)..].to_owned().into_boxed_str(); let offset = ByteIndex(string_before.len() as isize); match unscanned_text_fragment_info.selection { Some(ref mut selection) if selection.begin() >= offset => { // Selection is entirely in the second fragment. selection_before = None; selection.shift_by(-offset); } Some(ref mut selection) if selection.end() > offset => { // Selection is split across two fragments. selection_before = Some(Range::new(selection.begin(), offset)); *selection = Range::new(ByteIndex(0), selection.end() - offset); } _ => { // Selection is entirely in the first fragment. selection_before = unscanned_text_fragment_info.selection; unscanned_text_fragment_info.selection = None; } }; } first_fragment.transform( first_fragment.border_box.size, SpecificFragmentInfo::UnscannedText(Box::new( UnscannedTextFragmentInfo::new(string_before.into_boxed_str(), selection_before) )) ) }; fragments.push_front(new_fragment); } /// Information about a text run that we're about to create. This is used in `scan_for_runs`. struct RunInfo { /// The text that will go in this text run. text: String, /// The insertion point in this text run, if applicable. insertion_point: Option<ByteIndex>, /// The font that the text should be rendered with. font: Option<FontRef>, /// The bidirection embedding level of this text run. bidi_level: bidi::Level, /// The Unicode script property of this text run. script: Script, } impl RunInfo { fn new
()
identifier_name
lib.rs
#![doc(html_root_url = "http://garrensmith.com/mango_smoothie/")] //! Mango Smoothie //! Mango Smoothie is a [CouchDB Mango](http://docs.couchdb.org/en/latest/api/database/find.html) / //! [Cloudant Query](https://docs.cloudant.com/cloudant_query.html) client library. //! //! # Create Indexes //! //! To create an index first specify the url to the CouchDB/Cloudant instance, then //! specify the fields to be indexed. //! //! ```ignore //! extern crate mango_smoothie; //! use mango_smoothie::{database}; //! //! let resp = database("http://tester:[email protected]:5984/animaldb").unwrap() //! .create_index(&["class", "name"]); //! ``` //! //! # View Indexes //! //! To list all the available indexes do the following: //! //! ``` ignore //! let indexes = database("http://tester:[email protected]:5984/animaldb").unwrap() //! .list_indexes().unwrap(); //! //! assert!(indexes.total_rows > 0); //! assert_eq!(indexes.indexes[0].name, "_all_docs".to_string()); //! assert!(indexes.indexes[0].def.fields[0].contains_key(&"_id".to_string())); //! ``` //! //! # Query Indexes //! //! Mango Smoothie uses the [serde_json](https://docs.serde.rs/serde_json/) //! macro to help with querying indexes. //! //! ``` ignore //! extern crate mango_smoothie; //! use mango_smoothie::{database}; //! #[macro_use] //! extern crate serde_json; //! //! let query = json!({ //! "selector": { //! "_id": { //! "$gt": "1" //! } //! }, //! "fields": ["_id", "name"], //! "skip": 3, //! "sort": [{"_id": "asc"}] //! }); //! //! let query_resp = db.query_index(query).unwrap(); //! assert_eq!(result.docs.len(), 5); //! let doc = &result.docs[0];
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate hyper; pub mod http; pub mod errors; mod database; pub use database::database;
//! assert_eq!(doc["class"], "mammal"); //! ```
random_line_split
handler.rs
use super::Message; use super::responder::{MessageResponder,ResponderError}; use super::verify::{MessageVerifier,MessageVerifierError}; use std::sync::mpsc::SendError; pub enum MessageHandlingError { VerificationError, ResponseError } impl From<ResponderError> for MessageHandlingError { fn
(_: ResponderError) -> MessageHandlingError { MessageHandlingError::ResponseError } } impl From<MessageVerifierError> for MessageHandlingError { fn from(_: MessageVerifierError) -> MessageHandlingError { MessageHandlingError::VerificationError } } pub struct MessageHandler { message_verifier: MessageVerifier, message_responder: MessageResponder } impl MessageHandler { pub fn new(message_verifier: MessageVerifier, message_responder: MessageResponder) -> MessageHandler { MessageHandler { message_verifier: message_verifier, message_responder: message_responder } } pub fn send_version<F>(&self, f: F) -> Result<(), SendError<Message>> where F : Fn(Message) -> Result<(), SendError<Message>> { self.message_responder.send_version(f) } pub fn handle<F>(&mut self, message: Message, send: F) -> Result<(), MessageHandlingError> where F : Fn(Message) -> Result<(), SendError<Message>> { try!(self.message_verifier.verify(&message)); try!(self.message_responder.respond(message, send)); Ok(()) } }
from
identifier_name
handler.rs
use super::Message; use super::responder::{MessageResponder,ResponderError}; use super::verify::{MessageVerifier,MessageVerifierError}; use std::sync::mpsc::SendError; pub enum MessageHandlingError { VerificationError, ResponseError } impl From<ResponderError> for MessageHandlingError { fn from(_: ResponderError) -> MessageHandlingError { MessageHandlingError::ResponseError } } impl From<MessageVerifierError> for MessageHandlingError { fn from(_: MessageVerifierError) -> MessageHandlingError { MessageHandlingError::VerificationError } } pub struct MessageHandler { message_verifier: MessageVerifier, message_responder: MessageResponder } impl MessageHandler { pub fn new(message_verifier: MessageVerifier, message_responder: MessageResponder) -> MessageHandler { MessageHandler { message_verifier: message_verifier, message_responder: message_responder } } pub fn send_version<F>(&self, f: F) -> Result<(), SendError<Message>> where F : Fn(Message) -> Result<(), SendError<Message>> { self.message_responder.send_version(f) } pub fn handle<F>(&mut self, message: Message, send: F) -> Result<(), MessageHandlingError> where F : Fn(Message) -> Result<(), SendError<Message>>
}
{ try!(self.message_verifier.verify(&message)); try!(self.message_responder.respond(message, send)); Ok(()) }
identifier_body
handler.rs
use super::Message; use super::responder::{MessageResponder,ResponderError}; use super::verify::{MessageVerifier,MessageVerifierError}; use std::sync::mpsc::SendError; pub enum MessageHandlingError { VerificationError, ResponseError } impl From<ResponderError> for MessageHandlingError { fn from(_: ResponderError) -> MessageHandlingError { MessageHandlingError::ResponseError } } impl From<MessageVerifierError> for MessageHandlingError { fn from(_: MessageVerifierError) -> MessageHandlingError { MessageHandlingError::VerificationError }
message_verifier: MessageVerifier, message_responder: MessageResponder } impl MessageHandler { pub fn new(message_verifier: MessageVerifier, message_responder: MessageResponder) -> MessageHandler { MessageHandler { message_verifier: message_verifier, message_responder: message_responder } } pub fn send_version<F>(&self, f: F) -> Result<(), SendError<Message>> where F : Fn(Message) -> Result<(), SendError<Message>> { self.message_responder.send_version(f) } pub fn handle<F>(&mut self, message: Message, send: F) -> Result<(), MessageHandlingError> where F : Fn(Message) -> Result<(), SendError<Message>> { try!(self.message_verifier.verify(&message)); try!(self.message_responder.respond(message, send)); Ok(()) } }
} pub struct MessageHandler {
random_line_split
rfc2616.rs
//! Values taken from RFC 2616 use std::fmt; use std::str::FromStr; use std::ascii::AsciiExt; /// OCTET: any 8-bit sequence of data (typechecking ensures this to be true) #[inline] pub fn is_octet(_: u8) -> bool { true } /// CHAR: any US-ASCII character (octets 0 - 127) #[inline] pub fn is_char(octet: u8) -> bool { octet < 128 } /// UPALPHA: any US-ASCII uppercase letter "A".."Z"> #[inline] pub fn is_upalpha(octet: u8) -> bool { octet >= b'A' && octet <= b'Z' } /// LOALPHA: any US-ASCII lowercase letter "a".."z"> #[inline] pub fn is_loalpha(octet: u8) -> bool { octet >= b'a' && octet <= b'z' } /// ALPHA: UPALPHA | LOALPHA #[inline] pub fn is_alpha(octet: u8) -> bool { is_upalpha(octet) || is_loalpha(octet) } /// DIGIT: any US-ASCII digit "0".."9" #[inline] pub fn is_digit(octet: u8) -> bool { octet >= b'0' && octet <= b'9' } /// CTL: any US-ASCII control character (octets 0 - 31) and DEL (127) #[inline] pub fn is_ctl(octet: u8) -> bool { octet < 32 || octet == 127 } /// CR: US-ASCII CR, carriage return (13) pub const CR: u8 = b'\r'; /// LF: US-ASCII LF, linefeed (10) pub const LF: u8 = b'\n'; /// SP: US-ASCII SP, space (32) pub const SP: u8 = b' '; /// HT: US-ASCII HT, horizontal-tab (9) pub const HT: u8 = b'\t'; /// US-ASCII colon (58) pub const COLON: u8 = b':'; /// <">: US-ASCII double-quote mark (34) pub const DOUBLE_QUOTE: u8 = b'"'; /// "\": US-ASCII backslash (92) pub const BACKSLASH: u8 = b'\\'; // CRLF: CR LF //const CRLF: [u8] = [CR, LF]; // LWS: [CRLF] 1*( SP | HT ) /*#[inline] fn is_lws(octets: &[u8]) -> bool { let mut has_crlf = false; let mut iter = octets.iter(); if len(octets) == 0 { return false; } if len(octets) > 2 && octets[0] == CR && octets[1] == LF { iter = iter.next().next(); } iter.all(|&octet| octet == SP || octet == HT) } */ /* The TEXT rule is only used for descriptive field contents and values
TEXT = <any OCTET except CTLs, but including LWS> A CRLF is allowed in the definition of TEXT only as part of a header field continuation. It is expected that the folding LWS will be replaced with a single SP before interpretation of the TEXT value. */ /// HEX: "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f" | DIGIT #[inline] pub fn is_hex(octet: u8) -> bool { (octet >= b'A' && octet <= b'F') || (octet >= b'a' && octet <= b'f') || is_digit(octet) } /// token = 1*<any CHAR except CTLs or separators> #[inline] pub fn is_token_item(o: u8) -> bool { is_char(o) &&!is_ctl(o) &&!is_separator(o) } #[inline] pub fn is_token(s: &String) -> bool { s[].bytes().all(|b| is_token_item(b)) } /// separators: "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" /// | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" /// | "}" | SP | HT #[inline] pub fn is_separator(o: u8) -> bool { o == b'(' || o == b')' || o == b'<' || o == b'>' || o == b'@' || o == b',' || o == b';' || o == b':' || o == b'\\' || o == b'"' || o == b'/' || o == b'[' || o == b']' || o == b'?' || o == b'=' || o == b'{' || o == b'}' || o == SP || o == HT } /* * Comments can be included in some HTTP header fields by surrounding * the comment text with parentheses. Comments are only allowed in * fields containing "comment" as part of their field value definition. * In all other fields, parentheses are considered part of the field * value. * * comment = "(" *( ctext | quoted-pair | comment ) ")" * ctext = <any TEXT excluding "(" and ")"> * * A string of text is parsed as a single word if it is quoted using * double-quote marks. * * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) * qdtext = <any TEXT except <">> * * The backslash character ("\") MAY be used as a single-character * quoting mechanism only within quoted-string and comment constructs. * * quoted-pair = "\" CHAR */ //#[inline] //fn is_quoted_pair(o: &[u8,..2]) { o[0] == 92 } // IANA is assigned as maintaining the registry for these things: // see https://www.iana.org/assignments/http-parameters/http-parameters.xml /// Content-coding value tokens #[derive(Copy)] pub enum ContentCoding { // An encoding format produced by the file compression program "gzip" (GNU zip) as described // in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC. Gzip, // The encoding format produced by the common UNIX file compression program "compress". This // format is an adaptive Lempel-Ziv-Welch coding (LZW). // // Use of program names for the identification of encoding formats is not desirable and is // discouraged for future encodings. Their use here is representative of historical // practice, not good design. For compatibility with previous implementations of HTTP, // applications SHOULD consider "x-gzip" and "x-compress" to be equivalent to "gzip" and // "compress" respectively. Compress, // The "zlib" format defined in RFC 1950 [31] in combination with the "deflate" compression // mechanism described in RFC 1951 [29]. Deflate, // The default (identity) encoding; the use of no transformation whatsoever. This // content-coding is used only in the Accept- Encoding header, and SHOULD NOT be used in the // Content-Encoding header. Identity, // IANA has also assigned the following currently unsupported content codings: // // - "exi": W3C Efficient XML Interchange // - "pack200-gzip" (Network Transfer Format for Java Archives) } impl fmt::Show for ContentCoding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { ContentCoding::Gzip => "gzip", ContentCoding::Compress => "compress", ContentCoding::Deflate => "deflate", ContentCoding::Identity => "identity", }) } } impl FromStr for ContentCoding { fn from_str(s: &str) -> Option<ContentCoding> { if s.eq_ignore_ascii_case("gzip") { Some(ContentCoding::Gzip) } else if s.eq_ignore_ascii_case("compress") { Some(ContentCoding::Compress) } else if s.eq_ignore_ascii_case("deflate") { Some(ContentCoding::Deflate) } else if s.eq_ignore_ascii_case("identity") { Some(ContentCoding::Identity) } else { None } } } /// Transfer-coding value tokens // Identity is in RFC 2616 but is withdrawn in RFC 2616 errata ID 408 // http://www.rfc-editor.org/errata_search.php?rfc=2616&eid=408 #[derive(Copy)] pub enum TransferCoding { Chunked, // RFC 2616, §3.6.1 Gzip, // See above Compress, // See above Deflate, // See above } impl fmt::Show for TransferCoding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { TransferCoding::Chunked => "chunked", TransferCoding::Gzip => "gzip", TransferCoding::Compress => "compress", TransferCoding::Deflate => "deflate", }) } } impl FromStr for TransferCoding { fn from_str(s: &str) -> Option<TransferCoding> { if s.eq_ignore_ascii_case("gzip") { Some(TransferCoding::Gzip) } else if s.eq_ignore_ascii_case("compress") { Some(TransferCoding::Compress) } else if s.eq_ignore_ascii_case("deflate") { Some(TransferCoding::Deflate) } else if s.eq_ignore_ascii_case("chunked") { Some(TransferCoding::Chunked) } else { None } } } // A server which receives an entity-body with a transfer-coding it does // not understand SHOULD return 501 (Unimplemented), and close the // connection. A server MUST NOT send transfer-codings to an HTTP/1.0 // client. // [My note: implication of this is that I need to track HTTP version number of clients.]
that are not intended to be interpreted by the message parser. Words of *TEXT MAY contain characters from character sets other than ISO- 8859-1 [22] only when encoded according to the rules of RFC 2047 [14].
random_line_split
rfc2616.rs
//! Values taken from RFC 2616 use std::fmt; use std::str::FromStr; use std::ascii::AsciiExt; /// OCTET: any 8-bit sequence of data (typechecking ensures this to be true) #[inline] pub fn is_octet(_: u8) -> bool { true } /// CHAR: any US-ASCII character (octets 0 - 127) #[inline] pub fn is_char(octet: u8) -> bool { octet < 128 } /// UPALPHA: any US-ASCII uppercase letter "A".."Z"> #[inline] pub fn is_upalpha(octet: u8) -> bool { octet >= b'A' && octet <= b'Z' } /// LOALPHA: any US-ASCII lowercase letter "a".."z"> #[inline] pub fn is_loalpha(octet: u8) -> bool { octet >= b'a' && octet <= b'z' } /// ALPHA: UPALPHA | LOALPHA #[inline] pub fn is_alpha(octet: u8) -> bool { is_upalpha(octet) || is_loalpha(octet) } /// DIGIT: any US-ASCII digit "0".."9" #[inline] pub fn is_digit(octet: u8) -> bool { octet >= b'0' && octet <= b'9' } /// CTL: any US-ASCII control character (octets 0 - 31) and DEL (127) #[inline] pub fn is_ctl(octet: u8) -> bool { octet < 32 || octet == 127 } /// CR: US-ASCII CR, carriage return (13) pub const CR: u8 = b'\r'; /// LF: US-ASCII LF, linefeed (10) pub const LF: u8 = b'\n'; /// SP: US-ASCII SP, space (32) pub const SP: u8 = b' '; /// HT: US-ASCII HT, horizontal-tab (9) pub const HT: u8 = b'\t'; /// US-ASCII colon (58) pub const COLON: u8 = b':'; /// <">: US-ASCII double-quote mark (34) pub const DOUBLE_QUOTE: u8 = b'"'; /// "\": US-ASCII backslash (92) pub const BACKSLASH: u8 = b'\\'; // CRLF: CR LF //const CRLF: [u8] = [CR, LF]; // LWS: [CRLF] 1*( SP | HT ) /*#[inline] fn is_lws(octets: &[u8]) -> bool { let mut has_crlf = false; let mut iter = octets.iter(); if len(octets) == 0 { return false; } if len(octets) > 2 && octets[0] == CR && octets[1] == LF { iter = iter.next().next(); } iter.all(|&octet| octet == SP || octet == HT) } */ /* The TEXT rule is only used for descriptive field contents and values that are not intended to be interpreted by the message parser. Words of *TEXT MAY contain characters from character sets other than ISO- 8859-1 [22] only when encoded according to the rules of RFC 2047 [14]. TEXT = <any OCTET except CTLs, but including LWS> A CRLF is allowed in the definition of TEXT only as part of a header field continuation. It is expected that the folding LWS will be replaced with a single SP before interpretation of the TEXT value. */ /// HEX: "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f" | DIGIT #[inline] pub fn
(octet: u8) -> bool { (octet >= b'A' && octet <= b'F') || (octet >= b'a' && octet <= b'f') || is_digit(octet) } /// token = 1*<any CHAR except CTLs or separators> #[inline] pub fn is_token_item(o: u8) -> bool { is_char(o) &&!is_ctl(o) &&!is_separator(o) } #[inline] pub fn is_token(s: &String) -> bool { s[].bytes().all(|b| is_token_item(b)) } /// separators: "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" /// | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" /// | "}" | SP | HT #[inline] pub fn is_separator(o: u8) -> bool { o == b'(' || o == b')' || o == b'<' || o == b'>' || o == b'@' || o == b',' || o == b';' || o == b':' || o == b'\\' || o == b'"' || o == b'/' || o == b'[' || o == b']' || o == b'?' || o == b'=' || o == b'{' || o == b'}' || o == SP || o == HT } /* * Comments can be included in some HTTP header fields by surrounding * the comment text with parentheses. Comments are only allowed in * fields containing "comment" as part of their field value definition. * In all other fields, parentheses are considered part of the field * value. * * comment = "(" *( ctext | quoted-pair | comment ) ")" * ctext = <any TEXT excluding "(" and ")"> * * A string of text is parsed as a single word if it is quoted using * double-quote marks. * * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) * qdtext = <any TEXT except <">> * * The backslash character ("\") MAY be used as a single-character * quoting mechanism only within quoted-string and comment constructs. * * quoted-pair = "\" CHAR */ //#[inline] //fn is_quoted_pair(o: &[u8,..2]) { o[0] == 92 } // IANA is assigned as maintaining the registry for these things: // see https://www.iana.org/assignments/http-parameters/http-parameters.xml /// Content-coding value tokens #[derive(Copy)] pub enum ContentCoding { // An encoding format produced by the file compression program "gzip" (GNU zip) as described // in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC. Gzip, // The encoding format produced by the common UNIX file compression program "compress". This // format is an adaptive Lempel-Ziv-Welch coding (LZW). // // Use of program names for the identification of encoding formats is not desirable and is // discouraged for future encodings. Their use here is representative of historical // practice, not good design. For compatibility with previous implementations of HTTP, // applications SHOULD consider "x-gzip" and "x-compress" to be equivalent to "gzip" and // "compress" respectively. Compress, // The "zlib" format defined in RFC 1950 [31] in combination with the "deflate" compression // mechanism described in RFC 1951 [29]. Deflate, // The default (identity) encoding; the use of no transformation whatsoever. This // content-coding is used only in the Accept- Encoding header, and SHOULD NOT be used in the // Content-Encoding header. Identity, // IANA has also assigned the following currently unsupported content codings: // // - "exi": W3C Efficient XML Interchange // - "pack200-gzip" (Network Transfer Format for Java Archives) } impl fmt::Show for ContentCoding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { ContentCoding::Gzip => "gzip", ContentCoding::Compress => "compress", ContentCoding::Deflate => "deflate", ContentCoding::Identity => "identity", }) } } impl FromStr for ContentCoding { fn from_str(s: &str) -> Option<ContentCoding> { if s.eq_ignore_ascii_case("gzip") { Some(ContentCoding::Gzip) } else if s.eq_ignore_ascii_case("compress") { Some(ContentCoding::Compress) } else if s.eq_ignore_ascii_case("deflate") { Some(ContentCoding::Deflate) } else if s.eq_ignore_ascii_case("identity") { Some(ContentCoding::Identity) } else { None } } } /// Transfer-coding value tokens // Identity is in RFC 2616 but is withdrawn in RFC 2616 errata ID 408 // http://www.rfc-editor.org/errata_search.php?rfc=2616&eid=408 #[derive(Copy)] pub enum TransferCoding { Chunked, // RFC 2616, §3.6.1 Gzip, // See above Compress, // See above Deflate, // See above } impl fmt::Show for TransferCoding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { TransferCoding::Chunked => "chunked", TransferCoding::Gzip => "gzip", TransferCoding::Compress => "compress", TransferCoding::Deflate => "deflate", }) } } impl FromStr for TransferCoding { fn from_str(s: &str) -> Option<TransferCoding> { if s.eq_ignore_ascii_case("gzip") { Some(TransferCoding::Gzip) } else if s.eq_ignore_ascii_case("compress") { Some(TransferCoding::Compress) } else if s.eq_ignore_ascii_case("deflate") { Some(TransferCoding::Deflate) } else if s.eq_ignore_ascii_case("chunked") { Some(TransferCoding::Chunked) } else { None } } } // A server which receives an entity-body with a transfer-coding it does // not understand SHOULD return 501 (Unimplemented), and close the // connection. A server MUST NOT send transfer-codings to an HTTP/1.0 // client. // [My note: implication of this is that I need to track HTTP version number of clients.]
is_hex
identifier_name
rfc2616.rs
//! Values taken from RFC 2616 use std::fmt; use std::str::FromStr; use std::ascii::AsciiExt; /// OCTET: any 8-bit sequence of data (typechecking ensures this to be true) #[inline] pub fn is_octet(_: u8) -> bool { true } /// CHAR: any US-ASCII character (octets 0 - 127) #[inline] pub fn is_char(octet: u8) -> bool
/// UPALPHA: any US-ASCII uppercase letter "A".."Z"> #[inline] pub fn is_upalpha(octet: u8) -> bool { octet >= b'A' && octet <= b'Z' } /// LOALPHA: any US-ASCII lowercase letter "a".."z"> #[inline] pub fn is_loalpha(octet: u8) -> bool { octet >= b'a' && octet <= b'z' } /// ALPHA: UPALPHA | LOALPHA #[inline] pub fn is_alpha(octet: u8) -> bool { is_upalpha(octet) || is_loalpha(octet) } /// DIGIT: any US-ASCII digit "0".."9" #[inline] pub fn is_digit(octet: u8) -> bool { octet >= b'0' && octet <= b'9' } /// CTL: any US-ASCII control character (octets 0 - 31) and DEL (127) #[inline] pub fn is_ctl(octet: u8) -> bool { octet < 32 || octet == 127 } /// CR: US-ASCII CR, carriage return (13) pub const CR: u8 = b'\r'; /// LF: US-ASCII LF, linefeed (10) pub const LF: u8 = b'\n'; /// SP: US-ASCII SP, space (32) pub const SP: u8 = b' '; /// HT: US-ASCII HT, horizontal-tab (9) pub const HT: u8 = b'\t'; /// US-ASCII colon (58) pub const COLON: u8 = b':'; /// <">: US-ASCII double-quote mark (34) pub const DOUBLE_QUOTE: u8 = b'"'; /// "\": US-ASCII backslash (92) pub const BACKSLASH: u8 = b'\\'; // CRLF: CR LF //const CRLF: [u8] = [CR, LF]; // LWS: [CRLF] 1*( SP | HT ) /*#[inline] fn is_lws(octets: &[u8]) -> bool { let mut has_crlf = false; let mut iter = octets.iter(); if len(octets) == 0 { return false; } if len(octets) > 2 && octets[0] == CR && octets[1] == LF { iter = iter.next().next(); } iter.all(|&octet| octet == SP || octet == HT) } */ /* The TEXT rule is only used for descriptive field contents and values that are not intended to be interpreted by the message parser. Words of *TEXT MAY contain characters from character sets other than ISO- 8859-1 [22] only when encoded according to the rules of RFC 2047 [14]. TEXT = <any OCTET except CTLs, but including LWS> A CRLF is allowed in the definition of TEXT only as part of a header field continuation. It is expected that the folding LWS will be replaced with a single SP before interpretation of the TEXT value. */ /// HEX: "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f" | DIGIT #[inline] pub fn is_hex(octet: u8) -> bool { (octet >= b'A' && octet <= b'F') || (octet >= b'a' && octet <= b'f') || is_digit(octet) } /// token = 1*<any CHAR except CTLs or separators> #[inline] pub fn is_token_item(o: u8) -> bool { is_char(o) &&!is_ctl(o) &&!is_separator(o) } #[inline] pub fn is_token(s: &String) -> bool { s[].bytes().all(|b| is_token_item(b)) } /// separators: "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" /// | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" /// | "}" | SP | HT #[inline] pub fn is_separator(o: u8) -> bool { o == b'(' || o == b')' || o == b'<' || o == b'>' || o == b'@' || o == b',' || o == b';' || o == b':' || o == b'\\' || o == b'"' || o == b'/' || o == b'[' || o == b']' || o == b'?' || o == b'=' || o == b'{' || o == b'}' || o == SP || o == HT } /* * Comments can be included in some HTTP header fields by surrounding * the comment text with parentheses. Comments are only allowed in * fields containing "comment" as part of their field value definition. * In all other fields, parentheses are considered part of the field * value. * * comment = "(" *( ctext | quoted-pair | comment ) ")" * ctext = <any TEXT excluding "(" and ")"> * * A string of text is parsed as a single word if it is quoted using * double-quote marks. * * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) * qdtext = <any TEXT except <">> * * The backslash character ("\") MAY be used as a single-character * quoting mechanism only within quoted-string and comment constructs. * * quoted-pair = "\" CHAR */ //#[inline] //fn is_quoted_pair(o: &[u8,..2]) { o[0] == 92 } // IANA is assigned as maintaining the registry for these things: // see https://www.iana.org/assignments/http-parameters/http-parameters.xml /// Content-coding value tokens #[derive(Copy)] pub enum ContentCoding { // An encoding format produced by the file compression program "gzip" (GNU zip) as described // in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC. Gzip, // The encoding format produced by the common UNIX file compression program "compress". This // format is an adaptive Lempel-Ziv-Welch coding (LZW). // // Use of program names for the identification of encoding formats is not desirable and is // discouraged for future encodings. Their use here is representative of historical // practice, not good design. For compatibility with previous implementations of HTTP, // applications SHOULD consider "x-gzip" and "x-compress" to be equivalent to "gzip" and // "compress" respectively. Compress, // The "zlib" format defined in RFC 1950 [31] in combination with the "deflate" compression // mechanism described in RFC 1951 [29]. Deflate, // The default (identity) encoding; the use of no transformation whatsoever. This // content-coding is used only in the Accept- Encoding header, and SHOULD NOT be used in the // Content-Encoding header. Identity, // IANA has also assigned the following currently unsupported content codings: // // - "exi": W3C Efficient XML Interchange // - "pack200-gzip" (Network Transfer Format for Java Archives) } impl fmt::Show for ContentCoding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { ContentCoding::Gzip => "gzip", ContentCoding::Compress => "compress", ContentCoding::Deflate => "deflate", ContentCoding::Identity => "identity", }) } } impl FromStr for ContentCoding { fn from_str(s: &str) -> Option<ContentCoding> { if s.eq_ignore_ascii_case("gzip") { Some(ContentCoding::Gzip) } else if s.eq_ignore_ascii_case("compress") { Some(ContentCoding::Compress) } else if s.eq_ignore_ascii_case("deflate") { Some(ContentCoding::Deflate) } else if s.eq_ignore_ascii_case("identity") { Some(ContentCoding::Identity) } else { None } } } /// Transfer-coding value tokens // Identity is in RFC 2616 but is withdrawn in RFC 2616 errata ID 408 // http://www.rfc-editor.org/errata_search.php?rfc=2616&eid=408 #[derive(Copy)] pub enum TransferCoding { Chunked, // RFC 2616, §3.6.1 Gzip, // See above Compress, // See above Deflate, // See above } impl fmt::Show for TransferCoding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { TransferCoding::Chunked => "chunked", TransferCoding::Gzip => "gzip", TransferCoding::Compress => "compress", TransferCoding::Deflate => "deflate", }) } } impl FromStr for TransferCoding { fn from_str(s: &str) -> Option<TransferCoding> { if s.eq_ignore_ascii_case("gzip") { Some(TransferCoding::Gzip) } else if s.eq_ignore_ascii_case("compress") { Some(TransferCoding::Compress) } else if s.eq_ignore_ascii_case("deflate") { Some(TransferCoding::Deflate) } else if s.eq_ignore_ascii_case("chunked") { Some(TransferCoding::Chunked) } else { None } } } // A server which receives an entity-body with a transfer-coding it does // not understand SHOULD return 501 (Unimplemented), and close the // connection. A server MUST NOT send transfer-codings to an HTTP/1.0 // client. // [My note: implication of this is that I need to track HTTP version number of clients.]
{ octet < 128 }
identifier_body
arith-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// 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. pub fn main() { let i32_c: int = 0x10101010; assert!(i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3) == i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3)); }
// http://rust-lang.org/COPYRIGHT. //
random_line_split
arith-2.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. pub fn main()
{ let i32_c: int = 0x10101010; assert!(i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3) == i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3)); }
identifier_body
arith-2.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. pub fn
() { let i32_c: int = 0x10101010; assert!(i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3) == i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3)); }
main
identifier_name
day14.rs
extern crate clap; extern crate regex; use clap::App; use std::error::Error; use std::fs::File; use std::io::prelude::*; use regex::Regex; use std::collections::HashMap; #[derive(Debug, Clone)] struct ReindeerFlight { speed : u32, flight_time : u32, rest_time : u32 } impl ReindeerFlight { fn new(speed : u32, flight_time : u32, rest_time : u32) -> ReindeerFlight { ReindeerFlight { speed : speed, flight_time : flight_time, rest_time : rest_time, } } } fn main() { let matches = App::new("day14") .version("v1.0") .author("Andrew Rink <[email protected]>") .args_from_usage("-t <TIME> 'Total flight time' <FILE> 'File containing Reindeer flight data'") .get_matches(); let flight_time = matches.value_of("TIME").unwrap().parse::<u32>().unwrap(); let filename = matches.value_of("FILE").unwrap(); let mut file = match File::open(filename) { Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)), Ok(file) => file, }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)), Ok(_) => println!("Read file {}", filename), } let input = parse_input(s.trim().split('\n').collect()); let flight_results = calculate_flight_distance(flight_time, input.clone()); let distance_winner = reindeer_max_value(&flight_results); println!("Distance Winner: {} with a distance of {}", distance_winner.0, distance_winner.1); let points_result = calculate_points_winner(flight_time, input.clone()); let points_winner = reindeer_max_value(&points_result); println!("Points winner: {} with {} points", points_winner.0, points_winner.1); } fn reindeer_max_value(values : & HashMap<String, u32>) -> (String, u32) { let mut name_of_max : String = String::new(); let mut max_value : u32 = std::u32::MIN; for (key, value) in values { if *value > max_value { max_value = *value; name_of_max = key.clone(); } } (name_of_max, max_value) } fn calculate_points_winner(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> { let mut points : HashMap<String, u32> = HashMap::new(); let mut distance : HashMap<String, u32> = HashMap::new(); // Set cycle time for each reindeer. Init distance/points to 0 let mut cycles = HashMap::new(); for (key, value) in &flight_data { let cycle = value.flight_time + value.rest_time; cycles.insert(key.clone(), cycle); distance.insert(key.clone(), 0); points.insert(key.clone(), 0); } // Find distance for each time for t in 1..time+1 { for (key, value) in &flight_data { let offset = (t-1) % cycles.get(key).unwrap(); if offset < value.flight_time { if let Some(x) = distance.get_mut(key) { *x += value.speed; } } } let distance_winner = reindeer_max_value(&distance); // All reindeer in the lead get points (incl. ties) for (key, value) in &distance { if *value == distance_winner.1 { if let Some(x) = points.get_mut(key) { *x += 1; } } } } points } fn calculate_flight_distance(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> { let mut res = HashMap::new(); for (key, value) in flight_data { let cycle = value.flight_time + value.rest_time; let full_cycles = time / cycle; let mut distance : f64 = full_cycles as f64 * value.speed as f64 * value.flight_time as f64; let leftover_time = time - full_cycles * cycle; if leftover_time >= value.flight_time { distance += value.speed as f64 * value.flight_time as f64; } else { distance += value.speed as f64 * leftover_time as f64; } res.insert(key, distance as u32); } res } fn parse_input(input : Vec<&str>) -> HashMap<String, ReindeerFlight> { let mut flight = HashMap::new(); for s in input { let re = Regex::new(r"^(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.").unwrap(); for cap in re.captures_iter(s) { let name : String = String::from(cap.at(1).unwrap()); let flight_speed = cap.at(2).unwrap().parse::<u32>().unwrap(); let flight_time = cap.at(3).unwrap().parse::<u32>().unwrap(); let rest_time = cap.at(4).unwrap().parse::<u32>().unwrap(); flight.insert(name, ReindeerFlight::new(flight_speed, flight_time, rest_time)); } }
}
flight
random_line_split
day14.rs
extern crate clap; extern crate regex; use clap::App; use std::error::Error; use std::fs::File; use std::io::prelude::*; use regex::Regex; use std::collections::HashMap; #[derive(Debug, Clone)] struct ReindeerFlight { speed : u32, flight_time : u32, rest_time : u32 } impl ReindeerFlight { fn new(speed : u32, flight_time : u32, rest_time : u32) -> ReindeerFlight { ReindeerFlight { speed : speed, flight_time : flight_time, rest_time : rest_time, } } } fn main() { let matches = App::new("day14") .version("v1.0") .author("Andrew Rink <[email protected]>") .args_from_usage("-t <TIME> 'Total flight time' <FILE> 'File containing Reindeer flight data'") .get_matches(); let flight_time = matches.value_of("TIME").unwrap().parse::<u32>().unwrap(); let filename = matches.value_of("FILE").unwrap(); let mut file = match File::open(filename) { Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)), Ok(file) => file, }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)), Ok(_) => println!("Read file {}", filename), } let input = parse_input(s.trim().split('\n').collect()); let flight_results = calculate_flight_distance(flight_time, input.clone()); let distance_winner = reindeer_max_value(&flight_results); println!("Distance Winner: {} with a distance of {}", distance_winner.0, distance_winner.1); let points_result = calculate_points_winner(flight_time, input.clone()); let points_winner = reindeer_max_value(&points_result); println!("Points winner: {} with {} points", points_winner.0, points_winner.1); } fn reindeer_max_value(values : & HashMap<String, u32>) -> (String, u32) { let mut name_of_max : String = String::new(); let mut max_value : u32 = std::u32::MIN; for (key, value) in values { if *value > max_value { max_value = *value; name_of_max = key.clone(); } } (name_of_max, max_value) } fn calculate_points_winner(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> { let mut points : HashMap<String, u32> = HashMap::new(); let mut distance : HashMap<String, u32> = HashMap::new(); // Set cycle time for each reindeer. Init distance/points to 0 let mut cycles = HashMap::new(); for (key, value) in &flight_data { let cycle = value.flight_time + value.rest_time; cycles.insert(key.clone(), cycle); distance.insert(key.clone(), 0); points.insert(key.clone(), 0); } // Find distance for each time for t in 1..time+1 { for (key, value) in &flight_data { let offset = (t-1) % cycles.get(key).unwrap(); if offset < value.flight_time { if let Some(x) = distance.get_mut(key) { *x += value.speed; } } } let distance_winner = reindeer_max_value(&distance); // All reindeer in the lead get points (incl. ties) for (key, value) in &distance { if *value == distance_winner.1 { if let Some(x) = points.get_mut(key)
} } } points } fn calculate_flight_distance(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> { let mut res = HashMap::new(); for (key, value) in flight_data { let cycle = value.flight_time + value.rest_time; let full_cycles = time / cycle; let mut distance : f64 = full_cycles as f64 * value.speed as f64 * value.flight_time as f64; let leftover_time = time - full_cycles * cycle; if leftover_time >= value.flight_time { distance += value.speed as f64 * value.flight_time as f64; } else { distance += value.speed as f64 * leftover_time as f64; } res.insert(key, distance as u32); } res } fn parse_input(input : Vec<&str>) -> HashMap<String, ReindeerFlight> { let mut flight = HashMap::new(); for s in input { let re = Regex::new(r"^(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.").unwrap(); for cap in re.captures_iter(s) { let name : String = String::from(cap.at(1).unwrap()); let flight_speed = cap.at(2).unwrap().parse::<u32>().unwrap(); let flight_time = cap.at(3).unwrap().parse::<u32>().unwrap(); let rest_time = cap.at(4).unwrap().parse::<u32>().unwrap(); flight.insert(name, ReindeerFlight::new(flight_speed, flight_time, rest_time)); } } flight }
{ *x += 1; }
conditional_block
day14.rs
extern crate clap; extern crate regex; use clap::App; use std::error::Error; use std::fs::File; use std::io::prelude::*; use regex::Regex; use std::collections::HashMap; #[derive(Debug, Clone)] struct ReindeerFlight { speed : u32, flight_time : u32, rest_time : u32 } impl ReindeerFlight { fn new(speed : u32, flight_time : u32, rest_time : u32) -> ReindeerFlight { ReindeerFlight { speed : speed, flight_time : flight_time, rest_time : rest_time, } } } fn main() { let matches = App::new("day14") .version("v1.0") .author("Andrew Rink <[email protected]>") .args_from_usage("-t <TIME> 'Total flight time' <FILE> 'File containing Reindeer flight data'") .get_matches(); let flight_time = matches.value_of("TIME").unwrap().parse::<u32>().unwrap(); let filename = matches.value_of("FILE").unwrap(); let mut file = match File::open(filename) { Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)), Ok(file) => file, }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)), Ok(_) => println!("Read file {}", filename), } let input = parse_input(s.trim().split('\n').collect()); let flight_results = calculate_flight_distance(flight_time, input.clone()); let distance_winner = reindeer_max_value(&flight_results); println!("Distance Winner: {} with a distance of {}", distance_winner.0, distance_winner.1); let points_result = calculate_points_winner(flight_time, input.clone()); let points_winner = reindeer_max_value(&points_result); println!("Points winner: {} with {} points", points_winner.0, points_winner.1); } fn reindeer_max_value(values : & HashMap<String, u32>) -> (String, u32) { let mut name_of_max : String = String::new(); let mut max_value : u32 = std::u32::MIN; for (key, value) in values { if *value > max_value { max_value = *value; name_of_max = key.clone(); } } (name_of_max, max_value) } fn calculate_points_winner(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> { let mut points : HashMap<String, u32> = HashMap::new(); let mut distance : HashMap<String, u32> = HashMap::new(); // Set cycle time for each reindeer. Init distance/points to 0 let mut cycles = HashMap::new(); for (key, value) in &flight_data { let cycle = value.flight_time + value.rest_time; cycles.insert(key.clone(), cycle); distance.insert(key.clone(), 0); points.insert(key.clone(), 0); } // Find distance for each time for t in 1..time+1 { for (key, value) in &flight_data { let offset = (t-1) % cycles.get(key).unwrap(); if offset < value.flight_time { if let Some(x) = distance.get_mut(key) { *x += value.speed; } } } let distance_winner = reindeer_max_value(&distance); // All reindeer in the lead get points (incl. ties) for (key, value) in &distance { if *value == distance_winner.1 { if let Some(x) = points.get_mut(key) { *x += 1; } } } } points } fn calculate_flight_distance(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> { let mut res = HashMap::new(); for (key, value) in flight_data { let cycle = value.flight_time + value.rest_time; let full_cycles = time / cycle; let mut distance : f64 = full_cycles as f64 * value.speed as f64 * value.flight_time as f64; let leftover_time = time - full_cycles * cycle; if leftover_time >= value.flight_time { distance += value.speed as f64 * value.flight_time as f64; } else { distance += value.speed as f64 * leftover_time as f64; } res.insert(key, distance as u32); } res } fn parse_input(input : Vec<&str>) -> HashMap<String, ReindeerFlight>
{ let mut flight = HashMap::new(); for s in input { let re = Regex::new(r"^(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.").unwrap(); for cap in re.captures_iter(s) { let name : String = String::from(cap.at(1).unwrap()); let flight_speed = cap.at(2).unwrap().parse::<u32>().unwrap(); let flight_time = cap.at(3).unwrap().parse::<u32>().unwrap(); let rest_time = cap.at(4).unwrap().parse::<u32>().unwrap(); flight.insert(name, ReindeerFlight::new(flight_speed, flight_time, rest_time)); } } flight }
identifier_body
day14.rs
extern crate clap; extern crate regex; use clap::App; use std::error::Error; use std::fs::File; use std::io::prelude::*; use regex::Regex; use std::collections::HashMap; #[derive(Debug, Clone)] struct ReindeerFlight { speed : u32, flight_time : u32, rest_time : u32 } impl ReindeerFlight { fn new(speed : u32, flight_time : u32, rest_time : u32) -> ReindeerFlight { ReindeerFlight { speed : speed, flight_time : flight_time, rest_time : rest_time, } } } fn main() { let matches = App::new("day14") .version("v1.0") .author("Andrew Rink <[email protected]>") .args_from_usage("-t <TIME> 'Total flight time' <FILE> 'File containing Reindeer flight data'") .get_matches(); let flight_time = matches.value_of("TIME").unwrap().parse::<u32>().unwrap(); let filename = matches.value_of("FILE").unwrap(); let mut file = match File::open(filename) { Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)), Ok(file) => file, }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)), Ok(_) => println!("Read file {}", filename), } let input = parse_input(s.trim().split('\n').collect()); let flight_results = calculate_flight_distance(flight_time, input.clone()); let distance_winner = reindeer_max_value(&flight_results); println!("Distance Winner: {} with a distance of {}", distance_winner.0, distance_winner.1); let points_result = calculate_points_winner(flight_time, input.clone()); let points_winner = reindeer_max_value(&points_result); println!("Points winner: {} with {} points", points_winner.0, points_winner.1); } fn reindeer_max_value(values : & HashMap<String, u32>) -> (String, u32) { let mut name_of_max : String = String::new(); let mut max_value : u32 = std::u32::MIN; for (key, value) in values { if *value > max_value { max_value = *value; name_of_max = key.clone(); } } (name_of_max, max_value) } fn calculate_points_winner(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> { let mut points : HashMap<String, u32> = HashMap::new(); let mut distance : HashMap<String, u32> = HashMap::new(); // Set cycle time for each reindeer. Init distance/points to 0 let mut cycles = HashMap::new(); for (key, value) in &flight_data { let cycle = value.flight_time + value.rest_time; cycles.insert(key.clone(), cycle); distance.insert(key.clone(), 0); points.insert(key.clone(), 0); } // Find distance for each time for t in 1..time+1 { for (key, value) in &flight_data { let offset = (t-1) % cycles.get(key).unwrap(); if offset < value.flight_time { if let Some(x) = distance.get_mut(key) { *x += value.speed; } } } let distance_winner = reindeer_max_value(&distance); // All reindeer in the lead get points (incl. ties) for (key, value) in &distance { if *value == distance_winner.1 { if let Some(x) = points.get_mut(key) { *x += 1; } } } } points } fn
(time : u32, flight_data : HashMap<String, ReindeerFlight>) -> HashMap<String, u32> { let mut res = HashMap::new(); for (key, value) in flight_data { let cycle = value.flight_time + value.rest_time; let full_cycles = time / cycle; let mut distance : f64 = full_cycles as f64 * value.speed as f64 * value.flight_time as f64; let leftover_time = time - full_cycles * cycle; if leftover_time >= value.flight_time { distance += value.speed as f64 * value.flight_time as f64; } else { distance += value.speed as f64 * leftover_time as f64; } res.insert(key, distance as u32); } res } fn parse_input(input : Vec<&str>) -> HashMap<String, ReindeerFlight> { let mut flight = HashMap::new(); for s in input { let re = Regex::new(r"^(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.").unwrap(); for cap in re.captures_iter(s) { let name : String = String::from(cap.at(1).unwrap()); let flight_speed = cap.at(2).unwrap().parse::<u32>().unwrap(); let flight_time = cap.at(3).unwrap().parse::<u32>().unwrap(); let rest_time = cap.at(4).unwrap().parse::<u32>().unwrap(); flight.insert(name, ReindeerFlight::new(flight_speed, flight_time, rest_time)); } } flight }
calculate_flight_distance
identifier_name
equation_numbers.rs
use crate::{mesh::PointId, StrError}; use russell_lab::GenericMatrix; use std::fmt; /// Alias for DOF index pub type DofIndex = usize; /// DOF index: Displacement along the first dimension pub const DOF_UX: DofIndex = 0; /// DOF index: Displacement along the second dimension
pub const DOF_UY: DofIndex = 1; /// DOF index: Displacement along the third dimension pub const DOF_UZ: DofIndex = 2; /// DOF index: Rotation around the first axis pub const DOF_RX: DofIndex = 3; /// DOF index: Rotation around the second axis pub const DOF_RY: DofIndex = 4; /// DOF index: Rotation around the third axis pub const DOF_RZ: DofIndex = 5; /// DOF index: Temperature pub const DOF_T: DofIndex = 6; /// DOF index: Liquid pressure pub const DOF_PL: DofIndex = 7; /// DOF index: Gas pressure pub const DOF_PG: DofIndex = 8; /// DOF index: Free-surface-output (fso) enrichment pub const DOF_FSO: DofIndex = 9; /// Total number of available DOFs pub const DOF_TOTAL: usize = 10; /// Holds equation numbers (DOF numbers) pub struct EquationNumbers { /// Total number of equations count: i32, /// Equation numbers matrix [point][dof] numbers: GenericMatrix<i32>, } impl EquationNumbers { /// Creates a new Equation Numbers object pub fn new(npoint: usize) -> Self { EquationNumbers { count: 0, numbers: GenericMatrix::filled(npoint, DOF_TOTAL, -1), } } /// Activates equation corresponding to a point-DOF pair /// /// Note: Also increments the number of equations count /// if the equation does not exist yet pub fn activate_equation(&mut self, point_id: PointId, dof_index: DofIndex) { if self.numbers[point_id][dof_index] < 0 { self.numbers[point_id][dof_index] = self.count; self.count += 1; } } /// Returns the current total number of equations (DOFs) pub fn get_number_of_equations(&self) -> usize { self.count as usize } /// Returns the equation number corresponding to a point-DOF pair pub fn get_equation_number(&self, point_id: PointId, dof_index: DofIndex) -> Result<usize, StrError> { if self.numbers[point_id][dof_index] < 0 { return Err("equation number has not been set"); } Ok(self.numbers[point_id][dof_index] as usize) } } impl fmt::Display for EquationNumbers { /// Generates a string representation of the EquationNumbers fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.numbers) } }
random_line_split
equation_numbers.rs
use crate::{mesh::PointId, StrError}; use russell_lab::GenericMatrix; use std::fmt; /// Alias for DOF index pub type DofIndex = usize; /// DOF index: Displacement along the first dimension pub const DOF_UX: DofIndex = 0; /// DOF index: Displacement along the second dimension pub const DOF_UY: DofIndex = 1; /// DOF index: Displacement along the third dimension pub const DOF_UZ: DofIndex = 2; /// DOF index: Rotation around the first axis pub const DOF_RX: DofIndex = 3; /// DOF index: Rotation around the second axis pub const DOF_RY: DofIndex = 4; /// DOF index: Rotation around the third axis pub const DOF_RZ: DofIndex = 5; /// DOF index: Temperature pub const DOF_T: DofIndex = 6; /// DOF index: Liquid pressure pub const DOF_PL: DofIndex = 7; /// DOF index: Gas pressure pub const DOF_PG: DofIndex = 8; /// DOF index: Free-surface-output (fso) enrichment pub const DOF_FSO: DofIndex = 9; /// Total number of available DOFs pub const DOF_TOTAL: usize = 10; /// Holds equation numbers (DOF numbers) pub struct EquationNumbers { /// Total number of equations count: i32, /// Equation numbers matrix [point][dof] numbers: GenericMatrix<i32>, } impl EquationNumbers { /// Creates a new Equation Numbers object pub fn new(npoint: usize) -> Self { EquationNumbers { count: 0, numbers: GenericMatrix::filled(npoint, DOF_TOTAL, -1), } } /// Activates equation corresponding to a point-DOF pair /// /// Note: Also increments the number of equations count /// if the equation does not exist yet pub fn activate_equation(&mut self, point_id: PointId, dof_index: DofIndex) { if self.numbers[point_id][dof_index] < 0 { self.numbers[point_id][dof_index] = self.count; self.count += 1; } } /// Returns the current total number of equations (DOFs) pub fn
(&self) -> usize { self.count as usize } /// Returns the equation number corresponding to a point-DOF pair pub fn get_equation_number(&self, point_id: PointId, dof_index: DofIndex) -> Result<usize, StrError> { if self.numbers[point_id][dof_index] < 0 { return Err("equation number has not been set"); } Ok(self.numbers[point_id][dof_index] as usize) } } impl fmt::Display for EquationNumbers { /// Generates a string representation of the EquationNumbers fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.numbers) } }
get_number_of_equations
identifier_name
equation_numbers.rs
use crate::{mesh::PointId, StrError}; use russell_lab::GenericMatrix; use std::fmt; /// Alias for DOF index pub type DofIndex = usize; /// DOF index: Displacement along the first dimension pub const DOF_UX: DofIndex = 0; /// DOF index: Displacement along the second dimension pub const DOF_UY: DofIndex = 1; /// DOF index: Displacement along the third dimension pub const DOF_UZ: DofIndex = 2; /// DOF index: Rotation around the first axis pub const DOF_RX: DofIndex = 3; /// DOF index: Rotation around the second axis pub const DOF_RY: DofIndex = 4; /// DOF index: Rotation around the third axis pub const DOF_RZ: DofIndex = 5; /// DOF index: Temperature pub const DOF_T: DofIndex = 6; /// DOF index: Liquid pressure pub const DOF_PL: DofIndex = 7; /// DOF index: Gas pressure pub const DOF_PG: DofIndex = 8; /// DOF index: Free-surface-output (fso) enrichment pub const DOF_FSO: DofIndex = 9; /// Total number of available DOFs pub const DOF_TOTAL: usize = 10; /// Holds equation numbers (DOF numbers) pub struct EquationNumbers { /// Total number of equations count: i32, /// Equation numbers matrix [point][dof] numbers: GenericMatrix<i32>, } impl EquationNumbers { /// Creates a new Equation Numbers object pub fn new(npoint: usize) -> Self { EquationNumbers { count: 0, numbers: GenericMatrix::filled(npoint, DOF_TOTAL, -1), } } /// Activates equation corresponding to a point-DOF pair /// /// Note: Also increments the number of equations count /// if the equation does not exist yet pub fn activate_equation(&mut self, point_id: PointId, dof_index: DofIndex)
/// Returns the current total number of equations (DOFs) pub fn get_number_of_equations(&self) -> usize { self.count as usize } /// Returns the equation number corresponding to a point-DOF pair pub fn get_equation_number(&self, point_id: PointId, dof_index: DofIndex) -> Result<usize, StrError> { if self.numbers[point_id][dof_index] < 0 { return Err("equation number has not been set"); } Ok(self.numbers[point_id][dof_index] as usize) } } impl fmt::Display for EquationNumbers { /// Generates a string representation of the EquationNumbers fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.numbers) } }
{ if self.numbers[point_id][dof_index] < 0 { self.numbers[point_id][dof_index] = self.count; self.count += 1; } }
identifier_body
equation_numbers.rs
use crate::{mesh::PointId, StrError}; use russell_lab::GenericMatrix; use std::fmt; /// Alias for DOF index pub type DofIndex = usize; /// DOF index: Displacement along the first dimension pub const DOF_UX: DofIndex = 0; /// DOF index: Displacement along the second dimension pub const DOF_UY: DofIndex = 1; /// DOF index: Displacement along the third dimension pub const DOF_UZ: DofIndex = 2; /// DOF index: Rotation around the first axis pub const DOF_RX: DofIndex = 3; /// DOF index: Rotation around the second axis pub const DOF_RY: DofIndex = 4; /// DOF index: Rotation around the third axis pub const DOF_RZ: DofIndex = 5; /// DOF index: Temperature pub const DOF_T: DofIndex = 6; /// DOF index: Liquid pressure pub const DOF_PL: DofIndex = 7; /// DOF index: Gas pressure pub const DOF_PG: DofIndex = 8; /// DOF index: Free-surface-output (fso) enrichment pub const DOF_FSO: DofIndex = 9; /// Total number of available DOFs pub const DOF_TOTAL: usize = 10; /// Holds equation numbers (DOF numbers) pub struct EquationNumbers { /// Total number of equations count: i32, /// Equation numbers matrix [point][dof] numbers: GenericMatrix<i32>, } impl EquationNumbers { /// Creates a new Equation Numbers object pub fn new(npoint: usize) -> Self { EquationNumbers { count: 0, numbers: GenericMatrix::filled(npoint, DOF_TOTAL, -1), } } /// Activates equation corresponding to a point-DOF pair /// /// Note: Also increments the number of equations count /// if the equation does not exist yet pub fn activate_equation(&mut self, point_id: PointId, dof_index: DofIndex) { if self.numbers[point_id][dof_index] < 0 { self.numbers[point_id][dof_index] = self.count; self.count += 1; } } /// Returns the current total number of equations (DOFs) pub fn get_number_of_equations(&self) -> usize { self.count as usize } /// Returns the equation number corresponding to a point-DOF pair pub fn get_equation_number(&self, point_id: PointId, dof_index: DofIndex) -> Result<usize, StrError> { if self.numbers[point_id][dof_index] < 0
Ok(self.numbers[point_id][dof_index] as usize) } } impl fmt::Display for EquationNumbers { /// Generates a string representation of the EquationNumbers fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.numbers) } }
{ return Err("equation number has not been set"); }
conditional_block
common.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/. * * Copyright 2017 - Dario Ostuni <[email protected]> * */ #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)] pub struct Point { pub x: usize, pub y: usize, } #[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Player { pub name: String, pub points: u64, pub position: Point, pub id: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct Overview { pub players: Vec<Player>, pub grid: Vec<Vec<Option<u64>>>, pub turns_left: u64, pub ms_for_turn: u64, pub tokens: Vec<Point>, pub game_id: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct PlayerInfo { pub name: String, } #[derive(Serialize, Deserialize, Debug)] pub enum ClientRole { Viewer, Player(PlayerInfo), } #[derive(Serialize, Deserialize, Debug)] pub enum Direction { Up, Down, Left, Right, } #[derive(Serialize, Deserialize, Debug)] pub enum ClientCommand { Move(Direction), Nothing, } #[derive(Serialize, Deserialize, Debug)] pub enum ServerResponse { Ok, Error(String), } #[derive(Serialize, Deserialize, Debug)] pub enum ClientMessage { HandShake(ClientRole), Command(ClientCommand), }
random_line_split
common.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/. * * Copyright 2017 - Dario Ostuni <[email protected]> * */ #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)] pub struct Point { pub x: usize, pub y: usize, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Player { pub name: String, pub points: u64, pub position: Point, pub id: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct Overview { pub players: Vec<Player>, pub grid: Vec<Vec<Option<u64>>>, pub turns_left: u64, pub ms_for_turn: u64, pub tokens: Vec<Point>, pub game_id: u64, } #[derive(Serialize, Deserialize, Debug)] pub struct PlayerInfo { pub name: String, } #[derive(Serialize, Deserialize, Debug)] pub enum ClientRole { Viewer, Player(PlayerInfo), } #[derive(Serialize, Deserialize, Debug)] pub enum Direction { Up, Down, Left, Right, } #[derive(Serialize, Deserialize, Debug)] pub enum
{ Move(Direction), Nothing, } #[derive(Serialize, Deserialize, Debug)] pub enum ServerResponse { Ok, Error(String), } #[derive(Serialize, Deserialize, Debug)] pub enum ClientMessage { HandShake(ClientRole), Command(ClientCommand), }
ClientCommand
identifier_name
issue-21400.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // Regression test for #21400 which itself was extracted from // stackoverflow.com/questions/28031155/is-my-borrow-checker-drunk/28031580 fn main() { let mut t = Test; assert_eq!(t.method1("one"), Ok(1)); assert_eq!(t.method2("two"), Ok(2)); assert_eq!(t.test(), Ok(2)); } struct Test;
fn method2(self: &mut Test, _arg: &str) -> Result<usize, &str> { Ok(2) } fn test(self: &mut Test) -> Result<usize, &str> { let s = format!("abcde"); // (Originally, this invocation of method2 was saying that `s` // does not live long enough.) let data = match self.method2(&*s) { Ok(r) => r, Err(e) => return Err(e) }; Ok(data) } } // Below is a closer match for the original test that was failing to compile pub struct GitConnect; impl GitConnect { fn command(self: &mut GitConnect, _s: &str) -> Result<Vec<Vec<u8>>, &str> { unimplemented!() } pub fn git_upload_pack(self: &mut GitConnect) -> Result<String, &str> { let c = format!("git-upload-pack"); let mut out = String::new(); let data = self.command(&c)?; for line in data.iter() { out.push_str(&format!("{:?}", line)); } Ok(out) } }
impl Test { fn method1(&mut self, _arg: &str) -> Result<usize, &str> { Ok(1) }
random_line_split
issue-21400.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // Regression test for #21400 which itself was extracted from // stackoverflow.com/questions/28031155/is-my-borrow-checker-drunk/28031580 fn main() { let mut t = Test; assert_eq!(t.method1("one"), Ok(1)); assert_eq!(t.method2("two"), Ok(2)); assert_eq!(t.test(), Ok(2)); } struct Test; impl Test { fn method1(&mut self, _arg: &str) -> Result<usize, &str> { Ok(1) } fn method2(self: &mut Test, _arg: &str) -> Result<usize, &str> { Ok(2) } fn test(self: &mut Test) -> Result<usize, &str> { let s = format!("abcde"); // (Originally, this invocation of method2 was saying that `s` // does not live long enough.) let data = match self.method2(&*s) { Ok(r) => r, Err(e) => return Err(e) }; Ok(data) } } // Below is a closer match for the original test that was failing to compile pub struct GitConnect; impl GitConnect { fn
(self: &mut GitConnect, _s: &str) -> Result<Vec<Vec<u8>>, &str> { unimplemented!() } pub fn git_upload_pack(self: &mut GitConnect) -> Result<String, &str> { let c = format!("git-upload-pack"); let mut out = String::new(); let data = self.command(&c)?; for line in data.iter() { out.push_str(&format!("{:?}", line)); } Ok(out) } }
command
identifier_name
build.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::fs; use std::io; use std::path::Path; fn check_signed_source() -> io::Result<()> { // Check if lib.rs is in sync with the Thrift compiler. let manifest_dir_path = std::env::var("CARGO_MANIFEST_DIR").unwrap(); let crate_path = Path::new(&manifest_dir_path); let fbcode_path = crate_path.ancestors().nth(4).unwrap(); let thrift_file_path = fbcode_path.join("configerator/structs/scm/hg/hgclientconf/hgclient.thrift"); if!thrift_file_path.exists() { // Do not make it a fatal error on non-fbcode environment (ex. OSS). println!( "cargo:warning=Does not verify Thrift file at {}.", &thrift_file_path.display() ); return Ok(()); } println!( "cargo:rerun-if-changed={}", &thrift_file_path.to_string_lossy() ); let thrift_file_content = fs::read_to_string(&thrift_file_path)?; let hash = "4bc06e1c39884f65a4e9cd145972df39"; if!thrift_file_content.contains(hash) { let msg = format!( "thrift_types.rs and HASH need update: {} hash mismatch (expect: {})", &thrift_file_path.display(), hash, ); return Err(io::Error::new(io::ErrorKind::Other, msg)); } Ok(()) } fn
() -> io::Result<()> { check_signed_source() }
main
identifier_name
build.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::fs; use std::io; use std::path::Path; fn check_signed_source() -> io::Result<()> { // Check if lib.rs is in sync with the Thrift compiler. let manifest_dir_path = std::env::var("CARGO_MANIFEST_DIR").unwrap(); let crate_path = Path::new(&manifest_dir_path); let fbcode_path = crate_path.ancestors().nth(4).unwrap(); let thrift_file_path = fbcode_path.join("configerator/structs/scm/hg/hgclientconf/hgclient.thrift"); if!thrift_file_path.exists() { // Do not make it a fatal error on non-fbcode environment (ex. OSS). println!( "cargo:warning=Does not verify Thrift file at {}.", &thrift_file_path.display() ); return Ok(()); } println!( "cargo:rerun-if-changed={}", &thrift_file_path.to_string_lossy() ); let thrift_file_content = fs::read_to_string(&thrift_file_path)?; let hash = "4bc06e1c39884f65a4e9cd145972df39"; if!thrift_file_content.contains(hash) { let msg = format!( "thrift_types.rs and HASH need update: {} hash mismatch (expect: {})", &thrift_file_path.display(), hash, ); return Err(io::Error::new(io::ErrorKind::Other, msg)); } Ok(())
} fn main() -> io::Result<()> { check_signed_source() }
random_line_split