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
binlink.rs
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs; use std::path::Path; use common::ui::{Status, UI}; use hcore::package::{PackageIdent, PackageInstall}; use hcore::os::filesystem; use hcore::fs as hfs; use error::{Error, Result}; pub fn start( ui: &mut UI, ident: &PackageIdent, binary: &str, dest_path: &Path, fs_root_path: &Path, force: bool, ) -> Result<()> { let dst_path = fs_root_path.join(dest_path.strip_prefix("/")?); let dst = dst_path.join(&binary); ui.begin(format!( "Binlinking {} from {} into {}", &binary, &ident, dst_path.display() ))?; let pkg_install = PackageInstall::load(&ident, Some(fs_root_path))?; let src = match hfs::find_command_in_pkg(binary, &pkg_install, fs_root_path)? { Some(c) => c, None => { return Err(Error::CommandNotFoundInPkg( (pkg_install.ident().to_string(), binary.to_string()), )) } }; if!dst_path.is_dir() { ui.status( Status::Creating, format!("parent directory {}", dst_path.display()), )?; fs::create_dir_all(&dst_path)? } let ui_binlinked = format!( "Binlinked {} from {} to {}", &binary, &pkg_install.ident(), &dst.display(), ); match fs::read_link(&dst) { Ok(path) => { if force && path!= src { fs::remove_file(&dst)?; filesystem::symlink(&src, &dst)?; ui.end(&ui_binlinked)?; } else if path!= src { ui.warn( format!("Skipping binlink because {} already exists at {}. Use --force to overwrite", &binary, &dst.display(), ), )?; } else { ui.end(&ui_binlinked)?; } } Err(_) => { filesystem::symlink(&src, &dst)?; ui.end(&ui_binlinked)?; } } Ok(()) } pub fn binlink_all_in_pkg<F, D>( ui: &mut UI, pkg_ident: &PackageIdent, dest_path: D, fs_root_path: F, force: bool, ) -> Result<()> where D: AsRef<Path>, F: AsRef<Path>, { let fs_root_path = fs_root_path.as_ref(); let pkg_path = PackageInstall::load(&pkg_ident, Some(fs_root_path))?; for bin_path in pkg_path.paths()? { for bin in fs::read_dir(fs_root_path.join(bin_path.strip_prefix("/")?))? { let bin_file = bin?; let bin_name = match bin_file.file_name().to_str() { Some(bn) => bn.to_owned(), None => { ui.warn("Invalid binary name found. Skipping binlink")?; continue; } }; self::start( ui, &pkg_ident, &bin_name, dest_path.as_ref(), &fs_root_path, force, )?; } } Ok(()) } #[cfg(test)] mod test { use std::collections::HashMap; use std::io::{self, Cursor, Write}; use std::fs::{self, File}; use std::str::{self, FromStr}; use std::path::Path; use std::sync::{Arc, RwLock}; use common::ui::{Coloring, UI}; use hcore; use hcore::package::{PackageIdent, PackageTarget}; use tempdir::TempDir; use super::{binlink_all_in_pkg, start}; #[test] fn start_symlinks_binaries() { let rootfs = TempDir::new("rootfs").unwrap(); let mut tools = HashMap::new(); tools.insert("bin", vec!["magicate", "hypnoanalyze"]); let ident = fake_bin_pkg_install("acme/cooltools", tools, rootfs.path()); let dst_path = Path::new("/opt/bin"); let rootfs_src_dir = hcore::fs::pkg_install_path(&ident, None::<&Path>).join("bin"); let rootfs_bin_dir = rootfs.path().join("opt/bin"); let force = true; let (mut ui, _stdout, _stderr) = ui(); start(&mut ui, &ident, "magicate", &dst_path, rootfs.path(), force).unwrap(); assert_eq!( rootfs_src_dir.join("magicate"), rootfs_bin_dir.join("magicate").read_link().unwrap() ); start( &mut ui, &ident, "hypnoanalyze", &dst_path, rootfs.path(), force, ).unwrap(); assert_eq!( rootfs_src_dir.join("hypnoanalyze"), rootfs_bin_dir.join("hypnoanalyze").read_link().unwrap() ); } #[test] fn binlink_all_in_pkg_symlinks_all_binaries() { let rootfs = TempDir::new("rootfs").unwrap(); let mut tools = HashMap::new(); tools.insert("bin", vec!["magicate", "hypnoanalyze"]); tools.insert("sbin", vec!["securitize", "conceal"]); let ident = fake_bin_pkg_install("acme/securetools", tools, rootfs.path()); let dst_path = Path::new("/opt/bin"); let rootfs_src_dir = hcore::fs::pkg_install_path(&ident, None::<&Path>); let rootfs_bin_dir = rootfs.path().join("opt/bin"); let force = true; let (mut ui, _stdout, _stderr) = ui(); binlink_all_in_pkg(&mut ui, &ident, &dst_path, rootfs.path(), force).unwrap(); assert_eq!( rootfs_src_dir.join("bin/magicate"), rootfs_bin_dir.join("magicate").read_link().unwrap() ); assert_eq!( rootfs_src_dir.join("bin/hypnoanalyze"), rootfs_bin_dir.join("hypnoanalyze").read_link().unwrap() ); assert_eq!( rootfs_src_dir.join("sbin/securitize"), rootfs_bin_dir.join("securitize").read_link().unwrap() ); } fn ui() -> (UI, OutputBuffer, OutputBuffer) { let stdout_buf = OutputBuffer::new(); let stderr_buf = OutputBuffer::new(); let ui = UI::with_streams( Box::new(io::empty()), || Box::new(stdout_buf.clone()), || Box::new(stderr_buf.clone()), Coloring::Never, false, ); (ui, stdout_buf, stderr_buf) } fn fake_bin_pkg_install<P>( ident: &str, binaries: HashMap<&str, Vec<&str>>, rootfs: P, ) -> PackageIdent where P: AsRef<Path>, { let mut ident = PackageIdent::from_str(ident).unwrap(); if let None = ident.version { ident.version = Some("1.2.3".into()); } if let None = ident.release { ident.release = Some("21120102121200".into()); } let prefix = hcore::fs::pkg_install_path(&ident, Some(rootfs)); write_file(prefix.join("IDENT"), &ident.to_string()); write_file(prefix.join("TARGET"), &PackageTarget::default().to_string()); let mut paths = Vec::new(); for (path, bins) in binaries { let abspath = hcore::fs::pkg_install_path(&ident, None::<&Path>).join(path); paths.push(abspath.to_string_lossy().into_owned()); for bin in bins { write_file(prefix.join(path).join(bin), ""); } } write_file(prefix.join("PATH"), &paths.join(":")); ident } fn write_file<P: AsRef<Path>>(file: P, content: &str) { fs::create_dir_all(file.as_ref().parent().expect( "Parent directory doesn't exist", )).expect("Failed to create parent directory"); let mut f = File::create(file).expect("File is not created"); f.write_all(content.as_bytes()).expect( "Bytes not written to file",
pub cursor: Arc<RwLock<Cursor<Vec<u8>>>>, } impl OutputBuffer { fn new() -> Self { OutputBuffer { cursor: Arc::new(RwLock::new(Cursor::new(Vec::new()))) } } } impl Write for OutputBuffer { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.cursor .write() .expect("Cursor lock is poisoned") .write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor .write() .expect("Cursor lock is poisoned") .flush() } } }
); } #[derive(Clone)] pub struct OutputBuffer {
random_line_split
binlink.rs
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs; use std::path::Path; use common::ui::{Status, UI}; use hcore::package::{PackageIdent, PackageInstall}; use hcore::os::filesystem; use hcore::fs as hfs; use error::{Error, Result}; pub fn start( ui: &mut UI, ident: &PackageIdent, binary: &str, dest_path: &Path, fs_root_path: &Path, force: bool, ) -> Result<()> { let dst_path = fs_root_path.join(dest_path.strip_prefix("/")?); let dst = dst_path.join(&binary); ui.begin(format!( "Binlinking {} from {} into {}", &binary, &ident, dst_path.display() ))?; let pkg_install = PackageInstall::load(&ident, Some(fs_root_path))?; let src = match hfs::find_command_in_pkg(binary, &pkg_install, fs_root_path)? { Some(c) => c, None => { return Err(Error::CommandNotFoundInPkg( (pkg_install.ident().to_string(), binary.to_string()), )) } }; if!dst_path.is_dir() { ui.status( Status::Creating, format!("parent directory {}", dst_path.display()), )?; fs::create_dir_all(&dst_path)? } let ui_binlinked = format!( "Binlinked {} from {} to {}", &binary, &pkg_install.ident(), &dst.display(), ); match fs::read_link(&dst) { Ok(path) => { if force && path!= src { fs::remove_file(&dst)?; filesystem::symlink(&src, &dst)?; ui.end(&ui_binlinked)?; } else if path!= src { ui.warn( format!("Skipping binlink because {} already exists at {}. Use --force to overwrite", &binary, &dst.display(), ), )?; } else { ui.end(&ui_binlinked)?; } } Err(_) => { filesystem::symlink(&src, &dst)?; ui.end(&ui_binlinked)?; } } Ok(()) } pub fn binlink_all_in_pkg<F, D>( ui: &mut UI, pkg_ident: &PackageIdent, dest_path: D, fs_root_path: F, force: bool, ) -> Result<()> where D: AsRef<Path>, F: AsRef<Path>, { let fs_root_path = fs_root_path.as_ref(); let pkg_path = PackageInstall::load(&pkg_ident, Some(fs_root_path))?; for bin_path in pkg_path.paths()? { for bin in fs::read_dir(fs_root_path.join(bin_path.strip_prefix("/")?))? { let bin_file = bin?; let bin_name = match bin_file.file_name().to_str() { Some(bn) => bn.to_owned(), None => { ui.warn("Invalid binary name found. Skipping binlink")?; continue; } }; self::start( ui, &pkg_ident, &bin_name, dest_path.as_ref(), &fs_root_path, force, )?; } } Ok(()) } #[cfg(test)] mod test { use std::collections::HashMap; use std::io::{self, Cursor, Write}; use std::fs::{self, File}; use std::str::{self, FromStr}; use std::path::Path; use std::sync::{Arc, RwLock}; use common::ui::{Coloring, UI}; use hcore; use hcore::package::{PackageIdent, PackageTarget}; use tempdir::TempDir; use super::{binlink_all_in_pkg, start}; #[test] fn
() { let rootfs = TempDir::new("rootfs").unwrap(); let mut tools = HashMap::new(); tools.insert("bin", vec!["magicate", "hypnoanalyze"]); let ident = fake_bin_pkg_install("acme/cooltools", tools, rootfs.path()); let dst_path = Path::new("/opt/bin"); let rootfs_src_dir = hcore::fs::pkg_install_path(&ident, None::<&Path>).join("bin"); let rootfs_bin_dir = rootfs.path().join("opt/bin"); let force = true; let (mut ui, _stdout, _stderr) = ui(); start(&mut ui, &ident, "magicate", &dst_path, rootfs.path(), force).unwrap(); assert_eq!( rootfs_src_dir.join("magicate"), rootfs_bin_dir.join("magicate").read_link().unwrap() ); start( &mut ui, &ident, "hypnoanalyze", &dst_path, rootfs.path(), force, ).unwrap(); assert_eq!( rootfs_src_dir.join("hypnoanalyze"), rootfs_bin_dir.join("hypnoanalyze").read_link().unwrap() ); } #[test] fn binlink_all_in_pkg_symlinks_all_binaries() { let rootfs = TempDir::new("rootfs").unwrap(); let mut tools = HashMap::new(); tools.insert("bin", vec!["magicate", "hypnoanalyze"]); tools.insert("sbin", vec!["securitize", "conceal"]); let ident = fake_bin_pkg_install("acme/securetools", tools, rootfs.path()); let dst_path = Path::new("/opt/bin"); let rootfs_src_dir = hcore::fs::pkg_install_path(&ident, None::<&Path>); let rootfs_bin_dir = rootfs.path().join("opt/bin"); let force = true; let (mut ui, _stdout, _stderr) = ui(); binlink_all_in_pkg(&mut ui, &ident, &dst_path, rootfs.path(), force).unwrap(); assert_eq!( rootfs_src_dir.join("bin/magicate"), rootfs_bin_dir.join("magicate").read_link().unwrap() ); assert_eq!( rootfs_src_dir.join("bin/hypnoanalyze"), rootfs_bin_dir.join("hypnoanalyze").read_link().unwrap() ); assert_eq!( rootfs_src_dir.join("sbin/securitize"), rootfs_bin_dir.join("securitize").read_link().unwrap() ); } fn ui() -> (UI, OutputBuffer, OutputBuffer) { let stdout_buf = OutputBuffer::new(); let stderr_buf = OutputBuffer::new(); let ui = UI::with_streams( Box::new(io::empty()), || Box::new(stdout_buf.clone()), || Box::new(stderr_buf.clone()), Coloring::Never, false, ); (ui, stdout_buf, stderr_buf) } fn fake_bin_pkg_install<P>( ident: &str, binaries: HashMap<&str, Vec<&str>>, rootfs: P, ) -> PackageIdent where P: AsRef<Path>, { let mut ident = PackageIdent::from_str(ident).unwrap(); if let None = ident.version { ident.version = Some("1.2.3".into()); } if let None = ident.release { ident.release = Some("21120102121200".into()); } let prefix = hcore::fs::pkg_install_path(&ident, Some(rootfs)); write_file(prefix.join("IDENT"), &ident.to_string()); write_file(prefix.join("TARGET"), &PackageTarget::default().to_string()); let mut paths = Vec::new(); for (path, bins) in binaries { let abspath = hcore::fs::pkg_install_path(&ident, None::<&Path>).join(path); paths.push(abspath.to_string_lossy().into_owned()); for bin in bins { write_file(prefix.join(path).join(bin), ""); } } write_file(prefix.join("PATH"), &paths.join(":")); ident } fn write_file<P: AsRef<Path>>(file: P, content: &str) { fs::create_dir_all(file.as_ref().parent().expect( "Parent directory doesn't exist", )).expect("Failed to create parent directory"); let mut f = File::create(file).expect("File is not created"); f.write_all(content.as_bytes()).expect( "Bytes not written to file", ); } #[derive(Clone)] pub struct OutputBuffer { pub cursor: Arc<RwLock<Cursor<Vec<u8>>>>, } impl OutputBuffer { fn new() -> Self { OutputBuffer { cursor: Arc::new(RwLock::new(Cursor::new(Vec::new()))) } } } impl Write for OutputBuffer { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.cursor .write() .expect("Cursor lock is poisoned") .write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor .write() .expect("Cursor lock is poisoned") .flush() } } }
start_symlinks_binaries
identifier_name
binlink.rs
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs; use std::path::Path; use common::ui::{Status, UI}; use hcore::package::{PackageIdent, PackageInstall}; use hcore::os::filesystem; use hcore::fs as hfs; use error::{Error, Result}; pub fn start( ui: &mut UI, ident: &PackageIdent, binary: &str, dest_path: &Path, fs_root_path: &Path, force: bool, ) -> Result<()> { let dst_path = fs_root_path.join(dest_path.strip_prefix("/")?); let dst = dst_path.join(&binary); ui.begin(format!( "Binlinking {} from {} into {}", &binary, &ident, dst_path.display() ))?; let pkg_install = PackageInstall::load(&ident, Some(fs_root_path))?; let src = match hfs::find_command_in_pkg(binary, &pkg_install, fs_root_path)? { Some(c) => c, None => { return Err(Error::CommandNotFoundInPkg( (pkg_install.ident().to_string(), binary.to_string()), )) } }; if!dst_path.is_dir() { ui.status( Status::Creating, format!("parent directory {}", dst_path.display()), )?; fs::create_dir_all(&dst_path)? } let ui_binlinked = format!( "Binlinked {} from {} to {}", &binary, &pkg_install.ident(), &dst.display(), ); match fs::read_link(&dst) { Ok(path) => { if force && path!= src { fs::remove_file(&dst)?; filesystem::symlink(&src, &dst)?; ui.end(&ui_binlinked)?; } else if path!= src { ui.warn( format!("Skipping binlink because {} already exists at {}. Use --force to overwrite", &binary, &dst.display(), ), )?; } else { ui.end(&ui_binlinked)?; } } Err(_) => { filesystem::symlink(&src, &dst)?; ui.end(&ui_binlinked)?; } } Ok(()) } pub fn binlink_all_in_pkg<F, D>( ui: &mut UI, pkg_ident: &PackageIdent, dest_path: D, fs_root_path: F, force: bool, ) -> Result<()> where D: AsRef<Path>, F: AsRef<Path>, { let fs_root_path = fs_root_path.as_ref(); let pkg_path = PackageInstall::load(&pkg_ident, Some(fs_root_path))?; for bin_path in pkg_path.paths()? { for bin in fs::read_dir(fs_root_path.join(bin_path.strip_prefix("/")?))? { let bin_file = bin?; let bin_name = match bin_file.file_name().to_str() { Some(bn) => bn.to_owned(), None => { ui.warn("Invalid binary name found. Skipping binlink")?; continue; } }; self::start( ui, &pkg_ident, &bin_name, dest_path.as_ref(), &fs_root_path, force, )?; } } Ok(()) } #[cfg(test)] mod test { use std::collections::HashMap; use std::io::{self, Cursor, Write}; use std::fs::{self, File}; use std::str::{self, FromStr}; use std::path::Path; use std::sync::{Arc, RwLock}; use common::ui::{Coloring, UI}; use hcore; use hcore::package::{PackageIdent, PackageTarget}; use tempdir::TempDir; use super::{binlink_all_in_pkg, start}; #[test] fn start_symlinks_binaries() { let rootfs = TempDir::new("rootfs").unwrap(); let mut tools = HashMap::new(); tools.insert("bin", vec!["magicate", "hypnoanalyze"]); let ident = fake_bin_pkg_install("acme/cooltools", tools, rootfs.path()); let dst_path = Path::new("/opt/bin"); let rootfs_src_dir = hcore::fs::pkg_install_path(&ident, None::<&Path>).join("bin"); let rootfs_bin_dir = rootfs.path().join("opt/bin"); let force = true; let (mut ui, _stdout, _stderr) = ui(); start(&mut ui, &ident, "magicate", &dst_path, rootfs.path(), force).unwrap(); assert_eq!( rootfs_src_dir.join("magicate"), rootfs_bin_dir.join("magicate").read_link().unwrap() ); start( &mut ui, &ident, "hypnoanalyze", &dst_path, rootfs.path(), force, ).unwrap(); assert_eq!( rootfs_src_dir.join("hypnoanalyze"), rootfs_bin_dir.join("hypnoanalyze").read_link().unwrap() ); } #[test] fn binlink_all_in_pkg_symlinks_all_binaries() { let rootfs = TempDir::new("rootfs").unwrap(); let mut tools = HashMap::new(); tools.insert("bin", vec!["magicate", "hypnoanalyze"]); tools.insert("sbin", vec!["securitize", "conceal"]); let ident = fake_bin_pkg_install("acme/securetools", tools, rootfs.path()); let dst_path = Path::new("/opt/bin"); let rootfs_src_dir = hcore::fs::pkg_install_path(&ident, None::<&Path>); let rootfs_bin_dir = rootfs.path().join("opt/bin"); let force = true; let (mut ui, _stdout, _stderr) = ui(); binlink_all_in_pkg(&mut ui, &ident, &dst_path, rootfs.path(), force).unwrap(); assert_eq!( rootfs_src_dir.join("bin/magicate"), rootfs_bin_dir.join("magicate").read_link().unwrap() ); assert_eq!( rootfs_src_dir.join("bin/hypnoanalyze"), rootfs_bin_dir.join("hypnoanalyze").read_link().unwrap() ); assert_eq!( rootfs_src_dir.join("sbin/securitize"), rootfs_bin_dir.join("securitize").read_link().unwrap() ); } fn ui() -> (UI, OutputBuffer, OutputBuffer) { let stdout_buf = OutputBuffer::new(); let stderr_buf = OutputBuffer::new(); let ui = UI::with_streams( Box::new(io::empty()), || Box::new(stdout_buf.clone()), || Box::new(stderr_buf.clone()), Coloring::Never, false, ); (ui, stdout_buf, stderr_buf) } fn fake_bin_pkg_install<P>( ident: &str, binaries: HashMap<&str, Vec<&str>>, rootfs: P, ) -> PackageIdent where P: AsRef<Path>, { let mut ident = PackageIdent::from_str(ident).unwrap(); if let None = ident.version { ident.version = Some("1.2.3".into()); } if let None = ident.release { ident.release = Some("21120102121200".into()); } let prefix = hcore::fs::pkg_install_path(&ident, Some(rootfs)); write_file(prefix.join("IDENT"), &ident.to_string()); write_file(prefix.join("TARGET"), &PackageTarget::default().to_string()); let mut paths = Vec::new(); for (path, bins) in binaries { let abspath = hcore::fs::pkg_install_path(&ident, None::<&Path>).join(path); paths.push(abspath.to_string_lossy().into_owned()); for bin in bins { write_file(prefix.join(path).join(bin), ""); } } write_file(prefix.join("PATH"), &paths.join(":")); ident } fn write_file<P: AsRef<Path>>(file: P, content: &str) { fs::create_dir_all(file.as_ref().parent().expect( "Parent directory doesn't exist", )).expect("Failed to create parent directory"); let mut f = File::create(file).expect("File is not created"); f.write_all(content.as_bytes()).expect( "Bytes not written to file", ); } #[derive(Clone)] pub struct OutputBuffer { pub cursor: Arc<RwLock<Cursor<Vec<u8>>>>, } impl OutputBuffer { fn new() -> Self
} impl Write for OutputBuffer { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.cursor .write() .expect("Cursor lock is poisoned") .write(buf) } fn flush(&mut self) -> io::Result<()> { self.cursor .write() .expect("Cursor lock is poisoned") .flush() } } }
{ OutputBuffer { cursor: Arc::new(RwLock::new(Cursor::new(Vec::new()))) } }
identifier_body
controller.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/. */ extern crate serde_json; extern crate mio; use adapters::AdapterManager; use config_store::ConfigService; use foxbox_taxonomy::manager::AdapterManager as TaxoManager; use foxbox_users::UsersManager; use http_server::HttpServer; use profile_service::{ ProfilePath, ProfileService }; use std::collections::hash_map::HashMap; use std::io; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::path::PathBuf; use std::sync::{ Arc, Mutex }; use std::sync::atomic::{ AtomicBool, Ordering }; use std::vec::IntoIter; use upnp::UpnpManager; use tls::{ CertificateManager, CertificateRecord, SniSslContextProvider, TlsOption }; use traits::Controller; use ws_server::WsServer; use ws; #[derive(Clone)] pub struct FoxBox { pub verbose: bool, tls_option: TlsOption, certificate_manager: CertificateManager, hostname: String, http_port: u16, ws_port: u16, websockets: Arc<Mutex<HashMap<ws::util::Token, ws::Sender>>>, pub config: Arc<ConfigService>, upnp: Arc<UpnpManager>, users_manager: Arc<UsersManager>, profile_service: Arc<ProfileService>, } impl FoxBox { pub fn new(verbose: bool, hostname: String, http_port: u16, ws_port: u16, tls_option: TlsOption, profile_path: ProfilePath) -> Self { let profile_service = ProfileService::new(profile_path); let config = Arc::new(ConfigService::new(&profile_service.path_for("foxbox.conf"))); let certificate_directory = PathBuf::from( config.get_or_set_default("foxbox", "certificate_directory", &profile_service.path_for("certs/"))); FoxBox { certificate_manager: CertificateManager::new(certificate_directory, Box::new(SniSslContextProvider::new())), tls_option: tls_option, websockets: Arc::new(Mutex::new(HashMap::new())), verbose: verbose, hostname: hostname, http_port: http_port, ws_port: ws_port, config: config, upnp: Arc::new(UpnpManager::new()), users_manager: Arc::new(UsersManager::new(&profile_service.path_for("users_db.sqlite"))), profile_service: Arc::new(profile_service) } } } impl Controller for FoxBox { fn run(&mut self, shutdown_flag: &AtomicBool) { debug!("Starting controller"); let mut event_loop = mio::EventLoop::new().unwrap(); { Arc::get_mut(&mut self.upnp).unwrap().start().unwrap(); } // Create the taxonomy based AdapterManager let tags_db_path = PathBuf::from(self.profile_service.path_for("taxonomy_tags.sqlite")); let taxo_manager = Arc::new(TaxoManager::new(Some(tags_db_path))); let mut adapter_manager = AdapterManager::new(self.clone()); adapter_manager.start(&taxo_manager); HttpServer::new(self.clone()).start(&taxo_manager); WsServer::start(self.clone()); self.upnp.search(None).unwrap(); event_loop.run(&mut FoxBoxEventLoop { controller: self.clone(), shutdown_flag: &shutdown_flag }).unwrap(); debug!("Stopping controller"); adapter_manager.stop(); taxo_manager.stop(); } fn adapter_started(&self, adapter: String) { self.broadcast_to_websockets(json_value!({ type: "core/adapter/start", name: adapter })); } fn adapter_notification(&self, notification: serde_json::value::Value) { self.broadcast_to_websockets(json_value!({ type: "core/adapter/notification", message: notification })); } fn http_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("::", self.http_port).to_socket_addrs() } fn ws_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("::", self.ws_port).to_socket_addrs() } fn add_websocket(&mut self, socket: ws::Sender) { self.websockets.lock().unwrap().insert(socket.token(), socket); } fn remove_websocket(&mut self, socket: ws::Sender) { self.websockets.lock().unwrap().remove(&socket.token()); } fn broadcast_to_websockets(&self, data: serde_json::value::Value) { let serialized = serde_json::to_string(&data).unwrap_or("{}".to_owned()); debug!("broadcast_to_websockets {}", serialized.clone()); for socket in self.websockets.lock().unwrap().values() { match socket.send(serialized.clone()) { Ok(_) => (), Err(err) => error!("Error sending to socket: {}", err) } } } fn get_config(&self) -> Arc<ConfigService> { self.config.clone() } fn get_profile(&self) -> &ProfileService { &self.profile_service } fn get_upnp_manager(&self) -> Arc<UpnpManager> { self.upnp.clone() } fn get_users_manager(&self) -> Arc<UsersManager> { self.users_manager.clone() } fn get_certificate_manager(&self) -> CertificateManager { self.certificate_manager.clone() } /// Every box should create a self signed certificate for a local name. /// The fingerprint of that certificate becomes the box's identifier, /// which is used to create the public DNS zone and local /// (i.e. local.<fingerprint>.box.knilxof.org) and remote /// (i.e. remote.<fingerprint>.box.knilxof.org) origins fn get_box_certificate(&self) -> io::Result<CertificateRecord> { self.certificate_manager.get_box_certificate() } fn get_tls_enabled(&self) -> bool { self.tls_option == TlsOption::Enabled } fn get_hostname(&self) -> String { self.hostname.clone() } } #[allow(dead_code)] struct FoxBoxEventLoop<'a> { controller: FoxBox, shutdown_flag: &'a AtomicBool } impl<'a> mio::Handler for FoxBoxEventLoop<'a> { type Timeout = (); type Message = (); fn tick(&mut self, event_loop: &mut mio::EventLoop<Self>) { if self.shutdown_flag.load(Ordering::Acquire)
} }
{ event_loop.shutdown(); }
conditional_block
controller.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/. */ extern crate serde_json; extern crate mio; use adapters::AdapterManager; use config_store::ConfigService; use foxbox_taxonomy::manager::AdapterManager as TaxoManager; use foxbox_users::UsersManager; use http_server::HttpServer; use profile_service::{ ProfilePath, ProfileService }; use std::collections::hash_map::HashMap; use std::io; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::path::PathBuf; use std::sync::{ Arc, Mutex }; use std::sync::atomic::{ AtomicBool, Ordering }; use std::vec::IntoIter; use upnp::UpnpManager; use tls::{ CertificateManager, CertificateRecord, SniSslContextProvider, TlsOption }; use traits::Controller; use ws_server::WsServer; use ws; #[derive(Clone)] pub struct FoxBox { pub verbose: bool, tls_option: TlsOption, certificate_manager: CertificateManager, hostname: String, http_port: u16, ws_port: u16, websockets: Arc<Mutex<HashMap<ws::util::Token, ws::Sender>>>, pub config: Arc<ConfigService>, upnp: Arc<UpnpManager>, users_manager: Arc<UsersManager>, profile_service: Arc<ProfileService>, } impl FoxBox { pub fn new(verbose: bool, hostname: String, http_port: u16, ws_port: u16, tls_option: TlsOption, profile_path: ProfilePath) -> Self { let profile_service = ProfileService::new(profile_path); let config = Arc::new(ConfigService::new(&profile_service.path_for("foxbox.conf"))); let certificate_directory = PathBuf::from( config.get_or_set_default("foxbox", "certificate_directory", &profile_service.path_for("certs/"))); FoxBox { certificate_manager: CertificateManager::new(certificate_directory, Box::new(SniSslContextProvider::new())), tls_option: tls_option, websockets: Arc::new(Mutex::new(HashMap::new())), verbose: verbose, hostname: hostname, http_port: http_port, ws_port: ws_port, config: config, upnp: Arc::new(UpnpManager::new()), users_manager: Arc::new(UsersManager::new(&profile_service.path_for("users_db.sqlite"))), profile_service: Arc::new(profile_service) } } } impl Controller for FoxBox { fn run(&mut self, shutdown_flag: &AtomicBool) { debug!("Starting controller"); let mut event_loop = mio::EventLoop::new().unwrap(); { Arc::get_mut(&mut self.upnp).unwrap().start().unwrap(); } // Create the taxonomy based AdapterManager let tags_db_path = PathBuf::from(self.profile_service.path_for("taxonomy_tags.sqlite")); let taxo_manager = Arc::new(TaxoManager::new(Some(tags_db_path))); let mut adapter_manager = AdapterManager::new(self.clone()); adapter_manager.start(&taxo_manager); HttpServer::new(self.clone()).start(&taxo_manager); WsServer::start(self.clone()); self.upnp.search(None).unwrap(); event_loop.run(&mut FoxBoxEventLoop { controller: self.clone(), shutdown_flag: &shutdown_flag }).unwrap(); debug!("Stopping controller"); adapter_manager.stop(); taxo_manager.stop(); } fn adapter_started(&self, adapter: String) { self.broadcast_to_websockets(json_value!({ type: "core/adapter/start", name: adapter })); } fn adapter_notification(&self, notification: serde_json::value::Value) { self.broadcast_to_websockets(json_value!({ type: "core/adapter/notification", message: notification })); } fn http_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("::", self.http_port).to_socket_addrs() } fn ws_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("::", self.ws_port).to_socket_addrs() } fn add_websocket(&mut self, socket: ws::Sender) { self.websockets.lock().unwrap().insert(socket.token(), socket); } fn remove_websocket(&mut self, socket: ws::Sender) { self.websockets.lock().unwrap().remove(&socket.token()); } fn broadcast_to_websockets(&self, data: serde_json::value::Value) { let serialized = serde_json::to_string(&data).unwrap_or("{}".to_owned()); debug!("broadcast_to_websockets {}", serialized.clone()); for socket in self.websockets.lock().unwrap().values() { match socket.send(serialized.clone()) { Ok(_) => (), Err(err) => error!("Error sending to socket: {}", err) } } } fn get_config(&self) -> Arc<ConfigService> { self.config.clone() } fn get_profile(&self) -> &ProfileService { &self.profile_service } fn get_upnp_manager(&self) -> Arc<UpnpManager> { self.upnp.clone() } fn get_users_manager(&self) -> Arc<UsersManager> { self.users_manager.clone() } fn get_certificate_manager(&self) -> CertificateManager { self.certificate_manager.clone() } /// Every box should create a self signed certificate for a local name. /// The fingerprint of that certificate becomes the box's identifier, /// which is used to create the public DNS zone and local /// (i.e. local.<fingerprint>.box.knilxof.org) and remote /// (i.e. remote.<fingerprint>.box.knilxof.org) origins fn get_box_certificate(&self) -> io::Result<CertificateRecord> { self.certificate_manager.get_box_certificate() } fn get_tls_enabled(&self) -> bool { self.tls_option == TlsOption::Enabled } fn get_hostname(&self) -> String { self.hostname.clone() } } #[allow(dead_code)] struct FoxBoxEventLoop<'a> { controller: FoxBox, shutdown_flag: &'a AtomicBool } impl<'a> mio::Handler for FoxBoxEventLoop<'a> {
if self.shutdown_flag.load(Ordering::Acquire) { event_loop.shutdown(); } } }
type Timeout = (); type Message = (); fn tick(&mut self, event_loop: &mut mio::EventLoop<Self>) {
random_line_split
controller.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/. */ extern crate serde_json; extern crate mio; use adapters::AdapterManager; use config_store::ConfigService; use foxbox_taxonomy::manager::AdapterManager as TaxoManager; use foxbox_users::UsersManager; use http_server::HttpServer; use profile_service::{ ProfilePath, ProfileService }; use std::collections::hash_map::HashMap; use std::io; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::path::PathBuf; use std::sync::{ Arc, Mutex }; use std::sync::atomic::{ AtomicBool, Ordering }; use std::vec::IntoIter; use upnp::UpnpManager; use tls::{ CertificateManager, CertificateRecord, SniSslContextProvider, TlsOption }; use traits::Controller; use ws_server::WsServer; use ws; #[derive(Clone)] pub struct FoxBox { pub verbose: bool, tls_option: TlsOption, certificate_manager: CertificateManager, hostname: String, http_port: u16, ws_port: u16, websockets: Arc<Mutex<HashMap<ws::util::Token, ws::Sender>>>, pub config: Arc<ConfigService>, upnp: Arc<UpnpManager>, users_manager: Arc<UsersManager>, profile_service: Arc<ProfileService>, } impl FoxBox { pub fn new(verbose: bool, hostname: String, http_port: u16, ws_port: u16, tls_option: TlsOption, profile_path: ProfilePath) -> Self { let profile_service = ProfileService::new(profile_path); let config = Arc::new(ConfigService::new(&profile_service.path_for("foxbox.conf"))); let certificate_directory = PathBuf::from( config.get_or_set_default("foxbox", "certificate_directory", &profile_service.path_for("certs/"))); FoxBox { certificate_manager: CertificateManager::new(certificate_directory, Box::new(SniSslContextProvider::new())), tls_option: tls_option, websockets: Arc::new(Mutex::new(HashMap::new())), verbose: verbose, hostname: hostname, http_port: http_port, ws_port: ws_port, config: config, upnp: Arc::new(UpnpManager::new()), users_manager: Arc::new(UsersManager::new(&profile_service.path_for("users_db.sqlite"))), profile_service: Arc::new(profile_service) } } } impl Controller for FoxBox { fn run(&mut self, shutdown_flag: &AtomicBool) { debug!("Starting controller"); let mut event_loop = mio::EventLoop::new().unwrap(); { Arc::get_mut(&mut self.upnp).unwrap().start().unwrap(); } // Create the taxonomy based AdapterManager let tags_db_path = PathBuf::from(self.profile_service.path_for("taxonomy_tags.sqlite")); let taxo_manager = Arc::new(TaxoManager::new(Some(tags_db_path))); let mut adapter_manager = AdapterManager::new(self.clone()); adapter_manager.start(&taxo_manager); HttpServer::new(self.clone()).start(&taxo_manager); WsServer::start(self.clone()); self.upnp.search(None).unwrap(); event_loop.run(&mut FoxBoxEventLoop { controller: self.clone(), shutdown_flag: &shutdown_flag }).unwrap(); debug!("Stopping controller"); adapter_manager.stop(); taxo_manager.stop(); } fn adapter_started(&self, adapter: String) { self.broadcast_to_websockets(json_value!({ type: "core/adapter/start", name: adapter })); } fn adapter_notification(&self, notification: serde_json::value::Value) { self.broadcast_to_websockets(json_value!({ type: "core/adapter/notification", message: notification })); } fn http_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("::", self.http_port).to_socket_addrs() } fn ws_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("::", self.ws_port).to_socket_addrs() } fn add_websocket(&mut self, socket: ws::Sender) { self.websockets.lock().unwrap().insert(socket.token(), socket); } fn remove_websocket(&mut self, socket: ws::Sender) { self.websockets.lock().unwrap().remove(&socket.token()); } fn broadcast_to_websockets(&self, data: serde_json::value::Value) { let serialized = serde_json::to_string(&data).unwrap_or("{}".to_owned()); debug!("broadcast_to_websockets {}", serialized.clone()); for socket in self.websockets.lock().unwrap().values() { match socket.send(serialized.clone()) { Ok(_) => (), Err(err) => error!("Error sending to socket: {}", err) } } } fn get_config(&self) -> Arc<ConfigService> { self.config.clone() } fn get_profile(&self) -> &ProfileService { &self.profile_service } fn get_upnp_manager(&self) -> Arc<UpnpManager> { self.upnp.clone() } fn get_users_manager(&self) -> Arc<UsersManager> { self.users_manager.clone() } fn get_certificate_manager(&self) -> CertificateManager { self.certificate_manager.clone() } /// Every box should create a self signed certificate for a local name. /// The fingerprint of that certificate becomes the box's identifier, /// which is used to create the public DNS zone and local /// (i.e. local.<fingerprint>.box.knilxof.org) and remote /// (i.e. remote.<fingerprint>.box.knilxof.org) origins fn get_box_certificate(&self) -> io::Result<CertificateRecord> { self.certificate_manager.get_box_certificate() } fn get_tls_enabled(&self) -> bool { self.tls_option == TlsOption::Enabled } fn get_hostname(&self) -> String { self.hostname.clone() } } #[allow(dead_code)] struct FoxBoxEventLoop<'a> { controller: FoxBox, shutdown_flag: &'a AtomicBool } impl<'a> mio::Handler for FoxBoxEventLoop<'a> { type Timeout = (); type Message = (); fn
(&mut self, event_loop: &mut mio::EventLoop<Self>) { if self.shutdown_flag.load(Ordering::Acquire) { event_loop.shutdown(); } } }
tick
identifier_name
gpubindgrouplayout.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::GPUBindGroupLayoutBinding::GPUBindGroupLayoutMethods; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::USVString; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webgpu::WebGPUBindGroupLayout; #[dom_struct] pub struct GPUBindGroupLayout { reflector_: Reflector, label: DomRefCell<Option<USVString>>, bind_group_layout: WebGPUBindGroupLayout, } impl GPUBindGroupLayout { fn new_inherited(bind_group_layout: WebGPUBindGroupLayout, label: Option<USVString>) -> Self { Self { reflector_: Reflector::new(), label: DomRefCell::new(label), bind_group_layout, } } pub fn new( global: &GlobalScope, bind_group_layout: WebGPUBindGroupLayout, label: Option<USVString>, ) -> DomRoot<Self> { reflect_dom_object( Box::new(GPUBindGroupLayout::new_inherited(bind_group_layout, label)), global, ) } } impl GPUBindGroupLayout { pub fn id(&self) -> WebGPUBindGroupLayout { self.bind_group_layout } } impl GPUBindGroupLayoutMethods for GPUBindGroupLayout { /// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label fn GetLabel(&self) -> Option<USVString> { self.label.borrow().clone() } /// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label fn SetLabel(&self, value: Option<USVString>)
}
{ *self.label.borrow_mut() = value; }
identifier_body
gpubindgrouplayout.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::GPUBindGroupLayoutBinding::GPUBindGroupLayoutMethods; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::USVString; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webgpu::WebGPUBindGroupLayout; #[dom_struct] pub struct GPUBindGroupLayout { reflector_: Reflector, label: DomRefCell<Option<USVString>>, bind_group_layout: WebGPUBindGroupLayout, } impl GPUBindGroupLayout { fn new_inherited(bind_group_layout: WebGPUBindGroupLayout, label: Option<USVString>) -> Self { Self { reflector_: Reflector::new(), label: DomRefCell::new(label), bind_group_layout, } } pub fn new( global: &GlobalScope, bind_group_layout: WebGPUBindGroupLayout, label: Option<USVString>, ) -> DomRoot<Self> { reflect_dom_object( Box::new(GPUBindGroupLayout::new_inherited(bind_group_layout, label)), global, ) } }
} } impl GPUBindGroupLayoutMethods for GPUBindGroupLayout { /// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label fn GetLabel(&self) -> Option<USVString> { self.label.borrow().clone() } /// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label fn SetLabel(&self, value: Option<USVString>) { *self.label.borrow_mut() = value; } }
impl GPUBindGroupLayout { pub fn id(&self) -> WebGPUBindGroupLayout { self.bind_group_layout
random_line_split
gpubindgrouplayout.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::GPUBindGroupLayoutBinding::GPUBindGroupLayoutMethods; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::USVString; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webgpu::WebGPUBindGroupLayout; #[dom_struct] pub struct GPUBindGroupLayout { reflector_: Reflector, label: DomRefCell<Option<USVString>>, bind_group_layout: WebGPUBindGroupLayout, } impl GPUBindGroupLayout { fn new_inherited(bind_group_layout: WebGPUBindGroupLayout, label: Option<USVString>) -> Self { Self { reflector_: Reflector::new(), label: DomRefCell::new(label), bind_group_layout, } } pub fn
( global: &GlobalScope, bind_group_layout: WebGPUBindGroupLayout, label: Option<USVString>, ) -> DomRoot<Self> { reflect_dom_object( Box::new(GPUBindGroupLayout::new_inherited(bind_group_layout, label)), global, ) } } impl GPUBindGroupLayout { pub fn id(&self) -> WebGPUBindGroupLayout { self.bind_group_layout } } impl GPUBindGroupLayoutMethods for GPUBindGroupLayout { /// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label fn GetLabel(&self) -> Option<USVString> { self.label.borrow().clone() } /// https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label fn SetLabel(&self, value: Option<USVString>) { *self.label.borrow_mut() = value; } }
new
identifier_name
mod.rs
// Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice // shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER pub mod ncurses; pub mod termion;
// Copyright (c) Carl-Erwin Griffith //
random_line_split
Canonical_plain.rs
endogenous DPQ_P_NW, Y, ZGDP, ZI, ZPAI, ZY, D_GDP_NW, I, PAI, R, RN3M_NW exogenous EGDP, EI, EPAI, EY parameters beta_lag, beta_lead, beta_r, gam_lag, gam_y, gyss, iss, lamb_lag, lamb_lead, lamb_y, paiss, rhogdp, rhoi, rhopai, rhoy, siggdp, sigi, sigpai, sigy parameters prob_commit model(linear) Y=beta_lag*Y(-1)+beta_lead*Y(+1)-beta_r*R(-1)+ZY; PAI=lamb_lag*PAI(-1)+lamb_lead*PAI(+1)+lamb_y*Y(-1)+ZPAI; // // Taylor rule // I=gam_lag*I(-1)+(1-gam_lag)*(PAI(+4)+gam_y*Y)+ZI;
DPQ_P_NW=paiss+PAI; RN3M_NW=iss+I; ZI=rhoi*ZI(-1)+sigi*EI; ZPAI=rhopai*ZPAI(-1)+sigpai*EPAI; ZY=rhoy*ZY(-1)+sigy*EY; ZGDP=(1-rhogdp)*gyss+rhogdp*ZGDP(-1)+siggdp*EGDP; // the definition in the model is used in specifying the planner objective planner_objective{discount = 0.99,commitment=prob_commit} -.5*(1*PAI^2+.6*Y^2); observables DPQ_P_NW, D_GDP_NW, RN3M_NW; parameterization // not estimated gyss ,0 ; iss ,0 ; paiss ,0 ; beta_lag ,0.5000; beta_lead ,0.4000; beta_r ,0.9000; gam_lag ,0.6000; gam_y ,0.5000; lamb_lag ,0.8000; lamb_lead ,0.1000; lamb_y ,0.3000; rhogdp ,0.5000; rhoi ,0.5000; rhopai ,0.5000; rhoy ,0.5000; siggdp ,0.0050, 0.0001, 0.5000; sigi ,0.0050, 0.0001, 0.5000; sigpai ,0.0050, 0.0001, 0.5000; sigy ,0.0050, 0.0001, 0.5000; // probability of commitment prob_commit ,0.5000, 0.0000, 1.0000;
R=I-PAI(+1); D_GDP_NW=Y-Y(-1)+ZGDP;
random_line_split
hex.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. //! Hex binary-to-text encoding use std::str; use std::vec; /// A trait for converting a value to hexadecimal encoding pub trait ToHex { /// Converts the value of `self` to a hex value, returning the owned /// string. fn to_hex(&self) -> ~str; } static CHARS: &'static[u8] = bytes!("0123456789abcdef"); impl<'a> ToHex for &'a [u8] { /** * Turn a vector of `u8` bytes into a hexadecimal string. * * # Example * * ```rust * use extra::hex::ToHex; * * fn main () { * let str = [52,32].to_hex(); * println!("{}", str); * } * ``` */ fn to_hex(&self) -> ~str { let mut v = vec::with_capacity(self.len() * 2); for &byte in self.iter() { v.push(CHARS[byte >> 4]); v.push(CHARS[byte & 0xf]); } unsafe { str::raw::from_utf8_owned(v) } } } /// A trait for converting hexadecimal encoded values pub trait FromHex { /// Converts the value of `self`, interpreted as hexadecimal encoded data, /// into an owned vector of bytes, returning the vector. fn from_hex(&self) -> Result<~[u8], ~str>; } impl<'a> FromHex for &'a str { /** * Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`) * to the byte values it encodes. * * You can use the `from_utf8_owned` function in `std::str` * to turn a `[u8]` into a string with characters corresponding to those * values. * * # Example * * This converts a string literal to hexadecimal and back. * * ```rust * use extra::hex::{FromHex, ToHex}; * use std::str; * * fn main () { * let hello_str = "Hello, World".as_bytes().to_hex(); * println!("{}", hello_str); * let bytes = hello_str.from_hex().unwrap(); * println!("{:?}", bytes); * let result_str = str::from_utf8_owned(bytes); * println!("{}", result_str); * } * ``` */ fn from_hex(&self) -> Result<~[u8], ~str> { // This may be an overestimate if there is any whitespace let mut b = vec::with_capacity(self.len() / 2); let mut modulus = 0; let mut buf = 0u8; for (idx, byte) in self.bytes().enumerate() { buf <<= 4; match byte as char { 'A'..'F' => buf |= byte - ('A' as u8) + 10, 'a'..'f' => buf |= byte - ('a' as u8) + 10, '0'..'9' => buf |= byte - ('0' as u8), ''|'\r'|'\n'|'\t' => { buf >>= 4; continue } _ => return Err(format!("Invalid character '{}' at position {}", self.char_at(idx), idx)) } modulus += 1; if modulus == 2 { modulus = 0; b.push(buf); } } match modulus { 0 => Ok(b), _ => Err(~"Invalid input length") } } } #[cfg(test)] mod tests { use test::BenchHarness; use hex::*; #[test] pub fn test_to_hex() { assert_eq!("foobar".as_bytes().to_hex(), ~"666f6f626172"); } #[test] pub fn test_from_hex_okay() { assert_eq!("666f6f626172".from_hex().unwrap(), "foobar".as_bytes().to_owned()); assert_eq!("666F6F626172".from_hex().unwrap(), "foobar".as_bytes().to_owned()); } #[test] pub fn test_from_hex_odd_len() { assert!("666".from_hex().is_err()); assert!("66 6".from_hex().is_err()); } #[test] pub fn test_from_hex_invalid_char() { assert!("66y6".from_hex().is_err()); } #[test] pub fn test_from_hex_ignores_whitespace() { assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), "foobar".as_bytes().to_owned()); } #[test] pub fn test_to_hex_all_bytes() { for i in range(0, 256) { assert_eq!([i as u8].to_hex(), format!("{:02x}", i as uint)); } } #[test] pub fn test_from_hex_all_bytes() { for i in range(0, 256) { assert_eq!(format!("{:02x}", i as uint).from_hex().unwrap(), ~[i as u8]); assert_eq!(format!("{:02X}", i as uint).from_hex().unwrap(), ~[i as u8]); } } #[bench] pub fn bench_to_hex(bh: & mut BenchHarness) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; bh.iter(|| { s.as_bytes().to_hex(); }); bh.bytes = s.len() as u64; } #[bench] pub fn bench_from_hex(bh: & mut BenchHarness) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
let b = s.as_bytes().to_hex(); bh.iter(|| { b.from_hex(); }); bh.bytes = b.len() as u64; } }
identifier_body
hex.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. //! Hex binary-to-text encoding use std::str; use std::vec; /// A trait for converting a value to hexadecimal encoding pub trait ToHex { /// Converts the value of `self` to a hex value, returning the owned /// string. fn to_hex(&self) -> ~str; } static CHARS: &'static[u8] = bytes!("0123456789abcdef"); impl<'a> ToHex for &'a [u8] { /** * Turn a vector of `u8` bytes into a hexadecimal string. * * # Example * * ```rust * use extra::hex::ToHex; * * fn main () { * let str = [52,32].to_hex(); * println!("{}", str); * } * ``` */ fn to_hex(&self) -> ~str { let mut v = vec::with_capacity(self.len() * 2); for &byte in self.iter() { v.push(CHARS[byte >> 4]); v.push(CHARS[byte & 0xf]); } unsafe { str::raw::from_utf8_owned(v) } } } /// A trait for converting hexadecimal encoded values pub trait FromHex { /// Converts the value of `self`, interpreted as hexadecimal encoded data, /// into an owned vector of bytes, returning the vector. fn from_hex(&self) -> Result<~[u8], ~str>; } impl<'a> FromHex for &'a str { /** * Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`) * to the byte values it encodes. * * You can use the `from_utf8_owned` function in `std::str` * to turn a `[u8]` into a string with characters corresponding to those * values. * * # Example * * This converts a string literal to hexadecimal and back. * * ```rust * use extra::hex::{FromHex, ToHex}; * use std::str; * * fn main () { * let hello_str = "Hello, World".as_bytes().to_hex(); * println!("{}", hello_str); * let bytes = hello_str.from_hex().unwrap(); * println!("{:?}", bytes); * let result_str = str::from_utf8_owned(bytes); * println!("{}", result_str); * } * ``` */ fn from_hex(&self) -> Result<~[u8], ~str> { // This may be an overestimate if there is any whitespace let mut b = vec::with_capacity(self.len() / 2); let mut modulus = 0; let mut buf = 0u8; for (idx, byte) in self.bytes().enumerate() { buf <<= 4; match byte as char { 'A'..'F' => buf |= byte - ('A' as u8) + 10, 'a'..'f' => buf |= byte - ('a' as u8) + 10, '0'..'9' => buf |= byte - ('0' as u8), ''|'\r'|'\n'|'\t' => { buf >>= 4; continue } _ => return Err(format!("Invalid character '{}' at position {}", self.char_at(idx), idx)) } modulus += 1; if modulus == 2 { modulus = 0; b.push(buf); } } match modulus { 0 => Ok(b), _ => Err(~"Invalid input length") } } } #[cfg(test)] mod tests { use test::BenchHarness; use hex::*; #[test] pub fn test_to_hex() { assert_eq!("foobar".as_bytes().to_hex(), ~"666f6f626172"); } #[test] pub fn test_from_hex_okay() { assert_eq!("666f6f626172".from_hex().unwrap(), "foobar".as_bytes().to_owned()); assert_eq!("666F6F626172".from_hex().unwrap(), "foobar".as_bytes().to_owned()); } #[test] pub fn test_from_hex_odd_len() { assert!("666".from_hex().is_err()); assert!("66 6".from_hex().is_err()); } #[test] pub fn test_from_hex_invalid_char() { assert!("66y6".from_hex().is_err()); } #[test] pub fn
() { assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), "foobar".as_bytes().to_owned()); } #[test] pub fn test_to_hex_all_bytes() { for i in range(0, 256) { assert_eq!([i as u8].to_hex(), format!("{:02x}", i as uint)); } } #[test] pub fn test_from_hex_all_bytes() { for i in range(0, 256) { assert_eq!(format!("{:02x}", i as uint).from_hex().unwrap(), ~[i as u8]); assert_eq!(format!("{:02X}", i as uint).from_hex().unwrap(), ~[i as u8]); } } #[bench] pub fn bench_to_hex(bh: & mut BenchHarness) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; bh.iter(|| { s.as_bytes().to_hex(); }); bh.bytes = s.len() as u64; } #[bench] pub fn bench_from_hex(bh: & mut BenchHarness) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; let b = s.as_bytes().to_hex(); bh.iter(|| { b.from_hex(); }); bh.bytes = b.len() as u64; } }
test_from_hex_ignores_whitespace
identifier_name
hex.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. //! Hex binary-to-text encoding use std::str; use std::vec; /// A trait for converting a value to hexadecimal encoding pub trait ToHex { /// Converts the value of `self` to a hex value, returning the owned /// string. fn to_hex(&self) -> ~str; } static CHARS: &'static[u8] = bytes!("0123456789abcdef"); impl<'a> ToHex for &'a [u8] { /** * Turn a vector of `u8` bytes into a hexadecimal string. * * # Example * * ```rust * use extra::hex::ToHex; * * fn main () { * let str = [52,32].to_hex(); * println!("{}", str); * } * ``` */ fn to_hex(&self) -> ~str { let mut v = vec::with_capacity(self.len() * 2); for &byte in self.iter() { v.push(CHARS[byte >> 4]); v.push(CHARS[byte & 0xf]); } unsafe { str::raw::from_utf8_owned(v) } } } /// A trait for converting hexadecimal encoded values pub trait FromHex { /// Converts the value of `self`, interpreted as hexadecimal encoded data, /// into an owned vector of bytes, returning the vector. fn from_hex(&self) -> Result<~[u8], ~str>; } impl<'a> FromHex for &'a str { /** * Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`) * to the byte values it encodes. * * You can use the `from_utf8_owned` function in `std::str` * to turn a `[u8]` into a string with characters corresponding to those * values. * * # Example * * This converts a string literal to hexadecimal and back. * * ```rust * use extra::hex::{FromHex, ToHex}; * use std::str; * * fn main () { * let hello_str = "Hello, World".as_bytes().to_hex(); * println!("{}", hello_str); * let bytes = hello_str.from_hex().unwrap(); * println!("{:?}", bytes); * let result_str = str::from_utf8_owned(bytes); * println!("{}", result_str); * } * ``` */ fn from_hex(&self) -> Result<~[u8], ~str> { // This may be an overestimate if there is any whitespace let mut b = vec::with_capacity(self.len() / 2); let mut modulus = 0; let mut buf = 0u8; for (idx, byte) in self.bytes().enumerate() { buf <<= 4; match byte as char { 'A'..'F' => buf |= byte - ('A' as u8) + 10, 'a'..'f' => buf |= byte - ('a' as u8) + 10, '0'..'9' => buf |= byte - ('0' as u8), ''|'\r'|'\n'|'\t' => {
self.char_at(idx), idx)) } modulus += 1; if modulus == 2 { modulus = 0; b.push(buf); } } match modulus { 0 => Ok(b), _ => Err(~"Invalid input length") } } } #[cfg(test)] mod tests { use test::BenchHarness; use hex::*; #[test] pub fn test_to_hex() { assert_eq!("foobar".as_bytes().to_hex(), ~"666f6f626172"); } #[test] pub fn test_from_hex_okay() { assert_eq!("666f6f626172".from_hex().unwrap(), "foobar".as_bytes().to_owned()); assert_eq!("666F6F626172".from_hex().unwrap(), "foobar".as_bytes().to_owned()); } #[test] pub fn test_from_hex_odd_len() { assert!("666".from_hex().is_err()); assert!("66 6".from_hex().is_err()); } #[test] pub fn test_from_hex_invalid_char() { assert!("66y6".from_hex().is_err()); } #[test] pub fn test_from_hex_ignores_whitespace() { assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), "foobar".as_bytes().to_owned()); } #[test] pub fn test_to_hex_all_bytes() { for i in range(0, 256) { assert_eq!([i as u8].to_hex(), format!("{:02x}", i as uint)); } } #[test] pub fn test_from_hex_all_bytes() { for i in range(0, 256) { assert_eq!(format!("{:02x}", i as uint).from_hex().unwrap(), ~[i as u8]); assert_eq!(format!("{:02X}", i as uint).from_hex().unwrap(), ~[i as u8]); } } #[bench] pub fn bench_to_hex(bh: & mut BenchHarness) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; bh.iter(|| { s.as_bytes().to_hex(); }); bh.bytes = s.len() as u64; } #[bench] pub fn bench_from_hex(bh: & mut BenchHarness) { let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン"; let b = s.as_bytes().to_hex(); bh.iter(|| { b.from_hex(); }); bh.bytes = b.len() as u64; } }
buf >>= 4; continue } _ => return Err(format!("Invalid character '{}' at position {}",
random_line_split
shard_runner.rs
prelude::*; use internal::ws_impl::{ReceiverExt, SenderExt}; use model::event::{Event, GatewayEvent}; use parking_lot::Mutex; use serde::Deserialize; use std::sync::{ mpsc::{ self, Receiver, Sender, TryRecvError }, Arc }; use super::super::super::dispatch::{DispatchEvent, dispatch}; use super::super::super::EventHandler; use super::event::{ClientEvent, ShardStageUpdateEvent}; use super::{ShardClientMessage, ShardId, ShardManagerMessage, ShardRunnerMessage}; use threadpool::ThreadPool; use typemap::ShareMap; use websocket::{ message::{CloseData, OwnedMessage}, WebSocketError }; #[cfg(feature = "framework")] use framework::Framework; #[cfg(feature = "voice")] use super::super::voice::ClientVoiceManager; /// A runner for managing a [`Shard`] and its respective WebSocket client. /// /// [`Shard`]:../../../gateway/struct.Shard.html pub struct ShardRunner<H: EventHandler + Send + Sync +'static> { data: Arc<Mutex<ShareMap>>, event_handler: Arc<H>, #[cfg(feature = "framework")] framework: Arc<Mutex<Option<Box<Framework + Send>>>>, manager_tx: Sender<ShardManagerMessage>, // channel to receive messages from the shard manager and dispatches runner_rx: Receiver<InterMessage>, // channel to send messages to the shard runner from the shard manager runner_tx: Sender<InterMessage>, shard: Shard, threadpool: ThreadPool, #[cfg(feature = "voice")] voice_manager: Arc<Mutex<ClientVoiceManager>>, } impl<H: EventHandler + Send + Sync +'static> ShardRunner<H> { /// Creates a new runner for a Shard. pub fn
(opt: ShardRunnerOptions<H>) -> Self { let (tx, rx) = mpsc::channel(); Self { runner_rx: rx, runner_tx: tx, data: opt.data, event_handler: opt.event_handler, #[cfg(feature = "framework")] framework: opt.framework, manager_tx: opt.manager_tx, shard: opt.shard, threadpool: opt.threadpool, #[cfg(feature = "voice")] voice_manager: opt.voice_manager, } } /// Starts the runner's loop to receive events. /// /// This runs a loop that performs the following in each iteration: /// /// 1. checks the receiver for [`ShardRunnerMessage`]s, possibly from the /// [`ShardManager`], and if there is one, acts on it. /// /// 2. checks if a heartbeat should be sent to the discord Gateway, and if /// so, sends one. /// /// 3. attempts to retrieve a message from the WebSocket, processing it into /// a [`GatewayEvent`]. This will block for 100ms before assuming there is /// no message available. /// /// 4. Checks with the [`Shard`] to determine if the gateway event is /// specifying an action to take (e.g. resuming, reconnecting, heartbeating) /// and then performs that action, if any. /// /// 5. Dispatches the event via the Client. /// /// 6. Go back to 1. /// /// [`GatewayEvent`]:../../../model/event/enum.GatewayEvent.html /// [`Shard`]:../../../gateway/struct.Shard.html /// [`ShardManager`]: struct.ShardManager.html /// [`ShardRunnerMessage`]: enum.ShardRunnerMessage.html pub fn run(&mut self) -> Result<()> { debug!("[ShardRunner {:?}] Running", self.shard.shard_info()); loop { if!self.recv()? { return Ok(()); } // check heartbeat if!self.shard.check_heartbeat() { warn!( "[ShardRunner {:?}] Error heartbeating", self.shard.shard_info(), ); return self.request_restart(); } let pre = self.shard.stage(); let (event, action, successful) = self.recv_event(); let post = self.shard.stage(); if post!= pre { self.update_manager(); let e = ClientEvent::ShardStageUpdate(ShardStageUpdateEvent { new: post, old: pre, shard_id: ShardId(self.shard.shard_info()[0]), }); self.dispatch(DispatchEvent::Client(e)); } match action { Some(ShardAction::Reconnect(ReconnectType::Reidentify)) => { return self.request_restart() }, Some(other) => { let _ = self.action(&other); }, None => {}, } if let Some(event) = event { self.dispatch(DispatchEvent::Model(event)); } if!successful &&!self.shard.stage().is_connecting() { return self.request_restart(); } } } /// Clones the internal copy of the Sender to the shard runner. pub(super) fn runner_tx(&self) -> Sender<InterMessage> { self.runner_tx.clone() } /// Takes an action that a [`Shard`] has determined should happen and then /// does it. /// /// For example, if the shard says that an Identify message needs to be /// sent, this will do that. /// /// # Errors /// /// Returns fn action(&mut self, action: &ShardAction) -> Result<()> { match *action { ShardAction::Reconnect(ReconnectType::Reidentify) => { self.request_restart() }, ShardAction::Reconnect(ReconnectType::Resume) => { self.shard.resume() }, ShardAction::Heartbeat => self.shard.heartbeat(), ShardAction::Identify => self.shard.identify(), } } // Checks if the ID received to shutdown is equivalent to the ID of the // shard this runner is responsible. If so, it shuts down the WebSocket // client. // // Returns whether the WebSocket client is still active. // // If true, the WebSocket client was _not_ shutdown. If false, it was. fn checked_shutdown(&mut self, id: ShardId) -> bool { // First verify the ID so we know for certain this runner is // to shutdown. if id.0!= self.shard.shard_info()[0] { // Not meant for this runner for some reason, don't // shutdown. return true; } let close_data = CloseData::new(1000, String::new()); let msg = OwnedMessage::Close(Some(close_data)); let _ = self.shard.client.send_message(&msg); false } #[inline] fn dispatch(&self, event: DispatchEvent) { dispatch( event, #[cfg(feature = "framework")] &self.framework, &self.data, &self.event_handler, &self.runner_tx, &self.threadpool, self.shard.shard_info()[0], ); } // Handles a received value over the shard runner rx channel. // // Returns a boolean on whether the shard runner can continue. // // This always returns true, except in the case that the shard manager asked // the runner to shutdown. fn handle_rx_value(&mut self, value: InterMessage) -> bool { match value { InterMessage::Client(ShardClientMessage::Manager(x)) => match x { ShardManagerMessage::Restart(id) | ShardManagerMessage::Shutdown(id) => { self.checked_shutdown(id) }, ShardManagerMessage::ShutdownAll => { // This variant should never be received. warn!( "[ShardRunner {:?}] Received a ShutdownAll?", self.shard.shard_info(), ); true }, ShardManagerMessage::ShardUpdate {.. } | ShardManagerMessage::ShutdownInitiated => { // nb: not sent here true }, }, InterMessage::Client(ShardClientMessage::Runner(x)) => match x { ShardRunnerMessage::ChunkGuilds { guild_ids, limit, query } => { self.shard.chunk_guilds( guild_ids, limit, query.as_ref().map(String::as_str), ).is_ok() }, ShardRunnerMessage::Close(code, reason) => { let reason = reason.unwrap_or_else(String::new); let data = CloseData::new(code, reason); let msg = OwnedMessage::Close(Some(data)); self.shard.client.send_message(&msg).is_ok() }, ShardRunnerMessage::Message(msg) => { self.shard.client.send_message(&msg).is_ok() }, ShardRunnerMessage::SetGame(game) => { // To avoid a clone of `game`, we do a little bit of // trickery here: // // First, we obtain a reference to the current presence of // the shard, and create a new presence tuple of the new // game we received over the channel as well as the online // status that the shard already had. // // We then (attempt to) send the websocket message with the // status update, expressively returning: // // - whether the message successfully sent // - the original game we received over the channel self.shard.set_game(game); self.shard.update_presence().is_ok() }, ShardRunnerMessage::SetPresence(status, game) => { self.shard.set_presence(status, game); self.shard.update_presence().is_ok() }, ShardRunnerMessage::SetStatus(status) => { self.shard.set_status(status); self.shard.update_presence().is_ok() }, }, InterMessage::Json(value) => { // Value must be forwarded over the websocket self.shard.client.send_json(&value).is_ok() }, } } #[cfg(feature = "voice")] fn handle_voice_event(&self, event: &Event) { match *event { Event::Ready(_) => { self.voice_manager.lock().set( self.shard.shard_info()[0], self.runner_tx.clone(), ); }, Event::VoiceServerUpdate(ref event) => { if let Some(guild_id) = event.guild_id { let mut manager = self.voice_manager.lock(); let mut search = manager.get_mut(guild_id); if let Some(handler) = search { handler.update_server(&event.endpoint, &event.token); } } }, Event::VoiceStateUpdate(ref event) => { if let Some(guild_id) = event.guild_id { let mut manager = self.voice_manager.lock(); let mut search = manager.get_mut(guild_id); if let Some(handler) = search { handler.update_state(&event.voice_state); } } }, _ => {}, } } // Receives values over the internal shard runner rx channel and handles // them. // // This will loop over values until there is no longer one. // // Requests a restart if the sending half of the channel disconnects. This // should _never_ happen, as the sending half is kept on the runner. // Returns whether the shard runner is in a state that can continue. fn recv(&mut self) -> Result<bool> { loop { match self.runner_rx.try_recv() { Ok(value) => { if!self.handle_rx_value(value) { return Ok(false); } }, Err(TryRecvError::Disconnected) => { warn!( "[ShardRunner {:?}] Sending half DC; restarting", self.shard.shard_info(), ); let _ = self.request_restart(); return Ok(false); }, Err(TryRecvError::Empty) => break, } } // There are no longer any values available. Ok(true) } /// Returns a received event, as well as whether reading the potentially /// present event was successful. fn recv_event(&mut self) -> (Option<Event>, Option<ShardAction>, bool) { let gw_event = match self.shard.client.recv_json() { Ok(Some(value)) => { GatewayEvent::deserialize(value).map(Some).map_err(From::from) }, Ok(None) => Ok(None), Err(Error::WebSocket(WebSocketError::IoError(_))) => { // Check that an amount of time at least double the // heartbeat_interval has passed. // // If not, continue on trying to receive messages. // // If it has, attempt to auto-reconnect. { let last = self.shard.last_heartbeat_ack(); let interval = self.shard.heartbeat_interval(); if let (Some(last_heartbeat_ack), Some(interval)) = (last, interval) { let seconds_passed = last_heartbeat_ack.elapsed().as_secs(); let interval_in_secs = interval / 1000; if seconds_passed <= interval_in_secs * 2 { return (None, None, true); } } else { return (None, None, true); } } debug!("Attempting to auto-reconnect"); match self.shard.reconnection_type() { ReconnectType::Reidentify => return (None, None, false), ReconnectType::Resume => { if let Err(why) = self.shard.resume() { warn!("Failed to resume: {:?}", why); return (None, None, false); } }, } return (None, None, true); }, Err(Error::WebSocket(WebSocketError::NoDataAvailable)) => { // This is hit when the websocket client dies this will be // hit every iteration. return (None, None, false); }, Err(why) => Err(why), }; let event = match gw_event { Ok(Some(event)) => Ok(event), Ok(None) => return (None, None, true), Err(why) => Err(why), }; let action = match self.shard.handle_event(&event) { Ok(Some(action)) => Some(action), Ok(None) => None, Err(why) => { error!("Shard handler received err: {:?}", why); return (None, None, true); }, }; if let Ok(GatewayEvent::HeartbeatAck) = event { self.update_manager(); } #[cfg(feature = "voice")] { if let Ok(GatewayEvent::Dispatch(_, ref event)) = event { self.handle_voice_event(&event); } } let event = match event { Ok(GatewayEvent::Dispatch(_, event)) => Some(event), _ => None, }; (event, action, true) } fn request_restart(&self) -> Result<()> { self.update_manager(); debug!( "[ShardRunner {:?}] Requesting restart", self.shard.shard_info(), ); let shard_id = ShardId(self.shard.shard_info()[0]); let msg = ShardManagerMessage::Restart(shard_id); let _ = self.manager_tx.send(msg); #[cfg(feature = "voice")] { self.voice_manager.lock().manager_remove(&shard_id.0); } Ok(()) } fn update_manager(&self) { let _ = self.manager_tx.send(ShardManagerMessage::ShardUpdate { id: ShardId(self.shard.shard_info()[0]), latency: self.shard.latency(), stage: self.shard.stage(), }); } } /// Options to be passed to [`ShardRunner::new`]. /// /// [`ShardRunner::new`]: struct.ShardRunner.html#method.new pub struct ShardRunnerOptions<H: EventHandler + Send + Sync +'static> { pub data: Arc<Mutex<ShareMap>>, pub event_handler: Arc<H>, #[cfg(feature = "framework")] pub framework: Arc<Mutex<Option<Box<Framework + Send>>>>, pub manager_tx: Sender<ShardManagerMessage>,
new
identifier_name
shard_runner.rs
::prelude::*; use internal::ws_impl::{ReceiverExt, SenderExt}; use model::event::{Event, GatewayEvent}; use parking_lot::Mutex; use serde::Deserialize; use std::sync::{ mpsc::{ self, Receiver, Sender, TryRecvError }, Arc }; use super::super::super::dispatch::{DispatchEvent, dispatch}; use super::super::super::EventHandler; use super::event::{ClientEvent, ShardStageUpdateEvent}; use super::{ShardClientMessage, ShardId, ShardManagerMessage, ShardRunnerMessage}; use threadpool::ThreadPool; use typemap::ShareMap; use websocket::{ message::{CloseData, OwnedMessage}, WebSocketError }; #[cfg(feature = "framework")] use framework::Framework; #[cfg(feature = "voice")] use super::super::voice::ClientVoiceManager; /// A runner for managing a [`Shard`] and its respective WebSocket client. /// /// [`Shard`]:../../../gateway/struct.Shard.html pub struct ShardRunner<H: EventHandler + Send + Sync +'static> { data: Arc<Mutex<ShareMap>>, event_handler: Arc<H>, #[cfg(feature = "framework")] framework: Arc<Mutex<Option<Box<Framework + Send>>>>, manager_tx: Sender<ShardManagerMessage>, // channel to receive messages from the shard manager and dispatches runner_rx: Receiver<InterMessage>, // channel to send messages to the shard runner from the shard manager runner_tx: Sender<InterMessage>, shard: Shard, threadpool: ThreadPool, #[cfg(feature = "voice")] voice_manager: Arc<Mutex<ClientVoiceManager>>, } impl<H: EventHandler + Send + Sync +'static> ShardRunner<H> { /// Creates a new runner for a Shard. pub fn new(opt: ShardRunnerOptions<H>) -> Self { let (tx, rx) = mpsc::channel(); Self { runner_rx: rx, runner_tx: tx, data: opt.data, event_handler: opt.event_handler, #[cfg(feature = "framework")] framework: opt.framework, manager_tx: opt.manager_tx, shard: opt.shard, threadpool: opt.threadpool, #[cfg(feature = "voice")] voice_manager: opt.voice_manager, } } /// Starts the runner's loop to receive events. /// /// This runs a loop that performs the following in each iteration: /// /// 1. checks the receiver for [`ShardRunnerMessage`]s, possibly from the /// [`ShardManager`], and if there is one, acts on it. /// /// 2. checks if a heartbeat should be sent to the discord Gateway, and if /// so, sends one. /// /// 3. attempts to retrieve a message from the WebSocket, processing it into /// a [`GatewayEvent`]. This will block for 100ms before assuming there is /// no message available. /// /// 4. Checks with the [`Shard`] to determine if the gateway event is /// specifying an action to take (e.g. resuming, reconnecting, heartbeating) /// and then performs that action, if any. /// /// 5. Dispatches the event via the Client. /// /// 6. Go back to 1. /// /// [`GatewayEvent`]:../../../model/event/enum.GatewayEvent.html /// [`Shard`]:../../../gateway/struct.Shard.html /// [`ShardManager`]: struct.ShardManager.html /// [`ShardRunnerMessage`]: enum.ShardRunnerMessage.html pub fn run(&mut self) -> Result<()> { debug!("[ShardRunner {:?}] Running", self.shard.shard_info()); loop { if!self.recv()? { return Ok(()); } // check heartbeat if!self.shard.check_heartbeat() { warn!( "[ShardRunner {:?}] Error heartbeating", self.shard.shard_info(), ); return self.request_restart(); } let pre = self.shard.stage(); let (event, action, successful) = self.recv_event(); let post = self.shard.stage(); if post!= pre { self.update_manager(); let e = ClientEvent::ShardStageUpdate(ShardStageUpdateEvent { new: post, old: pre, shard_id: ShardId(self.shard.shard_info()[0]), }); self.dispatch(DispatchEvent::Client(e)); } match action { Some(ShardAction::Reconnect(ReconnectType::Reidentify)) => { return self.request_restart() }, Some(other) => { let _ = self.action(&other); }, None => {}, } if let Some(event) = event { self.dispatch(DispatchEvent::Model(event)); } if!successful &&!self.shard.stage().is_connecting() { return self.request_restart(); } } } /// Clones the internal copy of the Sender to the shard runner. pub(super) fn runner_tx(&self) -> Sender<InterMessage> { self.runner_tx.clone() } /// Takes an action that a [`Shard`] has determined should happen and then /// does it. /// /// For example, if the shard says that an Identify message needs to be /// sent, this will do that. /// /// # Errors /// /// Returns fn action(&mut self, action: &ShardAction) -> Result<()> { match *action { ShardAction::Reconnect(ReconnectType::Reidentify) => { self.request_restart() }, ShardAction::Reconnect(ReconnectType::Resume) => { self.shard.resume() }, ShardAction::Heartbeat => self.shard.heartbeat(), ShardAction::Identify => self.shard.identify(), } } // Checks if the ID received to shutdown is equivalent to the ID of the // shard this runner is responsible. If so, it shuts down the WebSocket // client. // // Returns whether the WebSocket client is still active. // // If true, the WebSocket client was _not_ shutdown. If false, it was. fn checked_shutdown(&mut self, id: ShardId) -> bool { // First verify the ID so we know for certain this runner is // to shutdown. if id.0!= self.shard.shard_info()[0] { // Not meant for this runner for some reason, don't // shutdown. return true; } let close_data = CloseData::new(1000, String::new()); let msg = OwnedMessage::Close(Some(close_data)); let _ = self.shard.client.send_message(&msg); false }
#[inline] fn dispatch(&self, event: DispatchEvent) { dispatch( event, #[cfg(feature = "framework")] &self.framework, &self.data, &self.event_handler, &self.runner_tx, &self.threadpool, self.shard.shard_info()[0], ); } // Handles a received value over the shard runner rx channel. // // Returns a boolean on whether the shard runner can continue. // // This always returns true, except in the case that the shard manager asked // the runner to shutdown. fn handle_rx_value(&mut self, value: InterMessage) -> bool { match value { InterMessage::Client(ShardClientMessage::Manager(x)) => match x { ShardManagerMessage::Restart(id) | ShardManagerMessage::Shutdown(id) => { self.checked_shutdown(id) }, ShardManagerMessage::ShutdownAll => { // This variant should never be received. warn!( "[ShardRunner {:?}] Received a ShutdownAll?", self.shard.shard_info(), ); true }, ShardManagerMessage::ShardUpdate {.. } | ShardManagerMessage::ShutdownInitiated => { // nb: not sent here true }, }, InterMessage::Client(ShardClientMessage::Runner(x)) => match x { ShardRunnerMessage::ChunkGuilds { guild_ids, limit, query } => { self.shard.chunk_guilds( guild_ids, limit, query.as_ref().map(String::as_str), ).is_ok() }, ShardRunnerMessage::Close(code, reason) => { let reason = reason.unwrap_or_else(String::new); let data = CloseData::new(code, reason); let msg = OwnedMessage::Close(Some(data)); self.shard.client.send_message(&msg).is_ok() }, ShardRunnerMessage::Message(msg) => { self.shard.client.send_message(&msg).is_ok() }, ShardRunnerMessage::SetGame(game) => { // To avoid a clone of `game`, we do a little bit of // trickery here: // // First, we obtain a reference to the current presence of // the shard, and create a new presence tuple of the new // game we received over the channel as well as the online // status that the shard already had. // // We then (attempt to) send the websocket message with the // status update, expressively returning: // // - whether the message successfully sent // - the original game we received over the channel self.shard.set_game(game); self.shard.update_presence().is_ok() }, ShardRunnerMessage::SetPresence(status, game) => { self.shard.set_presence(status, game); self.shard.update_presence().is_ok() }, ShardRunnerMessage::SetStatus(status) => { self.shard.set_status(status); self.shard.update_presence().is_ok() }, }, InterMessage::Json(value) => { // Value must be forwarded over the websocket self.shard.client.send_json(&value).is_ok() }, } } #[cfg(feature = "voice")] fn handle_voice_event(&self, event: &Event) { match *event { Event::Ready(_) => { self.voice_manager.lock().set( self.shard.shard_info()[0], self.runner_tx.clone(), ); }, Event::VoiceServerUpdate(ref event) => { if let Some(guild_id) = event.guild_id { let mut manager = self.voice_manager.lock(); let mut search = manager.get_mut(guild_id); if let Some(handler) = search { handler.update_server(&event.endpoint, &event.token); } } }, Event::VoiceStateUpdate(ref event) => { if let Some(guild_id) = event.guild_id { let mut manager = self.voice_manager.lock(); let mut search = manager.get_mut(guild_id); if let Some(handler) = search { handler.update_state(&event.voice_state); } } }, _ => {}, } } // Receives values over the internal shard runner rx channel and handles // them. // // This will loop over values until there is no longer one. // // Requests a restart if the sending half of the channel disconnects. This // should _never_ happen, as the sending half is kept on the runner. // Returns whether the shard runner is in a state that can continue. fn recv(&mut self) -> Result<bool> { loop { match self.runner_rx.try_recv() { Ok(value) => { if!self.handle_rx_value(value) { return Ok(false); } }, Err(TryRecvError::Disconnected) => { warn!( "[ShardRunner {:?}] Sending half DC; restarting", self.shard.shard_info(), ); let _ = self.request_restart(); return Ok(false); }, Err(TryRecvError::Empty) => break, } } // There are no longer any values available. Ok(true) } /// Returns a received event, as well as whether reading the potentially /// present event was successful. fn recv_event(&mut self) -> (Option<Event>, Option<ShardAction>, bool) { let gw_event = match self.shard.client.recv_json() { Ok(Some(value)) => { GatewayEvent::deserialize(value).map(Some).map_err(From::from) }, Ok(None) => Ok(None), Err(Error::WebSocket(WebSocketError::IoError(_))) => { // Check that an amount of time at least double the // heartbeat_interval has passed. // // If not, continue on trying to receive messages. // // If it has, attempt to auto-reconnect. { let last = self.shard.last_heartbeat_ack(); let interval = self.shard.heartbeat_interval(); if let (Some(last_heartbeat_ack), Some(interval)) = (last, interval) { let seconds_passed = last_heartbeat_ack.elapsed().as_secs(); let interval_in_secs = interval / 1000; if seconds_passed <= interval_in_secs * 2 { return (None, None, true); } } else { return (None, None, true); } } debug!("Attempting to auto-reconnect"); match self.shard.reconnection_type() { ReconnectType::Reidentify => return (None, None, false), ReconnectType::Resume => { if let Err(why) = self.shard.resume() { warn!("Failed to resume: {:?}", why); return (None, None, false); } }, } return (None, None, true); }, Err(Error::WebSocket(WebSocketError::NoDataAvailable)) => { // This is hit when the websocket client dies this will be // hit every iteration. return (None, None, false); }, Err(why) => Err(why), }; let event = match gw_event { Ok(Some(event)) => Ok(event), Ok(None) => return (None, None, true), Err(why) => Err(why), }; let action = match self.shard.handle_event(&event) { Ok(Some(action)) => Some(action), Ok(None) => None, Err(why) => { error!("Shard handler received err: {:?}", why); return (None, None, true); }, }; if let Ok(GatewayEvent::HeartbeatAck) = event { self.update_manager(); } #[cfg(feature = "voice")] { if let Ok(GatewayEvent::Dispatch(_, ref event)) = event { self.handle_voice_event(&event); } } let event = match event { Ok(GatewayEvent::Dispatch(_, event)) => Some(event), _ => None, }; (event, action, true) } fn request_restart(&self) -> Result<()> { self.update_manager(); debug!( "[ShardRunner {:?}] Requesting restart", self.shard.shard_info(), ); let shard_id = ShardId(self.shard.shard_info()[0]); let msg = ShardManagerMessage::Restart(shard_id); let _ = self.manager_tx.send(msg); #[cfg(feature = "voice")] { self.voice_manager.lock().manager_remove(&shard_id.0); } Ok(()) } fn update_manager(&self) { let _ = self.manager_tx.send(ShardManagerMessage::ShardUpdate { id: ShardId(self.shard.shard_info()[0]), latency: self.shard.latency(), stage: self.shard.stage(), }); } } /// Options to be passed to [`ShardRunner::new`]. /// /// [`ShardRunner::new`]: struct.ShardRunner.html#method.new pub struct ShardRunnerOptions<H: EventHandler + Send + Sync +'static> { pub data: Arc<Mutex<ShareMap>>, pub event_handler: Arc<H>, #[cfg(feature = "framework")] pub framework: Arc<Mutex<Option<Box<Framework + Send>>>>, pub manager_tx: Sender<ShardManagerMessage>, pub shard
random_line_split
shard_runner.rs
prelude::*; use internal::ws_impl::{ReceiverExt, SenderExt}; use model::event::{Event, GatewayEvent}; use parking_lot::Mutex; use serde::Deserialize; use std::sync::{ mpsc::{ self, Receiver, Sender, TryRecvError }, Arc }; use super::super::super::dispatch::{DispatchEvent, dispatch}; use super::super::super::EventHandler; use super::event::{ClientEvent, ShardStageUpdateEvent}; use super::{ShardClientMessage, ShardId, ShardManagerMessage, ShardRunnerMessage}; use threadpool::ThreadPool; use typemap::ShareMap; use websocket::{ message::{CloseData, OwnedMessage}, WebSocketError }; #[cfg(feature = "framework")] use framework::Framework; #[cfg(feature = "voice")] use super::super::voice::ClientVoiceManager; /// A runner for managing a [`Shard`] and its respective WebSocket client. /// /// [`Shard`]:../../../gateway/struct.Shard.html pub struct ShardRunner<H: EventHandler + Send + Sync +'static> { data: Arc<Mutex<ShareMap>>, event_handler: Arc<H>, #[cfg(feature = "framework")] framework: Arc<Mutex<Option<Box<Framework + Send>>>>, manager_tx: Sender<ShardManagerMessage>, // channel to receive messages from the shard manager and dispatches runner_rx: Receiver<InterMessage>, // channel to send messages to the shard runner from the shard manager runner_tx: Sender<InterMessage>, shard: Shard, threadpool: ThreadPool, #[cfg(feature = "voice")] voice_manager: Arc<Mutex<ClientVoiceManager>>, } impl<H: EventHandler + Send + Sync +'static> ShardRunner<H> { /// Creates a new runner for a Shard. pub fn new(opt: ShardRunnerOptions<H>) -> Self { let (tx, rx) = mpsc::channel(); Self { runner_rx: rx, runner_tx: tx, data: opt.data, event_handler: opt.event_handler, #[cfg(feature = "framework")] framework: opt.framework, manager_tx: opt.manager_tx, shard: opt.shard, threadpool: opt.threadpool, #[cfg(feature = "voice")] voice_manager: opt.voice_manager, } } /// Starts the runner's loop to receive events. /// /// This runs a loop that performs the following in each iteration: /// /// 1. checks the receiver for [`ShardRunnerMessage`]s, possibly from the /// [`ShardManager`], and if there is one, acts on it. /// /// 2. checks if a heartbeat should be sent to the discord Gateway, and if /// so, sends one. /// /// 3. attempts to retrieve a message from the WebSocket, processing it into /// a [`GatewayEvent`]. This will block for 100ms before assuming there is /// no message available. /// /// 4. Checks with the [`Shard`] to determine if the gateway event is /// specifying an action to take (e.g. resuming, reconnecting, heartbeating) /// and then performs that action, if any. /// /// 5. Dispatches the event via the Client. /// /// 6. Go back to 1. /// /// [`GatewayEvent`]:../../../model/event/enum.GatewayEvent.html /// [`Shard`]:../../../gateway/struct.Shard.html /// [`ShardManager`]: struct.ShardManager.html /// [`ShardRunnerMessage`]: enum.ShardRunnerMessage.html pub fn run(&mut self) -> Result<()> { debug!("[ShardRunner {:?}] Running", self.shard.shard_info()); loop { if!self.recv()? { return Ok(()); } // check heartbeat if!self.shard.check_heartbeat() { warn!( "[ShardRunner {:?}] Error heartbeating", self.shard.shard_info(), ); return self.request_restart(); } let pre = self.shard.stage(); let (event, action, successful) = self.recv_event(); let post = self.shard.stage(); if post!= pre { self.update_manager(); let e = ClientEvent::ShardStageUpdate(ShardStageUpdateEvent { new: post, old: pre, shard_id: ShardId(self.shard.shard_info()[0]), }); self.dispatch(DispatchEvent::Client(e)); } match action { Some(ShardAction::Reconnect(ReconnectType::Reidentify)) => { return self.request_restart() }, Some(other) => { let _ = self.action(&other); }, None => {}, } if let Some(event) = event { self.dispatch(DispatchEvent::Model(event)); } if!successful &&!self.shard.stage().is_connecting() { return self.request_restart(); } } } /// Clones the internal copy of the Sender to the shard runner. pub(super) fn runner_tx(&self) -> Sender<InterMessage>
/// Takes an action that a [`Shard`] has determined should happen and then /// does it. /// /// For example, if the shard says that an Identify message needs to be /// sent, this will do that. /// /// # Errors /// /// Returns fn action(&mut self, action: &ShardAction) -> Result<()> { match *action { ShardAction::Reconnect(ReconnectType::Reidentify) => { self.request_restart() }, ShardAction::Reconnect(ReconnectType::Resume) => { self.shard.resume() }, ShardAction::Heartbeat => self.shard.heartbeat(), ShardAction::Identify => self.shard.identify(), } } // Checks if the ID received to shutdown is equivalent to the ID of the // shard this runner is responsible. If so, it shuts down the WebSocket // client. // // Returns whether the WebSocket client is still active. // // If true, the WebSocket client was _not_ shutdown. If false, it was. fn checked_shutdown(&mut self, id: ShardId) -> bool { // First verify the ID so we know for certain this runner is // to shutdown. if id.0!= self.shard.shard_info()[0] { // Not meant for this runner for some reason, don't // shutdown. return true; } let close_data = CloseData::new(1000, String::new()); let msg = OwnedMessage::Close(Some(close_data)); let _ = self.shard.client.send_message(&msg); false } #[inline] fn dispatch(&self, event: DispatchEvent) { dispatch( event, #[cfg(feature = "framework")] &self.framework, &self.data, &self.event_handler, &self.runner_tx, &self.threadpool, self.shard.shard_info()[0], ); } // Handles a received value over the shard runner rx channel. // // Returns a boolean on whether the shard runner can continue. // // This always returns true, except in the case that the shard manager asked // the runner to shutdown. fn handle_rx_value(&mut self, value: InterMessage) -> bool { match value { InterMessage::Client(ShardClientMessage::Manager(x)) => match x { ShardManagerMessage::Restart(id) | ShardManagerMessage::Shutdown(id) => { self.checked_shutdown(id) }, ShardManagerMessage::ShutdownAll => { // This variant should never be received. warn!( "[ShardRunner {:?}] Received a ShutdownAll?", self.shard.shard_info(), ); true }, ShardManagerMessage::ShardUpdate {.. } | ShardManagerMessage::ShutdownInitiated => { // nb: not sent here true }, }, InterMessage::Client(ShardClientMessage::Runner(x)) => match x { ShardRunnerMessage::ChunkGuilds { guild_ids, limit, query } => { self.shard.chunk_guilds( guild_ids, limit, query.as_ref().map(String::as_str), ).is_ok() }, ShardRunnerMessage::Close(code, reason) => { let reason = reason.unwrap_or_else(String::new); let data = CloseData::new(code, reason); let msg = OwnedMessage::Close(Some(data)); self.shard.client.send_message(&msg).is_ok() }, ShardRunnerMessage::Message(msg) => { self.shard.client.send_message(&msg).is_ok() }, ShardRunnerMessage::SetGame(game) => { // To avoid a clone of `game`, we do a little bit of // trickery here: // // First, we obtain a reference to the current presence of // the shard, and create a new presence tuple of the new // game we received over the channel as well as the online // status that the shard already had. // // We then (attempt to) send the websocket message with the // status update, expressively returning: // // - whether the message successfully sent // - the original game we received over the channel self.shard.set_game(game); self.shard.update_presence().is_ok() }, ShardRunnerMessage::SetPresence(status, game) => { self.shard.set_presence(status, game); self.shard.update_presence().is_ok() }, ShardRunnerMessage::SetStatus(status) => { self.shard.set_status(status); self.shard.update_presence().is_ok() }, }, InterMessage::Json(value) => { // Value must be forwarded over the websocket self.shard.client.send_json(&value).is_ok() }, } } #[cfg(feature = "voice")] fn handle_voice_event(&self, event: &Event) { match *event { Event::Ready(_) => { self.voice_manager.lock().set( self.shard.shard_info()[0], self.runner_tx.clone(), ); }, Event::VoiceServerUpdate(ref event) => { if let Some(guild_id) = event.guild_id { let mut manager = self.voice_manager.lock(); let mut search = manager.get_mut(guild_id); if let Some(handler) = search { handler.update_server(&event.endpoint, &event.token); } } }, Event::VoiceStateUpdate(ref event) => { if let Some(guild_id) = event.guild_id { let mut manager = self.voice_manager.lock(); let mut search = manager.get_mut(guild_id); if let Some(handler) = search { handler.update_state(&event.voice_state); } } }, _ => {}, } } // Receives values over the internal shard runner rx channel and handles // them. // // This will loop over values until there is no longer one. // // Requests a restart if the sending half of the channel disconnects. This // should _never_ happen, as the sending half is kept on the runner. // Returns whether the shard runner is in a state that can continue. fn recv(&mut self) -> Result<bool> { loop { match self.runner_rx.try_recv() { Ok(value) => { if!self.handle_rx_value(value) { return Ok(false); } }, Err(TryRecvError::Disconnected) => { warn!( "[ShardRunner {:?}] Sending half DC; restarting", self.shard.shard_info(), ); let _ = self.request_restart(); return Ok(false); }, Err(TryRecvError::Empty) => break, } } // There are no longer any values available. Ok(true) } /// Returns a received event, as well as whether reading the potentially /// present event was successful. fn recv_event(&mut self) -> (Option<Event>, Option<ShardAction>, bool) { let gw_event = match self.shard.client.recv_json() { Ok(Some(value)) => { GatewayEvent::deserialize(value).map(Some).map_err(From::from) }, Ok(None) => Ok(None), Err(Error::WebSocket(WebSocketError::IoError(_))) => { // Check that an amount of time at least double the // heartbeat_interval has passed. // // If not, continue on trying to receive messages. // // If it has, attempt to auto-reconnect. { let last = self.shard.last_heartbeat_ack(); let interval = self.shard.heartbeat_interval(); if let (Some(last_heartbeat_ack), Some(interval)) = (last, interval) { let seconds_passed = last_heartbeat_ack.elapsed().as_secs(); let interval_in_secs = interval / 1000; if seconds_passed <= interval_in_secs * 2 { return (None, None, true); } } else { return (None, None, true); } } debug!("Attempting to auto-reconnect"); match self.shard.reconnection_type() { ReconnectType::Reidentify => return (None, None, false), ReconnectType::Resume => { if let Err(why) = self.shard.resume() { warn!("Failed to resume: {:?}", why); return (None, None, false); } }, } return (None, None, true); }, Err(Error::WebSocket(WebSocketError::NoDataAvailable)) => { // This is hit when the websocket client dies this will be // hit every iteration. return (None, None, false); }, Err(why) => Err(why), }; let event = match gw_event { Ok(Some(event)) => Ok(event), Ok(None) => return (None, None, true), Err(why) => Err(why), }; let action = match self.shard.handle_event(&event) { Ok(Some(action)) => Some(action), Ok(None) => None, Err(why) => { error!("Shard handler received err: {:?}", why); return (None, None, true); }, }; if let Ok(GatewayEvent::HeartbeatAck) = event { self.update_manager(); } #[cfg(feature = "voice")] { if let Ok(GatewayEvent::Dispatch(_, ref event)) = event { self.handle_voice_event(&event); } } let event = match event { Ok(GatewayEvent::Dispatch(_, event)) => Some(event), _ => None, }; (event, action, true) } fn request_restart(&self) -> Result<()> { self.update_manager(); debug!( "[ShardRunner {:?}] Requesting restart", self.shard.shard_info(), ); let shard_id = ShardId(self.shard.shard_info()[0]); let msg = ShardManagerMessage::Restart(shard_id); let _ = self.manager_tx.send(msg); #[cfg(feature = "voice")] { self.voice_manager.lock().manager_remove(&shard_id.0); } Ok(()) } fn update_manager(&self) { let _ = self.manager_tx.send(ShardManagerMessage::ShardUpdate { id: ShardId(self.shard.shard_info()[0]), latency: self.shard.latency(), stage: self.shard.stage(), }); } } /// Options to be passed to [`ShardRunner::new`]. /// /// [`ShardRunner::new`]: struct.ShardRunner.html#method.new pub struct ShardRunnerOptions<H: EventHandler + Send + Sync +'static> { pub data: Arc<Mutex<ShareMap>>, pub event_handler: Arc<H>, #[cfg(feature = "framework")] pub framework: Arc<Mutex<Option<Box<Framework + Send>>>>, pub manager_tx: Sender<ShardManagerMessage>,
{ self.runner_tx.clone() }
identifier_body
shard_runner.rs
prelude::*; use internal::ws_impl::{ReceiverExt, SenderExt}; use model::event::{Event, GatewayEvent}; use parking_lot::Mutex; use serde::Deserialize; use std::sync::{ mpsc::{ self, Receiver, Sender, TryRecvError }, Arc }; use super::super::super::dispatch::{DispatchEvent, dispatch}; use super::super::super::EventHandler; use super::event::{ClientEvent, ShardStageUpdateEvent}; use super::{ShardClientMessage, ShardId, ShardManagerMessage, ShardRunnerMessage}; use threadpool::ThreadPool; use typemap::ShareMap; use websocket::{ message::{CloseData, OwnedMessage}, WebSocketError }; #[cfg(feature = "framework")] use framework::Framework; #[cfg(feature = "voice")] use super::super::voice::ClientVoiceManager; /// A runner for managing a [`Shard`] and its respective WebSocket client. /// /// [`Shard`]:../../../gateway/struct.Shard.html pub struct ShardRunner<H: EventHandler + Send + Sync +'static> { data: Arc<Mutex<ShareMap>>, event_handler: Arc<H>, #[cfg(feature = "framework")] framework: Arc<Mutex<Option<Box<Framework + Send>>>>, manager_tx: Sender<ShardManagerMessage>, // channel to receive messages from the shard manager and dispatches runner_rx: Receiver<InterMessage>, // channel to send messages to the shard runner from the shard manager runner_tx: Sender<InterMessage>, shard: Shard, threadpool: ThreadPool, #[cfg(feature = "voice")] voice_manager: Arc<Mutex<ClientVoiceManager>>, } impl<H: EventHandler + Send + Sync +'static> ShardRunner<H> { /// Creates a new runner for a Shard. pub fn new(opt: ShardRunnerOptions<H>) -> Self { let (tx, rx) = mpsc::channel(); Self { runner_rx: rx, runner_tx: tx, data: opt.data, event_handler: opt.event_handler, #[cfg(feature = "framework")] framework: opt.framework, manager_tx: opt.manager_tx, shard: opt.shard, threadpool: opt.threadpool, #[cfg(feature = "voice")] voice_manager: opt.voice_manager, } } /// Starts the runner's loop to receive events. /// /// This runs a loop that performs the following in each iteration: /// /// 1. checks the receiver for [`ShardRunnerMessage`]s, possibly from the /// [`ShardManager`], and if there is one, acts on it. /// /// 2. checks if a heartbeat should be sent to the discord Gateway, and if /// so, sends one. /// /// 3. attempts to retrieve a message from the WebSocket, processing it into /// a [`GatewayEvent`]. This will block for 100ms before assuming there is /// no message available. /// /// 4. Checks with the [`Shard`] to determine if the gateway event is /// specifying an action to take (e.g. resuming, reconnecting, heartbeating) /// and then performs that action, if any. /// /// 5. Dispatches the event via the Client. /// /// 6. Go back to 1. /// /// [`GatewayEvent`]:../../../model/event/enum.GatewayEvent.html /// [`Shard`]:../../../gateway/struct.Shard.html /// [`ShardManager`]: struct.ShardManager.html /// [`ShardRunnerMessage`]: enum.ShardRunnerMessage.html pub fn run(&mut self) -> Result<()> { debug!("[ShardRunner {:?}] Running", self.shard.shard_info()); loop { if!self.recv()? { return Ok(()); } // check heartbeat if!self.shard.check_heartbeat() { warn!( "[ShardRunner {:?}] Error heartbeating", self.shard.shard_info(), ); return self.request_restart(); } let pre = self.shard.stage(); let (event, action, successful) = self.recv_event(); let post = self.shard.stage(); if post!= pre { self.update_manager(); let e = ClientEvent::ShardStageUpdate(ShardStageUpdateEvent { new: post, old: pre, shard_id: ShardId(self.shard.shard_info()[0]), }); self.dispatch(DispatchEvent::Client(e)); } match action { Some(ShardAction::Reconnect(ReconnectType::Reidentify)) => { return self.request_restart() }, Some(other) => { let _ = self.action(&other); }, None => {}, } if let Some(event) = event { self.dispatch(DispatchEvent::Model(event)); } if!successful &&!self.shard.stage().is_connecting() { return self.request_restart(); } } } /// Clones the internal copy of the Sender to the shard runner. pub(super) fn runner_tx(&self) -> Sender<InterMessage> { self.runner_tx.clone() } /// Takes an action that a [`Shard`] has determined should happen and then /// does it. /// /// For example, if the shard says that an Identify message needs to be /// sent, this will do that. /// /// # Errors /// /// Returns fn action(&mut self, action: &ShardAction) -> Result<()> { match *action { ShardAction::Reconnect(ReconnectType::Reidentify) => { self.request_restart() }, ShardAction::Reconnect(ReconnectType::Resume) => { self.shard.resume() }, ShardAction::Heartbeat => self.shard.heartbeat(), ShardAction::Identify => self.shard.identify(), } } // Checks if the ID received to shutdown is equivalent to the ID of the // shard this runner is responsible. If so, it shuts down the WebSocket // client. // // Returns whether the WebSocket client is still active. // // If true, the WebSocket client was _not_ shutdown. If false, it was. fn checked_shutdown(&mut self, id: ShardId) -> bool { // First verify the ID so we know for certain this runner is // to shutdown. if id.0!= self.shard.shard_info()[0] { // Not meant for this runner for some reason, don't // shutdown. return true; } let close_data = CloseData::new(1000, String::new()); let msg = OwnedMessage::Close(Some(close_data)); let _ = self.shard.client.send_message(&msg); false } #[inline] fn dispatch(&self, event: DispatchEvent) { dispatch( event, #[cfg(feature = "framework")] &self.framework, &self.data, &self.event_handler, &self.runner_tx, &self.threadpool, self.shard.shard_info()[0], ); } // Handles a received value over the shard runner rx channel. // // Returns a boolean on whether the shard runner can continue. // // This always returns true, except in the case that the shard manager asked // the runner to shutdown. fn handle_rx_value(&mut self, value: InterMessage) -> bool { match value { InterMessage::Client(ShardClientMessage::Manager(x)) => match x { ShardManagerMessage::Restart(id) | ShardManagerMessage::Shutdown(id) => { self.checked_shutdown(id) }, ShardManagerMessage::ShutdownAll => { // This variant should never be received. warn!( "[ShardRunner {:?}] Received a ShutdownAll?", self.shard.shard_info(), ); true }, ShardManagerMessage::ShardUpdate {.. } | ShardManagerMessage::ShutdownInitiated => { // nb: not sent here true }, }, InterMessage::Client(ShardClientMessage::Runner(x)) => match x { ShardRunnerMessage::ChunkGuilds { guild_ids, limit, query } => { self.shard.chunk_guilds( guild_ids, limit, query.as_ref().map(String::as_str), ).is_ok() }, ShardRunnerMessage::Close(code, reason) => { let reason = reason.unwrap_or_else(String::new); let data = CloseData::new(code, reason); let msg = OwnedMessage::Close(Some(data)); self.shard.client.send_message(&msg).is_ok() }, ShardRunnerMessage::Message(msg) => { self.shard.client.send_message(&msg).is_ok() }, ShardRunnerMessage::SetGame(game) => { // To avoid a clone of `game`, we do a little bit of // trickery here: // // First, we obtain a reference to the current presence of // the shard, and create a new presence tuple of the new // game we received over the channel as well as the online // status that the shard already had. // // We then (attempt to) send the websocket message with the // status update, expressively returning: // // - whether the message successfully sent // - the original game we received over the channel self.shard.set_game(game); self.shard.update_presence().is_ok() }, ShardRunnerMessage::SetPresence(status, game) => { self.shard.set_presence(status, game); self.shard.update_presence().is_ok() }, ShardRunnerMessage::SetStatus(status) => { self.shard.set_status(status); self.shard.update_presence().is_ok() }, }, InterMessage::Json(value) => { // Value must be forwarded over the websocket self.shard.client.send_json(&value).is_ok() }, } } #[cfg(feature = "voice")] fn handle_voice_event(&self, event: &Event) { match *event { Event::Ready(_) => { self.voice_manager.lock().set( self.shard.shard_info()[0], self.runner_tx.clone(), ); }, Event::VoiceServerUpdate(ref event) => { if let Some(guild_id) = event.guild_id { let mut manager = self.voice_manager.lock(); let mut search = manager.get_mut(guild_id); if let Some(handler) = search { handler.update_server(&event.endpoint, &event.token); } } }, Event::VoiceStateUpdate(ref event) => { if let Some(guild_id) = event.guild_id { let mut manager = self.voice_manager.lock(); let mut search = manager.get_mut(guild_id); if let Some(handler) = search { handler.update_state(&event.voice_state); } } }, _ => {}, } } // Receives values over the internal shard runner rx channel and handles // them. // // This will loop over values until there is no longer one. // // Requests a restart if the sending half of the channel disconnects. This // should _never_ happen, as the sending half is kept on the runner. // Returns whether the shard runner is in a state that can continue. fn recv(&mut self) -> Result<bool> { loop { match self.runner_rx.try_recv() { Ok(value) => { if!self.handle_rx_value(value) { return Ok(false); } }, Err(TryRecvError::Disconnected) => { warn!( "[ShardRunner {:?}] Sending half DC; restarting", self.shard.shard_info(), ); let _ = self.request_restart(); return Ok(false); }, Err(TryRecvError::Empty) => break, } } // There are no longer any values available. Ok(true) } /// Returns a received event, as well as whether reading the potentially /// present event was successful. fn recv_event(&mut self) -> (Option<Event>, Option<ShardAction>, bool) { let gw_event = match self.shard.client.recv_json() { Ok(Some(value)) => { GatewayEvent::deserialize(value).map(Some).map_err(From::from) }, Ok(None) => Ok(None), Err(Error::WebSocket(WebSocketError::IoError(_))) => { // Check that an amount of time at least double the // heartbeat_interval has passed. // // If not, continue on trying to receive messages. // // If it has, attempt to auto-reconnect. { let last = self.shard.last_heartbeat_ack(); let interval = self.shard.heartbeat_interval(); if let (Some(last_heartbeat_ack), Some(interval)) = (last, interval) { let seconds_passed = last_heartbeat_ack.elapsed().as_secs(); let interval_in_secs = interval / 1000; if seconds_passed <= interval_in_secs * 2
} else { return (None, None, true); } } debug!("Attempting to auto-reconnect"); match self.shard.reconnection_type() { ReconnectType::Reidentify => return (None, None, false), ReconnectType::Resume => { if let Err(why) = self.shard.resume() { warn!("Failed to resume: {:?}", why); return (None, None, false); } }, } return (None, None, true); }, Err(Error::WebSocket(WebSocketError::NoDataAvailable)) => { // This is hit when the websocket client dies this will be // hit every iteration. return (None, None, false); }, Err(why) => Err(why), }; let event = match gw_event { Ok(Some(event)) => Ok(event), Ok(None) => return (None, None, true), Err(why) => Err(why), }; let action = match self.shard.handle_event(&event) { Ok(Some(action)) => Some(action), Ok(None) => None, Err(why) => { error!("Shard handler received err: {:?}", why); return (None, None, true); }, }; if let Ok(GatewayEvent::HeartbeatAck) = event { self.update_manager(); } #[cfg(feature = "voice")] { if let Ok(GatewayEvent::Dispatch(_, ref event)) = event { self.handle_voice_event(&event); } } let event = match event { Ok(GatewayEvent::Dispatch(_, event)) => Some(event), _ => None, }; (event, action, true) } fn request_restart(&self) -> Result<()> { self.update_manager(); debug!( "[ShardRunner {:?}] Requesting restart", self.shard.shard_info(), ); let shard_id = ShardId(self.shard.shard_info()[0]); let msg = ShardManagerMessage::Restart(shard_id); let _ = self.manager_tx.send(msg); #[cfg(feature = "voice")] { self.voice_manager.lock().manager_remove(&shard_id.0); } Ok(()) } fn update_manager(&self) { let _ = self.manager_tx.send(ShardManagerMessage::ShardUpdate { id: ShardId(self.shard.shard_info()[0]), latency: self.shard.latency(), stage: self.shard.stage(), }); } } /// Options to be passed to [`ShardRunner::new`]. /// /// [`ShardRunner::new`]: struct.ShardRunner.html#method.new pub struct ShardRunnerOptions<H: EventHandler + Send + Sync +'static> { pub data: Arc<Mutex<ShareMap>>, pub event_handler: Arc<H>, #[cfg(feature = "framework")] pub framework: Arc<Mutex<Option<Box<Framework + Send>>>>, pub manager_tx: Sender<ShardManagerMessage>,
{ return (None, None, true); }
conditional_block
make_in_dir.rs
use prelude::*; pub fn make_inode_in_dir(fs: &mut Filesystem, dir_ino: u64, name: &[u8], mode: Mode, attr: FileAttr) -> Result<Inode> { let mut dir_inode = try!(get_inode(fs, dir_ino)); if dir_inode.mode.file_type!= FileType::Dir { return Err(Error::new(format!( "Inode {} is not a directory", dir_ino))); } let dir_group = get_ino_group(fs, dir_ino).0; let new_ino = match try!(alloc_inode(fs, dir_group)) { None => return Err(Error::new(format!("No free inodes left"))), Some(ino) => ino, }; let mut new_inode = try!(init_inode(fs, &mut dir_inode, new_ino, mode, attr)); try!(add_dir_entry(fs, &mut dir_inode, &mut new_inode, name)); Ok(new_inode) }
file_type: FileType::Symlink, suid: false, sgid: false, sticky: false, access_rights: 0o777, }; let mut inode = try!(make_inode_in_dir(fs, dir_ino, name, mode, attr)); try!(write_link_data(fs, &mut inode, link)); Ok(inode) } pub fn make_hardlink_in_dir(fs: &mut Filesystem, dir_ino: u64, name: &[u8], link_ino: u64) -> Result<Inode> { let mut dir_inode = try!(get_inode(fs, dir_ino)); let mut link_inode = try!(get_inode(fs, link_ino)); if dir_inode.mode.file_type!= FileType::Dir { return Err(Error::new(format!("Inode {} is not a directory", dir_ino))); } else if link_inode.mode.file_type == FileType::Dir { return Err(Error::new(format!("Inode {} is a directory", link_ino))); } try!(add_dir_entry(fs, &mut dir_inode, &mut link_inode, name)); Ok(link_inode) }
pub fn make_symlink_in_dir(fs: &mut Filesystem, dir_ino: u64, name: &[u8], link: &[u8], attr: FileAttr) -> Result<Inode> { let mode = Mode {
random_line_split
make_in_dir.rs
use prelude::*; pub fn make_inode_in_dir(fs: &mut Filesystem, dir_ino: u64, name: &[u8], mode: Mode, attr: FileAttr) -> Result<Inode> { let mut dir_inode = try!(get_inode(fs, dir_ino)); if dir_inode.mode.file_type!= FileType::Dir { return Err(Error::new(format!( "Inode {} is not a directory", dir_ino))); } let dir_group = get_ino_group(fs, dir_ino).0; let new_ino = match try!(alloc_inode(fs, dir_group)) { None => return Err(Error::new(format!("No free inodes left"))), Some(ino) => ino, }; let mut new_inode = try!(init_inode(fs, &mut dir_inode, new_ino, mode, attr)); try!(add_dir_entry(fs, &mut dir_inode, &mut new_inode, name)); Ok(new_inode) } pub fn make_symlink_in_dir(fs: &mut Filesystem, dir_ino: u64, name: &[u8], link: &[u8], attr: FileAttr) -> Result<Inode> { let mode = Mode { file_type: FileType::Symlink, suid: false, sgid: false, sticky: false, access_rights: 0o777, }; let mut inode = try!(make_inode_in_dir(fs, dir_ino, name, mode, attr)); try!(write_link_data(fs, &mut inode, link)); Ok(inode) } pub fn make_hardlink_in_dir(fs: &mut Filesystem, dir_ino: u64, name: &[u8], link_ino: u64) -> Result<Inode>
{ let mut dir_inode = try!(get_inode(fs, dir_ino)); let mut link_inode = try!(get_inode(fs, link_ino)); if dir_inode.mode.file_type != FileType::Dir { return Err(Error::new(format!("Inode {} is not a directory", dir_ino))); } else if link_inode.mode.file_type == FileType::Dir { return Err(Error::new(format!("Inode {} is a directory", link_ino))); } try!(add_dir_entry(fs, &mut dir_inode, &mut link_inode, name)); Ok(link_inode) }
identifier_body
make_in_dir.rs
use prelude::*; pub fn make_inode_in_dir(fs: &mut Filesystem, dir_ino: u64, name: &[u8], mode: Mode, attr: FileAttr) -> Result<Inode> { let mut dir_inode = try!(get_inode(fs, dir_ino)); if dir_inode.mode.file_type!= FileType::Dir { return Err(Error::new(format!( "Inode {} is not a directory", dir_ino))); } let dir_group = get_ino_group(fs, dir_ino).0; let new_ino = match try!(alloc_inode(fs, dir_group)) { None => return Err(Error::new(format!("No free inodes left"))), Some(ino) => ino, }; let mut new_inode = try!(init_inode(fs, &mut dir_inode, new_ino, mode, attr)); try!(add_dir_entry(fs, &mut dir_inode, &mut new_inode, name)); Ok(new_inode) } pub fn make_symlink_in_dir(fs: &mut Filesystem, dir_ino: u64, name: &[u8], link: &[u8], attr: FileAttr) -> Result<Inode> { let mode = Mode { file_type: FileType::Symlink, suid: false, sgid: false, sticky: false, access_rights: 0o777, }; let mut inode = try!(make_inode_in_dir(fs, dir_ino, name, mode, attr)); try!(write_link_data(fs, &mut inode, link)); Ok(inode) } pub fn
(fs: &mut Filesystem, dir_ino: u64, name: &[u8], link_ino: u64) -> Result<Inode> { let mut dir_inode = try!(get_inode(fs, dir_ino)); let mut link_inode = try!(get_inode(fs, link_ino)); if dir_inode.mode.file_type!= FileType::Dir { return Err(Error::new(format!("Inode {} is not a directory", dir_ino))); } else if link_inode.mode.file_type == FileType::Dir { return Err(Error::new(format!("Inode {} is a directory", link_ino))); } try!(add_dir_entry(fs, &mut dir_inode, &mut link_inode, name)); Ok(link_inode) }
make_hardlink_in_dir
identifier_name
dst-deref-mut.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. // Test that a custom deref with a fat pointer return type does not ICE use std::ops::{Deref, DerefMut}; pub struct Arr { ptr: Box<[usize]> } impl Deref for Arr { type Target = [usize]; fn deref(&self) -> &[usize] { panic!(); } } impl DerefMut for Arr { fn deref_mut(&mut self) -> &mut [usize] { &mut *self.ptr } } pub fn foo(arr: &mut Arr) { let x: &mut [usize] = &mut **arr; assert!(x[0] == 1); assert!(x[1] == 2); assert!(x[2] == 3); } fn main() {
}
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let mut a = Arr { ptr: Box::new([1, 2, 3]) }; foo(&mut a);
random_line_split
dst-deref-mut.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. // Test that a custom deref with a fat pointer return type does not ICE use std::ops::{Deref, DerefMut}; pub struct Arr { ptr: Box<[usize]> } impl Deref for Arr { type Target = [usize]; fn deref(&self) -> &[usize] { panic!(); } } impl DerefMut for Arr { fn deref_mut(&mut self) -> &mut [usize] { &mut *self.ptr } } pub fn foo(arr: &mut Arr)
fn main() { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let mut a = Arr { ptr: Box::new([1, 2, 3]) }; foo(&mut a); }
{ let x: &mut [usize] = &mut **arr; assert!(x[0] == 1); assert!(x[1] == 2); assert!(x[2] == 3); }
identifier_body
dst-deref-mut.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. // Test that a custom deref with a fat pointer return type does not ICE use std::ops::{Deref, DerefMut}; pub struct Arr { ptr: Box<[usize]> } impl Deref for Arr { type Target = [usize]; fn deref(&self) -> &[usize] { panic!(); } } impl DerefMut for Arr { fn
(&mut self) -> &mut [usize] { &mut *self.ptr } } pub fn foo(arr: &mut Arr) { let x: &mut [usize] = &mut **arr; assert!(x[0] == 1); assert!(x[1] == 2); assert!(x[2] == 3); } fn main() { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let mut a = Arr { ptr: Box::new([1, 2, 3]) }; foo(&mut a); }
deref_mut
identifier_name
lib.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/. */ #[macro_use] extern crate quote; #[macro_use] extern crate syn; #[macro_use] extern crate synstructure; decl_derive!([JSTraceable] => js_traceable_derive); fn
(s: synstructure::Structure) -> quote::Tokens { let match_body = s.each(|binding| { Some(quote!(#binding.trace(tracer);)) }); let ast = s.ast(); let name = ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone(); for param in ast.generics.type_params() { let ident = param.ident; where_clause.predicates.push(parse_quote!(#ident: ::dom::bindings::trace::JSTraceable)) } let tokens = quote! { #[allow(unsafe_code)] unsafe impl #impl_generics ::dom::bindings::trace::JSTraceable for #name #ty_generics #where_clause { #[inline] #[allow(unused_variables, unused_imports)] unsafe fn trace(&self, tracer: *mut ::js::jsapi::JSTracer) { use ::dom::bindings::trace::JSTraceable; match *self { #match_body } } } }; tokens }
js_traceable_derive
identifier_name
lib.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/. */ #[macro_use] extern crate quote; #[macro_use] extern crate syn; #[macro_use] extern crate synstructure; decl_derive!([JSTraceable] => js_traceable_derive); fn js_traceable_derive(s: synstructure::Structure) -> quote::Tokens { let match_body = s.each(|binding| { Some(quote!(#binding.trace(tracer);)) }); let ast = s.ast(); let name = ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone(); for param in ast.generics.type_params() { let ident = param.ident; where_clause.predicates.push(parse_quote!(#ident: ::dom::bindings::trace::JSTraceable)) } let tokens = quote! { #[allow(unsafe_code)] unsafe impl #impl_generics ::dom::bindings::trace::JSTraceable for #name #ty_generics #where_clause { #[inline] #[allow(unused_variables, unused_imports)] unsafe fn trace(&self, tracer: *mut ::js::jsapi::JSTracer) { use ::dom::bindings::trace::JSTraceable; match *self { #match_body } } } }; tokens }
random_line_split
lib.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/. */ #[macro_use] extern crate quote; #[macro_use] extern crate syn; #[macro_use] extern crate synstructure; decl_derive!([JSTraceable] => js_traceable_derive); fn js_traceable_derive(s: synstructure::Structure) -> quote::Tokens
use ::dom::bindings::trace::JSTraceable; match *self { #match_body } } } }; tokens }
{ let match_body = s.each(|binding| { Some(quote!(#binding.trace(tracer);)) }); let ast = s.ast(); let name = ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone(); for param in ast.generics.type_params() { let ident = param.ident; where_clause.predicates.push(parse_quote!(#ident: ::dom::bindings::trace::JSTraceable)) } let tokens = quote! { #[allow(unsafe_code)] unsafe impl #impl_generics ::dom::bindings::trace::JSTraceable for #name #ty_generics #where_clause { #[inline] #[allow(unused_variables, unused_imports)] unsafe fn trace(&self, tracer: *mut ::js::jsapi::JSTracer) {
identifier_body
extension_class_container_impl1.rs
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0
* Contact: [email protected] * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct ExtensionClassContainerImpl1 { #[serde(rename = "_class", skip_serializing_if = "Option::is_none")] pub _class: Option<String>, #[serde(rename = "_links", skip_serializing_if = "Option::is_none")] pub _links: Option<Box<crate::models::ExtensionClassContainerImpl1links>>, #[serde(rename = "map", skip_serializing_if = "Option::is_none")] pub map: Option<Box<crate::models::ExtensionClassContainerImpl1map>>, } impl ExtensionClassContainerImpl1 { pub fn new() -> ExtensionClassContainerImpl1 { ExtensionClassContainerImpl1 { _class: None, _links: None, map: None, } } }
random_line_split
extension_class_container_impl1.rs
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct ExtensionClassContainerImpl1 { #[serde(rename = "_class", skip_serializing_if = "Option::is_none")] pub _class: Option<String>, #[serde(rename = "_links", skip_serializing_if = "Option::is_none")] pub _links: Option<Box<crate::models::ExtensionClassContainerImpl1links>>, #[serde(rename = "map", skip_serializing_if = "Option::is_none")] pub map: Option<Box<crate::models::ExtensionClassContainerImpl1map>>, } impl ExtensionClassContainerImpl1 { pub fn
() -> ExtensionClassContainerImpl1 { ExtensionClassContainerImpl1 { _class: None, _links: None, map: None, } } }
new
identifier_name
firm.rs
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use ldr; use mem; use utils::bytes; #[derive(Debug, Error)] pub enum ErrorKind { Io(::std::io::Error) } struct FirmSection { data_offs: usize, size: usize, dst_addr: u32, } impl FirmSection { fn from_header(header: &[u8; 0x30]) -> Option<Self> { let offs: u32 = unsafe { bytes::val_at_offs(header, 0x0) }; let dst: u32 = unsafe { bytes::val_at_offs(header, 0x4) }; let size: u32 = unsafe { bytes::val_at_offs(header, 0x8) }; if size == 0 { None } else { Some(FirmSection { data_offs: offs as usize, size: size as usize, dst_addr: dst }) } } } pub struct FirmLoader { filename: PathBuf, entry9: u32, entry11: u32, sections: Vec<FirmSection> } impl FirmLoader { pub fn from_file(filename: &Path) -> Result<Self, ErrorKind> { let mut file = File::open(filename)?; let mut header = [0u8; 0x200]; file.read_exact(&mut header)?; assert!(&header[..4] == b"FIRM"); let entry11: u32 = unsafe { bytes::val_at_offs(&header, 0x8) }; let entry9: u32 = unsafe { bytes::val_at_offs(&header, 0xC) }; let mut sections = Vec::new(); for i in 0..4 { let section: [u8; 0x30] = unsafe { bytes::val_at_offs(&header, 0x40 + 0x30*i) }; if let Some(section) = FirmSection::from_header(&section) { sections.push(section); } } Ok(FirmLoader { filename: filename.to_owned(), entry9, entry11, sections }) } } impl ldr::Loader for FirmLoader { fn entrypoint9(&self) -> u32 { self.entry9 } fn load9(&self, controller: &mut mem::MemController) { let mut file = File::open(&self.filename).unwrap(); for section in &self.sections { file.seek(SeekFrom::Start(section.data_offs as u64)).unwrap(); let mut vaddr = section.dst_addr; let mut read_amount = 0; let mut read_buf = [0u8; 1024]; loop { let read_buf_size = 1024.min(section.size - read_amount); let read_buf = &mut read_buf[..read_buf_size]; if read_buf_size == 0
file.read_exact(read_buf).unwrap(); controller.write_buf(vaddr, read_buf); read_amount += read_buf_size; vaddr += read_buf_size as u32; } } } fn entrypoint11(&self) -> u32 { self.entry11 } fn load11(&self, _controller: &mut mem::MemController) { // Unnecessary because FIRMs on the 3DS can only load into ARM9-accessible memory } }
{ break }
conditional_block
firm.rs
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use ldr; use mem; use utils::bytes; #[derive(Debug, Error)] pub enum ErrorKind { Io(::std::io::Error) } struct FirmSection { data_offs: usize, size: usize, dst_addr: u32, } impl FirmSection { fn from_header(header: &[u8; 0x30]) -> Option<Self> { let offs: u32 = unsafe { bytes::val_at_offs(header, 0x0) }; let dst: u32 = unsafe { bytes::val_at_offs(header, 0x4) }; let size: u32 = unsafe { bytes::val_at_offs(header, 0x8) }; if size == 0 { None } else { Some(FirmSection { data_offs: offs as usize, size: size as usize, dst_addr: dst }) } } } pub struct FirmLoader { filename: PathBuf, entry9: u32, entry11: u32, sections: Vec<FirmSection> } impl FirmLoader { pub fn
(filename: &Path) -> Result<Self, ErrorKind> { let mut file = File::open(filename)?; let mut header = [0u8; 0x200]; file.read_exact(&mut header)?; assert!(&header[..4] == b"FIRM"); let entry11: u32 = unsafe { bytes::val_at_offs(&header, 0x8) }; let entry9: u32 = unsafe { bytes::val_at_offs(&header, 0xC) }; let mut sections = Vec::new(); for i in 0..4 { let section: [u8; 0x30] = unsafe { bytes::val_at_offs(&header, 0x40 + 0x30*i) }; if let Some(section) = FirmSection::from_header(&section) { sections.push(section); } } Ok(FirmLoader { filename: filename.to_owned(), entry9, entry11, sections }) } } impl ldr::Loader for FirmLoader { fn entrypoint9(&self) -> u32 { self.entry9 } fn load9(&self, controller: &mut mem::MemController) { let mut file = File::open(&self.filename).unwrap(); for section in &self.sections { file.seek(SeekFrom::Start(section.data_offs as u64)).unwrap(); let mut vaddr = section.dst_addr; let mut read_amount = 0; let mut read_buf = [0u8; 1024]; loop { let read_buf_size = 1024.min(section.size - read_amount); let read_buf = &mut read_buf[..read_buf_size]; if read_buf_size == 0 { break } file.read_exact(read_buf).unwrap(); controller.write_buf(vaddr, read_buf); read_amount += read_buf_size; vaddr += read_buf_size as u32; } } } fn entrypoint11(&self) -> u32 { self.entry11 } fn load11(&self, _controller: &mut mem::MemController) { // Unnecessary because FIRMs on the 3DS can only load into ARM9-accessible memory } }
from_file
identifier_name
firm.rs
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use ldr; use mem; use utils::bytes; #[derive(Debug, Error)] pub enum ErrorKind { Io(::std::io::Error) } struct FirmSection { data_offs: usize, size: usize, dst_addr: u32, } impl FirmSection { fn from_header(header: &[u8; 0x30]) -> Option<Self> { let offs: u32 = unsafe { bytes::val_at_offs(header, 0x0) }; let dst: u32 = unsafe { bytes::val_at_offs(header, 0x4) }; let size: u32 = unsafe { bytes::val_at_offs(header, 0x8) }; if size == 0 { None } else { Some(FirmSection { data_offs: offs as usize, size: size as usize, dst_addr: dst }) } } } pub struct FirmLoader { filename: PathBuf, entry9: u32, entry11: u32, sections: Vec<FirmSection> } impl FirmLoader { pub fn from_file(filename: &Path) -> Result<Self, ErrorKind> { let mut file = File::open(filename)?; let mut header = [0u8; 0x200]; file.read_exact(&mut header)?; assert!(&header[..4] == b"FIRM"); let entry11: u32 = unsafe { bytes::val_at_offs(&header, 0x8) }; let entry9: u32 = unsafe { bytes::val_at_offs(&header, 0xC) }; let mut sections = Vec::new(); for i in 0..4 { let section: [u8; 0x30] = unsafe { bytes::val_at_offs(&header, 0x40 + 0x30*i) }; if let Some(section) = FirmSection::from_header(&section) { sections.push(section); } } Ok(FirmLoader { filename: filename.to_owned(), entry9, entry11, sections }) } } impl ldr::Loader for FirmLoader { fn entrypoint9(&self) -> u32 { self.entry9 } fn load9(&self, controller: &mut mem::MemController) { let mut file = File::open(&self.filename).unwrap(); for section in &self.sections { file.seek(SeekFrom::Start(section.data_offs as u64)).unwrap(); let mut vaddr = section.dst_addr; let mut read_amount = 0; let mut read_buf = [0u8; 1024]; loop { let read_buf_size = 1024.min(section.size - read_amount); let read_buf = &mut read_buf[..read_buf_size]; if read_buf_size == 0 { break } file.read_exact(read_buf).unwrap(); controller.write_buf(vaddr, read_buf); read_amount += read_buf_size; vaddr += read_buf_size as u32; } } } fn entrypoint11(&self) -> u32
fn load11(&self, _controller: &mut mem::MemController) { // Unnecessary because FIRMs on the 3DS can only load into ARM9-accessible memory } }
{ self.entry11 }
identifier_body
firm.rs
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use ldr; use mem; use utils::bytes; #[derive(Debug, Error)] pub enum ErrorKind { Io(::std::io::Error) } struct FirmSection { data_offs: usize, size: usize, dst_addr: u32, } impl FirmSection { fn from_header(header: &[u8; 0x30]) -> Option<Self> { let offs: u32 = unsafe { bytes::val_at_offs(header, 0x0) }; let dst: u32 = unsafe { bytes::val_at_offs(header, 0x4) }; let size: u32 = unsafe { bytes::val_at_offs(header, 0x8) }; if size == 0 { None } else { Some(FirmSection { data_offs: offs as usize, size: size as usize, dst_addr: dst }) } } } pub struct FirmLoader { filename: PathBuf, entry9: u32, entry11: u32, sections: Vec<FirmSection> } impl FirmLoader { pub fn from_file(filename: &Path) -> Result<Self, ErrorKind> { let mut file = File::open(filename)?; let mut header = [0u8; 0x200]; file.read_exact(&mut header)?; assert!(&header[..4] == b"FIRM"); let entry11: u32 = unsafe { bytes::val_at_offs(&header, 0x8) }; let entry9: u32 = unsafe { bytes::val_at_offs(&header, 0xC) }; let mut sections = Vec::new(); for i in 0..4 { let section: [u8; 0x30] = unsafe { bytes::val_at_offs(&header, 0x40 + 0x30*i) }; if let Some(section) = FirmSection::from_header(&section) { sections.push(section); } } Ok(FirmLoader { filename: filename.to_owned(), entry9, entry11, sections }) } } impl ldr::Loader for FirmLoader { fn entrypoint9(&self) -> u32 { self.entry9 } fn load9(&self, controller: &mut mem::MemController) { let mut file = File::open(&self.filename).unwrap(); for section in &self.sections { file.seek(SeekFrom::Start(section.data_offs as u64)).unwrap(); let mut vaddr = section.dst_addr; let mut read_amount = 0; let mut read_buf = [0u8; 1024]; loop { let read_buf_size = 1024.min(section.size - read_amount); let read_buf = &mut read_buf[..read_buf_size]; if read_buf_size == 0 { break } file.read_exact(read_buf).unwrap(); controller.write_buf(vaddr, read_buf); read_amount += read_buf_size; vaddr += read_buf_size as u32; } } } fn entrypoint11(&self) -> u32 { self.entry11 } fn load11(&self, _controller: &mut mem::MemController) { // Unnecessary because FIRMs on the 3DS can only load into ARM9-accessible memory
}
}
random_line_split
lib.rs
a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[unrooted_must_root_lint::must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[unrooted_must_root_lint::must_root]`. //! Use this for structs that correspond to a DOM type #![deny(unsafe_code)] #![feature(plugin)] #![feature(plugin_registrar)] #![feature(rustc_private)] #![cfg(feature = "unrooted_must_root_lint")] extern crate rustc; extern crate rustc_ast; extern crate rustc_driver; extern crate rustc_hir; extern crate rustc_lint; extern crate rustc_session; extern crate rustc_span; use rustc::ty; use rustc_ast::ast::{AttrKind, Attribute}; use rustc_driver::plugin::Registry; use rustc_hir::def_id::DefId; use rustc_hir::intravisit as visit; use rustc_hir::{self as hir, ExprKind, HirId}; use rustc_lint::{LateContext, LateLintPass, LintContext, LintPass}; use rustc_session::declare_lint; use rustc_span::source_map; use rustc_span::source_map::{ExpnKind, MacroKind, Span}; use rustc_span::symbol::sym; use rustc_span::symbol::Symbol; #[allow(deprecated)] #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { registrar(reg) } fn registrar(reg: &mut Registry)
declare_lint!( UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects" ); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that /// `#[unrooted_must_root_lint::must_root]` values are used correctly. /// /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[unrooted_must_root_lint::must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a /// GC pass. /// /// Structs which have their own mechanism of rooting their unrooted contents (e.g. `ScriptThread`) /// can be marked as `#[allow(unrooted_must_root)]`. Smart pointers which root their interior type /// can be marked as `#[unrooted_must_root_lint::allow_unrooted_interior]` pub(crate) struct UnrootedPass { symbols: Symbols, } impl UnrootedPass { pub fn new(symbols: Symbols) -> UnrootedPass { UnrootedPass { symbols } } } fn has_lint_attr(sym: &Symbols, attrs: &[Attribute], name: Symbol) -> bool { attrs.iter().any(|attr| { matches!( &attr.kind, AttrKind::Normal(attr_item) if attr_item.path.segments.len() == 2 && attr_item.path.segments[0].ident.name == sym.unrooted_must_root_lint && attr_item.path.segments[1].ident.name == name ) }) } /// Checks if a type is unrooted or contains any owned unrooted types fn is_unrooted_ty(sym: &Symbols, cx: &LateContext, ty: &ty::TyS, in_new_function: bool) -> bool { let mut ret = false; ty.maybe_walk(|t| { match t.kind { ty::Adt(did, substs) => { let has_attr = |did, name| has_lint_attr(sym, &cx.tcx.get_attrs(did), name); if has_attr(did.did, sym.must_root) { ret = true; false } else if has_attr(did.did, sym.allow_unrooted_interior) { false } else if match_def_path(cx, did.did, &[sym.alloc, sym.rc, sym.Rc]) { // Rc<Promise> is okay let inner = substs.type_at(0); if let ty::Adt(did, _) = inner.kind { if has_attr(did.did, sym.allow_unrooted_in_rc) { false } else { true } } else { true } } else if match_def_path(cx, did.did, &[sym::core, sym.cell, sym.Ref]) || match_def_path(cx, did.did, &[sym::core, sym.cell, sym.RefMut]) || match_def_path(cx, did.did, &[sym::core, sym.slice, sym.Iter]) || match_def_path(cx, did.did, &[sym::core, sym.slice, sym.IterMut]) || match_def_path(cx, did.did, &[sym.accountable_refcell, sym.Ref]) || match_def_path(cx, did.did, &[sym.accountable_refcell, sym.RefMut]) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.map, sym.Entry], ) || match_def_path( cx, did.did, &[ sym::std, sym.collections, sym.hash, sym.map, sym.OccupiedEntry, ], ) || match_def_path( cx, did.did, &[ sym::std, sym.collections, sym.hash, sym.map, sym.VacantEntry, ], ) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.map, sym.Iter], ) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.set, sym.Iter], ) { // Structures which are semantically similar to an &ptr. false } else if did.is_box() && in_new_function { // box in new() is okay false } else { true } }, ty::Ref(..) => false, // don't recurse down &ptrs ty::RawPtr(..) => false, // don't recurse down *ptrs ty::FnDef(..) | ty::FnPtr(_) => false, _ => true, } }); ret } impl LintPass for UnrootedPass { fn name(&self) -> &'static str { "ServoUnrootedPass" } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnrootedPass { /// All structs containing #[unrooted_must_root_lint::must_root] types /// must be #[unrooted_must_root_lint::must_root] themselves fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) { if has_lint_attr(&self.symbols, &item.attrs, self.symbols.must_root) { return; } if let hir::ItemKind::Struct(def,..) = &item.kind { for ref field in def.fields() { let def_id = cx.tcx.hir().local_def_id(field.hir_id); if is_unrooted_ty(&self.symbols, cx, cx.tcx.type_of(def_id), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build( "Type must be rooted, use #[unrooted_must_root_lint::must_root] \ on the struct definition to propagate", ) .set_span(field.span) .emit() }) } } } } /// All enums containing #[unrooted_must_root_lint::must_root] types /// must be #[unrooted_must_root_lint::must_root] themselves fn check_variant(&mut self, cx: &LateContext, var: &hir::Variant) { let ref map = cx.tcx.hir(); let parent_item = map.expect_item(map.get_parent_item(var.id)); if!has_lint_attr(&self.symbols, &parent_item.attrs, self.symbols.must_root) { match var.data { hir::VariantData::Tuple(fields,..) => { for field in fields { let def_id = cx.tcx.hir().local_def_id(field.hir_id); if is_unrooted_ty(&self.symbols, cx, cx.tcx.type_of(def_id), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build( "Type must be rooted, \ use #[unrooted_must_root_lint::must_root] \ on the enum definition to propagate", ) .set_span(field.ty.span) .emit() }) } } }, _ => (), // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[unrooted_must_root_lint::must_root] types are not allowed fn check_fn( &mut self, cx: &LateContext<'a, 'tcx>, kind: visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl, body: &'tcx hir::Body, span: source_map::Span, id: HirId, ) { let in_new_function = match kind { visit::FnKind::ItemFn(n, _, _, _, _) | visit::FnKind::Method(n, _, _, _) => { &*n.as_str() == "new" || n.as_str().starts_with("new_") }, visit::FnKind::Closure(_) => return, }; if!in_derive_expn(span) { let def_id = cx.tcx.hir().local_def_id(id); let sig = cx.tcx.type_of(def_id).fn_sig(cx.tcx); for (arg, ty) in decl.inputs.iter().zip(sig.inputs().skip_binder().iter()) { if is_unrooted_ty(&self.symbols, cx, ty, false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build("Type must be rooted").set_span(arg.span).emit() }) } } if!in_new_function { if is_unrooted_ty(&self.symbols, cx, sig.output().skip_binder(), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build("Type must be rooted") .set_span(decl.output.span()) .emit() }) } } } let mut visitor = FnDefVisitor { symbols: &self.symbols, cx: cx, in_new_function: in_new_function, }; visit::walk_expr(&mut visitor, &body.value); } } struct FnDefVisitor<'a, 'b: 'a, 'tcx: 'a + 'b> { symbols: &'a Symbols, cx: &'a LateContext<'b, 'tcx>, in_new_function: bool, } impl<'a, 'b, 'tcx> visit::Visitor<'tcx> for FnDefVisitor<'a, 'b, 'tcx> { type Map = rustc::hir::map::Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx hir::Expr) { let cx = self.cx; let require_rooted = |cx: &LateContext, in_new_function: bool, subexpr: &hir::Expr| { let ty = cx.tables.expr_ty(&subexpr); if is_unrooted_ty(&self.symbols, cx, ty, in_new_function) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build(&format!("Expression of type {:?} must be rooted", ty)) .set_span(subexpr.span) .emit() }) } }; match expr.kind { // Trait casts from #[unrooted_must_root_lint::must_root] types are not allowed ExprKind::Cast(ref subexpr, _) => require_rooted(cx, self.in_new_function, &*subexpr), // This catches assignments... the main point of this would be to catch mutable // references to `JS<T>`. // FIXME: Enable this? Triggers on certain kinds of uses of DomRefCell. // hir::ExprAssign(_, ref rhs) => require_rooted(cx, self.in_new_function, &*rhs), // This catches calls; basically, this enforces the constraint that only constructors // can call other constructors. // FIXME: Enable this? Currently triggers with constructs involving DomRefCell, and // constructs like Vec<JS<T>> and RootedVec<JS<T>>. // hir::ExprCall(..) if!self.in_new_function => { // require_rooted(cx, self.in_new_function, expr); // } _ => { // TODO(pcwalton): Check generics with a whitelist of allowed generics. }, } visit::walk_expr(self, expr); } fn visit_pat(&mut self, pat: &'tcx hir::Pat) { let cx = self.cx; // We want to detect pattern bindings that move a value onto the stack. // When "default binding modes" https://github.com/rust-lang/rust/issues/42640 // are implemented, the `Unannotated` case could cause false-positives. // These should be fixable by adding an explicit `ref`. match pat.kind { hir::PatKind::Binding(hir::BindingAnnotation::Unannotated,..) | hir::PatKind::Binding(hir::BindingAnnotation::Mutable,..) => { let ty = cx.tables.pat_ty(pat); if is_unrooted_ty(&self.symbols, cx, ty, self.in_new_function) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build(&format!("Expression of type {:?} must be rooted", ty)) .set_span(pat.span) .emit() }) } }, _ => {}, } visit::walk_pat(self, pat); } fn visit_ty(&mut self, _: &'tcx hir::Ty) {} fn nested_visit_map<'this>( &'this mut self, ) -> hir::intravisit::NestedVisitorMap<'this, Self::Map> { hir::intravisit::NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir()) } } /// check if a DefId's path matches the given absolute type path /// usage e.g. with /// `match_def_path(cx, id, &["core", "option", "Option"])` fn match_def_path(cx: &LateContext, def_id: DefId, path: &[Symbol]) -> bool { let krate = &cx.tcx.crate_name(def_id.krate); if krate!= &path[0] { return false; } let path = &path[1..]; let other = cx.tcx.def_path(def_id).data; if other.len()!= path.len() { return false; } other .into_iter() .zip(path) .all(|(e, p)| e.data.as_symbol() == *p) } fn in_derive_expn(span: Span) -> bool { matches!( span.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _) ) } macro_rules! symbols { ($($s: ident)+) => { #[derive(Clone)] #[allow(non_snake_case)] struct Symbols { $( $s: Symbol, )+ } impl Symbols { fn new() -> Self { Symbols { $( $s: Symbol::intern(stringify!($s)), )+ } } } } } symbols! { unrooted_must_root_lint allow_unrooted_interior allow_unrooted_in_rc must_root alloc rc Rc cell accountable_refcell Ref Ref
{ let symbols = Symbols::new(); reg.lint_store.register_lints(&[&UNROOTED_MUST_ROOT]); reg.lint_store .register_late_pass(move || Box::new(UnrootedPass::new(symbols.clone()))); }
identifier_body
lib.rs
a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[unrooted_must_root_lint::must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[unrooted_must_root_lint::must_root]`. //! Use this for structs that correspond to a DOM type #![deny(unsafe_code)] #![feature(plugin)] #![feature(plugin_registrar)] #![feature(rustc_private)] #![cfg(feature = "unrooted_must_root_lint")] extern crate rustc; extern crate rustc_ast; extern crate rustc_driver; extern crate rustc_hir; extern crate rustc_lint; extern crate rustc_session; extern crate rustc_span; use rustc::ty; use rustc_ast::ast::{AttrKind, Attribute}; use rustc_driver::plugin::Registry; use rustc_hir::def_id::DefId; use rustc_hir::intravisit as visit; use rustc_hir::{self as hir, ExprKind, HirId}; use rustc_lint::{LateContext, LateLintPass, LintContext, LintPass}; use rustc_session::declare_lint; use rustc_span::source_map; use rustc_span::source_map::{ExpnKind, MacroKind, Span}; use rustc_span::symbol::sym; use rustc_span::symbol::Symbol; #[allow(deprecated)] #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { registrar(reg) } fn registrar(reg: &mut Registry) { let symbols = Symbols::new(); reg.lint_store.register_lints(&[&UNROOTED_MUST_ROOT]); reg.lint_store .register_late_pass(move || Box::new(UnrootedPass::new(symbols.clone()))); } declare_lint!( UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects" ); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that /// `#[unrooted_must_root_lint::must_root]` values are used correctly. /// /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[unrooted_must_root_lint::must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a /// GC pass. /// /// Structs which have their own mechanism of rooting their unrooted contents (e.g. `ScriptThread`) /// can be marked as `#[allow(unrooted_must_root)]`. Smart pointers which root their interior type /// can be marked as `#[unrooted_must_root_lint::allow_unrooted_interior]` pub(crate) struct UnrootedPass { symbols: Symbols, } impl UnrootedPass { pub fn new(symbols: Symbols) -> UnrootedPass { UnrootedPass { symbols } } } fn has_lint_attr(sym: &Symbols, attrs: &[Attribute], name: Symbol) -> bool { attrs.iter().any(|attr| { matches!( &attr.kind, AttrKind::Normal(attr_item) if attr_item.path.segments.len() == 2 && attr_item.path.segments[0].ident.name == sym.unrooted_must_root_lint && attr_item.path.segments[1].ident.name == name ) }) } /// Checks if a type is unrooted or contains any owned unrooted types fn is_unrooted_ty(sym: &Symbols, cx: &LateContext, ty: &ty::TyS, in_new_function: bool) -> bool { let mut ret = false; ty.maybe_walk(|t| { match t.kind { ty::Adt(did, substs) => { let has_attr = |did, name| has_lint_attr(sym, &cx.tcx.get_attrs(did), name); if has_attr(did.did, sym.must_root) { ret = true; false } else if has_attr(did.did, sym.allow_unrooted_interior) { false } else if match_def_path(cx, did.did, &[sym.alloc, sym.rc, sym.Rc]) { // Rc<Promise> is okay let inner = substs.type_at(0); if let ty::Adt(did, _) = inner.kind { if has_attr(did.did, sym.allow_unrooted_in_rc) { false } else { true } } else { true } } else if match_def_path(cx, did.did, &[sym::core, sym.cell, sym.Ref]) || match_def_path(cx, did.did, &[sym::core, sym.cell, sym.RefMut]) || match_def_path(cx, did.did, &[sym::core, sym.slice, sym.Iter]) || match_def_path(cx, did.did, &[sym::core, sym.slice, sym.IterMut]) || match_def_path(cx, did.did, &[sym.accountable_refcell, sym.Ref]) || match_def_path(cx, did.did, &[sym.accountable_refcell, sym.RefMut]) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.map, sym.Entry], ) || match_def_path( cx, did.did, &[ sym::std, sym.collections, sym.hash, sym.map, sym.OccupiedEntry, ], ) || match_def_path( cx, did.did, &[ sym::std, sym.collections, sym.hash, sym.map, sym.VacantEntry, ], ) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.map, sym.Iter], ) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.set, sym.Iter], ) { // Structures which are semantically similar to an &ptr. false } else if did.is_box() && in_new_function { // box in new() is okay false } else { true } }, ty::Ref(..) => false, // don't recurse down &ptrs ty::RawPtr(..) => false, // don't recurse down *ptrs ty::FnDef(..) | ty::FnPtr(_) => false, _ => true, } }); ret } impl LintPass for UnrootedPass { fn name(&self) -> &'static str { "ServoUnrootedPass" } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnrootedPass { /// All structs containing #[unrooted_must_root_lint::must_root] types /// must be #[unrooted_must_root_lint::must_root] themselves fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) { if has_lint_attr(&self.symbols, &item.attrs, self.symbols.must_root) { return; } if let hir::ItemKind::Struct(def,..) = &item.kind { for ref field in def.fields() { let def_id = cx.tcx.hir().local_def_id(field.hir_id); if is_unrooted_ty(&self.symbols, cx, cx.tcx.type_of(def_id), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build( "Type must be rooted, use #[unrooted_must_root_lint::must_root] \ on the struct definition to propagate", ) .set_span(field.span) .emit() }) } } } } /// All enums containing #[unrooted_must_root_lint::must_root] types /// must be #[unrooted_must_root_lint::must_root] themselves fn check_variant(&mut self, cx: &LateContext, var: &hir::Variant) { let ref map = cx.tcx.hir(); let parent_item = map.expect_item(map.get_parent_item(var.id)); if!has_lint_attr(&self.symbols, &parent_item.attrs, self.symbols.must_root) { match var.data { hir::VariantData::Tuple(fields,..) => { for field in fields { let def_id = cx.tcx.hir().local_def_id(field.hir_id); if is_unrooted_ty(&self.symbols, cx, cx.tcx.type_of(def_id), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build( "Type must be rooted, \ use #[unrooted_must_root_lint::must_root] \ on the enum definition to propagate", ) .set_span(field.ty.span) .emit() }) } } }, _ => (), // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[unrooted_must_root_lint::must_root] types are not allowed fn check_fn( &mut self, cx: &LateContext<'a, 'tcx>, kind: visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl, body: &'tcx hir::Body, span: source_map::Span, id: HirId, ) { let in_new_function = match kind { visit::FnKind::ItemFn(n, _, _, _, _) | visit::FnKind::Method(n, _, _, _) => { &*n.as_str() == "new" || n.as_str().starts_with("new_") }, visit::FnKind::Closure(_) => return, }; if!in_derive_expn(span)
} } let mut visitor = FnDefVisitor { symbols: &self.symbols, cx: cx, in_new_function: in_new_function, }; visit::walk_expr(&mut visitor, &body.value); } } struct FnDefVisitor<'a, 'b: 'a, 'tcx: 'a + 'b> { symbols: &'a Symbols, cx: &'a LateContext<'b, 'tcx>, in_new_function: bool, } impl<'a, 'b, 'tcx> visit::Visitor<'tcx> for FnDefVisitor<'a, 'b, 'tcx> { type Map = rustc::hir::map::Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx hir::Expr) { let cx = self.cx; let require_rooted = |cx: &LateContext, in_new_function: bool, subexpr: &hir::Expr| { let ty = cx.tables.expr_ty(&subexpr); if is_unrooted_ty(&self.symbols, cx, ty, in_new_function) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build(&format!("Expression of type {:?} must be rooted", ty)) .set_span(subexpr.span) .emit() }) } }; match expr.kind { // Trait casts from #[unrooted_must_root_lint::must_root] types are not allowed ExprKind::Cast(ref subexpr, _) => require_rooted(cx, self.in_new_function, &*subexpr), // This catches assignments... the main point of this would be to catch mutable // references to `JS<T>`. // FIXME: Enable this? Triggers on certain kinds of uses of DomRefCell. // hir::ExprAssign(_, ref rhs) => require_rooted(cx, self.in_new_function, &*rhs), // This catches calls; basically, this enforces the constraint that only constructors // can call other constructors. // FIXME: Enable this? Currently triggers with constructs involving DomRefCell, and // constructs like Vec<JS<T>> and RootedVec<JS<T>>. // hir::ExprCall(..) if!self.in_new_function => { // require_rooted(cx, self.in_new_function, expr); // } _ => { // TODO(pcwalton): Check generics with a whitelist of allowed generics. }, } visit::walk_expr(self, expr); } fn visit_pat(&mut self, pat: &'tcx hir::Pat) { let cx = self.cx; // We want to detect pattern bindings that move a value onto the stack. // When "default binding modes" https://github.com/rust-lang/rust/issues/42640 // are implemented, the `Unannotated` case could cause false-positives. // These should be fixable by adding an explicit `ref`. match pat.kind { hir::PatKind::Binding(hir::BindingAnnotation::Unannotated,..) | hir::PatKind::Binding(hir::BindingAnnotation::Mutable,..) => { let ty = cx.tables.pat_ty(pat); if is_unrooted_ty(&self.symbols, cx, ty, self.in_new_function) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build(&format!("Expression of type {:?} must be rooted", ty)) .set_span(pat.span) .emit() }) } }, _ => {}, } visit::walk_pat(self, pat); } fn visit_ty(&mut self, _: &'tcx hir::Ty) {} fn nested_visit_map<'this>( &'this mut self, ) -> hir::intravisit::NestedVisitorMap<'this, Self::Map> { hir::intravisit::NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir()) } } /// check if a DefId's path matches the given absolute type path /// usage e.g. with /// `match_def_path(cx, id, &["core", "option", "Option"])` fn match_def_path(cx: &LateContext, def_id: DefId, path: &[Symbol]) -> bool { let krate = &cx.tcx.crate_name(def_id.krate); if krate!= &path[0] { return false; } let path = &path[1..]; let other = cx.tcx.def_path(def_id).data; if other.len()!= path.len() { return false; } other .into_iter() .zip(path) .all(|(e, p)| e.data.as_symbol() == *p) } fn in_derive_expn(span: Span) -> bool { matches!( span.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _) ) } macro_rules! symbols { ($($s: ident)+) => { #[derive(Clone)] #[allow(non_snake_case)] struct Symbols { $( $s: Symbol, )+ } impl Symbols { fn new() -> Self { Symbols { $( $s: Symbol::intern(stringify!($s)), )+ } } } } } symbols! { unrooted_must_root_lint allow_unrooted_interior allow_unrooted_in_rc must_root alloc rc Rc cell accountable_refcell Ref Ref
{ let def_id = cx.tcx.hir().local_def_id(id); let sig = cx.tcx.type_of(def_id).fn_sig(cx.tcx); for (arg, ty) in decl.inputs.iter().zip(sig.inputs().skip_binder().iter()) { if is_unrooted_ty(&self.symbols, cx, ty, false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build("Type must be rooted").set_span(arg.span).emit() }) } } if !in_new_function { if is_unrooted_ty(&self.symbols, cx, sig.output().skip_binder(), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build("Type must be rooted") .set_span(decl.output.span()) .emit() }) }
conditional_block
lib.rs
a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[unrooted_must_root_lint::must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[unrooted_must_root_lint::must_root]`. //! Use this for structs that correspond to a DOM type #![deny(unsafe_code)] #![feature(plugin)] #![feature(plugin_registrar)] #![feature(rustc_private)] #![cfg(feature = "unrooted_must_root_lint")] extern crate rustc; extern crate rustc_ast; extern crate rustc_driver; extern crate rustc_hir; extern crate rustc_lint; extern crate rustc_session; extern crate rustc_span; use rustc::ty; use rustc_ast::ast::{AttrKind, Attribute}; use rustc_driver::plugin::Registry; use rustc_hir::def_id::DefId; use rustc_hir::intravisit as visit; use rustc_hir::{self as hir, ExprKind, HirId}; use rustc_lint::{LateContext, LateLintPass, LintContext, LintPass}; use rustc_session::declare_lint; use rustc_span::source_map; use rustc_span::source_map::{ExpnKind, MacroKind, Span}; use rustc_span::symbol::sym; use rustc_span::symbol::Symbol; #[allow(deprecated)] #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { registrar(reg) } fn registrar(reg: &mut Registry) { let symbols = Symbols::new(); reg.lint_store.register_lints(&[&UNROOTED_MUST_ROOT]); reg.lint_store .register_late_pass(move || Box::new(UnrootedPass::new(symbols.clone()))); } declare_lint!( UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects" ); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that /// `#[unrooted_must_root_lint::must_root]` values are used correctly. /// /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[unrooted_must_root_lint::must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a /// GC pass. /// /// Structs which have their own mechanism of rooting their unrooted contents (e.g. `ScriptThread`) /// can be marked as `#[allow(unrooted_must_root)]`. Smart pointers which root their interior type /// can be marked as `#[unrooted_must_root_lint::allow_unrooted_interior]` pub(crate) struct UnrootedPass { symbols: Symbols, } impl UnrootedPass { pub fn new(symbols: Symbols) -> UnrootedPass { UnrootedPass { symbols } } } fn has_lint_attr(sym: &Symbols, attrs: &[Attribute], name: Symbol) -> bool { attrs.iter().any(|attr| { matches!( &attr.kind, AttrKind::Normal(attr_item) if attr_item.path.segments.len() == 2 && attr_item.path.segments[0].ident.name == sym.unrooted_must_root_lint && attr_item.path.segments[1].ident.name == name ) }) } /// Checks if a type is unrooted or contains any owned unrooted types fn
(sym: &Symbols, cx: &LateContext, ty: &ty::TyS, in_new_function: bool) -> bool { let mut ret = false; ty.maybe_walk(|t| { match t.kind { ty::Adt(did, substs) => { let has_attr = |did, name| has_lint_attr(sym, &cx.tcx.get_attrs(did), name); if has_attr(did.did, sym.must_root) { ret = true; false } else if has_attr(did.did, sym.allow_unrooted_interior) { false } else if match_def_path(cx, did.did, &[sym.alloc, sym.rc, sym.Rc]) { // Rc<Promise> is okay let inner = substs.type_at(0); if let ty::Adt(did, _) = inner.kind { if has_attr(did.did, sym.allow_unrooted_in_rc) { false } else { true } } else { true } } else if match_def_path(cx, did.did, &[sym::core, sym.cell, sym.Ref]) || match_def_path(cx, did.did, &[sym::core, sym.cell, sym.RefMut]) || match_def_path(cx, did.did, &[sym::core, sym.slice, sym.Iter]) || match_def_path(cx, did.did, &[sym::core, sym.slice, sym.IterMut]) || match_def_path(cx, did.did, &[sym.accountable_refcell, sym.Ref]) || match_def_path(cx, did.did, &[sym.accountable_refcell, sym.RefMut]) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.map, sym.Entry], ) || match_def_path( cx, did.did, &[ sym::std, sym.collections, sym.hash, sym.map, sym.OccupiedEntry, ], ) || match_def_path( cx, did.did, &[ sym::std, sym.collections, sym.hash, sym.map, sym.VacantEntry, ], ) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.map, sym.Iter], ) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.set, sym.Iter], ) { // Structures which are semantically similar to an &ptr. false } else if did.is_box() && in_new_function { // box in new() is okay false } else { true } }, ty::Ref(..) => false, // don't recurse down &ptrs ty::RawPtr(..) => false, // don't recurse down *ptrs ty::FnDef(..) | ty::FnPtr(_) => false, _ => true, } }); ret } impl LintPass for UnrootedPass { fn name(&self) -> &'static str { "ServoUnrootedPass" } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnrootedPass { /// All structs containing #[unrooted_must_root_lint::must_root] types /// must be #[unrooted_must_root_lint::must_root] themselves fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) { if has_lint_attr(&self.symbols, &item.attrs, self.symbols.must_root) { return; } if let hir::ItemKind::Struct(def,..) = &item.kind { for ref field in def.fields() { let def_id = cx.tcx.hir().local_def_id(field.hir_id); if is_unrooted_ty(&self.symbols, cx, cx.tcx.type_of(def_id), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build( "Type must be rooted, use #[unrooted_must_root_lint::must_root] \ on the struct definition to propagate", ) .set_span(field.span) .emit() }) } } } } /// All enums containing #[unrooted_must_root_lint::must_root] types /// must be #[unrooted_must_root_lint::must_root] themselves fn check_variant(&mut self, cx: &LateContext, var: &hir::Variant) { let ref map = cx.tcx.hir(); let parent_item = map.expect_item(map.get_parent_item(var.id)); if!has_lint_attr(&self.symbols, &parent_item.attrs, self.symbols.must_root) { match var.data { hir::VariantData::Tuple(fields,..) => { for field in fields { let def_id = cx.tcx.hir().local_def_id(field.hir_id); if is_unrooted_ty(&self.symbols, cx, cx.tcx.type_of(def_id), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build( "Type must be rooted, \ use #[unrooted_must_root_lint::must_root] \ on the enum definition to propagate", ) .set_span(field.ty.span) .emit() }) } } }, _ => (), // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[unrooted_must_root_lint::must_root] types are not allowed fn check_fn( &mut self, cx: &LateContext<'a, 'tcx>, kind: visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl, body: &'tcx hir::Body, span: source_map::Span, id: HirId, ) { let in_new_function = match kind { visit::FnKind::ItemFn(n, _, _, _, _) | visit::FnKind::Method(n, _, _, _) => { &*n.as_str() == "new" || n.as_str().starts_with("new_") }, visit::FnKind::Closure(_) => return, }; if!in_derive_expn(span) { let def_id = cx.tcx.hir().local_def_id(id); let sig = cx.tcx.type_of(def_id).fn_sig(cx.tcx); for (arg, ty) in decl.inputs.iter().zip(sig.inputs().skip_binder().iter()) { if is_unrooted_ty(&self.symbols, cx, ty, false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build("Type must be rooted").set_span(arg.span).emit() }) } } if!in_new_function { if is_unrooted_ty(&self.symbols, cx, sig.output().skip_binder(), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build("Type must be rooted") .set_span(decl.output.span()) .emit() }) } } } let mut visitor = FnDefVisitor { symbols: &self.symbols, cx: cx, in_new_function: in_new_function, }; visit::walk_expr(&mut visitor, &body.value); } } struct FnDefVisitor<'a, 'b: 'a, 'tcx: 'a + 'b> { symbols: &'a Symbols, cx: &'a LateContext<'b, 'tcx>, in_new_function: bool, } impl<'a, 'b, 'tcx> visit::Visitor<'tcx> for FnDefVisitor<'a, 'b, 'tcx> { type Map = rustc::hir::map::Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx hir::Expr) { let cx = self.cx; let require_rooted = |cx: &LateContext, in_new_function: bool, subexpr: &hir::Expr| { let ty = cx.tables.expr_ty(&subexpr); if is_unrooted_ty(&self.symbols, cx, ty, in_new_function) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build(&format!("Expression of type {:?} must be rooted", ty)) .set_span(subexpr.span) .emit() }) } }; match expr.kind { // Trait casts from #[unrooted_must_root_lint::must_root] types are not allowed ExprKind::Cast(ref subexpr, _) => require_rooted(cx, self.in_new_function, &*subexpr), // This catches assignments... the main point of this would be to catch mutable // references to `JS<T>`. // FIXME: Enable this? Triggers on certain kinds of uses of DomRefCell. // hir::ExprAssign(_, ref rhs) => require_rooted(cx, self.in_new_function, &*rhs), // This catches calls; basically, this enforces the constraint that only constructors // can call other constructors. // FIXME: Enable this? Currently triggers with constructs involving DomRefCell, and // constructs like Vec<JS<T>> and RootedVec<JS<T>>. // hir::ExprCall(..) if!self.in_new_function => { // require_rooted(cx, self.in_new_function, expr); // } _ => { // TODO(pcwalton): Check generics with a whitelist of allowed generics. }, } visit::walk_expr(self, expr); } fn visit_pat(&mut self, pat: &'tcx hir::Pat) { let cx = self.cx; // We want to detect pattern bindings that move a value onto the stack. // When "default binding modes" https://github.com/rust-lang/rust/issues/42640 // are implemented, the `Unannotated` case could cause false-positives. // These should be fixable by adding an explicit `ref`. match pat.kind { hir::PatKind::Binding(hir::BindingAnnotation::Unannotated,..) | hir::PatKind::Binding(hir::BindingAnnotation::Mutable,..) => { let ty = cx.tables.pat_ty(pat); if is_unrooted_ty(&self.symbols, cx, ty, self.in_new_function) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build(&format!("Expression of type {:?} must be rooted", ty)) .set_span(pat.span) .emit() }) } }, _ => {}, } visit::walk_pat(self, pat); } fn visit_ty(&mut self, _: &'tcx hir::Ty) {} fn nested_visit_map<'this>( &'this mut self, ) -> hir::intravisit::NestedVisitorMap<'this, Self::Map> { hir::intravisit::NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir()) } } /// check if a DefId's path matches the given absolute type path /// usage e.g. with /// `match_def_path(cx, id, &["core", "option", "Option"])` fn match_def_path(cx: &LateContext, def_id: DefId, path: &[Symbol]) -> bool { let krate = &cx.tcx.crate_name(def_id.krate); if krate!= &path[0] { return false; } let path = &path[1..]; let other = cx.tcx.def_path(def_id).data; if other.len()!= path.len() { return false; } other .into_iter() .zip(path) .all(|(e, p)| e.data.as_symbol() == *p) } fn in_derive_expn(span: Span) -> bool { matches!( span.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _) ) } macro_rules! symbols { ($($s: ident)+) => { #[derive(Clone)] #[allow(non_snake_case)] struct Symbols { $( $s: Symbol, )+ } impl Symbols { fn new() -> Self { Symbols { $( $s: Symbol::intern(stringify!($s)), )+ } } } } } symbols! { unrooted_must_root_lint allow_unrooted_interior allow_unrooted_in_rc must_root alloc rc Rc cell accountable_refcell Ref Ref
is_unrooted_ty
identifier_name
lib.rs
If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private //! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate //! - `#[unrooted_must_root_lint::must_root]` : Prevents data of the marked type from being used on the stack. //! See the lints module for more details //! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[unrooted_must_root_lint::must_root]`. //! Use this for structs that correspond to a DOM type #![deny(unsafe_code)] #![feature(plugin)] #![feature(plugin_registrar)] #![feature(rustc_private)] #![cfg(feature = "unrooted_must_root_lint")] extern crate rustc; extern crate rustc_ast; extern crate rustc_driver; extern crate rustc_hir; extern crate rustc_lint; extern crate rustc_session; extern crate rustc_span; use rustc::ty; use rustc_ast::ast::{AttrKind, Attribute}; use rustc_driver::plugin::Registry; use rustc_hir::def_id::DefId; use rustc_hir::intravisit as visit; use rustc_hir::{self as hir, ExprKind, HirId}; use rustc_lint::{LateContext, LateLintPass, LintContext, LintPass}; use rustc_session::declare_lint; use rustc_span::source_map; use rustc_span::source_map::{ExpnKind, MacroKind, Span}; use rustc_span::symbol::sym; use rustc_span::symbol::Symbol; #[allow(deprecated)] #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { registrar(reg) } fn registrar(reg: &mut Registry) { let symbols = Symbols::new(); reg.lint_store.register_lints(&[&UNROOTED_MUST_ROOT]); reg.lint_store .register_late_pass(move || Box::new(UnrootedPass::new(symbols.clone()))); } declare_lint!( UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects" ); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that /// `#[unrooted_must_root_lint::must_root]` values are used correctly. /// /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[unrooted_must_root_lint::must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a /// GC pass. /// /// Structs which have their own mechanism of rooting their unrooted contents (e.g. `ScriptThread`) /// can be marked as `#[allow(unrooted_must_root)]`. Smart pointers which root their interior type /// can be marked as `#[unrooted_must_root_lint::allow_unrooted_interior]` pub(crate) struct UnrootedPass { symbols: Symbols, } impl UnrootedPass { pub fn new(symbols: Symbols) -> UnrootedPass { UnrootedPass { symbols } } } fn has_lint_attr(sym: &Symbols, attrs: &[Attribute], name: Symbol) -> bool { attrs.iter().any(|attr| { matches!( &attr.kind, AttrKind::Normal(attr_item) if attr_item.path.segments.len() == 2 && attr_item.path.segments[0].ident.name == sym.unrooted_must_root_lint && attr_item.path.segments[1].ident.name == name ) }) } /// Checks if a type is unrooted or contains any owned unrooted types fn is_unrooted_ty(sym: &Symbols, cx: &LateContext, ty: &ty::TyS, in_new_function: bool) -> bool { let mut ret = false; ty.maybe_walk(|t| { match t.kind { ty::Adt(did, substs) => { let has_attr = |did, name| has_lint_attr(sym, &cx.tcx.get_attrs(did), name); if has_attr(did.did, sym.must_root) { ret = true; false } else if has_attr(did.did, sym.allow_unrooted_interior) { false } else if match_def_path(cx, did.did, &[sym.alloc, sym.rc, sym.Rc]) { // Rc<Promise> is okay let inner = substs.type_at(0); if let ty::Adt(did, _) = inner.kind { if has_attr(did.did, sym.allow_unrooted_in_rc) { false } else { true } } else { true } } else if match_def_path(cx, did.did, &[sym::core, sym.cell, sym.Ref]) || match_def_path(cx, did.did, &[sym::core, sym.cell, sym.RefMut]) || match_def_path(cx, did.did, &[sym::core, sym.slice, sym.Iter]) || match_def_path(cx, did.did, &[sym::core, sym.slice, sym.IterMut]) || match_def_path(cx, did.did, &[sym.accountable_refcell, sym.Ref]) || match_def_path(cx, did.did, &[sym.accountable_refcell, sym.RefMut]) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.map, sym.Entry], ) || match_def_path( cx, did.did, &[ sym::std, sym.collections, sym.hash, sym.map, sym.OccupiedEntry, ], ) || match_def_path( cx, did.did, &[ sym::std, sym.collections, sym.hash, sym.map, sym.VacantEntry, ], ) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.map, sym.Iter], ) || match_def_path( cx, did.did, &[sym::std, sym.collections, sym.hash, sym.set, sym.Iter], ) { // Structures which are semantically similar to an &ptr. false } else if did.is_box() && in_new_function { // box in new() is okay false } else { true } }, ty::Ref(..) => false, // don't recurse down &ptrs ty::RawPtr(..) => false, // don't recurse down *ptrs ty::FnDef(..) | ty::FnPtr(_) => false, _ => true, } }); ret } impl LintPass for UnrootedPass { fn name(&self) -> &'static str { "ServoUnrootedPass" } }
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnrootedPass { /// All structs containing #[unrooted_must_root_lint::must_root] types /// must be #[unrooted_must_root_lint::must_root] themselves fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) { if has_lint_attr(&self.symbols, &item.attrs, self.symbols.must_root) { return; } if let hir::ItemKind::Struct(def,..) = &item.kind { for ref field in def.fields() { let def_id = cx.tcx.hir().local_def_id(field.hir_id); if is_unrooted_ty(&self.symbols, cx, cx.tcx.type_of(def_id), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build( "Type must be rooted, use #[unrooted_must_root_lint::must_root] \ on the struct definition to propagate", ) .set_span(field.span) .emit() }) } } } } /// All enums containing #[unrooted_must_root_lint::must_root] types /// must be #[unrooted_must_root_lint::must_root] themselves fn check_variant(&mut self, cx: &LateContext, var: &hir::Variant) { let ref map = cx.tcx.hir(); let parent_item = map.expect_item(map.get_parent_item(var.id)); if!has_lint_attr(&self.symbols, &parent_item.attrs, self.symbols.must_root) { match var.data { hir::VariantData::Tuple(fields,..) => { for field in fields { let def_id = cx.tcx.hir().local_def_id(field.hir_id); if is_unrooted_ty(&self.symbols, cx, cx.tcx.type_of(def_id), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build( "Type must be rooted, \ use #[unrooted_must_root_lint::must_root] \ on the enum definition to propagate", ) .set_span(field.ty.span) .emit() }) } } }, _ => (), // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[unrooted_must_root_lint::must_root] types are not allowed fn check_fn( &mut self, cx: &LateContext<'a, 'tcx>, kind: visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl, body: &'tcx hir::Body, span: source_map::Span, id: HirId, ) { let in_new_function = match kind { visit::FnKind::ItemFn(n, _, _, _, _) | visit::FnKind::Method(n, _, _, _) => { &*n.as_str() == "new" || n.as_str().starts_with("new_") }, visit::FnKind::Closure(_) => return, }; if!in_derive_expn(span) { let def_id = cx.tcx.hir().local_def_id(id); let sig = cx.tcx.type_of(def_id).fn_sig(cx.tcx); for (arg, ty) in decl.inputs.iter().zip(sig.inputs().skip_binder().iter()) { if is_unrooted_ty(&self.symbols, cx, ty, false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build("Type must be rooted").set_span(arg.span).emit() }) } } if!in_new_function { if is_unrooted_ty(&self.symbols, cx, sig.output().skip_binder(), false) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build("Type must be rooted") .set_span(decl.output.span()) .emit() }) } } } let mut visitor = FnDefVisitor { symbols: &self.symbols, cx: cx, in_new_function: in_new_function, }; visit::walk_expr(&mut visitor, &body.value); } } struct FnDefVisitor<'a, 'b: 'a, 'tcx: 'a + 'b> { symbols: &'a Symbols, cx: &'a LateContext<'b, 'tcx>, in_new_function: bool, } impl<'a, 'b, 'tcx> visit::Visitor<'tcx> for FnDefVisitor<'a, 'b, 'tcx> { type Map = rustc::hir::map::Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx hir::Expr) { let cx = self.cx; let require_rooted = |cx: &LateContext, in_new_function: bool, subexpr: &hir::Expr| { let ty = cx.tables.expr_ty(&subexpr); if is_unrooted_ty(&self.symbols, cx, ty, in_new_function) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build(&format!("Expression of type {:?} must be rooted", ty)) .set_span(subexpr.span) .emit() }) } }; match expr.kind { // Trait casts from #[unrooted_must_root_lint::must_root] types are not allowed ExprKind::Cast(ref subexpr, _) => require_rooted(cx, self.in_new_function, &*subexpr), // This catches assignments... the main point of this would be to catch mutable // references to `JS<T>`. // FIXME: Enable this? Triggers on certain kinds of uses of DomRefCell. // hir::ExprAssign(_, ref rhs) => require_rooted(cx, self.in_new_function, &*rhs), // This catches calls; basically, this enforces the constraint that only constructors // can call other constructors. // FIXME: Enable this? Currently triggers with constructs involving DomRefCell, and // constructs like Vec<JS<T>> and RootedVec<JS<T>>. // hir::ExprCall(..) if!self.in_new_function => { // require_rooted(cx, self.in_new_function, expr); // } _ => { // TODO(pcwalton): Check generics with a whitelist of allowed generics. }, } visit::walk_expr(self, expr); } fn visit_pat(&mut self, pat: &'tcx hir::Pat) { let cx = self.cx; // We want to detect pattern bindings that move a value onto the stack. // When "default binding modes" https://github.com/rust-lang/rust/issues/42640 // are implemented, the `Unannotated` case could cause false-positives. // These should be fixable by adding an explicit `ref`. match pat.kind { hir::PatKind::Binding(hir::BindingAnnotation::Unannotated,..) | hir::PatKind::Binding(hir::BindingAnnotation::Mutable,..) => { let ty = cx.tables.pat_ty(pat); if is_unrooted_ty(&self.symbols, cx, ty, self.in_new_function) { cx.lint(UNROOTED_MUST_ROOT, |lint| { lint.build(&format!("Expression of type {:?} must be rooted", ty)) .set_span(pat.span) .emit() }) } }, _ => {}, } visit::walk_pat(self, pat); } fn visit_ty(&mut self, _: &'tcx hir::Ty) {} fn nested_visit_map<'this>( &'this mut self, ) -> hir::intravisit::NestedVisitorMap<'this, Self::Map> { hir::intravisit::NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir()) } } /// check if a DefId's path matches the given absolute type path /// usage e.g. with /// `match_def_path(cx, id, &["core", "option", "Option"])` fn match_def_path(cx: &LateContext, def_id: DefId, path: &[Symbol]) -> bool { let krate = &cx.tcx.crate_name(def_id.krate); if krate!= &path[0] { return false; } let path = &path[1..]; let other = cx.tcx.def_path(def_id).data; if other.len()!= path.len() { return false; } other .into_iter() .zip(path) .all(|(e, p)| e.data.as_symbol() == *p) } fn in_derive_expn(span: Span) -> bool { matches!( span.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _) ) } macro_rules! symbols { ($($s: ident)+) => { #[derive(Clone)] #[allow(non_snake_case)] struct Symbols { $( $s: Symbol, )+ } impl Symbols { fn new() -> Self { Symbols { $( $s: Symbol::intern(stringify!($s)), )+ } } } } } symbols! { unrooted_must_root_lint allow_unrooted_interior allow_unrooted_in_rc must_root alloc rc Rc cell accountable_refcell Ref RefMut
random_line_split
persistent_list.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/. */ //! A persistent, thread-safe singly-linked list. use std::mem; use std::sync::Arc; pub struct PersistentList<T> { head: PersistentListLink<T>, length: uint, } struct PersistentListEntry<T> { value: T, next: PersistentListLink<T>, } type PersistentListLink<T> = Option<Arc<PersistentListEntry<T>>>; impl<T> PersistentList<T> where T: Send + Sync { #[inline] pub fn new() -> PersistentList<T> { PersistentList { head: None, length: 0, } } #[inline] pub fn len(&self) -> uint { self.length } #[inline] pub fn front(&self) -> Option<&T> { self.head.as_ref().map(|head| &head.value) } #[inline] pub fn prepend_elem(&self, value: T) -> PersistentList<T> { PersistentList { head: Some(Arc::new(PersistentListEntry { value: value, next: self.head.clone(), })), length: self.length + 1, } } #[inline] pub fn iter<'a>(&'a self) -> PersistentListIterator<'a,T> { // This could clone (and would not need the lifetime if it did), but then it would incur // atomic operations on every call to `.next()`. Bad. PersistentListIterator { entry: self.head.as_ref().map(|head| &**head), } } } impl<T> Clone for PersistentList<T> where T: Send + Sync { fn clone(&self) -> PersistentList<T> { // This establishes the persistent nature of this list: we can clone a list by just cloning // its head. PersistentList { head: self.head.clone(), length: self.length, } } } pub struct
<'a,T> where T: 'a + Send + Sync { entry: Option<&'a PersistentListEntry<T>>, } impl<'a,T> Iterator<&'a T> for PersistentListIterator<'a,T> where T: Send + Sync { #[inline] fn next(&mut self) -> Option<&'a T> { let entry = match self.entry { None => return None, Some(entry) => { // This `transmute` is necessary to ensure that the lifetimes of the next entry and // this entry match up; the compiler doesn't know this, but we do because of the // reference counting behavior of `Arc`. unsafe { mem::transmute::<&'a PersistentListEntry<T>, &'static PersistentListEntry<T>>(entry) } } }; let value = &entry.value; self.entry = match entry.next { None => None, Some(ref entry) => Some(&**entry), }; Some(value) } }
PersistentListIterator
identifier_name
persistent_list.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/. */ //! A persistent, thread-safe singly-linked list. use std::mem; use std::sync::Arc; pub struct PersistentList<T> { head: PersistentListLink<T>, length: uint, } struct PersistentListEntry<T> { value: T, next: PersistentListLink<T>, } type PersistentListLink<T> = Option<Arc<PersistentListEntry<T>>>; impl<T> PersistentList<T> where T: Send + Sync { #[inline] pub fn new() -> PersistentList<T> { PersistentList { head: None, length: 0, } } #[inline] pub fn len(&self) -> uint
#[inline] pub fn front(&self) -> Option<&T> { self.head.as_ref().map(|head| &head.value) } #[inline] pub fn prepend_elem(&self, value: T) -> PersistentList<T> { PersistentList { head: Some(Arc::new(PersistentListEntry { value: value, next: self.head.clone(), })), length: self.length + 1, } } #[inline] pub fn iter<'a>(&'a self) -> PersistentListIterator<'a,T> { // This could clone (and would not need the lifetime if it did), but then it would incur // atomic operations on every call to `.next()`. Bad. PersistentListIterator { entry: self.head.as_ref().map(|head| &**head), } } } impl<T> Clone for PersistentList<T> where T: Send + Sync { fn clone(&self) -> PersistentList<T> { // This establishes the persistent nature of this list: we can clone a list by just cloning // its head. PersistentList { head: self.head.clone(), length: self.length, } } } pub struct PersistentListIterator<'a,T> where T: 'a + Send + Sync { entry: Option<&'a PersistentListEntry<T>>, } impl<'a,T> Iterator<&'a T> for PersistentListIterator<'a,T> where T: Send + Sync { #[inline] fn next(&mut self) -> Option<&'a T> { let entry = match self.entry { None => return None, Some(entry) => { // This `transmute` is necessary to ensure that the lifetimes of the next entry and // this entry match up; the compiler doesn't know this, but we do because of the // reference counting behavior of `Arc`. unsafe { mem::transmute::<&'a PersistentListEntry<T>, &'static PersistentListEntry<T>>(entry) } } }; let value = &entry.value; self.entry = match entry.next { None => None, Some(ref entry) => Some(&**entry), }; Some(value) } }
{ self.length }
identifier_body
persistent_list.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/. */ //! A persistent, thread-safe singly-linked list. use std::mem; use std::sync::Arc; pub struct PersistentList<T> { head: PersistentListLink<T>, length: uint, } struct PersistentListEntry<T> { value: T, next: PersistentListLink<T>, } type PersistentListLink<T> = Option<Arc<PersistentListEntry<T>>>; impl<T> PersistentList<T> where T: Send + Sync { #[inline] pub fn new() -> PersistentList<T> { PersistentList { head: None, length: 0, } } #[inline] pub fn len(&self) -> uint { self.length } #[inline] pub fn front(&self) -> Option<&T> { self.head.as_ref().map(|head| &head.value) } #[inline] pub fn prepend_elem(&self, value: T) -> PersistentList<T> { PersistentList { head: Some(Arc::new(PersistentListEntry { value: value, next: self.head.clone(), })), length: self.length + 1, } } #[inline] pub fn iter<'a>(&'a self) -> PersistentListIterator<'a,T> { // This could clone (and would not need the lifetime if it did), but then it would incur // atomic operations on every call to `.next()`. Bad. PersistentListIterator { entry: self.head.as_ref().map(|head| &**head), } } } impl<T> Clone for PersistentList<T> where T: Send + Sync { fn clone(&self) -> PersistentList<T> { // This establishes the persistent nature of this list: we can clone a list by just cloning // its head. PersistentList { head: self.head.clone(), length: self.length, } } } pub struct PersistentListIterator<'a,T> where T: 'a + Send + Sync { entry: Option<&'a PersistentListEntry<T>>, } impl<'a,T> Iterator<&'a T> for PersistentListIterator<'a,T> where T: Send + Sync { #[inline] fn next(&mut self) -> Option<&'a T> { let entry = match self.entry { None => return None, Some(entry) => { // This `transmute` is necessary to ensure that the lifetimes of the next entry and // this entry match up; the compiler doesn't know this, but we do because of the // reference counting behavior of `Arc`. unsafe {
&'static PersistentListEntry<T>>(entry) } } }; let value = &entry.value; self.entry = match entry.next { None => None, Some(ref entry) => Some(&**entry), }; Some(value) } }
mem::transmute::<&'a PersistentListEntry<T>,
random_line_split
ranked-routing.rs
#![feature(test, plugin)] #![plugin(rocket_codegen)] extern crate rocket; use rocket::config::{Environment, Config}; #[get("/", format = "application/json")] fn get() -> &'static str { "json" } #[get("/", format = "text/html")] fn get2() -> &'static str { "html" } #[get("/", format = "text/plain")] fn get3() -> &'static str { "plain" } #[post("/", format = "application/json")] fn post() -> &'static str
#[post("/", format = "text/html")] fn post2() -> &'static str { "html" } #[post("/", format = "text/plain")] fn post3() -> &'static str { "plain" } fn rocket() -> rocket::Rocket { let config = Config::new(Environment::Production).unwrap(); rocket::custom(config, false) .mount("/", routes![get, get2, get3]) .mount("/", routes![post, post2, post3]) } mod benches { extern crate test; use super::rocket; use self::test::Bencher; use rocket::local::Client; use rocket::http::{Accept, ContentType}; #[bench] fn accept_format(b: &mut Bencher) { let client = Client::new(rocket()).unwrap(); let mut requests = vec![]; requests.push(client.get("/").header(Accept::JSON)); requests.push(client.get("/").header(Accept::HTML)); requests.push(client.get("/").header(Accept::Plain)); b.iter(|| { for request in requests.iter_mut() { request.mut_dispatch(); } }); } #[bench] fn content_type_format(b: &mut Bencher) { let client = Client::new(rocket()).unwrap(); let mut requests = vec![]; requests.push(client.post("/").header(ContentType::JSON)); requests.push(client.post("/").header(ContentType::HTML)); requests.push(client.post("/").header(ContentType::Plain)); b.iter(|| { for request in requests.iter_mut() { request.mut_dispatch(); } }); } }
{ "json" }
identifier_body
ranked-routing.rs
#![feature(test, plugin)] #![plugin(rocket_codegen)] extern crate rocket; use rocket::config::{Environment, Config}; #[get("/", format = "application/json")] fn get() -> &'static str { "json" } #[get("/", format = "text/html")] fn get2() -> &'static str { "html" } #[get("/", format = "text/plain")] fn get3() -> &'static str { "plain" } #[post("/", format = "application/json")] fn post() -> &'static str { "json" } #[post("/", format = "text/html")] fn post2() -> &'static str { "html" } #[post("/", format = "text/plain")] fn post3() -> &'static str { "plain" } fn rocket() -> rocket::Rocket { let config = Config::new(Environment::Production).unwrap(); rocket::custom(config, false) .mount("/", routes![get, get2, get3]) .mount("/", routes![post, post2, post3]) } mod benches { extern crate test; use super::rocket; use self::test::Bencher; use rocket::local::Client; use rocket::http::{Accept, ContentType}; #[bench] fn accept_format(b: &mut Bencher) { let client = Client::new(rocket()).unwrap(); let mut requests = vec![]; requests.push(client.get("/").header(Accept::JSON)); requests.push(client.get("/").header(Accept::HTML)); requests.push(client.get("/").header(Accept::Plain)); b.iter(|| { for request in requests.iter_mut() { request.mut_dispatch(); } }); }
#[bench] fn content_type_format(b: &mut Bencher) { let client = Client::new(rocket()).unwrap(); let mut requests = vec![]; requests.push(client.post("/").header(ContentType::JSON)); requests.push(client.post("/").header(ContentType::HTML)); requests.push(client.post("/").header(ContentType::Plain)); b.iter(|| { for request in requests.iter_mut() { request.mut_dispatch(); } }); } }
random_line_split
ranked-routing.rs
#![feature(test, plugin)] #![plugin(rocket_codegen)] extern crate rocket; use rocket::config::{Environment, Config}; #[get("/", format = "application/json")] fn
() -> &'static str { "json" } #[get("/", format = "text/html")] fn get2() -> &'static str { "html" } #[get("/", format = "text/plain")] fn get3() -> &'static str { "plain" } #[post("/", format = "application/json")] fn post() -> &'static str { "json" } #[post("/", format = "text/html")] fn post2() -> &'static str { "html" } #[post("/", format = "text/plain")] fn post3() -> &'static str { "plain" } fn rocket() -> rocket::Rocket { let config = Config::new(Environment::Production).unwrap(); rocket::custom(config, false) .mount("/", routes![get, get2, get3]) .mount("/", routes![post, post2, post3]) } mod benches { extern crate test; use super::rocket; use self::test::Bencher; use rocket::local::Client; use rocket::http::{Accept, ContentType}; #[bench] fn accept_format(b: &mut Bencher) { let client = Client::new(rocket()).unwrap(); let mut requests = vec![]; requests.push(client.get("/").header(Accept::JSON)); requests.push(client.get("/").header(Accept::HTML)); requests.push(client.get("/").header(Accept::Plain)); b.iter(|| { for request in requests.iter_mut() { request.mut_dispatch(); } }); } #[bench] fn content_type_format(b: &mut Bencher) { let client = Client::new(rocket()).unwrap(); let mut requests = vec![]; requests.push(client.post("/").header(ContentType::JSON)); requests.push(client.post("/").header(ContentType::HTML)); requests.push(client.post("/").header(ContentType::Plain)); b.iter(|| { for request in requests.iter_mut() { request.mut_dispatch(); } }); } }
get
identifier_name
pushrebase.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 anyhow::{anyhow, Error}; use blobrepo::BlobRepo; use blobstore::Loadable; use bookmarks::BookmarkName; use clap_old::{App, Arg, ArgMatches, SubCommand}; use fbinit::FacebookInit; use futures::TryFutureExt; use cmdlib::{ args::{self, MononokeMatches}, helpers, }; use context::CoreContext; use maplit::hashset; use metaconfig_types::BookmarkAttrs; use pushrebase::do_pushrebase_bonsai; use slog::Logger; use crate::error::SubcommandError; pub const ARG_BOOKMARK: &str = "bookmark"; pub const ARG_CSID: &str = "csid"; pub const PUSHREBASE: &str = "pushrebase"; pub fn build_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(PUSHREBASE) .about("pushrebases a commit to a bookmark") .arg( Arg::with_name(ARG_CSID) .long(ARG_CSID) .takes_value(true) .required(true) .help("{hg|bonsai} changeset id or bookmark name"), ) .arg( Arg::with_name(ARG_BOOKMARK) .long(ARG_BOOKMARK) .takes_value(true) .required(true) .help("name of the bookmark to pushrebase to"), ) } pub async fn subcommand_pushrebase<'a>( fb: FacebookInit, logger: Logger, matches: &'a MononokeMatches<'_>, sub_matches: &'a ArgMatches<'_>, ) -> Result<(), SubcommandError>
let pushrebase_hooks = bookmarks_movement::get_pushrebase_hooks( &ctx, &repo, &bookmark, &bookmark_attrs, &repo_config.pushrebase, ) .map_err(Error::from)?; let bcs = cs_id .load(&ctx, &repo.get_blobstore()) .map_err(Error::from) .await?; let pushrebase_res = do_pushrebase_bonsai( &ctx, &repo, &pushrebase_flags, &bookmark, &hashset![bcs], None, &pushrebase_hooks, ) .map_err(Error::from) .await?; println!("{}", pushrebase_res.head); Ok(()) }
{ let ctx = CoreContext::new_with_logger(fb, logger.clone()); let repo: BlobRepo = args::open_repo(fb, &logger, &matches).await?; let cs_id = sub_matches .value_of(ARG_CSID) .ok_or_else(|| anyhow!("{} arg is not specified", ARG_CSID))?; let cs_id = helpers::csid_resolve(&ctx, &repo, cs_id).await?; let bookmark = sub_matches .value_of(ARG_BOOKMARK) .ok_or_else(|| anyhow!("{} arg is not specified", ARG_BOOKMARK))?; let config_store = matches.config_store(); let (_, repo_config) = args::get_config(config_store, matches)?; let bookmark = BookmarkName::new(bookmark)?; let pushrebase_flags = repo_config.pushrebase.flags; let bookmark_attrs = BookmarkAttrs::new(fb, repo_config.bookmarks.clone()).await?;
identifier_body
pushrebase.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 anyhow::{anyhow, Error}; use blobrepo::BlobRepo; use blobstore::Loadable; use bookmarks::BookmarkName; use clap_old::{App, Arg, ArgMatches, SubCommand}; use fbinit::FacebookInit; use futures::TryFutureExt; use cmdlib::{ args::{self, MononokeMatches}, helpers, }; use context::CoreContext; use maplit::hashset; use metaconfig_types::BookmarkAttrs; use pushrebase::do_pushrebase_bonsai; use slog::Logger; use crate::error::SubcommandError; pub const ARG_BOOKMARK: &str = "bookmark"; pub const ARG_CSID: &str = "csid"; pub const PUSHREBASE: &str = "pushrebase"; pub fn
<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(PUSHREBASE) .about("pushrebases a commit to a bookmark") .arg( Arg::with_name(ARG_CSID) .long(ARG_CSID) .takes_value(true) .required(true) .help("{hg|bonsai} changeset id or bookmark name"), ) .arg( Arg::with_name(ARG_BOOKMARK) .long(ARG_BOOKMARK) .takes_value(true) .required(true) .help("name of the bookmark to pushrebase to"), ) } pub async fn subcommand_pushrebase<'a>( fb: FacebookInit, logger: Logger, matches: &'a MononokeMatches<'_>, sub_matches: &'a ArgMatches<'_>, ) -> Result<(), SubcommandError> { let ctx = CoreContext::new_with_logger(fb, logger.clone()); let repo: BlobRepo = args::open_repo(fb, &logger, &matches).await?; let cs_id = sub_matches .value_of(ARG_CSID) .ok_or_else(|| anyhow!("{} arg is not specified", ARG_CSID))?; let cs_id = helpers::csid_resolve(&ctx, &repo, cs_id).await?; let bookmark = sub_matches .value_of(ARG_BOOKMARK) .ok_or_else(|| anyhow!("{} arg is not specified", ARG_BOOKMARK))?; let config_store = matches.config_store(); let (_, repo_config) = args::get_config(config_store, matches)?; let bookmark = BookmarkName::new(bookmark)?; let pushrebase_flags = repo_config.pushrebase.flags; let bookmark_attrs = BookmarkAttrs::new(fb, repo_config.bookmarks.clone()).await?; let pushrebase_hooks = bookmarks_movement::get_pushrebase_hooks( &ctx, &repo, &bookmark, &bookmark_attrs, &repo_config.pushrebase, ) .map_err(Error::from)?; let bcs = cs_id .load(&ctx, &repo.get_blobstore()) .map_err(Error::from) .await?; let pushrebase_res = do_pushrebase_bonsai( &ctx, &repo, &pushrebase_flags, &bookmark, &hashset![bcs], None, &pushrebase_hooks, ) .map_err(Error::from) .await?; println!("{}", pushrebase_res.head); Ok(()) }
build_subcommand
identifier_name
pushrebase.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 anyhow::{anyhow, Error}; use blobrepo::BlobRepo; use blobstore::Loadable; use bookmarks::BookmarkName; use clap_old::{App, Arg, ArgMatches, SubCommand}; use fbinit::FacebookInit; use futures::TryFutureExt; use cmdlib::{ args::{self, MononokeMatches}, helpers, }; use context::CoreContext; use maplit::hashset; use metaconfig_types::BookmarkAttrs; use pushrebase::do_pushrebase_bonsai; use slog::Logger; use crate::error::SubcommandError; pub const ARG_BOOKMARK: &str = "bookmark"; pub const ARG_CSID: &str = "csid"; pub const PUSHREBASE: &str = "pushrebase"; pub fn build_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(PUSHREBASE) .about("pushrebases a commit to a bookmark") .arg( Arg::with_name(ARG_CSID) .long(ARG_CSID) .takes_value(true) .required(true) .help("{hg|bonsai} changeset id or bookmark name"), ) .arg( Arg::with_name(ARG_BOOKMARK) .long(ARG_BOOKMARK) .takes_value(true) .required(true) .help("name of the bookmark to pushrebase to"), ) } pub async fn subcommand_pushrebase<'a>( fb: FacebookInit, logger: Logger, matches: &'a MononokeMatches<'_>, sub_matches: &'a ArgMatches<'_>, ) -> Result<(), SubcommandError> { let ctx = CoreContext::new_with_logger(fb, logger.clone());
let repo: BlobRepo = args::open_repo(fb, &logger, &matches).await?; let cs_id = sub_matches .value_of(ARG_CSID) .ok_or_else(|| anyhow!("{} arg is not specified", ARG_CSID))?; let cs_id = helpers::csid_resolve(&ctx, &repo, cs_id).await?; let bookmark = sub_matches .value_of(ARG_BOOKMARK) .ok_or_else(|| anyhow!("{} arg is not specified", ARG_BOOKMARK))?; let config_store = matches.config_store(); let (_, repo_config) = args::get_config(config_store, matches)?; let bookmark = BookmarkName::new(bookmark)?; let pushrebase_flags = repo_config.pushrebase.flags; let bookmark_attrs = BookmarkAttrs::new(fb, repo_config.bookmarks.clone()).await?; let pushrebase_hooks = bookmarks_movement::get_pushrebase_hooks( &ctx, &repo, &bookmark, &bookmark_attrs, &repo_config.pushrebase, ) .map_err(Error::from)?; let bcs = cs_id .load(&ctx, &repo.get_blobstore()) .map_err(Error::from) .await?; let pushrebase_res = do_pushrebase_bonsai( &ctx, &repo, &pushrebase_flags, &bookmark, &hashset![bcs], None, &pushrebase_hooks, ) .map_err(Error::from) .await?; println!("{}", pushrebase_res.head); Ok(()) }
random_line_split
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use cssparser::{self, Color, RGBA}; use js::conversions::{FromJSValConvertible, ToJSValConvertible, latin1_to_string}; use js::jsapi::{JSContext, JSString, HandleValue, MutableHandleValue}; use js::jsapi::{JS_GetTwoByteStringCharsAndLength, JS_StringHasLatin1Chars}; use js::rust::ToString; use libc::c_char; use num_lib::ToPrimitive; use opts; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::char; use std::convert::AsRef; use std::ffi::CStr; use std::fmt; use std::iter::{Filter, Peekable}; use std::ops::{Deref, DerefMut}; use std::ptr; use std::slice; use std::str::{CharIndices, FromStr, Split, from_utf8}; #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Deserialize, Serialize, Hash, Debug)] pub struct DOMString(String); impl!Send for DOMString {} impl DOMString { pub fn new() -> DOMString { DOMString(String::new()) } // FIXME(ajeffrey): implement more of the String methods on DOMString? pub fn push_str(&mut self, string: &str) { self.0.push_str(string) } pub fn clear(&mut self) { self.0.clear() } } impl Default for DOMString { fn default() -> Self { DOMString(String::new()) } } impl Deref for DOMString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for DOMString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for DOMString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for DOMString { #[inline] fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for DOMString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for DOMString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for DOMString { fn from(contents: String) -> DOMString { DOMString(contents) } } impl<'a> From<&'a str> for DOMString { fn from(contents: &str) -> DOMString { DOMString::from(String::from(contents)) } } impl From<DOMString> for String { fn from(contents: DOMString) -> String { contents.0 } } impl Into<Vec<u8>> for DOMString { fn into(self) -> Vec<u8> { self.0.into() } } // https://heycam.github.io/webidl/#es-DOMString impl ToJSValConvertible for DOMString { unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { (**self).to_jsval(cx, rval); } } /// Behavior for stringification of `JSVal`s. #[derive(PartialEq)] pub enum StringificationBehavior { /// Convert `null` to the string `"null"`. Default, /// Convert `null` to the empty string. Empty, } /// Convert the given `JSString` to a `DOMString`. Fails if the string does not /// contain valid UTF-16. pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString { let latin1 = JS_StringHasLatin1Chars(s); DOMString(if latin1 { latin1_to_string(cx, s) } else { let mut length = 0; let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), s, &mut length); assert!(!chars.is_null()); let potentially_ill_formed_utf16 = slice::from_raw_parts(chars, length as usize); let mut s = String::with_capacity(length as usize); for item in char::decode_utf16(potentially_ill_formed_utf16.iter().cloned()) { match item { Ok(c) => s.push(c), Err(_) => { // FIXME: Add more info like document URL in the message? macro_rules! message { () => { "Found an unpaired surrogate in a DOM string. \ If you see this in real web content, \ please comment on https://github.com/servo/servo/issues/6564" } } if opts::get().replace_surrogates { error!(message!()); s.push('\u{FFFD}'); } else { panic!(concat!(message!(), " Use `-Z replace-surrogates` \ on the command line to make this non-fatal.")); } } } } s }) } // https://heycam.github.io/webidl/#es-DOMString impl FromJSValConvertible for DOMString { type Config = StringificationBehavior; unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, null_behavior: StringificationBehavior) -> Result<DOMString, ()> { if null_behavior == StringificationBehavior::Empty && value.get().is_null() { Ok(DOMString::new()) } else { let jsstr = ToString(cx, value); if jsstr.is_null() { debug!("ToString failed"); Err(()) } else { Ok(jsstring_to_str(cx, jsstr)) } } } } impl Extend<char> for DOMString { fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item=char> { self.0.extend(iterable) } } pub type StaticCharVec = &'static [char]; pub type StaticStringVec = &'static [&'static str]; /// Whitespace as defined by HTML5 § 2.4.1. // TODO(SimonSapin) Maybe a custom Pattern can be more efficient? const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d']; pub fn is_whitespace(s: &str) -> bool { s.chars().all(char_is_whitespace) } #[inline] pub fn char_is_whitespace(c: char) -> bool { WHITESPACE.contains(&c) } /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } fn is_ascii_digit(c: &char) -> bool { match *c { '0'...'9' => true, _ => false, } } fn read_numbers<I: Iterator<Item=char>>(mut iter: Peekable<I>) -> Option<i64> { match iter.peek() { Some(c) if is_ascii_digit(c) => (), _ => return None, } iter.take_while(is_ascii_digit).map(|d| { d as i64 - '0' as i64 }).fold(Some(0i64), |accumulator, d| { accumulator.and_then(|accumulator| { accumulator.checked_mul(10) }).and_then(|accumulator| { accumulator.checked_add(d) }) }) } /// Shared implementation to parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-integers> or /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-non-negative-integers> fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> { let mut input = input.skip_while(|c| { HTML_SPACE_CHARACTERS.iter().any(|s| s == c) }).peekable(); let sign = match input.peek() { None => return None, Some(&'-') => { input.next(); -1 }, Some(&'+') => { input.next(); 1 }, Some(_) => 1, }; let value = read_numbers(input); value.and_then(|value| value.checked_mul(sign)) } /// Parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-integers>. pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> { do_parse_integer(input).and_then(|result| { result.to_i32() }) } /// Parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-non-negative-integers> pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> { do_parse_integer(input).and_then(|result| { result.to_u32() }) } #[derive(Copy, Clone, Debug, PartialEq)] pub enum LengthOrPercentageOrAuto { Auto, Percentage(f32), Length(Au), } /// TODO: this function can be rewritten to return Result<LengthOrPercentage, _> /// Parses a dimension value per HTML5 § 2.4.4.4. If unparseable, `Auto` is /// returned. /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-dimension-values pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { // Steps 1 & 2 are not relevant // Step 3 value = value.trim_left_matches(WHITESPACE); // Step 4 if value.is_empty() { return LengthOrPercentageOrAuto::Auto } // Step 5 if value.starts_with("+") { value = &value[1..] } // Steps 6 & 7 match value.chars().nth(0) { Some('0'...'9') => {}, _ => return LengthOrPercentageOrAuto::Auto, } // Steps 8 to 13 // We trim the string length to the minimum of: // 1. the end of the string // 2. the first occurence of a '%' (U+0025 PERCENT SIGN) // 3. the second occurrence of a '.' (U+002E FULL STOP) // 4. the occurrence of a character that is neither a digit nor '%' nor '.' // Note: Step 10 is directly subsumed by FromStr::from_str let mut end_index = value.len(); let (mut found_full_stop, mut found_percent) = (false, false); for (i, ch) in value.chars().enumerate() { match ch { '0'...'9' => continue, '%' => { found_percent = true; end_index = i; break } '.' if!found_full_stop => { found_full_stop = true; continue } _ => { end_index = i; break } } } value = &value[..end_index]; if found_percent { let result: Result<f32, _> = FromStr::from_str(value); match result { Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0), Err(_) => return LengthOrPercentageOrAuto::Auto, } } match FromStr::from_str(value) { Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_f64_px(number)), Err(_) => LengthOrPercentageOrAuto::Auto, } } /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size pub fn parse_legacy_font_size(mut input: &str) -> Option<&'static str> { // Steps 1 & 2 are not relevant // Step 3 input = input.trim_matches(WHITESPACE); enum ParseMode { RelativePlus, RelativeMinus, Absolute, } let mut input_chars = input.chars().peekable(); let parse_mode = match input_chars.peek() { // Step 4 None => return None, // Step 5 Some(&'+') => { let _ = input_chars.next(); // consume the '+' ParseMode::RelativePlus } Some(&'-') => { let _ = input_chars.next(); // consume the '-' ParseMode::RelativeMinus } Some(_) => ParseMode::Absolute, }; // Steps 6, 7, 8 let mut value = match read_numbers(input_chars) { Some(v) => v, None => return None, }; // Step 9 match parse_mode { ParseMode::RelativePlus => value = 3 + value, ParseMode::RelativeMinus => value = 3 - value, ParseMode::Absolute => (), } // Steps 10, 11, 12 Some(match value { n if n >= 7 => "xxx-large", 6 => "xx-large", 5 => "x-large", 4 => "large", 3 => "medium", 2 => "small", n if n <= 1 => "x-small", _ => unreachable!(), }) } /// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned. pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> { // Steps 1 and 2. if input.is_empty() { return Err(()) } // Step 3. input = input.trim_matches(WHITESPACE); // Step 4. if input.eq_ignore_ascii_case("transparent") { return Err(()) } // Step 5. if let Ok(Color::RGBA(rgba)) = cssparser::parse_color_keyword(input) { return Ok(rgba); } // Step 6. if input.len() == 4 { match (input.as_bytes()[0], hex(input.as_bytes()[1] as char), hex(input.as_bytes()[2] as char), hex(input.as_bytes()[3] as char)) { (b'#', Ok(r), Ok(g), Ok(b)) => { return Ok(RGBA { red: (r as f32) * 17.0 / 255.0, green: (g as f32) * 17.0 / 255.0, blue: (b as f32) * 17.0 / 255.0, alpha: 1.0, }) } _ => {} } } // Step 7. let mut new_input = String::new(); for ch in input.chars() { if ch as u32 > 0xffff { new_input.push_str("00") } else { new_input.push(ch) } } let mut input = &*new_input; // Step 8. for (char_count, (index, _)) in input.char_indices().enumerate() { if char_count == 128 { input = &input[..index]; break } } // Step 9. if input.as_bytes()[0] == b'#' { input = &input[1..] } // Step 10. let mut new_input = Vec::new(); for ch in input.chars() { if hex(ch).is_ok() { new_input.push(ch as u8) } else { new_input.push(b'0') } } let mut input = new_input; // Step 11. while input.is_empty() || (input.len() % 3)!= 0 { input.push(b'0') } // Step 12. let mut length = input.len() / 3; let (mut red, mut green, mut blue) = (&input[..length], &input[length..length * 2], &input[length * 2..]); // Step 13. if length > 8 { red = &red[length - 8..]; green = &green[length - 8..]; blue = &blue[length - 8..]; length = 8 } // Step 14. while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' { red = &red[1..]; green = &green[1..]; blue = &blue[1..]; length -= 1 } // Steps 15-20. return Ok(RGBA { red: hex_string(red).unwrap() as f32 / 255.0, green: hex_string(green).unwrap() as f32 / 255.0, blue: hex_string(blue).unwrap() as f32 / 255.0, alpha: 1.0, }); fn hex(ch: char) -> Result<u8, ()> { match ch { '0'...'9' => Ok((ch as u8) - b'0'), 'a'...'f' => Ok((ch as u8) - b'a' + 10), 'A'...'F' => Ok((ch as u8) - b'A' + 10), _ => Err(()), } } fn hex_string(string: &[u8]) -> Result<u8, ()> { match string.len() { 0 => Err(()), 1 => hex(string[0] as char), _ => { let upper = try!(hex(string[0] as char)); let lower = try!(hex(string[1] as char)); Ok((upper << 4) | lower) } } } } #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct LowercaseString { inner: String, } impl LowercaseString { pub fn new(s: &str) -> LowercaseString { LowercaseString { inner: s.to_lowercase(), } } } impl Deref for LowercaseString { type Target = str; #[inline] fn deref(&self) -> &str { &*self.inner } } /// Creates a String from the given null-terminated buffer. /// Panics if the buffer does not contain UTF-8. pub unsafe fn c_str_to_string(s: *const c_char) -> String { from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned() } pub fn str_join<I, T>(strs: I, join: &str) -> String where I: IntoIterator<Item=T>, T: AsRef<str>, { strs.into_iter().enumerate().fold(String::new(), |mut acc, (i, s)| { if i > 0 { acc.push_str(join); } acc.push_str(s.as_ref()); acc }) } // Lifted from Rust's StrExt implementation, which is being removed. pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str { assert!(begin <= end); let mut count = 0; let mut begin_byte = None; let mut end_byte = None; // This could be even more efficient by not decoding, // only finding the char boundaries for (idx, _) in s.char_indices() { if count == begin { begin_byte = Some(idx); } if count == end { end_byte = Some(idx); break; } count += 1; } if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) } if end_byte.is_none() && count == end { end_byte = Some(s.len()) } match (begin_byte, end_byte) { (None, _) => panic!("slice_chars: `begin` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"), (Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) } } } // searches a character index in CharIndices // returns indices.count if not found pub fn search_index(index: usize, indices: CharIndices) -> isize { let mut character_count = 0; for (character_index, _) in indices { if character_index == index { return character_count; } character_count += 1 } character_count }
fmt
identifier_name
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use cssparser::{self, Color, RGBA}; use js::conversions::{FromJSValConvertible, ToJSValConvertible, latin1_to_string}; use js::jsapi::{JSContext, JSString, HandleValue, MutableHandleValue}; use js::jsapi::{JS_GetTwoByteStringCharsAndLength, JS_StringHasLatin1Chars}; use js::rust::ToString; use libc::c_char; use num_lib::ToPrimitive; use opts; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::char; use std::convert::AsRef; use std::ffi::CStr; use std::fmt; use std::iter::{Filter, Peekable}; use std::ops::{Deref, DerefMut}; use std::ptr; use std::slice; use std::str::{CharIndices, FromStr, Split, from_utf8}; #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Deserialize, Serialize, Hash, Debug)] pub struct DOMString(String); impl!Send for DOMString {} impl DOMString { pub fn new() -> DOMString { DOMString(String::new()) } // FIXME(ajeffrey): implement more of the String methods on DOMString? pub fn push_str(&mut self, string: &str) { self.0.push_str(string) } pub fn clear(&mut self) { self.0.clear() } } impl Default for DOMString { fn default() -> Self { DOMString(String::new()) } } impl Deref for DOMString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for DOMString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for DOMString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for DOMString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for DOMString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for DOMString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for DOMString { fn from(contents: String) -> DOMString { DOMString(contents) } } impl<'a> From<&'a str> for DOMString { fn from(contents: &str) -> DOMString { DOMString::from(String::from(contents)) } } impl From<DOMString> for String { fn from(contents: DOMString) -> String { contents.0 } } impl Into<Vec<u8>> for DOMString { fn into(self) -> Vec<u8> { self.0.into() } } // https://heycam.github.io/webidl/#es-DOMString impl ToJSValConvertible for DOMString { unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { (**self).to_jsval(cx, rval); } } /// Behavior for stringification of `JSVal`s. #[derive(PartialEq)] pub enum StringificationBehavior { /// Convert `null` to the string `"null"`. Default, /// Convert `null` to the empty string. Empty, } /// Convert the given `JSString` to a `DOMString`. Fails if the string does not /// contain valid UTF-16. pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString { let latin1 = JS_StringHasLatin1Chars(s); DOMString(if latin1 { latin1_to_string(cx, s) } else { let mut length = 0; let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), s, &mut length); assert!(!chars.is_null()); let potentially_ill_formed_utf16 = slice::from_raw_parts(chars, length as usize); let mut s = String::with_capacity(length as usize); for item in char::decode_utf16(potentially_ill_formed_utf16.iter().cloned()) { match item { Ok(c) => s.push(c), Err(_) => { // FIXME: Add more info like document URL in the message? macro_rules! message { () => { "Found an unpaired surrogate in a DOM string. \ If you see this in real web content, \ please comment on https://github.com/servo/servo/issues/6564" } } if opts::get().replace_surrogates { error!(message!()); s.push('\u{FFFD}'); } else { panic!(concat!(message!(), " Use `-Z replace-surrogates` \ on the command line to make this non-fatal.")); } } } } s }) } // https://heycam.github.io/webidl/#es-DOMString impl FromJSValConvertible for DOMString { type Config = StringificationBehavior; unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, null_behavior: StringificationBehavior) -> Result<DOMString, ()> { if null_behavior == StringificationBehavior::Empty && value.get().is_null() { Ok(DOMString::new()) } else { let jsstr = ToString(cx, value); if jsstr.is_null() { debug!("ToString failed"); Err(()) } else { Ok(jsstring_to_str(cx, jsstr)) } } } } impl Extend<char> for DOMString { fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item=char> { self.0.extend(iterable) } } pub type StaticCharVec = &'static [char]; pub type StaticStringVec = &'static [&'static str]; /// Whitespace as defined by HTML5 § 2.4.1. // TODO(SimonSapin) Maybe a custom Pattern can be more efficient? const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d']; pub fn is_whitespace(s: &str) -> bool { s.chars().all(char_is_whitespace) } #[inline] pub fn char_is_whitespace(c: char) -> bool { WHITESPACE.contains(&c) } /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } fn is_ascii_digit(c: &char) -> bool { match *c { '0'...'9' => true, _ => false, } } fn read_numbers<I: Iterator<Item=char>>(mut iter: Peekable<I>) -> Option<i64> { match iter.peek() { Some(c) if is_ascii_digit(c) => (), _ => return None, } iter.take_while(is_ascii_digit).map(|d| { d as i64 - '0' as i64 }).fold(Some(0i64), |accumulator, d| { accumulator.and_then(|accumulator| { accumulator.checked_mul(10) }).and_then(|accumulator| { accumulator.checked_add(d) }) }) } /// Shared implementation to parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-integers> or /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-non-negative-integers> fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> { let mut input = input.skip_while(|c| { HTML_SPACE_CHARACTERS.iter().any(|s| s == c) }).peekable(); let sign = match input.peek() { None => return None, Some(&'-') => { input.next(); -1 }, Some(&'+') => { input.next(); 1 }, Some(_) => 1, }; let value = read_numbers(input); value.and_then(|value| value.checked_mul(sign)) } /// Parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-integers>. pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> { do_parse_integer(input).and_then(|result| { result.to_i32() }) } /// Parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-non-negative-integers> pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> {
#[derive(Copy, Clone, Debug, PartialEq)] pub enum LengthOrPercentageOrAuto { Auto, Percentage(f32), Length(Au), } /// TODO: this function can be rewritten to return Result<LengthOrPercentage, _> /// Parses a dimension value per HTML5 § 2.4.4.4. If unparseable, `Auto` is /// returned. /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-dimension-values pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { // Steps 1 & 2 are not relevant // Step 3 value = value.trim_left_matches(WHITESPACE); // Step 4 if value.is_empty() { return LengthOrPercentageOrAuto::Auto } // Step 5 if value.starts_with("+") { value = &value[1..] } // Steps 6 & 7 match value.chars().nth(0) { Some('0'...'9') => {}, _ => return LengthOrPercentageOrAuto::Auto, } // Steps 8 to 13 // We trim the string length to the minimum of: // 1. the end of the string // 2. the first occurence of a '%' (U+0025 PERCENT SIGN) // 3. the second occurrence of a '.' (U+002E FULL STOP) // 4. the occurrence of a character that is neither a digit nor '%' nor '.' // Note: Step 10 is directly subsumed by FromStr::from_str let mut end_index = value.len(); let (mut found_full_stop, mut found_percent) = (false, false); for (i, ch) in value.chars().enumerate() { match ch { '0'...'9' => continue, '%' => { found_percent = true; end_index = i; break } '.' if!found_full_stop => { found_full_stop = true; continue } _ => { end_index = i; break } } } value = &value[..end_index]; if found_percent { let result: Result<f32, _> = FromStr::from_str(value); match result { Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0), Err(_) => return LengthOrPercentageOrAuto::Auto, } } match FromStr::from_str(value) { Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_f64_px(number)), Err(_) => LengthOrPercentageOrAuto::Auto, } } /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size pub fn parse_legacy_font_size(mut input: &str) -> Option<&'static str> { // Steps 1 & 2 are not relevant // Step 3 input = input.trim_matches(WHITESPACE); enum ParseMode { RelativePlus, RelativeMinus, Absolute, } let mut input_chars = input.chars().peekable(); let parse_mode = match input_chars.peek() { // Step 4 None => return None, // Step 5 Some(&'+') => { let _ = input_chars.next(); // consume the '+' ParseMode::RelativePlus } Some(&'-') => { let _ = input_chars.next(); // consume the '-' ParseMode::RelativeMinus } Some(_) => ParseMode::Absolute, }; // Steps 6, 7, 8 let mut value = match read_numbers(input_chars) { Some(v) => v, None => return None, }; // Step 9 match parse_mode { ParseMode::RelativePlus => value = 3 + value, ParseMode::RelativeMinus => value = 3 - value, ParseMode::Absolute => (), } // Steps 10, 11, 12 Some(match value { n if n >= 7 => "xxx-large", 6 => "xx-large", 5 => "x-large", 4 => "large", 3 => "medium", 2 => "small", n if n <= 1 => "x-small", _ => unreachable!(), }) } /// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned. pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> { // Steps 1 and 2. if input.is_empty() { return Err(()) } // Step 3. input = input.trim_matches(WHITESPACE); // Step 4. if input.eq_ignore_ascii_case("transparent") { return Err(()) } // Step 5. if let Ok(Color::RGBA(rgba)) = cssparser::parse_color_keyword(input) { return Ok(rgba); } // Step 6. if input.len() == 4 { match (input.as_bytes()[0], hex(input.as_bytes()[1] as char), hex(input.as_bytes()[2] as char), hex(input.as_bytes()[3] as char)) { (b'#', Ok(r), Ok(g), Ok(b)) => { return Ok(RGBA { red: (r as f32) * 17.0 / 255.0, green: (g as f32) * 17.0 / 255.0, blue: (b as f32) * 17.0 / 255.0, alpha: 1.0, }) } _ => {} } } // Step 7. let mut new_input = String::new(); for ch in input.chars() { if ch as u32 > 0xffff { new_input.push_str("00") } else { new_input.push(ch) } } let mut input = &*new_input; // Step 8. for (char_count, (index, _)) in input.char_indices().enumerate() { if char_count == 128 { input = &input[..index]; break } } // Step 9. if input.as_bytes()[0] == b'#' { input = &input[1..] } // Step 10. let mut new_input = Vec::new(); for ch in input.chars() { if hex(ch).is_ok() { new_input.push(ch as u8) } else { new_input.push(b'0') } } let mut input = new_input; // Step 11. while input.is_empty() || (input.len() % 3)!= 0 { input.push(b'0') } // Step 12. let mut length = input.len() / 3; let (mut red, mut green, mut blue) = (&input[..length], &input[length..length * 2], &input[length * 2..]); // Step 13. if length > 8 { red = &red[length - 8..]; green = &green[length - 8..]; blue = &blue[length - 8..]; length = 8 } // Step 14. while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' { red = &red[1..]; green = &green[1..]; blue = &blue[1..]; length -= 1 } // Steps 15-20. return Ok(RGBA { red: hex_string(red).unwrap() as f32 / 255.0, green: hex_string(green).unwrap() as f32 / 255.0, blue: hex_string(blue).unwrap() as f32 / 255.0, alpha: 1.0, }); fn hex(ch: char) -> Result<u8, ()> { match ch { '0'...'9' => Ok((ch as u8) - b'0'), 'a'...'f' => Ok((ch as u8) - b'a' + 10), 'A'...'F' => Ok((ch as u8) - b'A' + 10), _ => Err(()), } } fn hex_string(string: &[u8]) -> Result<u8, ()> { match string.len() { 0 => Err(()), 1 => hex(string[0] as char), _ => { let upper = try!(hex(string[0] as char)); let lower = try!(hex(string[1] as char)); Ok((upper << 4) | lower) } } } } #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct LowercaseString { inner: String, } impl LowercaseString { pub fn new(s: &str) -> LowercaseString { LowercaseString { inner: s.to_lowercase(), } } } impl Deref for LowercaseString { type Target = str; #[inline] fn deref(&self) -> &str { &*self.inner } } /// Creates a String from the given null-terminated buffer. /// Panics if the buffer does not contain UTF-8. pub unsafe fn c_str_to_string(s: *const c_char) -> String { from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned() } pub fn str_join<I, T>(strs: I, join: &str) -> String where I: IntoIterator<Item=T>, T: AsRef<str>, { strs.into_iter().enumerate().fold(String::new(), |mut acc, (i, s)| { if i > 0 { acc.push_str(join); } acc.push_str(s.as_ref()); acc }) } // Lifted from Rust's StrExt implementation, which is being removed. pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str { assert!(begin <= end); let mut count = 0; let mut begin_byte = None; let mut end_byte = None; // This could be even more efficient by not decoding, // only finding the char boundaries for (idx, _) in s.char_indices() { if count == begin { begin_byte = Some(idx); } if count == end { end_byte = Some(idx); break; } count += 1; } if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) } if end_byte.is_none() && count == end { end_byte = Some(s.len()) } match (begin_byte, end_byte) { (None, _) => panic!("slice_chars: `begin` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"), (Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) } } } // searches a character index in CharIndices // returns indices.count if not found pub fn search_index(index: usize, indices: CharIndices) -> isize { let mut character_count = 0; for (character_index, _) in indices { if character_index == index { return character_count; } character_count += 1 } character_count }
do_parse_integer(input).and_then(|result| { result.to_u32() }) }
identifier_body
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use cssparser::{self, Color, RGBA}; use js::conversions::{FromJSValConvertible, ToJSValConvertible, latin1_to_string}; use js::jsapi::{JSContext, JSString, HandleValue, MutableHandleValue}; use js::jsapi::{JS_GetTwoByteStringCharsAndLength, JS_StringHasLatin1Chars}; use js::rust::ToString; use libc::c_char; use num_lib::ToPrimitive; use opts; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::char; use std::convert::AsRef; use std::ffi::CStr; use std::fmt; use std::iter::{Filter, Peekable}; use std::ops::{Deref, DerefMut}; use std::ptr; use std::slice; use std::str::{CharIndices, FromStr, Split, from_utf8}; #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Deserialize, Serialize, Hash, Debug)] pub struct DOMString(String); impl!Send for DOMString {} impl DOMString { pub fn new() -> DOMString { DOMString(String::new()) } // FIXME(ajeffrey): implement more of the String methods on DOMString? pub fn push_str(&mut self, string: &str) { self.0.push_str(string) } pub fn clear(&mut self) { self.0.clear() } } impl Default for DOMString { fn default() -> Self { DOMString(String::new()) } } impl Deref for DOMString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for DOMString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for DOMString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for DOMString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for DOMString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for DOMString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for DOMString { fn from(contents: String) -> DOMString { DOMString(contents) } } impl<'a> From<&'a str> for DOMString { fn from(contents: &str) -> DOMString { DOMString::from(String::from(contents)) } } impl From<DOMString> for String { fn from(contents: DOMString) -> String { contents.0 } } impl Into<Vec<u8>> for DOMString { fn into(self) -> Vec<u8> { self.0.into() } } // https://heycam.github.io/webidl/#es-DOMString impl ToJSValConvertible for DOMString { unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { (**self).to_jsval(cx, rval); } } /// Behavior for stringification of `JSVal`s. #[derive(PartialEq)] pub enum StringificationBehavior { /// Convert `null` to the string `"null"`. Default, /// Convert `null` to the empty string. Empty, } /// Convert the given `JSString` to a `DOMString`. Fails if the string does not /// contain valid UTF-16. pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString { let latin1 = JS_StringHasLatin1Chars(s); DOMString(if latin1 { latin1_to_string(cx, s) } else { let mut length = 0; let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), s, &mut length); assert!(!chars.is_null()); let potentially_ill_formed_utf16 = slice::from_raw_parts(chars, length as usize); let mut s = String::with_capacity(length as usize); for item in char::decode_utf16(potentially_ill_formed_utf16.iter().cloned()) { match item { Ok(c) => s.push(c), Err(_) => { // FIXME: Add more info like document URL in the message? macro_rules! message { () => { "Found an unpaired surrogate in a DOM string. \ If you see this in real web content, \ please comment on https://github.com/servo/servo/issues/6564" } } if opts::get().replace_surrogates { error!(message!()); s.push('\u{FFFD}'); } else { panic!(concat!(message!(), " Use `-Z replace-surrogates` \ on the command line to make this non-fatal.")); } } } } s }) } // https://heycam.github.io/webidl/#es-DOMString impl FromJSValConvertible for DOMString { type Config = StringificationBehavior; unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, null_behavior: StringificationBehavior) -> Result<DOMString, ()> { if null_behavior == StringificationBehavior::Empty && value.get().is_null() { Ok(DOMString::new()) } else { let jsstr = ToString(cx, value); if jsstr.is_null() { debug!("ToString failed"); Err(()) } else { Ok(jsstring_to_str(cx, jsstr)) } } } } impl Extend<char> for DOMString { fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item=char> { self.0.extend(iterable) } } pub type StaticCharVec = &'static [char]; pub type StaticStringVec = &'static [&'static str]; /// Whitespace as defined by HTML5 § 2.4.1. // TODO(SimonSapin) Maybe a custom Pattern can be more efficient? const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d']; pub fn is_whitespace(s: &str) -> bool { s.chars().all(char_is_whitespace) } #[inline] pub fn char_is_whitespace(c: char) -> bool { WHITESPACE.contains(&c) } /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } fn is_ascii_digit(c: &char) -> bool { match *c { '0'...'9' => true, _ => false, } } fn read_numbers<I: Iterator<Item=char>>(mut iter: Peekable<I>) -> Option<i64> { match iter.peek() { Some(c) if is_ascii_digit(c) => (), _ => return None, } iter.take_while(is_ascii_digit).map(|d| { d as i64 - '0' as i64 }).fold(Some(0i64), |accumulator, d| { accumulator.and_then(|accumulator| { accumulator.checked_mul(10) }).and_then(|accumulator| { accumulator.checked_add(d) }) }) } /// Shared implementation to parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-integers> or /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-non-negative-integers> fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> { let mut input = input.skip_while(|c| { HTML_SPACE_CHARACTERS.iter().any(|s| s == c) }).peekable(); let sign = match input.peek() { None => return None, Some(&'-') => { input.next(); -1 }, Some(&'+') => { input.next(); 1 }, Some(_) => 1, }; let value = read_numbers(input); value.and_then(|value| value.checked_mul(sign)) } /// Parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-integers>. pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> { do_parse_integer(input).and_then(|result| { result.to_i32() }) } /// Parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-non-negative-integers> pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> { do_parse_integer(input).and_then(|result| { result.to_u32() }) } #[derive(Copy, Clone, Debug, PartialEq)] pub enum LengthOrPercentageOrAuto { Auto, Percentage(f32), Length(Au), } /// TODO: this function can be rewritten to return Result<LengthOrPercentage, _> /// Parses a dimension value per HTML5 § 2.4.4.4. If unparseable, `Auto` is /// returned. /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-dimension-values pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { // Steps 1 & 2 are not relevant // Step 3 value = value.trim_left_matches(WHITESPACE); // Step 4 if value.is_empty() { return LengthOrPercentageOrAuto::Auto } // Step 5 if value.starts_with("+") { value = &value[1..] } // Steps 6 & 7 match value.chars().nth(0) { Some('0'...'9') => {}, _ => return LengthOrPercentageOrAuto::Auto, } // Steps 8 to 13 // We trim the string length to the minimum of: // 1. the end of the string // 2. the first occurence of a '%' (U+0025 PERCENT SIGN) // 3. the second occurrence of a '.' (U+002E FULL STOP) // 4. the occurrence of a character that is neither a digit nor '%' nor '.' // Note: Step 10 is directly subsumed by FromStr::from_str let mut end_index = value.len(); let (mut found_full_stop, mut found_percent) = (false, false); for (i, ch) in value.chars().enumerate() { match ch { '0'...'9' => continue, '%' => { found_percent = true; end_index = i; break } '.' if!found_full_stop => { found_full_stop = true; continue } _ => { end_index = i; break } } } value = &value[..end_index]; if found_percent { let result: Result<f32, _> = FromStr::from_str(value); match result { Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0), Err(_) => return LengthOrPercentageOrAuto::Auto, } } match FromStr::from_str(value) { Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_f64_px(number)), Err(_) => LengthOrPercentageOrAuto::Auto, } } /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size pub fn parse_legacy_font_size(mut input: &str) -> Option<&'static str> { // Steps 1 & 2 are not relevant // Step 3 input = input.trim_matches(WHITESPACE); enum ParseMode { RelativePlus, RelativeMinus, Absolute, } let mut input_chars = input.chars().peekable(); let parse_mode = match input_chars.peek() { // Step 4 None => return None, // Step 5 Some(&'+') => { let _ = input_chars.next(); // consume the '+' ParseMode::RelativePlus } Some(&'-') => { let _ = input_chars.next(); // consume the '-' ParseMode::RelativeMinus } Some(_) => ParseMode::Absolute, }; // Steps 6, 7, 8 let mut value = match read_numbers(input_chars) { Some(v) => v, None => return None, }; // Step 9 match parse_mode { ParseMode::RelativePlus => value = 3 + value, ParseMode::RelativeMinus => value = 3 - value, ParseMode::Absolute => (), } // Steps 10, 11, 12 Some(match value { n if n >= 7 => "xxx-large", 6 => "xx-large", 5 => "x-large", 4 => "large", 3 => "medium", 2 => "small", n if n <= 1 => "x-small", _ => unreachable!(), }) } /// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned. pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> { // Steps 1 and 2. if input.is_empty() { return Err(()) } // Step 3. input = input.trim_matches(WHITESPACE); // Step 4. if input.eq_ignore_ascii_case("transparent") { return Err(()) } // Step 5. if let Ok(Color::RGBA(rgba)) = cssparser::parse_color_keyword(input) { return Ok(rgba); } // Step 6. if input.len() == 4 { match (input.as_bytes()[0], hex(input.as_bytes()[1] as char), hex(input.as_bytes()[2] as char), hex(input.as_bytes()[3] as char)) { (b'#', Ok(r), Ok(g), Ok(b)) => { return Ok(RGBA { red: (r as f32) * 17.0 / 255.0, green: (g as f32) * 17.0 / 255.0, blue: (b as f32) * 17.0 / 255.0, alpha: 1.0, }) } _ => {} } } // Step 7. let mut new_input = String::new(); for ch in input.chars() { if ch as u32 > 0xffff { new_input.push_str("00") } else { new_input.push(ch) } } let mut input = &*new_input; // Step 8. for (char_count, (index, _)) in input.char_indices().enumerate() { if char_count == 128 { input = &input[..index]; break } } // Step 9. if input.as_bytes()[0] == b'#' { input = &input[1..] } // Step 10. let mut new_input = Vec::new(); for ch in input.chars() { if hex(ch).is_ok() { new_input.push(ch as u8) } else { new_input.push(b'0') } } let mut input = new_input; // Step 11. while input.is_empty() || (input.len() % 3)!= 0 { input.push(b'0') } // Step 12. let mut length = input.len() / 3; let (mut red, mut green, mut blue) = (&input[..length], &input[length..length * 2], &input[length * 2..]); // Step 13. if length > 8 { red = &red[length - 8..]; green = &green[length - 8..]; blue = &blue[length - 8..]; length = 8 } // Step 14. while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' { red = &red[1..]; green = &green[1..]; blue = &blue[1..]; length -= 1 } // Steps 15-20. return Ok(RGBA { red: hex_string(red).unwrap() as f32 / 255.0, green: hex_string(green).unwrap() as f32 / 255.0, blue: hex_string(blue).unwrap() as f32 / 255.0, alpha: 1.0, }); fn hex(ch: char) -> Result<u8, ()> { match ch { '0'...'9' => Ok((ch as u8) - b'0'), 'a'...'f' => Ok((ch as u8) - b'a' + 10), 'A'...'F' => Ok((ch as u8) - b'A' + 10), _ => Err(()), } } fn hex_string(string: &[u8]) -> Result<u8, ()> { match string.len() { 0 => Err(()), 1 => hex(string[0] as char), _ => { let upper = try!(hex(string[0] as char)); let lower = try!(hex(string[1] as char)); Ok((upper << 4) | lower) } } } } #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct LowercaseString { inner: String, } impl LowercaseString { pub fn new(s: &str) -> LowercaseString { LowercaseString { inner: s.to_lowercase(), } } }
type Target = str; #[inline] fn deref(&self) -> &str { &*self.inner } } /// Creates a String from the given null-terminated buffer. /// Panics if the buffer does not contain UTF-8. pub unsafe fn c_str_to_string(s: *const c_char) -> String { from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned() } pub fn str_join<I, T>(strs: I, join: &str) -> String where I: IntoIterator<Item=T>, T: AsRef<str>, { strs.into_iter().enumerate().fold(String::new(), |mut acc, (i, s)| { if i > 0 { acc.push_str(join); } acc.push_str(s.as_ref()); acc }) } // Lifted from Rust's StrExt implementation, which is being removed. pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str { assert!(begin <= end); let mut count = 0; let mut begin_byte = None; let mut end_byte = None; // This could be even more efficient by not decoding, // only finding the char boundaries for (idx, _) in s.char_indices() { if count == begin { begin_byte = Some(idx); } if count == end { end_byte = Some(idx); break; } count += 1; } if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) } if end_byte.is_none() && count == end { end_byte = Some(s.len()) } match (begin_byte, end_byte) { (None, _) => panic!("slice_chars: `begin` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"), (Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) } } } // searches a character index in CharIndices // returns indices.count if not found pub fn search_index(index: usize, indices: CharIndices) -> isize { let mut character_count = 0; for (character_index, _) in indices { if character_index == index { return character_count; } character_count += 1 } character_count }
impl Deref for LowercaseString {
random_line_split
str.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; use cssparser::{self, Color, RGBA}; use js::conversions::{FromJSValConvertible, ToJSValConvertible, latin1_to_string}; use js::jsapi::{JSContext, JSString, HandleValue, MutableHandleValue}; use js::jsapi::{JS_GetTwoByteStringCharsAndLength, JS_StringHasLatin1Chars}; use js::rust::ToString; use libc::c_char; use num_lib::ToPrimitive; use opts; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::char; use std::convert::AsRef; use std::ffi::CStr; use std::fmt; use std::iter::{Filter, Peekable}; use std::ops::{Deref, DerefMut}; use std::ptr; use std::slice; use std::str::{CharIndices, FromStr, Split, from_utf8}; #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Deserialize, Serialize, Hash, Debug)] pub struct DOMString(String); impl!Send for DOMString {} impl DOMString { pub fn new() -> DOMString { DOMString(String::new()) } // FIXME(ajeffrey): implement more of the String methods on DOMString? pub fn push_str(&mut self, string: &str) { self.0.push_str(string) } pub fn clear(&mut self) { self.0.clear() } } impl Default for DOMString { fn default() -> Self { DOMString(String::new()) } } impl Deref for DOMString { type Target = str; #[inline] fn deref(&self) -> &str { &self.0 } } impl DerefMut for DOMString { #[inline] fn deref_mut(&mut self) -> &mut str { &mut self.0 } } impl AsRef<str> for DOMString { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for DOMString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl PartialEq<str> for DOMString { fn eq(&self, other: &str) -> bool { &**self == other } } impl<'a> PartialEq<&'a str> for DOMString { fn eq(&self, other: &&'a str) -> bool { &**self == *other } } impl From<String> for DOMString { fn from(contents: String) -> DOMString { DOMString(contents) } } impl<'a> From<&'a str> for DOMString { fn from(contents: &str) -> DOMString { DOMString::from(String::from(contents)) } } impl From<DOMString> for String { fn from(contents: DOMString) -> String { contents.0 } } impl Into<Vec<u8>> for DOMString { fn into(self) -> Vec<u8> { self.0.into() } } // https://heycam.github.io/webidl/#es-DOMString impl ToJSValConvertible for DOMString { unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { (**self).to_jsval(cx, rval); } } /// Behavior for stringification of `JSVal`s. #[derive(PartialEq)] pub enum StringificationBehavior { /// Convert `null` to the string `"null"`. Default, /// Convert `null` to the empty string. Empty, } /// Convert the given `JSString` to a `DOMString`. Fails if the string does not /// contain valid UTF-16. pub unsafe fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString { let latin1 = JS_StringHasLatin1Chars(s); DOMString(if latin1 { latin1_to_string(cx, s) } else { let mut length = 0; let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), s, &mut length); assert!(!chars.is_null()); let potentially_ill_formed_utf16 = slice::from_raw_parts(chars, length as usize); let mut s = String::with_capacity(length as usize); for item in char::decode_utf16(potentially_ill_formed_utf16.iter().cloned()) { match item { Ok(c) => s.push(c), Err(_) => { // FIXME: Add more info like document URL in the message? macro_rules! message { () => { "Found an unpaired surrogate in a DOM string. \ If you see this in real web content, \ please comment on https://github.com/servo/servo/issues/6564" } } if opts::get().replace_surrogates { error!(message!()); s.push('\u{FFFD}'); } else { panic!(concat!(message!(), " Use `-Z replace-surrogates` \ on the command line to make this non-fatal.")); } } } } s }) } // https://heycam.github.io/webidl/#es-DOMString impl FromJSValConvertible for DOMString { type Config = StringificationBehavior; unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, null_behavior: StringificationBehavior) -> Result<DOMString, ()> { if null_behavior == StringificationBehavior::Empty && value.get().is_null() { Ok(DOMString::new()) } else { let jsstr = ToString(cx, value); if jsstr.is_null() { debug!("ToString failed"); Err(()) } else { Ok(jsstring_to_str(cx, jsstr)) } } } } impl Extend<char> for DOMString { fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item=char> { self.0.extend(iterable) } } pub type StaticCharVec = &'static [char]; pub type StaticStringVec = &'static [&'static str]; /// Whitespace as defined by HTML5 § 2.4.1. // TODO(SimonSapin) Maybe a custom Pattern can be more efficient? const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d']; pub fn is_whitespace(s: &str) -> bool { s.chars().all(char_is_whitespace) } #[inline] pub fn char_is_whitespace(c: char) -> bool { WHITESPACE.contains(&c) } /// A "space character" according to: /// /// https://html.spec.whatwg.org/multipage/#space-character pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ '\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}', ]; pub fn split_html_space_chars<'a>(s: &'a str) -> Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> { fn not_empty(&split: &&str) -> bool {!split.is_empty() } s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } fn is_ascii_digit(c: &char) -> bool { match *c { '0'...'9' => true, _ => false, } } fn read_numbers<I: Iterator<Item=char>>(mut iter: Peekable<I>) -> Option<i64> { match iter.peek() { Some(c) if is_ascii_digit(c) => (), _ => return None, } iter.take_while(is_ascii_digit).map(|d| { d as i64 - '0' as i64 }).fold(Some(0i64), |accumulator, d| { accumulator.and_then(|accumulator| { accumulator.checked_mul(10) }).and_then(|accumulator| { accumulator.checked_add(d) }) }) } /// Shared implementation to parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-integers> or /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-non-negative-integers> fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> { let mut input = input.skip_while(|c| { HTML_SPACE_CHARACTERS.iter().any(|s| s == c) }).peekable(); let sign = match input.peek() { None => return None, Some(&'-') => { input.next(); -1 }, Some(&'+') => { input.next(); 1 }, Some(_) => 1, }; let value = read_numbers(input); value.and_then(|value| value.checked_mul(sign)) } /// Parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-integers>. pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> { do_parse_integer(input).and_then(|result| { result.to_i32() }) } /// Parse an integer according to /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-non-negative-integers> pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> { do_parse_integer(input).and_then(|result| { result.to_u32() }) } #[derive(Copy, Clone, Debug, PartialEq)] pub enum LengthOrPercentageOrAuto { Auto, Percentage(f32), Length(Au), } /// TODO: this function can be rewritten to return Result<LengthOrPercentage, _> /// Parses a dimension value per HTML5 § 2.4.4.4. If unparseable, `Auto` is /// returned. /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-dimension-values pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto { // Steps 1 & 2 are not relevant // Step 3 value = value.trim_left_matches(WHITESPACE); // Step 4 if value.is_empty() { return LengthOrPercentageOrAuto::Auto } // Step 5 if value.starts_with("+") { value = &value[1..] } // Steps 6 & 7 match value.chars().nth(0) { Some('0'...'9') => {}, _ => return LengthOrPercentageOrAuto::Auto, } // Steps 8 to 13 // We trim the string length to the minimum of: // 1. the end of the string // 2. the first occurence of a '%' (U+0025 PERCENT SIGN) // 3. the second occurrence of a '.' (U+002E FULL STOP) // 4. the occurrence of a character that is neither a digit nor '%' nor '.' // Note: Step 10 is directly subsumed by FromStr::from_str let mut end_index = value.len(); let (mut found_full_stop, mut found_percent) = (false, false); for (i, ch) in value.chars().enumerate() { match ch { '0'...'9' => continue, '%' => { found_percent = true; end_index = i; break } '.' if!found_full_stop => { found_full_stop = true; continue } _ => { end_index = i; break } } } value = &value[..end_index]; if found_percent { let result: Result<f32, _> = FromStr::from_str(value); match result { Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0), Err(_) => return LengthOrPercentageOrAuto::Auto, } } match FromStr::from_str(value) { Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_f64_px(number)), Err(_) => LengthOrPercentageOrAuto::Auto, } } /// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size pub fn parse_legacy_font_size(mut input: &str) -> Option<&'static str> { // Steps 1 & 2 are not relevant // Step 3 input = input.trim_matches(WHITESPACE); enum ParseMode { RelativePlus, RelativeMinus, Absolute, } let mut input_chars = input.chars().peekable(); let parse_mode = match input_chars.peek() { // Step 4 None => return None, // Step 5 Some(&'+') => { let _ = input_chars.next(); // consume the '+' ParseMode::RelativePlus } Some(&'-') => { let _ = input_chars.next(); // consume the '-' ParseMode::RelativeMinus } Some(_) => ParseMode::Absolute, }; // Steps 6, 7, 8 let mut value = match read_numbers(input_chars) { Some(v) => v, None => return None, }; // Step 9 match parse_mode { ParseMode::RelativePlus => value = 3 + value, ParseMode::RelativeMinus => value = 3 - value, ParseMode::Absolute => (), } // Steps 10, 11, 12 Some(match value { n if n >= 7 => "xxx-large", 6 => "xx-large", 5 => "x-large", 4 => "large", 3 => "medium", 2 => "small", n if n <= 1 => "x-small", _ => unreachable!(), }) } /// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned. pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> { // Steps 1 and 2. if input.is_empty() { return Err(()) } // Step 3. input = input.trim_matches(WHITESPACE); // Step 4. if input.eq_ignore_ascii_case("transparent") { return Err(()) } // Step 5. if let Ok(Color::RGBA(rgba)) = cssparser::parse_color_keyword(input) { return Ok(rgba); } // Step 6. if input.len() == 4 { match (input.as_bytes()[0], hex(input.as_bytes()[1] as char), hex(input.as_bytes()[2] as char), hex(input.as_bytes()[3] as char)) { (b'#', Ok(r), Ok(g), Ok(b)) => { return Ok(RGBA { red: (r as f32) * 17.0 / 255.0, green: (g as f32) * 17.0 / 255.0, blue: (b as f32) * 17.0 / 255.0, alpha: 1.0, }) } _ => {} } } // Step 7. let mut new_input = String::new(); for ch in input.chars() { if ch as u32 > 0xffff { new_input.push_str("00") } else { new_input.push(ch) } } let mut input = &*new_input; // Step 8. for (char_count, (index, _)) in input.char_indices().enumerate() { if char_count == 128 { input = &input[..index]; break } } // Step 9. if input.as_bytes()[0] == b'#' { input = &input[1..] } // Step 10. let mut new_input = Vec::new(); for ch in input.chars() { if hex(ch).is_ok() { new_input.push(ch as u8) } else { new_input.push(b'0') } } let mut input = new_input; // Step 11. while input.is_empty() || (input.len() % 3)!= 0 { input.push(b'0') } // Step 12. let mut length = input.len() / 3; let (mut red, mut green, mut blue) = (&input[..length], &input[length..length * 2], &input[length * 2..]); // Step 13. if length > 8 { red = &red[length - 8..]; green = &green[length - 8..]; blue = &blue[length - 8..]; length = 8 } // Step 14. while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' { red = &red[1..]; green = &green[1..]; blue = &blue[1..]; length -= 1 } // Steps 15-20. return Ok(RGBA { red: hex_string(red).unwrap() as f32 / 255.0, green: hex_string(green).unwrap() as f32 / 255.0, blue: hex_string(blue).unwrap() as f32 / 255.0, alpha: 1.0, }); fn hex(ch: char) -> Result<u8, ()> { match ch { '0'...'9' => Ok((ch as u8) - b'0'), 'a'...'f' => Ok((ch as u8) - b'a' + 10), 'A'...'F' => Ok((ch as u8) - b'A' + 10), _ => Err(()), } } fn hex_string(string: &[u8]) -> Result<u8, ()> { match string.len() { 0 => Err(()), 1 => hex(string[0] as char), _ => {
} } } #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct LowercaseString { inner: String, } impl LowercaseString { pub fn new(s: &str) -> LowercaseString { LowercaseString { inner: s.to_lowercase(), } } } impl Deref for LowercaseString { type Target = str; #[inline] fn deref(&self) -> &str { &*self.inner } } /// Creates a String from the given null-terminated buffer. /// Panics if the buffer does not contain UTF-8. pub unsafe fn c_str_to_string(s: *const c_char) -> String { from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned() } pub fn str_join<I, T>(strs: I, join: &str) -> String where I: IntoIterator<Item=T>, T: AsRef<str>, { strs.into_iter().enumerate().fold(String::new(), |mut acc, (i, s)| { if i > 0 { acc.push_str(join); } acc.push_str(s.as_ref()); acc }) } // Lifted from Rust's StrExt implementation, which is being removed. pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str { assert!(begin <= end); let mut count = 0; let mut begin_byte = None; let mut end_byte = None; // This could be even more efficient by not decoding, // only finding the char boundaries for (idx, _) in s.char_indices() { if count == begin { begin_byte = Some(idx); } if count == end { end_byte = Some(idx); break; } count += 1; } if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) } if end_byte.is_none() && count == end { end_byte = Some(s.len()) } match (begin_byte, end_byte) { (None, _) => panic!("slice_chars: `begin` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"), (Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) } } } // searches a character index in CharIndices // returns indices.count if not found pub fn search_index(index: usize, indices: CharIndices) -> isize { let mut character_count = 0; for (character_index, _) in indices { if character_index == index { return character_count; } character_count += 1 } character_count }
let upper = try!(hex(string[0] as char)); let lower = try!(hex(string[1] as char)); Ok((upper << 4) | lower) }
conditional_block
atlas.rs
use std::collections::HashMap; use ui::lit::Lit; #[derive(Serialize, Deserialize)] pub struct TexmapBucket(pub HashMap<String, Texmap>); #[derive(Serialize, Deserialize)] pub struct Texmap(pub HashMap<String, TextureSelection>); impl Texmap { pub fn
(name: String) -> Self { let mut map = HashMap::new(); map.insert(name, TextureSelection::identity()); Texmap(map) } } #[derive(Copy, Clone, Debug, Serialize, Deserialize)] /// A selection in UV space: bottom left is [0.0, 0.0], top right is [1.0, 1.0] pub struct TextureSelection { pub min: [Lit; 2], pub size: [Lit; 2] } impl TextureSelection { pub fn identity() -> Self { TextureSelection { min: [Lit::from_part(0.0), Lit::from_part(0.0)], size: [Lit::from_part(1.0), Lit::from_part(1.0)] } } }
new
identifier_name
atlas.rs
use std::collections::HashMap; use ui::lit::Lit; #[derive(Serialize, Deserialize)] pub struct TexmapBucket(pub HashMap<String, Texmap>); #[derive(Serialize, Deserialize)] pub struct Texmap(pub HashMap<String, TextureSelection>); impl Texmap { pub fn new(name: String) -> Self { let mut map = HashMap::new(); map.insert(name, TextureSelection::identity()); Texmap(map) } } #[derive(Copy, Clone, Debug, Serialize, Deserialize)] /// A selection in UV space: bottom left is [0.0, 0.0], top right is [1.0, 1.0] pub struct TextureSelection { pub min: [Lit; 2], pub size: [Lit; 2] } impl TextureSelection { pub fn identity() -> Self { TextureSelection { min: [Lit::from_part(0.0), Lit::from_part(0.0)],
size: [Lit::from_part(1.0), Lit::from_part(1.0)] } } }
random_line_split
mod.rs
// Copyright 2015-2017 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/>. //! Trie interface and implementation. use hash::H256; use hashdb::{HashDB, DBValue}; use std::fmt; /// Export the standardmap module. pub mod standardmap; /// Export the node module. pub mod node; /// Export the triedb module. pub mod triedb; /// Export the triedbmut module. pub mod triedbmut; /// Export the sectriedb module. pub mod sectriedb; /// Export the sectriedbmut module. pub mod sectriedbmut; /// Trie query recording. pub mod recorder; mod fatdb; mod fatdbmut; mod lookup; pub use self::fatdb::{FatDB, FatDBIterator}; pub use self::fatdbmut::FatDBMut; pub use self::recorder::Recorder; pub use self::sectriedb::SecTrieDB; pub use self::sectriedbmut::SecTrieDBMut; pub use self::standardmap::{Alphabet, StandardMap, ValueMode}; pub use self::triedb::{TrieDB, TrieDBIterator}; pub use self::triedbmut::TrieDBMut; /// Trie Errors. /// /// These borrow the data within them to avoid excessive copying on every /// trie operation. #[derive(Debug, PartialEq, Eq, Clone)] pub enum TrieError { /// Attempted to create a trie with a state root not in the DB. InvalidStateRoot(H256), /// Trie item not found in the database, IncompleteDatabase(H256), } impl fmt::Display for TrieError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TrieError::InvalidStateRoot(ref root) => write!(f, "Invalid state root: {}", root), TrieError::IncompleteDatabase(ref missing) => write!(f, "Database missing expected key: {}", missing), } } } /// Trie result type. Boxed to avoid copying around extra space for `H256`s on successful queries. pub type Result<T> = ::std::result::Result<T, Box<TrieError>>; /// Trie-Item type. pub type TrieItem<'a> = Result<(Vec<u8>, DBValue)>; /// Description of what kind of query will be made to the trie. /// /// This is implemented for any &mut recorder (where the query will return /// a DBValue), any function taking raw bytes (where no recording will be made), /// or any tuple of (&mut Recorder, FnOnce(&[u8])) pub trait Query { /// Output item. type Item; /// Decode a byte-slice into the desired item. fn decode(self, &[u8]) -> Self::Item; /// Record that a node has been passed through. fn record(&mut self, &H256, &[u8], u32) {} } impl<'a> Query for &'a mut Recorder { type Item = DBValue; fn decode(self, value: &[u8]) -> DBValue { DBValue::from_slice(value) } fn record(&mut self, hash: &H256, data: &[u8], depth: u32) { (&mut **self).record(hash, data, depth); } } impl<F, T> Query for F where F: for<'a> FnOnce(&'a [u8]) -> T, { type Item = T; fn decode(self, value: &[u8]) -> T { (self)(value) } } impl<'a, F, T> Query for (&'a mut Recorder, F) where F: FnOnce(&[u8]) -> T, { type Item = T; fn decode(self, value: &[u8]) -> T { (self.1)(value) } fn record(&mut self, hash: &H256, data: &[u8], depth: u32) { self.0.record(hash, data, depth) } } /// A key-value datastore implemented as a database-backed modified Merkle tree. pub trait Trie { /// Return the root of the trie. fn root(&self) -> &H256; /// Is the trie empty? fn is_empty(&self) -> bool { *self.root() == ::hashable::HASH_NULL_RLP } /// Does the trie contain a given key? fn contains(&self, key: &[u8]) -> Result<bool> { self.get(key).map(|x| x.is_some()) } /// What is the value of the given key in this trie? fn get<'a, 'key>(&'a self, key: &'key [u8]) -> Result<Option<DBValue>> where 'a: 'key, { self.get_with(key, DBValue::from_slice) } /// Search for the key with the given query parameter. See the docs of the `Query` /// trait for more details. fn get_with<'a, 'key, Q: Query>(&'a self, key: &'key [u8], query: Q) -> Result<Option<Q::Item>> where 'a: 'key; /// Returns a depth-first iterator over the elements of trie. fn iter<'a>(&'a self) -> Result<Box<TrieIterator<Item = TrieItem> + 'a>>; } /// A key-value datastore implemented as a database-backed modified Merkle tree. pub trait TrieMut { /// Return the root of the trie. fn root(&mut self) -> &H256; /// Is the trie empty? fn is_empty(&self) -> bool; /// Does the trie contain a given key? fn contains(&self, key: &[u8]) -> Result<bool> { self.get(key).map(|x| x.is_some()) } /// What is the value of the given key in this trie? fn get<'a, 'key>(&'a self, key: &'key [u8]) -> Result<Option<DBValue>> where 'a: 'key; /// Insert a `key`/`value` pair into the trie. An empty value is equivalent to removing /// `key` from the trie. Returns the old value associated with this key, if it existed. fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<Option<DBValue>>; /// Remove a `key` from the trie. Equivalent to making it equal to the empty /// value. Returns the old value associated with this key, if it existed. fn remove(&mut self, key: &[u8]) -> Result<Option<DBValue>>; } /// A trie iterator that also supports random access. pub trait TrieIterator: Iterator { /// Position the iterator on the first element with key > `key` fn seek(&mut self, key: &[u8]) -> Result<()>; } /// Trie types #[derive(Debug, PartialEq, Clone)] pub enum TrieSpec { /// Generic trie. Generic, /// Secure trie. Secure, /// Secure trie with fat database. Fat, } impl Default for TrieSpec { fn default() -> TrieSpec { TrieSpec::Secure } } /// Trie factory. #[derive(Default, Clone)] pub struct TrieFactory { spec: TrieSpec, } /// All different kinds of tries. /// This is used to prevent a heap allocation for every created trie. pub enum TrieKinds<'db> { /// A generic trie db. Generic(TrieDB<'db>), /// A secure trie db. Secure(SecTrieDB<'db>), /// A fat trie db. Fat(FatDB<'db>), } // wrapper macro for making the match easier to deal with. macro_rules! wrapper {
TrieKinds::Fat(ref t) => t.$f_name($($param),*), } } } impl<'db> Trie for TrieKinds<'db> { fn root(&self) -> &H256 { wrapper!(self, root,) } fn is_empty(&self) -> bool { wrapper!(self, is_empty,) } fn contains(&self, key: &[u8]) -> Result<bool> { wrapper!(self, contains, key) } fn get_with<'a, 'key, Q: Query>(&'a self, key: &'key [u8], query: Q) -> Result<Option<Q::Item>> where 'a: 'key, { wrapper!(self, get_with, key, query) } fn iter<'a>(&'a self) -> Result<Box<TrieIterator<Item = TrieItem> + 'a>> { wrapper!(self, iter,) } } #[cfg_attr(feature = "dev", allow(wrong_self_convention))] impl TrieFactory { /// Creates new factory. pub fn new(spec: TrieSpec) -> Self { TrieFactory { spec: spec } } /// Create new immutable instance of Trie. pub fn readonly<'db>(&self, db: &'db HashDB, root: &'db H256) -> Result<TrieKinds<'db>> { match self.spec { TrieSpec::Generic => Ok(TrieKinds::Generic(TrieDB::new(db, root)?)), TrieSpec::Secure => Ok(TrieKinds::Secure(SecTrieDB::new(db, root)?)), TrieSpec::Fat => Ok(TrieKinds::Fat(FatDB::new(db, root)?)), } } /// Create new mutable instance of Trie. pub fn create<'db>(&self, db: &'db mut HashDB, root: &'db mut H256) -> Box<TrieMut + 'db> { match self.spec { TrieSpec::Generic => Box::new(TrieDBMut::new(db, root)), TrieSpec::Secure => Box::new(SecTrieDBMut::new(db, root)), TrieSpec::Fat => Box::new(FatDBMut::new(db, root)), } } /// Create new mutable instance of trie and check for errors. pub fn from_existing<'db>(&self, db: &'db mut HashDB, root: &'db mut H256) -> Result<Box<TrieMut + 'db>> { match self.spec { TrieSpec::Generic => Ok(Box::new(TrieDBMut::from_existing(db, root)?)), TrieSpec::Secure => Ok(Box::new(SecTrieDBMut::from_existing(db, root)?)), TrieSpec::Fat => Ok(Box::new(FatDBMut::from_existing(db, root)?)), } } /// Returns true iff the trie DB is a fat DB (allows enumeration of keys). pub fn is_fat(&self) -> bool { self.spec == TrieSpec::Fat } }
($me: ident, $f_name: ident, $($param: ident),*) => { match *$me { TrieKinds::Generic(ref t) => t.$f_name($($param),*), TrieKinds::Secure(ref t) => t.$f_name($($param),*),
random_line_split
mod.rs
// Copyright 2015-2017 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/>. //! Trie interface and implementation. use hash::H256; use hashdb::{HashDB, DBValue}; use std::fmt; /// Export the standardmap module. pub mod standardmap; /// Export the node module. pub mod node; /// Export the triedb module. pub mod triedb; /// Export the triedbmut module. pub mod triedbmut; /// Export the sectriedb module. pub mod sectriedb; /// Export the sectriedbmut module. pub mod sectriedbmut; /// Trie query recording. pub mod recorder; mod fatdb; mod fatdbmut; mod lookup; pub use self::fatdb::{FatDB, FatDBIterator}; pub use self::fatdbmut::FatDBMut; pub use self::recorder::Recorder; pub use self::sectriedb::SecTrieDB; pub use self::sectriedbmut::SecTrieDBMut; pub use self::standardmap::{Alphabet, StandardMap, ValueMode}; pub use self::triedb::{TrieDB, TrieDBIterator}; pub use self::triedbmut::TrieDBMut; /// Trie Errors. /// /// These borrow the data within them to avoid excessive copying on every /// trie operation. #[derive(Debug, PartialEq, Eq, Clone)] pub enum TrieError { /// Attempted to create a trie with a state root not in the DB. InvalidStateRoot(H256), /// Trie item not found in the database, IncompleteDatabase(H256), } impl fmt::Display for TrieError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { TrieError::InvalidStateRoot(ref root) => write!(f, "Invalid state root: {}", root), TrieError::IncompleteDatabase(ref missing) => write!(f, "Database missing expected key: {}", missing), } } } /// Trie result type. Boxed to avoid copying around extra space for `H256`s on successful queries. pub type Result<T> = ::std::result::Result<T, Box<TrieError>>; /// Trie-Item type. pub type TrieItem<'a> = Result<(Vec<u8>, DBValue)>; /// Description of what kind of query will be made to the trie. /// /// This is implemented for any &mut recorder (where the query will return /// a DBValue), any function taking raw bytes (where no recording will be made), /// or any tuple of (&mut Recorder, FnOnce(&[u8])) pub trait Query { /// Output item. type Item; /// Decode a byte-slice into the desired item. fn decode(self, &[u8]) -> Self::Item; /// Record that a node has been passed through. fn record(&mut self, &H256, &[u8], u32) {} } impl<'a> Query for &'a mut Recorder { type Item = DBValue; fn decode(self, value: &[u8]) -> DBValue { DBValue::from_slice(value) } fn record(&mut self, hash: &H256, data: &[u8], depth: u32) { (&mut **self).record(hash, data, depth); } } impl<F, T> Query for F where F: for<'a> FnOnce(&'a [u8]) -> T, { type Item = T; fn decode(self, value: &[u8]) -> T { (self)(value) } } impl<'a, F, T> Query for (&'a mut Recorder, F) where F: FnOnce(&[u8]) -> T, { type Item = T; fn decode(self, value: &[u8]) -> T { (self.1)(value) } fn record(&mut self, hash: &H256, data: &[u8], depth: u32) { self.0.record(hash, data, depth) } } /// A key-value datastore implemented as a database-backed modified Merkle tree. pub trait Trie { /// Return the root of the trie. fn root(&self) -> &H256; /// Is the trie empty? fn is_empty(&self) -> bool { *self.root() == ::hashable::HASH_NULL_RLP } /// Does the trie contain a given key? fn contains(&self, key: &[u8]) -> Result<bool> { self.get(key).map(|x| x.is_some()) } /// What is the value of the given key in this trie? fn get<'a, 'key>(&'a self, key: &'key [u8]) -> Result<Option<DBValue>> where 'a: 'key, { self.get_with(key, DBValue::from_slice) } /// Search for the key with the given query parameter. See the docs of the `Query` /// trait for more details. fn get_with<'a, 'key, Q: Query>(&'a self, key: &'key [u8], query: Q) -> Result<Option<Q::Item>> where 'a: 'key; /// Returns a depth-first iterator over the elements of trie. fn iter<'a>(&'a self) -> Result<Box<TrieIterator<Item = TrieItem> + 'a>>; } /// A key-value datastore implemented as a database-backed modified Merkle tree. pub trait TrieMut { /// Return the root of the trie. fn root(&mut self) -> &H256; /// Is the trie empty? fn is_empty(&self) -> bool; /// Does the trie contain a given key? fn contains(&self, key: &[u8]) -> Result<bool> { self.get(key).map(|x| x.is_some()) } /// What is the value of the given key in this trie? fn get<'a, 'key>(&'a self, key: &'key [u8]) -> Result<Option<DBValue>> where 'a: 'key; /// Insert a `key`/`value` pair into the trie. An empty value is equivalent to removing /// `key` from the trie. Returns the old value associated with this key, if it existed. fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<Option<DBValue>>; /// Remove a `key` from the trie. Equivalent to making it equal to the empty /// value. Returns the old value associated with this key, if it existed. fn remove(&mut self, key: &[u8]) -> Result<Option<DBValue>>; } /// A trie iterator that also supports random access. pub trait TrieIterator: Iterator { /// Position the iterator on the first element with key > `key` fn seek(&mut self, key: &[u8]) -> Result<()>; } /// Trie types #[derive(Debug, PartialEq, Clone)] pub enum TrieSpec { /// Generic trie. Generic, /// Secure trie. Secure, /// Secure trie with fat database. Fat, } impl Default for TrieSpec { fn default() -> TrieSpec { TrieSpec::Secure } } /// Trie factory. #[derive(Default, Clone)] pub struct TrieFactory { spec: TrieSpec, } /// All different kinds of tries. /// This is used to prevent a heap allocation for every created trie. pub enum TrieKinds<'db> { /// A generic trie db. Generic(TrieDB<'db>), /// A secure trie db. Secure(SecTrieDB<'db>), /// A fat trie db. Fat(FatDB<'db>), } // wrapper macro for making the match easier to deal with. macro_rules! wrapper { ($me: ident, $f_name: ident, $($param: ident),*) => { match *$me { TrieKinds::Generic(ref t) => t.$f_name($($param),*), TrieKinds::Secure(ref t) => t.$f_name($($param),*), TrieKinds::Fat(ref t) => t.$f_name($($param),*), } } } impl<'db> Trie for TrieKinds<'db> { fn root(&self) -> &H256 { wrapper!(self, root,) } fn is_empty(&self) -> bool { wrapper!(self, is_empty,) } fn contains(&self, key: &[u8]) -> Result<bool> { wrapper!(self, contains, key) } fn get_with<'a, 'key, Q: Query>(&'a self, key: &'key [u8], query: Q) -> Result<Option<Q::Item>> where 'a: 'key, { wrapper!(self, get_with, key, query) } fn iter<'a>(&'a self) -> Result<Box<TrieIterator<Item = TrieItem> + 'a>> { wrapper!(self, iter,) } } #[cfg_attr(feature = "dev", allow(wrong_self_convention))] impl TrieFactory { /// Creates new factory. pub fn new(spec: TrieSpec) -> Self { TrieFactory { spec: spec } } /// Create new immutable instance of Trie. pub fn
<'db>(&self, db: &'db HashDB, root: &'db H256) -> Result<TrieKinds<'db>> { match self.spec { TrieSpec::Generic => Ok(TrieKinds::Generic(TrieDB::new(db, root)?)), TrieSpec::Secure => Ok(TrieKinds::Secure(SecTrieDB::new(db, root)?)), TrieSpec::Fat => Ok(TrieKinds::Fat(FatDB::new(db, root)?)), } } /// Create new mutable instance of Trie. pub fn create<'db>(&self, db: &'db mut HashDB, root: &'db mut H256) -> Box<TrieMut + 'db> { match self.spec { TrieSpec::Generic => Box::new(TrieDBMut::new(db, root)), TrieSpec::Secure => Box::new(SecTrieDBMut::new(db, root)), TrieSpec::Fat => Box::new(FatDBMut::new(db, root)), } } /// Create new mutable instance of trie and check for errors. pub fn from_existing<'db>(&self, db: &'db mut HashDB, root: &'db mut H256) -> Result<Box<TrieMut + 'db>> { match self.spec { TrieSpec::Generic => Ok(Box::new(TrieDBMut::from_existing(db, root)?)), TrieSpec::Secure => Ok(Box::new(SecTrieDBMut::from_existing(db, root)?)), TrieSpec::Fat => Ok(Box::new(FatDBMut::from_existing(db, root)?)), } } /// Returns true iff the trie DB is a fat DB (allows enumeration of keys). pub fn is_fat(&self) -> bool { self.spec == TrieSpec::Fat } }
readonly
identifier_name
cors.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/. */ //! A partial implementation of CORS //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what //! the request mode should be and compare with the fetch spec //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) use hyper::client::Request; use hyper::header::{AccessControlAllowHeaders, AccessControlRequestHeaders}; use hyper::header::{AccessControlAllowMethods, AccessControlRequestMethod}; use hyper::header::{AccessControlAllowOrigin, AccessControlMaxAge}; use hyper::header::{ContentType, Host}; use hyper::header::{HeaderView, Headers}; use hyper::method::Method; use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper::status::StatusClass::Success; use net_traits::{AsyncResponseListener, Metadata, ResponseAction}; use network_listener::{NetworkListener, PreInvoke}; use script_task::ScriptChan; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::sync::{Arc, Mutex}; use time::{self, Timespec, now}; use unicase::UniCase; use url::{SchemeData, Url}; use util::mem::HeapSizeOf; use util::task::spawn_named; /// Interface for network listeners concerned with CORS checks. Proper network requests /// should be initiated from this method, based on the response provided. pub trait AsyncCORSResponseListener { fn response_available(&self, response: CORSResponse); } #[derive(Clone, HeapSizeOf)] pub struct CORSRequest { pub origin: Url, pub destination: Url, pub mode: RequestMode, pub method: Method, #[ignore_heap_size_of = "Defined in hyper"] pub headers: Headers, /// CORS preflight flag (https://fetch.spec.whatwg.org/#concept-http-fetch) /// Indicates that a CORS preflight request and/or cache check is to be performed pub preflight_flag: bool, } /// https://fetch.spec.whatwg.org/#concept-request-mode /// This only covers some of the request modes. The /// `same-origin` and `no CORS` modes are unnecessary for XHR. #[derive(PartialEq, Copy, Clone, HeapSizeOf)] pub enum RequestMode { CORS, // CORS ForcedPreflight, // CORS-with-forced-preflight } impl CORSRequest { /// Creates a CORS request if necessary. Will return an error when fetching is forbidden pub fn maybe_new(referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> Result<Option<CORSRequest>, ()> { if referer.scheme == destination.scheme && referer.host() == destination.host() && referer.port() == destination.port() { return Ok(None); // Not cross-origin, proceed with a normal fetch } match &*destination.scheme { // TODO: If the request's same origin data url flag is set (which isn't the case for XHR) // we can fetch a data URL normally. about:blank can also be fetched by XHR "http" | "https" => { let mut req = CORSRequest::new(referer, destination, mode, method, headers); req.preflight_flag =!is_simple_method(&req.method) || mode == RequestMode::ForcedPreflight; if req.headers.iter().all(|h| is_simple_header(&h)) { req.preflight_flag = true; } Ok(Some(req)) }, _ => Err(()), } } fn new(mut referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> CORSRequest { if let SchemeData::Relative(ref mut data) = referer.scheme_data { data.path = vec![]; } referer.fragment = None; referer.query = None; CORSRequest { origin: referer, destination: destination, mode: mode, method: method, headers: headers, preflight_flag: false, } } pub fn http_fetch_async(&self, listener: Box<AsyncCORSResponseListener + Send>, script_chan: Box<ScriptChan + Send>) { struct CORSContext { listener: Box<AsyncCORSResponseListener + Send>, response: Option<CORSResponse>, } // This is shoe-horning the CORSReponse stuff into the rest of the async network // framework right now. It would be worth redesigning http_fetch to do this properly. impl AsyncResponseListener for CORSContext { fn headers_available(&mut self, _metadata: Metadata) { } fn data_available(&mut self, _payload: Vec<u8>) { } fn response_complete(&mut self, _status: Result<(), String>) { let response = self.response.take().unwrap(); self.listener.response_available(response); } } impl PreInvoke for CORSContext {} let context = CORSContext { listener: listener, response: None, }; let listener = NetworkListener { context: Arc::new(Mutex::new(context)), script_chan: script_chan, }; // TODO: this exists only to make preflight check non-blocking // perhaps should be handled by the resource task? let req = self.clone(); spawn_named("cors".to_owned(), move || { let response = req.http_fetch(); let mut context = listener.context.lock(); let context = context.as_mut().unwrap(); context.response = Some(response); listener.notify(ResponseAction::ResponseComplete(Ok(()))); }); } /// http://fetch.spec.whatwg.org/#concept-http-fetch /// This method assumes that the CORS flag is set /// This does not perform the full HTTP fetch, rather it handles part of the CORS filtering /// if self.mode is ForcedPreflight, then the CORS-with-forced-preflight /// fetch flag is set as well pub fn http_fetch(&self) -> CORSResponse { let response = CORSResponse::new(); // Step 2: Handle service workers (unimplemented) // Step 3 // Substep 1: Service workers (unimplemented ) // Substep 2 let cache = &mut CORSCache(vec!()); // XXXManishearth Should come from user agent if self.preflight_flag && !cache.match_method(self, &self.method) && !self.headers.iter().all(|h| is_simple_header(&h) && cache.match_header(self, h.name())) && (!is_simple_method(&self.method) || self.mode == RequestMode::ForcedPreflight)
response } /// https://fetch.spec.whatwg.org/#cors-preflight-fetch fn preflight_fetch(&self) -> CORSResponse { let error = CORSResponse::new_error(); let mut cors_response = CORSResponse::new(); // Step 1 let mut preflight = self.clone(); preflight.method = Method::Options; preflight.headers = Headers::new(); // Step 2 preflight.headers.set(AccessControlRequestMethod(self.method.clone())); // Steps 3-5 let mut header_names = vec![]; for header in self.headers.iter() { header_names.push(header.name().to_owned()); } header_names.sort(); preflight.headers .set(AccessControlRequestHeaders(header_names.into_iter().map(UniCase).collect())); let preflight_request = Request::new(preflight.method, preflight.destination); let mut req = match preflight_request { Ok(req) => req, Err(_) => return error, }; let host = req.headers().get::<Host>().unwrap().clone(); *req.headers_mut() = preflight.headers.clone(); req.headers_mut().set(host); let stream = match req.start() { Ok(s) => s, Err(_) => return error, }; // Step 6 let response = match stream.send() { Ok(r) => r, Err(_) => return error, }; // Step 7: We don't perform a CORS check here // FYI, fn allow_cross_origin_request() performs the CORS check match response.status.class() { Success => {} _ => return error, } cors_response.headers = response.headers.clone(); // Substeps 1-3 (parsing rules: https://fetch.spec.whatwg.org/#http-new-header-syntax) let methods_substep4 = [self.method.clone()]; let mut methods = match response.headers.get() { Some(&AccessControlAllowMethods(ref v)) => &**v, _ => return error, }; let headers = match response.headers.get() { Some(&AccessControlAllowHeaders(ref h)) => h, _ => return error, }; // Substep 4 if methods.is_empty() && preflight.mode == RequestMode::ForcedPreflight { methods = &methods_substep4; } // Substep 5 if!is_simple_method(&self.method) &&!methods.iter().any(|m| m == &self.method) { return error; } // Substep 6 for h in self.headers.iter() { if is_simple_header(&h) { continue; } if!headers.iter().any(|ref h2| h.name().eq_ignore_ascii_case(h2)) { return error; } } // Substeps 7-8 let max_age = match response.headers.get() { Some(&AccessControlMaxAge(num)) => num, None => 0, }; // Substep 9: Impose restrictions on max-age, if any (unimplemented) // Substeps 10-12: Add a cache (partially implemented, XXXManishearth) // This cache should come from the user agent, creating a new one here to check // for compile time errors let cache = &mut CORSCache(vec![]); for m in methods { let cache_match = cache.match_method_and_update(self, m, max_age); if!cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), max_age, false, HeaderOrMethod::MethodData(m.clone()))); } } // Substeps 13-14 for h in response.headers.iter() { let cache_match = cache.match_header_and_update(self, h.name(), max_age); if!cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), max_age, false, HeaderOrMethod::HeaderData(h.to_string()))); } } // Substep 15 cors_response } } pub struct CORSResponse { pub network_error: bool, pub headers: Headers, } impl CORSResponse { fn new() -> CORSResponse { CORSResponse { network_error: false, headers: Headers::new(), } } fn new_error() -> CORSResponse { CORSResponse { network_error: true, headers: Headers::new(), } } } // CORS Cache stuff /// A CORS cache object. Anchor it somewhere to the user agent. #[derive(Clone)] pub struct CORSCache(Vec<CORSCacheEntry>); /// Union type for CORS cache entries /// Each entry might pertain to a header or method #[derive(Clone)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method), } impl HeaderOrMethod { fn match_header(&self, header_name: &str) -> bool { match *self { HeaderOrMethod::HeaderData(ref s) => s.eq_ignore_ascii_case(header_name), _ => false, } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, _ => false, } } } // An entry in the CORS cache #[derive(Clone)] pub struct CORSCacheEntry { pub origin: Url, pub url: Url, pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, created: Timespec, } impl CORSCacheEntry { fn new(origin: Url, url: Url, max_age: u32, credentials: bool, header_or_method: HeaderOrMethod) -> CORSCacheEntry { CORSCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, created: time::now().to_timespec(), } } } impl CORSCache { /// https://fetch.spec.whatwg.org/#concept-cache-clear #[allow(dead_code)] fn clear(&mut self, request: &CORSRequest) { let CORSCache(buf) = self.clone(); let new_buf: Vec<CORSCacheEntry> = buf.into_iter() .filter(|e| e.origin == request.origin && request.destination == e.url) .collect(); *self = CORSCache(new_buf); } // Remove old entries fn cleanup(&mut self) { let CORSCache(buf) = self.clone(); let now = time::now().to_timespec(); let new_buf: Vec<CORSCacheEntry> = buf.into_iter() .filter(|e| now.sec > e.created.sec + e.max_age as i64) .collect(); *self = CORSCache(new_buf); } /// https://fetch.spec.whatwg.org/#concept-cache-match-header fn find_entry_by_header<'a>(&'a mut self, request: &CORSRequest, header_name: &str) -> Option<&'a mut CORSCacheEntry> { self.cleanup(); let CORSCache(ref mut buf) = *self; // Credentials are not yet implemented here buf.iter_mut().find(|e| { e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() && e.origin.port() == request.origin.port() && e.url == request.destination && e.header_or_method.match_header(header_name) }) } fn match_header(&mut self, request: &CORSRequest, header_name: &str) -> bool { self.find_entry_by_header(request, header_name).is_some() } fn match_header_and_update(&mut self, request: &CORSRequest, header_name: &str, new_max_age: u32) -> bool { self.find_entry_by_header(request, header_name).map(|e| e.max_age = new_max_age).is_some() } fn find_entry_by_method<'a>(&'a mut self, request: &CORSRequest, method: &Method) -> Option<&'a mut CORSCacheEntry> { // we can take the method from CORSRequest itself self.cleanup(); let CORSCache(ref mut buf) = *self; // Credentials are not yet implemented here buf.iter_mut().find(|e| { e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() && e.origin.port() == request.origin.port() && e.url == request.destination && e.header_or_method.match_method(method) }) } /// https://fetch.spec.whatwg.org/#concept-cache-match-method fn match_method(&mut self, request: &CORSRequest, method: &Method) -> bool { self.find_entry_by_method(request, method).is_some() } fn match_method_and_update(&mut self, request: &CORSRequest, method: &Method, new_max_age: u32) -> bool { self.find_entry_by_method(request, method).map(|e| e.max_age = new_max_age).is_some() } fn insert(&mut self, entry: CORSCacheEntry) { self.cleanup(); let CORSCache(ref mut buf) = *self; buf.push(entry); } } fn is_simple_header(h: &HeaderView) -> bool { // FIXME: use h.is::<HeaderType>() when AcceptLanguage and // ContentLanguage headers exist match &*h.name().to_ascii_lowercase() { "accept" | "accept-language" | "content-language" => true, "content-type" => match h.value() { Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) | Some(&ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _))) | Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, _))) => true, _ => false, }, _ => false, } } fn is_simple_method(m: &Method) -> bool { match *m { Method::Get | Method::Head | Method::Post => true, _ => false, } } /// Perform a CORS check on a header list and CORS request /// https://fetch.spec.whatwg.org/#cors-check pub fn allow_cross_origin_request(req: &CORSRequest, headers: &Headers) -> bool { match headers.get::<AccessControlAllowOrigin>() { Some(&AccessControlAllowOrigin::Any) => true, // Not always true, depends on credentials mode Some(&AccessControlAllowOrigin::Value(ref url)) => req.origin.serialize() == *url, Some(&AccessControlAllowOrigin::Null) | None => false, } }
{ return self.preflight_fetch(); // Everything after this is part of XHR::fetch() // Expect the organization of code to improve once we have a fetch crate }
conditional_block
cors.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/. */ //! A partial implementation of CORS //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what //! the request mode should be and compare with the fetch spec //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) use hyper::client::Request; use hyper::header::{AccessControlAllowHeaders, AccessControlRequestHeaders}; use hyper::header::{AccessControlAllowMethods, AccessControlRequestMethod}; use hyper::header::{AccessControlAllowOrigin, AccessControlMaxAge}; use hyper::header::{ContentType, Host}; use hyper::header::{HeaderView, Headers}; use hyper::method::Method; use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper::status::StatusClass::Success; use net_traits::{AsyncResponseListener, Metadata, ResponseAction}; use network_listener::{NetworkListener, PreInvoke}; use script_task::ScriptChan; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::sync::{Arc, Mutex}; use time::{self, Timespec, now}; use unicase::UniCase; use url::{SchemeData, Url}; use util::mem::HeapSizeOf; use util::task::spawn_named; /// Interface for network listeners concerned with CORS checks. Proper network requests /// should be initiated from this method, based on the response provided. pub trait AsyncCORSResponseListener { fn response_available(&self, response: CORSResponse); } #[derive(Clone, HeapSizeOf)] pub struct CORSRequest { pub origin: Url, pub destination: Url, pub mode: RequestMode, pub method: Method, #[ignore_heap_size_of = "Defined in hyper"] pub headers: Headers, /// CORS preflight flag (https://fetch.spec.whatwg.org/#concept-http-fetch) /// Indicates that a CORS preflight request and/or cache check is to be performed pub preflight_flag: bool, } /// https://fetch.spec.whatwg.org/#concept-request-mode /// This only covers some of the request modes. The /// `same-origin` and `no CORS` modes are unnecessary for XHR. #[derive(PartialEq, Copy, Clone, HeapSizeOf)] pub enum RequestMode { CORS, // CORS ForcedPreflight, // CORS-with-forced-preflight } impl CORSRequest { /// Creates a CORS request if necessary. Will return an error when fetching is forbidden pub fn maybe_new(referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> Result<Option<CORSRequest>, ()> { if referer.scheme == destination.scheme && referer.host() == destination.host() && referer.port() == destination.port() { return Ok(None); // Not cross-origin, proceed with a normal fetch } match &*destination.scheme { // TODO: If the request's same origin data url flag is set (which isn't the case for XHR) // we can fetch a data URL normally. about:blank can also be fetched by XHR "http" | "https" => { let mut req = CORSRequest::new(referer, destination, mode, method, headers); req.preflight_flag =!is_simple_method(&req.method) || mode == RequestMode::ForcedPreflight; if req.headers.iter().all(|h| is_simple_header(&h)) { req.preflight_flag = true; } Ok(Some(req)) }, _ => Err(()), } } fn new(mut referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> CORSRequest { if let SchemeData::Relative(ref mut data) = referer.scheme_data { data.path = vec![]; } referer.fragment = None; referer.query = None; CORSRequest { origin: referer, destination: destination, mode: mode, method: method, headers: headers, preflight_flag: false, } } pub fn http_fetch_async(&self, listener: Box<AsyncCORSResponseListener + Send>, script_chan: Box<ScriptChan + Send>) { struct CORSContext { listener: Box<AsyncCORSResponseListener + Send>, response: Option<CORSResponse>, } // This is shoe-horning the CORSReponse stuff into the rest of the async network // framework right now. It would be worth redesigning http_fetch to do this properly. impl AsyncResponseListener for CORSContext { fn headers_available(&mut self, _metadata: Metadata) { } fn data_available(&mut self, _payload: Vec<u8>) { } fn response_complete(&mut self, _status: Result<(), String>) { let response = self.response.take().unwrap(); self.listener.response_available(response); } } impl PreInvoke for CORSContext {} let context = CORSContext { listener: listener, response: None, }; let listener = NetworkListener { context: Arc::new(Mutex::new(context)), script_chan: script_chan, }; // TODO: this exists only to make preflight check non-blocking // perhaps should be handled by the resource task? let req = self.clone(); spawn_named("cors".to_owned(), move || { let response = req.http_fetch(); let mut context = listener.context.lock(); let context = context.as_mut().unwrap(); context.response = Some(response); listener.notify(ResponseAction::ResponseComplete(Ok(()))); }); } /// http://fetch.spec.whatwg.org/#concept-http-fetch /// This method assumes that the CORS flag is set /// This does not perform the full HTTP fetch, rather it handles part of the CORS filtering /// if self.mode is ForcedPreflight, then the CORS-with-forced-preflight /// fetch flag is set as well pub fn http_fetch(&self) -> CORSResponse { let response = CORSResponse::new(); // Step 2: Handle service workers (unimplemented) // Step 3 // Substep 1: Service workers (unimplemented ) // Substep 2 let cache = &mut CORSCache(vec!()); // XXXManishearth Should come from user agent if self.preflight_flag && !cache.match_method(self, &self.method) && !self.headers.iter().all(|h| is_simple_header(&h) && cache.match_header(self, h.name())) && (!is_simple_method(&self.method) || self.mode == RequestMode::ForcedPreflight) { return self.preflight_fetch(); // Everything after this is part of XHR::fetch() // Expect the organization of code to improve once we have a fetch crate } response } /// https://fetch.spec.whatwg.org/#cors-preflight-fetch fn preflight_fetch(&self) -> CORSResponse { let error = CORSResponse::new_error(); let mut cors_response = CORSResponse::new(); // Step 1 let mut preflight = self.clone(); preflight.method = Method::Options; preflight.headers = Headers::new(); // Step 2 preflight.headers.set(AccessControlRequestMethod(self.method.clone())); // Steps 3-5 let mut header_names = vec![]; for header in self.headers.iter() { header_names.push(header.name().to_owned()); } header_names.sort(); preflight.headers .set(AccessControlRequestHeaders(header_names.into_iter().map(UniCase).collect())); let preflight_request = Request::new(preflight.method, preflight.destination); let mut req = match preflight_request { Ok(req) => req, Err(_) => return error, }; let host = req.headers().get::<Host>().unwrap().clone(); *req.headers_mut() = preflight.headers.clone(); req.headers_mut().set(host); let stream = match req.start() { Ok(s) => s, Err(_) => return error, }; // Step 6 let response = match stream.send() { Ok(r) => r, Err(_) => return error, }; // Step 7: We don't perform a CORS check here // FYI, fn allow_cross_origin_request() performs the CORS check match response.status.class() { Success => {} _ => return error, } cors_response.headers = response.headers.clone(); // Substeps 1-3 (parsing rules: https://fetch.spec.whatwg.org/#http-new-header-syntax) let methods_substep4 = [self.method.clone()]; let mut methods = match response.headers.get() { Some(&AccessControlAllowMethods(ref v)) => &**v, _ => return error, }; let headers = match response.headers.get() { Some(&AccessControlAllowHeaders(ref h)) => h, _ => return error, }; // Substep 4 if methods.is_empty() && preflight.mode == RequestMode::ForcedPreflight { methods = &methods_substep4; } // Substep 5 if!is_simple_method(&self.method) &&!methods.iter().any(|m| m == &self.method) { return error; } // Substep 6 for h in self.headers.iter() { if is_simple_header(&h) { continue; } if!headers.iter().any(|ref h2| h.name().eq_ignore_ascii_case(h2)) { return error; } } // Substeps 7-8 let max_age = match response.headers.get() { Some(&AccessControlMaxAge(num)) => num, None => 0, }; // Substep 9: Impose restrictions on max-age, if any (unimplemented) // Substeps 10-12: Add a cache (partially implemented, XXXManishearth) // This cache should come from the user agent, creating a new one here to check // for compile time errors let cache = &mut CORSCache(vec![]); for m in methods { let cache_match = cache.match_method_and_update(self, m, max_age); if!cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), max_age, false, HeaderOrMethod::MethodData(m.clone()))); } } // Substeps 13-14 for h in response.headers.iter() { let cache_match = cache.match_header_and_update(self, h.name(), max_age); if!cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), max_age, false, HeaderOrMethod::HeaderData(h.to_string()))); } } // Substep 15 cors_response } } pub struct CORSResponse { pub network_error: bool, pub headers: Headers, } impl CORSResponse { fn new() -> CORSResponse { CORSResponse { network_error: false, headers: Headers::new(), } } fn new_error() -> CORSResponse { CORSResponse { network_error: true, headers: Headers::new(), } } } // CORS Cache stuff /// A CORS cache object. Anchor it somewhere to the user agent. #[derive(Clone)] pub struct CORSCache(Vec<CORSCacheEntry>); /// Union type for CORS cache entries /// Each entry might pertain to a header or method #[derive(Clone)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method), } impl HeaderOrMethod { fn match_header(&self, header_name: &str) -> bool { match *self { HeaderOrMethod::HeaderData(ref s) => s.eq_ignore_ascii_case(header_name), _ => false, } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, _ => false, } } } // An entry in the CORS cache #[derive(Clone)] pub struct CORSCacheEntry { pub origin: Url, pub url: Url, pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, created: Timespec, } impl CORSCacheEntry { fn new(origin: Url, url: Url, max_age: u32, credentials: bool, header_or_method: HeaderOrMethod) -> CORSCacheEntry { CORSCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, created: time::now().to_timespec(), } } } impl CORSCache { /// https://fetch.spec.whatwg.org/#concept-cache-clear #[allow(dead_code)] fn clear(&mut self, request: &CORSRequest) { let CORSCache(buf) = self.clone(); let new_buf: Vec<CORSCacheEntry> = buf.into_iter() .filter(|e| e.origin == request.origin && request.destination == e.url) .collect(); *self = CORSCache(new_buf); } // Remove old entries fn cleanup(&mut self) { let CORSCache(buf) = self.clone(); let now = time::now().to_timespec(); let new_buf: Vec<CORSCacheEntry> = buf.into_iter() .filter(|e| now.sec > e.created.sec + e.max_age as i64) .collect(); *self = CORSCache(new_buf); } /// https://fetch.spec.whatwg.org/#concept-cache-match-header fn find_entry_by_header<'a>(&'a mut self, request: &CORSRequest, header_name: &str) -> Option<&'a mut CORSCacheEntry> { self.cleanup(); let CORSCache(ref mut buf) = *self; // Credentials are not yet implemented here buf.iter_mut().find(|e| { e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() && e.origin.port() == request.origin.port() && e.url == request.destination && e.header_or_method.match_header(header_name) }) } fn match_header(&mut self, request: &CORSRequest, header_name: &str) -> bool { self.find_entry_by_header(request, header_name).is_some() } fn match_header_and_update(&mut self, request: &CORSRequest, header_name: &str, new_max_age: u32) -> bool { self.find_entry_by_header(request, header_name).map(|e| e.max_age = new_max_age).is_some() } fn find_entry_by_method<'a>(&'a mut self, request: &CORSRequest, method: &Method) -> Option<&'a mut CORSCacheEntry> { // we can take the method from CORSRequest itself self.cleanup(); let CORSCache(ref mut buf) = *self; // Credentials are not yet implemented here buf.iter_mut().find(|e| { e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() && e.origin.port() == request.origin.port() && e.url == request.destination && e.header_or_method.match_method(method) }) } /// https://fetch.spec.whatwg.org/#concept-cache-match-method fn
(&mut self, request: &CORSRequest, method: &Method) -> bool { self.find_entry_by_method(request, method).is_some() } fn match_method_and_update(&mut self, request: &CORSRequest, method: &Method, new_max_age: u32) -> bool { self.find_entry_by_method(request, method).map(|e| e.max_age = new_max_age).is_some() } fn insert(&mut self, entry: CORSCacheEntry) { self.cleanup(); let CORSCache(ref mut buf) = *self; buf.push(entry); } } fn is_simple_header(h: &HeaderView) -> bool { // FIXME: use h.is::<HeaderType>() when AcceptLanguage and // ContentLanguage headers exist match &*h.name().to_ascii_lowercase() { "accept" | "accept-language" | "content-language" => true, "content-type" => match h.value() { Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) | Some(&ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _))) | Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, _))) => true, _ => false, }, _ => false, } } fn is_simple_method(m: &Method) -> bool { match *m { Method::Get | Method::Head | Method::Post => true, _ => false, } } /// Perform a CORS check on a header list and CORS request /// https://fetch.spec.whatwg.org/#cors-check pub fn allow_cross_origin_request(req: &CORSRequest, headers: &Headers) -> bool { match headers.get::<AccessControlAllowOrigin>() { Some(&AccessControlAllowOrigin::Any) => true, // Not always true, depends on credentials mode Some(&AccessControlAllowOrigin::Value(ref url)) => req.origin.serialize() == *url, Some(&AccessControlAllowOrigin::Null) | None => false, } }
match_method
identifier_name
cors.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/. */ //! A partial implementation of CORS //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what //! the request mode should be and compare with the fetch spec //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) use hyper::client::Request; use hyper::header::{AccessControlAllowHeaders, AccessControlRequestHeaders}; use hyper::header::{AccessControlAllowMethods, AccessControlRequestMethod}; use hyper::header::{AccessControlAllowOrigin, AccessControlMaxAge}; use hyper::header::{ContentType, Host}; use hyper::header::{HeaderView, Headers}; use hyper::method::Method; use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper::status::StatusClass::Success; use net_traits::{AsyncResponseListener, Metadata, ResponseAction}; use network_listener::{NetworkListener, PreInvoke}; use script_task::ScriptChan; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::sync::{Arc, Mutex}; use time::{self, Timespec, now}; use unicase::UniCase; use url::{SchemeData, Url}; use util::mem::HeapSizeOf; use util::task::spawn_named; /// Interface for network listeners concerned with CORS checks. Proper network requests /// should be initiated from this method, based on the response provided. pub trait AsyncCORSResponseListener { fn response_available(&self, response: CORSResponse); } #[derive(Clone, HeapSizeOf)] pub struct CORSRequest { pub origin: Url, pub destination: Url, pub mode: RequestMode, pub method: Method, #[ignore_heap_size_of = "Defined in hyper"] pub headers: Headers, /// CORS preflight flag (https://fetch.spec.whatwg.org/#concept-http-fetch) /// Indicates that a CORS preflight request and/or cache check is to be performed pub preflight_flag: bool, } /// https://fetch.spec.whatwg.org/#concept-request-mode /// This only covers some of the request modes. The /// `same-origin` and `no CORS` modes are unnecessary for XHR. #[derive(PartialEq, Copy, Clone, HeapSizeOf)] pub enum RequestMode { CORS, // CORS ForcedPreflight, // CORS-with-forced-preflight } impl CORSRequest { /// Creates a CORS request if necessary. Will return an error when fetching is forbidden pub fn maybe_new(referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> Result<Option<CORSRequest>, ()> { if referer.scheme == destination.scheme && referer.host() == destination.host() && referer.port() == destination.port() { return Ok(None); // Not cross-origin, proceed with a normal fetch } match &*destination.scheme { // TODO: If the request's same origin data url flag is set (which isn't the case for XHR) // we can fetch a data URL normally. about:blank can also be fetched by XHR "http" | "https" => { let mut req = CORSRequest::new(referer, destination, mode, method, headers); req.preflight_flag =!is_simple_method(&req.method) || mode == RequestMode::ForcedPreflight; if req.headers.iter().all(|h| is_simple_header(&h)) { req.preflight_flag = true; } Ok(Some(req)) }, _ => Err(()), } } fn new(mut referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> CORSRequest { if let SchemeData::Relative(ref mut data) = referer.scheme_data { data.path = vec![]; } referer.fragment = None; referer.query = None; CORSRequest { origin: referer, destination: destination, mode: mode, method: method, headers: headers, preflight_flag: false, } } pub fn http_fetch_async(&self, listener: Box<AsyncCORSResponseListener + Send>, script_chan: Box<ScriptChan + Send>) { struct CORSContext { listener: Box<AsyncCORSResponseListener + Send>, response: Option<CORSResponse>, } // This is shoe-horning the CORSReponse stuff into the rest of the async network // framework right now. It would be worth redesigning http_fetch to do this properly. impl AsyncResponseListener for CORSContext { fn headers_available(&mut self, _metadata: Metadata) { } fn data_available(&mut self, _payload: Vec<u8>) { } fn response_complete(&mut self, _status: Result<(), String>) { let response = self.response.take().unwrap(); self.listener.response_available(response); } } impl PreInvoke for CORSContext {} let context = CORSContext { listener: listener, response: None, }; let listener = NetworkListener { context: Arc::new(Mutex::new(context)), script_chan: script_chan, }; // TODO: this exists only to make preflight check non-blocking // perhaps should be handled by the resource task? let req = self.clone(); spawn_named("cors".to_owned(), move || { let response = req.http_fetch(); let mut context = listener.context.lock(); let context = context.as_mut().unwrap(); context.response = Some(response); listener.notify(ResponseAction::ResponseComplete(Ok(()))); }); } /// http://fetch.spec.whatwg.org/#concept-http-fetch /// This method assumes that the CORS flag is set /// This does not perform the full HTTP fetch, rather it handles part of the CORS filtering /// if self.mode is ForcedPreflight, then the CORS-with-forced-preflight /// fetch flag is set as well pub fn http_fetch(&self) -> CORSResponse { let response = CORSResponse::new(); // Step 2: Handle service workers (unimplemented) // Step 3 // Substep 1: Service workers (unimplemented ) // Substep 2 let cache = &mut CORSCache(vec!()); // XXXManishearth Should come from user agent if self.preflight_flag && !cache.match_method(self, &self.method) && !self.headers.iter().all(|h| is_simple_header(&h) && cache.match_header(self, h.name())) && (!is_simple_method(&self.method) || self.mode == RequestMode::ForcedPreflight) { return self.preflight_fetch(); // Everything after this is part of XHR::fetch() // Expect the organization of code to improve once we have a fetch crate } response } /// https://fetch.spec.whatwg.org/#cors-preflight-fetch fn preflight_fetch(&self) -> CORSResponse { let error = CORSResponse::new_error(); let mut cors_response = CORSResponse::new(); // Step 1 let mut preflight = self.clone(); preflight.method = Method::Options; preflight.headers = Headers::new(); // Step 2 preflight.headers.set(AccessControlRequestMethod(self.method.clone())); // Steps 3-5 let mut header_names = vec![]; for header in self.headers.iter() { header_names.push(header.name().to_owned()); } header_names.sort(); preflight.headers .set(AccessControlRequestHeaders(header_names.into_iter().map(UniCase).collect())); let preflight_request = Request::new(preflight.method, preflight.destination); let mut req = match preflight_request { Ok(req) => req, Err(_) => return error, }; let host = req.headers().get::<Host>().unwrap().clone(); *req.headers_mut() = preflight.headers.clone(); req.headers_mut().set(host); let stream = match req.start() { Ok(s) => s, Err(_) => return error, }; // Step 6 let response = match stream.send() { Ok(r) => r, Err(_) => return error, }; // Step 7: We don't perform a CORS check here // FYI, fn allow_cross_origin_request() performs the CORS check match response.status.class() { Success => {} _ => return error, } cors_response.headers = response.headers.clone(); // Substeps 1-3 (parsing rules: https://fetch.spec.whatwg.org/#http-new-header-syntax) let methods_substep4 = [self.method.clone()]; let mut methods = match response.headers.get() { Some(&AccessControlAllowMethods(ref v)) => &**v, _ => return error, }; let headers = match response.headers.get() { Some(&AccessControlAllowHeaders(ref h)) => h, _ => return error, }; // Substep 4 if methods.is_empty() && preflight.mode == RequestMode::ForcedPreflight { methods = &methods_substep4; } // Substep 5 if!is_simple_method(&self.method) &&!methods.iter().any(|m| m == &self.method) { return error; } // Substep 6 for h in self.headers.iter() { if is_simple_header(&h) { continue; } if!headers.iter().any(|ref h2| h.name().eq_ignore_ascii_case(h2)) { return error; } } // Substeps 7-8 let max_age = match response.headers.get() { Some(&AccessControlMaxAge(num)) => num, None => 0, }; // Substep 9: Impose restrictions on max-age, if any (unimplemented) // Substeps 10-12: Add a cache (partially implemented, XXXManishearth) // This cache should come from the user agent, creating a new one here to check // for compile time errors let cache = &mut CORSCache(vec![]); for m in methods { let cache_match = cache.match_method_and_update(self, m, max_age); if!cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), max_age, false, HeaderOrMethod::MethodData(m.clone()))); } } // Substeps 13-14 for h in response.headers.iter() { let cache_match = cache.match_header_and_update(self, h.name(), max_age); if!cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), max_age, false, HeaderOrMethod::HeaderData(h.to_string()))); } } // Substep 15 cors_response } } pub struct CORSResponse { pub network_error: bool, pub headers: Headers, } impl CORSResponse { fn new() -> CORSResponse { CORSResponse { network_error: false, headers: Headers::new(), } } fn new_error() -> CORSResponse { CORSResponse { network_error: true, headers: Headers::new(), } } } // CORS Cache stuff /// A CORS cache object. Anchor it somewhere to the user agent. #[derive(Clone)] pub struct CORSCache(Vec<CORSCacheEntry>); /// Union type for CORS cache entries /// Each entry might pertain to a header or method #[derive(Clone)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method), } impl HeaderOrMethod { fn match_header(&self, header_name: &str) -> bool { match *self { HeaderOrMethod::HeaderData(ref s) => s.eq_ignore_ascii_case(header_name), _ => false, } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, _ => false, } } } // An entry in the CORS cache #[derive(Clone)] pub struct CORSCacheEntry { pub origin: Url, pub url: Url, pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, created: Timespec, } impl CORSCacheEntry { fn new(origin: Url, url: Url, max_age: u32, credentials: bool, header_or_method: HeaderOrMethod) -> CORSCacheEntry { CORSCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, created: time::now().to_timespec(), } } } impl CORSCache { /// https://fetch.spec.whatwg.org/#concept-cache-clear #[allow(dead_code)] fn clear(&mut self, request: &CORSRequest) { let CORSCache(buf) = self.clone(); let new_buf: Vec<CORSCacheEntry> = buf.into_iter() .filter(|e| e.origin == request.origin && request.destination == e.url) .collect(); *self = CORSCache(new_buf); } // Remove old entries fn cleanup(&mut self) { let CORSCache(buf) = self.clone(); let now = time::now().to_timespec(); let new_buf: Vec<CORSCacheEntry> = buf.into_iter() .filter(|e| now.sec > e.created.sec + e.max_age as i64) .collect(); *self = CORSCache(new_buf); } /// https://fetch.spec.whatwg.org/#concept-cache-match-header fn find_entry_by_header<'a>(&'a mut self, request: &CORSRequest, header_name: &str) -> Option<&'a mut CORSCacheEntry> { self.cleanup(); let CORSCache(ref mut buf) = *self; // Credentials are not yet implemented here buf.iter_mut().find(|e| { e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() && e.origin.port() == request.origin.port() && e.url == request.destination && e.header_or_method.match_header(header_name) }) } fn match_header(&mut self, request: &CORSRequest, header_name: &str) -> bool { self.find_entry_by_header(request, header_name).is_some() } fn match_header_and_update(&mut self, request: &CORSRequest, header_name: &str, new_max_age: u32) -> bool { self.find_entry_by_header(request, header_name).map(|e| e.max_age = new_max_age).is_some() } fn find_entry_by_method<'a>(&'a mut self, request: &CORSRequest, method: &Method) -> Option<&'a mut CORSCacheEntry> { // we can take the method from CORSRequest itself self.cleanup(); let CORSCache(ref mut buf) = *self; // Credentials are not yet implemented here buf.iter_mut().find(|e| { e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() && e.origin.port() == request.origin.port() && e.url == request.destination && e.header_or_method.match_method(method) }) } /// https://fetch.spec.whatwg.org/#concept-cache-match-method fn match_method(&mut self, request: &CORSRequest, method: &Method) -> bool { self.find_entry_by_method(request, method).is_some() } fn match_method_and_update(&mut self, request: &CORSRequest, method: &Method, new_max_age: u32) -> bool { self.find_entry_by_method(request, method).map(|e| e.max_age = new_max_age).is_some() } fn insert(&mut self, entry: CORSCacheEntry) { self.cleanup(); let CORSCache(ref mut buf) = *self; buf.push(entry); } } fn is_simple_header(h: &HeaderView) -> bool
fn is_simple_method(m: &Method) -> bool { match *m { Method::Get | Method::Head | Method::Post => true, _ => false, } } /// Perform a CORS check on a header list and CORS request /// https://fetch.spec.whatwg.org/#cors-check pub fn allow_cross_origin_request(req: &CORSRequest, headers: &Headers) -> bool { match headers.get::<AccessControlAllowOrigin>() { Some(&AccessControlAllowOrigin::Any) => true, // Not always true, depends on credentials mode Some(&AccessControlAllowOrigin::Value(ref url)) => req.origin.serialize() == *url, Some(&AccessControlAllowOrigin::Null) | None => false, } }
{ // FIXME: use h.is::<HeaderType>() when AcceptLanguage and // ContentLanguage headers exist match &*h.name().to_ascii_lowercase() { "accept" | "accept-language" | "content-language" => true, "content-type" => match h.value() { Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) | Some(&ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _))) | Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, _))) => true, _ => false, }, _ => false, } }
identifier_body
cors.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/. */ //! A partial implementation of CORS //! For now this library is XHR-specific. //! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what //! the request mode should be and compare with the fetch spec //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) use hyper::client::Request; use hyper::header::{AccessControlAllowHeaders, AccessControlRequestHeaders}; use hyper::header::{AccessControlAllowMethods, AccessControlRequestMethod}; use hyper::header::{AccessControlAllowOrigin, AccessControlMaxAge}; use hyper::header::{ContentType, Host}; use hyper::header::{HeaderView, Headers}; use hyper::method::Method; use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper::status::StatusClass::Success; use net_traits::{AsyncResponseListener, Metadata, ResponseAction}; use network_listener::{NetworkListener, PreInvoke}; use script_task::ScriptChan; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::sync::{Arc, Mutex}; use time::{self, Timespec, now}; use unicase::UniCase; use url::{SchemeData, Url}; use util::mem::HeapSizeOf; use util::task::spawn_named; /// Interface for network listeners concerned with CORS checks. Proper network requests /// should be initiated from this method, based on the response provided. pub trait AsyncCORSResponseListener { fn response_available(&self, response: CORSResponse); } #[derive(Clone, HeapSizeOf)] pub struct CORSRequest { pub origin: Url, pub destination: Url, pub mode: RequestMode, pub method: Method, #[ignore_heap_size_of = "Defined in hyper"] pub headers: Headers, /// CORS preflight flag (https://fetch.spec.whatwg.org/#concept-http-fetch) /// Indicates that a CORS preflight request and/or cache check is to be performed pub preflight_flag: bool, } /// https://fetch.spec.whatwg.org/#concept-request-mode /// This only covers some of the request modes. The /// `same-origin` and `no CORS` modes are unnecessary for XHR. #[derive(PartialEq, Copy, Clone, HeapSizeOf)] pub enum RequestMode { CORS, // CORS ForcedPreflight, // CORS-with-forced-preflight } impl CORSRequest { /// Creates a CORS request if necessary. Will return an error when fetching is forbidden pub fn maybe_new(referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> Result<Option<CORSRequest>, ()> { if referer.scheme == destination.scheme && referer.host() == destination.host() && referer.port() == destination.port() { return Ok(None); // Not cross-origin, proceed with a normal fetch } match &*destination.scheme { // TODO: If the request's same origin data url flag is set (which isn't the case for XHR) // we can fetch a data URL normally. about:blank can also be fetched by XHR "http" | "https" => { let mut req = CORSRequest::new(referer, destination, mode, method, headers); req.preflight_flag =!is_simple_method(&req.method) || mode == RequestMode::ForcedPreflight; if req.headers.iter().all(|h| is_simple_header(&h)) { req.preflight_flag = true; } Ok(Some(req)) }, _ => Err(()), } } fn new(mut referer: Url, destination: Url, mode: RequestMode, method: Method, headers: Headers) -> CORSRequest { if let SchemeData::Relative(ref mut data) = referer.scheme_data { data.path = vec![]; } referer.fragment = None; referer.query = None; CORSRequest { origin: referer, destination: destination, mode: mode, method: method, headers: headers, preflight_flag: false, } } pub fn http_fetch_async(&self, listener: Box<AsyncCORSResponseListener + Send>, script_chan: Box<ScriptChan + Send>) { struct CORSContext { listener: Box<AsyncCORSResponseListener + Send>, response: Option<CORSResponse>, } // This is shoe-horning the CORSReponse stuff into the rest of the async network // framework right now. It would be worth redesigning http_fetch to do this properly. impl AsyncResponseListener for CORSContext { fn headers_available(&mut self, _metadata: Metadata) { } fn data_available(&mut self, _payload: Vec<u8>) { } fn response_complete(&mut self, _status: Result<(), String>) { let response = self.response.take().unwrap(); self.listener.response_available(response); } } impl PreInvoke for CORSContext {} let context = CORSContext { listener: listener, response: None, }; let listener = NetworkListener { context: Arc::new(Mutex::new(context)), script_chan: script_chan, }; // TODO: this exists only to make preflight check non-blocking // perhaps should be handled by the resource task? let req = self.clone(); spawn_named("cors".to_owned(), move || { let response = req.http_fetch(); let mut context = listener.context.lock(); let context = context.as_mut().unwrap(); context.response = Some(response); listener.notify(ResponseAction::ResponseComplete(Ok(()))); }); } /// http://fetch.spec.whatwg.org/#concept-http-fetch /// This method assumes that the CORS flag is set /// This does not perform the full HTTP fetch, rather it handles part of the CORS filtering /// if self.mode is ForcedPreflight, then the CORS-with-forced-preflight /// fetch flag is set as well pub fn http_fetch(&self) -> CORSResponse { let response = CORSResponse::new(); // Step 2: Handle service workers (unimplemented) // Step 3 // Substep 1: Service workers (unimplemented ) // Substep 2 let cache = &mut CORSCache(vec!()); // XXXManishearth Should come from user agent if self.preflight_flag && !cache.match_method(self, &self.method) && !self.headers.iter().all(|h| is_simple_header(&h) && cache.match_header(self, h.name())) && (!is_simple_method(&self.method) || self.mode == RequestMode::ForcedPreflight) { return self.preflight_fetch(); // Everything after this is part of XHR::fetch() // Expect the organization of code to improve once we have a fetch crate } response } /// https://fetch.spec.whatwg.org/#cors-preflight-fetch fn preflight_fetch(&self) -> CORSResponse { let error = CORSResponse::new_error(); let mut cors_response = CORSResponse::new(); // Step 1 let mut preflight = self.clone(); preflight.method = Method::Options; preflight.headers = Headers::new(); // Step 2 preflight.headers.set(AccessControlRequestMethod(self.method.clone())); // Steps 3-5 let mut header_names = vec![]; for header in self.headers.iter() { header_names.push(header.name().to_owned()); } header_names.sort(); preflight.headers .set(AccessControlRequestHeaders(header_names.into_iter().map(UniCase).collect())); let preflight_request = Request::new(preflight.method, preflight.destination); let mut req = match preflight_request { Ok(req) => req, Err(_) => return error, }; let host = req.headers().get::<Host>().unwrap().clone(); *req.headers_mut() = preflight.headers.clone(); req.headers_mut().set(host); let stream = match req.start() { Ok(s) => s, Err(_) => return error, }; // Step 6 let response = match stream.send() { Ok(r) => r, Err(_) => return error, }; // Step 7: We don't perform a CORS check here // FYI, fn allow_cross_origin_request() performs the CORS check match response.status.class() { Success => {} _ => return error, } cors_response.headers = response.headers.clone(); // Substeps 1-3 (parsing rules: https://fetch.spec.whatwg.org/#http-new-header-syntax) let methods_substep4 = [self.method.clone()]; let mut methods = match response.headers.get() { Some(&AccessControlAllowMethods(ref v)) => &**v, _ => return error, }; let headers = match response.headers.get() { Some(&AccessControlAllowHeaders(ref h)) => h, _ => return error, }; // Substep 4 if methods.is_empty() && preflight.mode == RequestMode::ForcedPreflight { methods = &methods_substep4; } // Substep 5 if!is_simple_method(&self.method) &&!methods.iter().any(|m| m == &self.method) { return error; } // Substep 6 for h in self.headers.iter() { if is_simple_header(&h) { continue; } if!headers.iter().any(|ref h2| h.name().eq_ignore_ascii_case(h2)) { return error; } } // Substeps 7-8 let max_age = match response.headers.get() { Some(&AccessControlMaxAge(num)) => num, None => 0, }; // Substep 9: Impose restrictions on max-age, if any (unimplemented) // Substeps 10-12: Add a cache (partially implemented, XXXManishearth) // This cache should come from the user agent, creating a new one here to check // for compile time errors let cache = &mut CORSCache(vec![]); for m in methods { let cache_match = cache.match_method_and_update(self, m, max_age); if!cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), max_age, false, HeaderOrMethod::MethodData(m.clone()))); } } // Substeps 13-14 for h in response.headers.iter() { let cache_match = cache.match_header_and_update(self, h.name(), max_age); if!cache_match { cache.insert(CORSCacheEntry::new(self.origin.clone(), self.destination.clone(), max_age, false, HeaderOrMethod::HeaderData(h.to_string()))); } } // Substep 15 cors_response } } pub struct CORSResponse { pub network_error: bool, pub headers: Headers, } impl CORSResponse { fn new() -> CORSResponse { CORSResponse { network_error: false, headers: Headers::new(), } } fn new_error() -> CORSResponse { CORSResponse { network_error: true, headers: Headers::new(), } } } // CORS Cache stuff /// A CORS cache object. Anchor it somewhere to the user agent. #[derive(Clone)] pub struct CORSCache(Vec<CORSCacheEntry>); /// Union type for CORS cache entries /// Each entry might pertain to a header or method #[derive(Clone)] pub enum HeaderOrMethod { HeaderData(String), MethodData(Method), } impl HeaderOrMethod { fn match_header(&self, header_name: &str) -> bool { match *self { HeaderOrMethod::HeaderData(ref s) => s.eq_ignore_ascii_case(header_name), _ => false, } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, _ => false, } } } // An entry in the CORS cache #[derive(Clone)] pub struct CORSCacheEntry { pub origin: Url, pub url: Url, pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, created: Timespec, } impl CORSCacheEntry { fn new(origin: Url, url: Url, max_age: u32, credentials: bool, header_or_method: HeaderOrMethod) -> CORSCacheEntry { CORSCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, created: time::now().to_timespec(), } } } impl CORSCache { /// https://fetch.spec.whatwg.org/#concept-cache-clear #[allow(dead_code)] fn clear(&mut self, request: &CORSRequest) { let CORSCache(buf) = self.clone(); let new_buf: Vec<CORSCacheEntry> = buf.into_iter() .filter(|e| e.origin == request.origin && request.destination == e.url) .collect(); *self = CORSCache(new_buf); } // Remove old entries fn cleanup(&mut self) { let CORSCache(buf) = self.clone(); let now = time::now().to_timespec(); let new_buf: Vec<CORSCacheEntry> = buf.into_iter() .filter(|e| now.sec > e.created.sec + e.max_age as i64) .collect(); *self = CORSCache(new_buf); } /// https://fetch.spec.whatwg.org/#concept-cache-match-header fn find_entry_by_header<'a>(&'a mut self, request: &CORSRequest, header_name: &str) -> Option<&'a mut CORSCacheEntry> { self.cleanup(); let CORSCache(ref mut buf) = *self; // Credentials are not yet implemented here buf.iter_mut().find(|e| { e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() && e.origin.port() == request.origin.port() && e.url == request.destination && e.header_or_method.match_header(header_name) }) } fn match_header(&mut self, request: &CORSRequest, header_name: &str) -> bool { self.find_entry_by_header(request, header_name).is_some() } fn match_header_and_update(&mut self, request: &CORSRequest, header_name: &str, new_max_age: u32) -> bool { self.find_entry_by_header(request, header_name).map(|e| e.max_age = new_max_age).is_some() } fn find_entry_by_method<'a>(&'a mut self, request: &CORSRequest, method: &Method) -> Option<&'a mut CORSCacheEntry> { // we can take the method from CORSRequest itself self.cleanup(); let CORSCache(ref mut buf) = *self; // Credentials are not yet implemented here buf.iter_mut().find(|e| { e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() && e.origin.port() == request.origin.port() && e.url == request.destination && e.header_or_method.match_method(method)
}) } /// https://fetch.spec.whatwg.org/#concept-cache-match-method fn match_method(&mut self, request: &CORSRequest, method: &Method) -> bool { self.find_entry_by_method(request, method).is_some() } fn match_method_and_update(&mut self, request: &CORSRequest, method: &Method, new_max_age: u32) -> bool { self.find_entry_by_method(request, method).map(|e| e.max_age = new_max_age).is_some() } fn insert(&mut self, entry: CORSCacheEntry) { self.cleanup(); let CORSCache(ref mut buf) = *self; buf.push(entry); } } fn is_simple_header(h: &HeaderView) -> bool { // FIXME: use h.is::<HeaderType>() when AcceptLanguage and // ContentLanguage headers exist match &*h.name().to_ascii_lowercase() { "accept" | "accept-language" | "content-language" => true, "content-type" => match h.value() { Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) | Some(&ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _))) | Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, _))) => true, _ => false, }, _ => false, } } fn is_simple_method(m: &Method) -> bool { match *m { Method::Get | Method::Head | Method::Post => true, _ => false, } } /// Perform a CORS check on a header list and CORS request /// https://fetch.spec.whatwg.org/#cors-check pub fn allow_cross_origin_request(req: &CORSRequest, headers: &Headers) -> bool { match headers.get::<AccessControlAllowOrigin>() { Some(&AccessControlAllowOrigin::Any) => true, // Not always true, depends on credentials mode Some(&AccessControlAllowOrigin::Value(ref url)) => req.origin.serialize() == *url, Some(&AccessControlAllowOrigin::Null) | None => false, } }
random_line_split
and.rs
// Copyright 2014 Strahinja Val Markovic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::{Expression, ParseState, ParseResult}; macro_rules! and( ( $ex:expr ) => ( &base::And::new( $ex ) ); ); pub struct And<'a> { expr: &'a ( Expression + 'a ) }
impl<'a> And<'a> { pub fn new( expr: &Expression ) -> And { And { expr: expr } } } impl<'b> Expression for And<'b> { fn apply<'a>( &self, parse_state: &ParseState<'a> ) -> Option< ParseResult<'a> > { match self.expr.apply( parse_state ) { Some( _ ) => Some( ParseResult::fromParseState( *parse_state ) ), _ => None } } } #[cfg(test)] mod tests { use base; use base::{ParseResult, Expression}; #[test] fn And_Match_WithLiteral() { let orig_state = input_state!( "foo" ); match and!( lit!( "foo" ) ).apply( &orig_state ) { Some( ParseResult{ nodes, parse_state } ) => { assert!( nodes.is_empty() ); assert_eq!( parse_state, orig_state ); } _ => panic!( "No match." ) } } #[test] fn And_Match_WithCharClass() { let orig_state = input_state!( "c" ); match and!( class!( "a-z" ) ).apply( &orig_state ) { Some( ParseResult{ nodes, parse_state } ) => { assert!( nodes.is_empty() ); assert_eq!( parse_state, orig_state ); } _ => panic!( "No match." ) } } #[test] fn And_NoMatch() { assert!( and!( class!( "a-z" ) ).apply( &input_state!( "0" ) ).is_none() ); assert!( and!( lit!( "x" ) ).apply( &input_state!( "y" ) ).is_none() ); } }
random_line_split
and.rs
// Copyright 2014 Strahinja Val Markovic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::{Expression, ParseState, ParseResult}; macro_rules! and( ( $ex:expr ) => ( &base::And::new( $ex ) ); ); pub struct And<'a> { expr: &'a ( Expression + 'a ) } impl<'a> And<'a> { pub fn new( expr: &Expression ) -> And
} impl<'b> Expression for And<'b> { fn apply<'a>( &self, parse_state: &ParseState<'a> ) -> Option< ParseResult<'a> > { match self.expr.apply( parse_state ) { Some( _ ) => Some( ParseResult::fromParseState( *parse_state ) ), _ => None } } } #[cfg(test)] mod tests { use base; use base::{ParseResult, Expression}; #[test] fn And_Match_WithLiteral() { let orig_state = input_state!( "foo" ); match and!( lit!( "foo" ) ).apply( &orig_state ) { Some( ParseResult{ nodes, parse_state } ) => { assert!( nodes.is_empty() ); assert_eq!( parse_state, orig_state ); } _ => panic!( "No match." ) } } #[test] fn And_Match_WithCharClass() { let orig_state = input_state!( "c" ); match and!( class!( "a-z" ) ).apply( &orig_state ) { Some( ParseResult{ nodes, parse_state } ) => { assert!( nodes.is_empty() ); assert_eq!( parse_state, orig_state ); } _ => panic!( "No match." ) } } #[test] fn And_NoMatch() { assert!( and!( class!( "a-z" ) ).apply( &input_state!( "0" ) ).is_none() ); assert!( and!( lit!( "x" ) ).apply( &input_state!( "y" ) ).is_none() ); } }
{ And { expr: expr } }
identifier_body
and.rs
// Copyright 2014 Strahinja Val Markovic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use super::{Expression, ParseState, ParseResult}; macro_rules! and( ( $ex:expr ) => ( &base::And::new( $ex ) ); ); pub struct And<'a> { expr: &'a ( Expression + 'a ) } impl<'a> And<'a> { pub fn new( expr: &Expression ) -> And { And { expr: expr } } } impl<'b> Expression for And<'b> { fn apply<'a>( &self, parse_state: &ParseState<'a> ) -> Option< ParseResult<'a> > { match self.expr.apply( parse_state ) { Some( _ ) => Some( ParseResult::fromParseState( *parse_state ) ), _ => None } } } #[cfg(test)] mod tests { use base; use base::{ParseResult, Expression}; #[test] fn And_Match_WithLiteral() { let orig_state = input_state!( "foo" ); match and!( lit!( "foo" ) ).apply( &orig_state ) { Some( ParseResult{ nodes, parse_state } ) => { assert!( nodes.is_empty() ); assert_eq!( parse_state, orig_state ); } _ => panic!( "No match." ) } } #[test] fn And_Match_WithCharClass() { let orig_state = input_state!( "c" ); match and!( class!( "a-z" ) ).apply( &orig_state ) { Some( ParseResult{ nodes, parse_state } ) => { assert!( nodes.is_empty() ); assert_eq!( parse_state, orig_state ); } _ => panic!( "No match." ) } } #[test] fn
() { assert!( and!( class!( "a-z" ) ).apply( &input_state!( "0" ) ).is_none() ); assert!( and!( lit!( "x" ) ).apply( &input_state!( "y" ) ).is_none() ); } }
And_NoMatch
identifier_name
context.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::uint; use std::cast::{transmute, transmute_mut_unsafe}; use stack::Stack; use std::rt::stack; use std::raw; // FIXME #7761: Registers is boxed so that it is 16-byte aligned, for storing // SSE regs. It would be marginally better not to do this. In C++ we // use an attribute on a struct. // FIXME #7761: It would be nice to define regs as `~Option<Registers>` since // the registers are sometimes empty, but the discriminant would // then misalign the regs again. pub struct Context { /// Hold the registers while the task or scheduler is suspended regs: ~Registers, /// Lower bound and upper bound for the stack stack_bounds: Option<(uint, uint)>, } pub type InitFn = extern "C" fn(uint, *(), *()) ->!; impl Context { pub fn empty() -> Context { Context { regs: new_regs(), stack_bounds: None, } } /// Create a new context that will resume execution by running proc() /// /// The `init` function will be run with `arg` and the `start` procedure /// split up into code and env pointers. It is required that the `init` /// function never return. /// /// FIXME: this is basically an awful the interface. The main reason for /// this is to reduce the number of allocations made when a green /// task is spawned as much as possible pub fn new(init: InitFn, arg: uint, start: proc(), stack: &mut Stack) -> Context { let sp: *uint = stack.end(); let sp: *mut uint = unsafe { transmute_mut_unsafe(sp) }; // Save and then immediately load the current context, // which we will then modify to call the given function when restored let mut regs = new_regs(); initialize_call_frame(&mut *regs, init, arg, unsafe { transmute(start) }, sp); // Scheduler tasks don't have a stack in the "we allocated it" sense, // but rather they run on pthreads stacks. We have complete control over // them in terms of the code running on them (and hopefully they don't // overflow). Additionally, their coroutine stacks are listed as being // zero-length, so that's how we detect what's what here. let stack_base: *uint = stack.start(); let bounds = if sp as uint == stack_base as uint { None } else { Some((stack_base as uint, sp as uint)) }; return Context { regs: regs, stack_bounds: bounds, } } /* Switch contexts Suspend the current execution context and resume another by saving the registers values of the executing thread to a Context then loading the registers from a previously saved Context. */ pub fn swap(out_context: &mut Context, in_context: &Context) { rtdebug!("swapping contexts"); let out_regs: &mut Registers = match out_context { &Context { regs: ~ref mut r,.. } => r }; let in_regs: &Registers = match in_context { &Context { regs: ~ref r,.. } => r }; rtdebug!("noting the stack limit and doing raw swap"); unsafe { // Right before we switch to the new context, set the new context's // stack limit in the OS-specified TLS slot. This also means that // we cannot call any more rust functions after record_stack_bounds // returns because they would all likely fail due to the limit being // invalid for the current task. Lucky for us `rust_swap_registers` // is a C function so we don't have to worry about that! match in_context.stack_bounds { Some((lo, hi)) => stack::record_stack_bounds(lo, hi), // If we're going back to one of the original contexts or // something that's possibly not a "normal task", then reset // the stack limit to 0 to make morestack never fail None => stack::record_stack_bounds(0, uint::MAX), } rust_swap_registers(out_regs, in_regs) } } } #[link(name = "context_switch", kind = "static")] extern { fn rust_swap_registers(out_regs: *mut Registers, in_regs: *Registers); } // Register contexts used in various architectures // // These structures all represent a context of one task throughout its // execution. Each struct is a representation of the architecture's register // set. When swapping between tasks, these register sets are used to save off // the current registers into one struct, and load them all from another. // // Note that this is only used for context switching, which means that some of // the registers may go unused. For example, for architectures with // callee/caller saved registers, the context will only reflect the callee-saved // registers. This is because the caller saved registers are already stored // elsewhere on the stack (if it was necessary anyway). // // Additionally, there may be fields on various architectures which are unused // entirely because they only reflect what is theoretically possible for a // "complete register set" to show, but user-space cannot alter these registers. // An example of this would be the segment selectors for x86. // // These structures/functions are roughly in-sync with the source files inside // of src/rt/arch/$arch. The only currently used function from those folders is // the `rust_swap_registers` function, but that's only because for now segmented // stacks are disabled. #[cfg(target_arch = "x86")] struct Registers { eax: u32, ebx: u32, ecx: u32, edx: u32, ebp: u32, esi: u32, edi: u32, esp: u32, cs: u16, ds: u16, ss: u16, es: u16, fs: u16, gs: u16, eflags: u32, eip: u32 } #[cfg(target_arch = "x86")] fn new_regs() -> ~Registers { ~Registers { eax: 0, ebx: 0, ecx: 0, edx: 0, ebp: 0, esi: 0, edi: 0, esp: 0, cs: 0, ds: 0, ss: 0, es: 0, fs: 0, gs: 0, eflags: 0, eip: 0 } } #[cfg(target_arch = "x86")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { // x86 has interesting stack alignment requirements, so do some alignment // plus some offsetting to figure out what the actual stack should be. let sp = align_down(sp); let sp = mut_offset(sp, -4); unsafe { *mut_offset(sp, 2) = procedure.env as uint }; unsafe { *mut_offset(sp, 1) = procedure.code as uint }; unsafe { *mut_offset(sp, 0) = arg as uint }; let sp = mut_offset(sp, -1); unsafe { *sp = 0 }; // The final return address regs.esp = sp as u32; regs.eip = fptr as u32; // Last base pointer on the stack is 0 regs.ebp = 0; } // windows requires saving more registers (both general and XMM), so the windows // register context must be larger. #[cfg(windows, target_arch = "x86_64")] type Registers = [uint,..34]; #[cfg(not(windows), target_arch = "x86_64")] type Registers = [uint,..22]; #[cfg(windows, target_arch = "x86_64")] fn new_regs() -> ~Registers { ~([0,.. 34]) } #[cfg(not(windows), target_arch = "x86_64")] fn new_regs() -> ~Registers
#[cfg(target_arch = "x86_64")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { extern { fn rust_bootstrap_green_task(); } // Redefinitions from rt/arch/x86_64/regs.h static RUSTRT_RSP: uint = 1; static RUSTRT_IP: uint = 8; static RUSTRT_RBP: uint = 2; static RUSTRT_R12: uint = 4; static RUSTRT_R13: uint = 5; static RUSTRT_R14: uint = 6; static RUSTRT_R15: uint = 7; let sp = align_down(sp); let sp = mut_offset(sp, -1); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } rtdebug!("creating call frame"); rtdebug!("fptr {:#x}", fptr as uint); rtdebug!("arg {:#x}", arg); rtdebug!("sp {}", sp); // These registers are frobbed by rust_bootstrap_green_task into the right // location so we can invoke the "real init function", `fptr`. regs[RUSTRT_R12] = arg as uint; regs[RUSTRT_R13] = procedure.code as uint; regs[RUSTRT_R14] = procedure.env as uint; regs[RUSTRT_R15] = fptr as uint; // These registers are picked up by the regulard context switch paths. These // will put us in "mostly the right context" except for frobbing all the // arguments to the right place. We have the small trampoline code inside of // rust_bootstrap_green_task to do that. regs[RUSTRT_RSP] = sp as uint; regs[RUSTRT_IP] = rust_bootstrap_green_task as uint; // Last base pointer on the stack should be 0 regs[RUSTRT_RBP] = 0; } #[cfg(target_arch = "arm")] type Registers = [uint,..32]; #[cfg(target_arch = "arm")] fn new_regs() -> ~Registers { ~([0,.. 32]) } #[cfg(target_arch = "arm")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { extern { fn rust_bootstrap_green_task(); } let sp = align_down(sp); // sp of arm eabi is 8-byte aligned let sp = mut_offset(sp, -2); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } // ARM uses the same technique as x86_64 to have a landing pad for the start // of all new green tasks. Neither r1/r2 are saved on a context switch, so // the shim will copy r3/r4 into r1/r2 and then execute the function in r5 regs[0] = arg as uint; // r0 regs[3] = procedure.code as uint; // r3 regs[4] = procedure.env as uint; // r4 regs[5] = fptr as uint; // r5 regs[13] = sp as uint; // #52 sp, r13 regs[14] = rust_bootstrap_green_task as uint; // #56 pc, r14 --> lr } #[cfg(target_arch = "mips")] type Registers = [uint,..32]; #[cfg(target_arch = "mips")] fn new_regs() -> ~Registers { ~([0,.. 32]) } #[cfg(target_arch = "mips")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { let sp = align_down(sp); // sp of mips o32 is 8-byte aligned let sp = mut_offset(sp, -2); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } regs[4] = arg as uint; regs[5] = procedure.code as uint; regs[6] = procedure.env as uint; regs[29] = sp as uint; regs[25] = fptr as uint; regs[31] = fptr as uint; } fn align_down(sp: *mut uint) -> *mut uint { let sp = (sp as uint) &!(16 - 1); sp as *mut uint } // ptr::mut_offset is positive ints only #[inline] pub fn mut_offset<T>(ptr: *mut T, count: int) -> *mut T { use std::mem::size_of; (ptr as int + count * (size_of::<T>() as int)) as *mut T }
{ ~([0, .. 22]) }
identifier_body
context.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::uint; use std::cast::{transmute, transmute_mut_unsafe}; use stack::Stack; use std::rt::stack; use std::raw; // FIXME #7761: Registers is boxed so that it is 16-byte aligned, for storing // SSE regs. It would be marginally better not to do this. In C++ we // use an attribute on a struct. // FIXME #7761: It would be nice to define regs as `~Option<Registers>` since // the registers are sometimes empty, but the discriminant would // then misalign the regs again. pub struct Context { /// Hold the registers while the task or scheduler is suspended regs: ~Registers, /// Lower bound and upper bound for the stack stack_bounds: Option<(uint, uint)>, } pub type InitFn = extern "C" fn(uint, *(), *()) ->!; impl Context { pub fn empty() -> Context { Context { regs: new_regs(), stack_bounds: None, } } /// Create a new context that will resume execution by running proc() /// /// The `init` function will be run with `arg` and the `start` procedure /// split up into code and env pointers. It is required that the `init` /// function never return. /// /// FIXME: this is basically an awful the interface. The main reason for /// this is to reduce the number of allocations made when a green /// task is spawned as much as possible pub fn new(init: InitFn, arg: uint, start: proc(), stack: &mut Stack) -> Context { let sp: *uint = stack.end(); let sp: *mut uint = unsafe { transmute_mut_unsafe(sp) }; // Save and then immediately load the current context, // which we will then modify to call the given function when restored let mut regs = new_regs(); initialize_call_frame(&mut *regs, init, arg, unsafe { transmute(start) }, sp); // Scheduler tasks don't have a stack in the "we allocated it" sense, // but rather they run on pthreads stacks. We have complete control over // them in terms of the code running on them (and hopefully they don't // overflow). Additionally, their coroutine stacks are listed as being // zero-length, so that's how we detect what's what here. let stack_base: *uint = stack.start(); let bounds = if sp as uint == stack_base as uint { None } else { Some((stack_base as uint, sp as uint)) }; return Context { regs: regs, stack_bounds: bounds, } } /* Switch contexts Suspend the current execution context and resume another by saving the registers values of the executing thread to a Context then loading the registers from a previously saved Context. */ pub fn
(out_context: &mut Context, in_context: &Context) { rtdebug!("swapping contexts"); let out_regs: &mut Registers = match out_context { &Context { regs: ~ref mut r,.. } => r }; let in_regs: &Registers = match in_context { &Context { regs: ~ref r,.. } => r }; rtdebug!("noting the stack limit and doing raw swap"); unsafe { // Right before we switch to the new context, set the new context's // stack limit in the OS-specified TLS slot. This also means that // we cannot call any more rust functions after record_stack_bounds // returns because they would all likely fail due to the limit being // invalid for the current task. Lucky for us `rust_swap_registers` // is a C function so we don't have to worry about that! match in_context.stack_bounds { Some((lo, hi)) => stack::record_stack_bounds(lo, hi), // If we're going back to one of the original contexts or // something that's possibly not a "normal task", then reset // the stack limit to 0 to make morestack never fail None => stack::record_stack_bounds(0, uint::MAX), } rust_swap_registers(out_regs, in_regs) } } } #[link(name = "context_switch", kind = "static")] extern { fn rust_swap_registers(out_regs: *mut Registers, in_regs: *Registers); } // Register contexts used in various architectures // // These structures all represent a context of one task throughout its // execution. Each struct is a representation of the architecture's register // set. When swapping between tasks, these register sets are used to save off // the current registers into one struct, and load them all from another. // // Note that this is only used for context switching, which means that some of // the registers may go unused. For example, for architectures with // callee/caller saved registers, the context will only reflect the callee-saved // registers. This is because the caller saved registers are already stored // elsewhere on the stack (if it was necessary anyway). // // Additionally, there may be fields on various architectures which are unused // entirely because they only reflect what is theoretically possible for a // "complete register set" to show, but user-space cannot alter these registers. // An example of this would be the segment selectors for x86. // // These structures/functions are roughly in-sync with the source files inside // of src/rt/arch/$arch. The only currently used function from those folders is // the `rust_swap_registers` function, but that's only because for now segmented // stacks are disabled. #[cfg(target_arch = "x86")] struct Registers { eax: u32, ebx: u32, ecx: u32, edx: u32, ebp: u32, esi: u32, edi: u32, esp: u32, cs: u16, ds: u16, ss: u16, es: u16, fs: u16, gs: u16, eflags: u32, eip: u32 } #[cfg(target_arch = "x86")] fn new_regs() -> ~Registers { ~Registers { eax: 0, ebx: 0, ecx: 0, edx: 0, ebp: 0, esi: 0, edi: 0, esp: 0, cs: 0, ds: 0, ss: 0, es: 0, fs: 0, gs: 0, eflags: 0, eip: 0 } } #[cfg(target_arch = "x86")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { // x86 has interesting stack alignment requirements, so do some alignment // plus some offsetting to figure out what the actual stack should be. let sp = align_down(sp); let sp = mut_offset(sp, -4); unsafe { *mut_offset(sp, 2) = procedure.env as uint }; unsafe { *mut_offset(sp, 1) = procedure.code as uint }; unsafe { *mut_offset(sp, 0) = arg as uint }; let sp = mut_offset(sp, -1); unsafe { *sp = 0 }; // The final return address regs.esp = sp as u32; regs.eip = fptr as u32; // Last base pointer on the stack is 0 regs.ebp = 0; } // windows requires saving more registers (both general and XMM), so the windows // register context must be larger. #[cfg(windows, target_arch = "x86_64")] type Registers = [uint,..34]; #[cfg(not(windows), target_arch = "x86_64")] type Registers = [uint,..22]; #[cfg(windows, target_arch = "x86_64")] fn new_regs() -> ~Registers { ~([0,.. 34]) } #[cfg(not(windows), target_arch = "x86_64")] fn new_regs() -> ~Registers { ~([0,.. 22]) } #[cfg(target_arch = "x86_64")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { extern { fn rust_bootstrap_green_task(); } // Redefinitions from rt/arch/x86_64/regs.h static RUSTRT_RSP: uint = 1; static RUSTRT_IP: uint = 8; static RUSTRT_RBP: uint = 2; static RUSTRT_R12: uint = 4; static RUSTRT_R13: uint = 5; static RUSTRT_R14: uint = 6; static RUSTRT_R15: uint = 7; let sp = align_down(sp); let sp = mut_offset(sp, -1); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } rtdebug!("creating call frame"); rtdebug!("fptr {:#x}", fptr as uint); rtdebug!("arg {:#x}", arg); rtdebug!("sp {}", sp); // These registers are frobbed by rust_bootstrap_green_task into the right // location so we can invoke the "real init function", `fptr`. regs[RUSTRT_R12] = arg as uint; regs[RUSTRT_R13] = procedure.code as uint; regs[RUSTRT_R14] = procedure.env as uint; regs[RUSTRT_R15] = fptr as uint; // These registers are picked up by the regulard context switch paths. These // will put us in "mostly the right context" except for frobbing all the // arguments to the right place. We have the small trampoline code inside of // rust_bootstrap_green_task to do that. regs[RUSTRT_RSP] = sp as uint; regs[RUSTRT_IP] = rust_bootstrap_green_task as uint; // Last base pointer on the stack should be 0 regs[RUSTRT_RBP] = 0; } #[cfg(target_arch = "arm")] type Registers = [uint,..32]; #[cfg(target_arch = "arm")] fn new_regs() -> ~Registers { ~([0,.. 32]) } #[cfg(target_arch = "arm")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { extern { fn rust_bootstrap_green_task(); } let sp = align_down(sp); // sp of arm eabi is 8-byte aligned let sp = mut_offset(sp, -2); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } // ARM uses the same technique as x86_64 to have a landing pad for the start // of all new green tasks. Neither r1/r2 are saved on a context switch, so // the shim will copy r3/r4 into r1/r2 and then execute the function in r5 regs[0] = arg as uint; // r0 regs[3] = procedure.code as uint; // r3 regs[4] = procedure.env as uint; // r4 regs[5] = fptr as uint; // r5 regs[13] = sp as uint; // #52 sp, r13 regs[14] = rust_bootstrap_green_task as uint; // #56 pc, r14 --> lr } #[cfg(target_arch = "mips")] type Registers = [uint,..32]; #[cfg(target_arch = "mips")] fn new_regs() -> ~Registers { ~([0,.. 32]) } #[cfg(target_arch = "mips")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { let sp = align_down(sp); // sp of mips o32 is 8-byte aligned let sp = mut_offset(sp, -2); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } regs[4] = arg as uint; regs[5] = procedure.code as uint; regs[6] = procedure.env as uint; regs[29] = sp as uint; regs[25] = fptr as uint; regs[31] = fptr as uint; } fn align_down(sp: *mut uint) -> *mut uint { let sp = (sp as uint) &!(16 - 1); sp as *mut uint } // ptr::mut_offset is positive ints only #[inline] pub fn mut_offset<T>(ptr: *mut T, count: int) -> *mut T { use std::mem::size_of; (ptr as int + count * (size_of::<T>() as int)) as *mut T }
swap
identifier_name
context.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::uint; use std::cast::{transmute, transmute_mut_unsafe}; use stack::Stack; use std::rt::stack; use std::raw; // FIXME #7761: Registers is boxed so that it is 16-byte aligned, for storing // SSE regs. It would be marginally better not to do this. In C++ we // use an attribute on a struct. // FIXME #7761: It would be nice to define regs as `~Option<Registers>` since // the registers are sometimes empty, but the discriminant would // then misalign the regs again. pub struct Context { /// Hold the registers while the task or scheduler is suspended regs: ~Registers, /// Lower bound and upper bound for the stack stack_bounds: Option<(uint, uint)>, } pub type InitFn = extern "C" fn(uint, *(), *()) ->!; impl Context { pub fn empty() -> Context { Context { regs: new_regs(), stack_bounds: None, } } /// Create a new context that will resume execution by running proc() /// /// The `init` function will be run with `arg` and the `start` procedure /// split up into code and env pointers. It is required that the `init` /// function never return. /// /// FIXME: this is basically an awful the interface. The main reason for /// this is to reduce the number of allocations made when a green /// task is spawned as much as possible pub fn new(init: InitFn, arg: uint, start: proc(), stack: &mut Stack) -> Context { let sp: *uint = stack.end(); let sp: *mut uint = unsafe { transmute_mut_unsafe(sp) }; // Save and then immediately load the current context, // which we will then modify to call the given function when restored let mut regs = new_regs(); initialize_call_frame(&mut *regs, init, arg, unsafe { transmute(start) }, sp); // Scheduler tasks don't have a stack in the "we allocated it" sense, // but rather they run on pthreads stacks. We have complete control over // them in terms of the code running on them (and hopefully they don't // overflow). Additionally, their coroutine stacks are listed as being // zero-length, so that's how we detect what's what here. let stack_base: *uint = stack.start(); let bounds = if sp as uint == stack_base as uint { None } else { Some((stack_base as uint, sp as uint)) }; return Context { regs: regs, stack_bounds: bounds, } } /* Switch contexts Suspend the current execution context and resume another by saving the registers values of the executing thread to a Context then loading the registers from a previously saved Context. */ pub fn swap(out_context: &mut Context, in_context: &Context) { rtdebug!("swapping contexts"); let out_regs: &mut Registers = match out_context { &Context { regs: ~ref mut r,.. } => r }; let in_regs: &Registers = match in_context { &Context { regs: ~ref r,.. } => r }; rtdebug!("noting the stack limit and doing raw swap"); unsafe { // Right before we switch to the new context, set the new context's // stack limit in the OS-specified TLS slot. This also means that // we cannot call any more rust functions after record_stack_bounds // returns because they would all likely fail due to the limit being // invalid for the current task. Lucky for us `rust_swap_registers` // is a C function so we don't have to worry about that! match in_context.stack_bounds { Some((lo, hi)) => stack::record_stack_bounds(lo, hi), // If we're going back to one of the original contexts or // something that's possibly not a "normal task", then reset // the stack limit to 0 to make morestack never fail None => stack::record_stack_bounds(0, uint::MAX), } rust_swap_registers(out_regs, in_regs) } } } #[link(name = "context_switch", kind = "static")] extern { fn rust_swap_registers(out_regs: *mut Registers, in_regs: *Registers); } // Register contexts used in various architectures // // These structures all represent a context of one task throughout its // execution. Each struct is a representation of the architecture's register // set. When swapping between tasks, these register sets are used to save off // the current registers into one struct, and load them all from another. // // Note that this is only used for context switching, which means that some of // the registers may go unused. For example, for architectures with // callee/caller saved registers, the context will only reflect the callee-saved // registers. This is because the caller saved registers are already stored // elsewhere on the stack (if it was necessary anyway). // // Additionally, there may be fields on various architectures which are unused // entirely because they only reflect what is theoretically possible for a // "complete register set" to show, but user-space cannot alter these registers. // An example of this would be the segment selectors for x86. // // These structures/functions are roughly in-sync with the source files inside // of src/rt/arch/$arch. The only currently used function from those folders is // the `rust_swap_registers` function, but that's only because for now segmented // stacks are disabled. #[cfg(target_arch = "x86")] struct Registers { eax: u32, ebx: u32, ecx: u32, edx: u32, ebp: u32, esi: u32, edi: u32, esp: u32, cs: u16, ds: u16, ss: u16, es: u16, fs: u16, gs: u16, eflags: u32, eip: u32 } #[cfg(target_arch = "x86")] fn new_regs() -> ~Registers { ~Registers { eax: 0, ebx: 0, ecx: 0, edx: 0, ebp: 0, esi: 0, edi: 0, esp: 0, cs: 0, ds: 0, ss: 0, es: 0, fs: 0, gs: 0, eflags: 0, eip: 0 } } #[cfg(target_arch = "x86")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { // x86 has interesting stack alignment requirements, so do some alignment // plus some offsetting to figure out what the actual stack should be. let sp = align_down(sp); let sp = mut_offset(sp, -4); unsafe { *mut_offset(sp, 2) = procedure.env as uint }; unsafe { *mut_offset(sp, 1) = procedure.code as uint }; unsafe { *mut_offset(sp, 0) = arg as uint }; let sp = mut_offset(sp, -1); unsafe { *sp = 0 }; // The final return address regs.esp = sp as u32; regs.eip = fptr as u32; // Last base pointer on the stack is 0 regs.ebp = 0; } // windows requires saving more registers (both general and XMM), so the windows // register context must be larger. #[cfg(windows, target_arch = "x86_64")] type Registers = [uint,..34]; #[cfg(not(windows), target_arch = "x86_64")] type Registers = [uint,..22]; #[cfg(windows, target_arch = "x86_64")] fn new_regs() -> ~Registers { ~([0,.. 34]) } #[cfg(not(windows), target_arch = "x86_64")] fn new_regs() -> ~Registers { ~([0,.. 22]) } #[cfg(target_arch = "x86_64")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { extern { fn rust_bootstrap_green_task(); } // Redefinitions from rt/arch/x86_64/regs.h static RUSTRT_RSP: uint = 1; static RUSTRT_IP: uint = 8; static RUSTRT_RBP: uint = 2; static RUSTRT_R12: uint = 4; static RUSTRT_R13: uint = 5; static RUSTRT_R14: uint = 6; static RUSTRT_R15: uint = 7; let sp = align_down(sp); let sp = mut_offset(sp, -1); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } rtdebug!("creating call frame"); rtdebug!("fptr {:#x}", fptr as uint); rtdebug!("arg {:#x}", arg); rtdebug!("sp {}", sp); // These registers are frobbed by rust_bootstrap_green_task into the right // location so we can invoke the "real init function", `fptr`. regs[RUSTRT_R12] = arg as uint; regs[RUSTRT_R13] = procedure.code as uint; regs[RUSTRT_R14] = procedure.env as uint; regs[RUSTRT_R15] = fptr as uint; // These registers are picked up by the regulard context switch paths. These // will put us in "mostly the right context" except for frobbing all the // arguments to the right place. We have the small trampoline code inside of // rust_bootstrap_green_task to do that. regs[RUSTRT_RSP] = sp as uint; regs[RUSTRT_IP] = rust_bootstrap_green_task as uint; // Last base pointer on the stack should be 0 regs[RUSTRT_RBP] = 0; } #[cfg(target_arch = "arm")] type Registers = [uint,..32]; #[cfg(target_arch = "arm")] fn new_regs() -> ~Registers { ~([0,.. 32]) } #[cfg(target_arch = "arm")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { extern { fn rust_bootstrap_green_task(); } let sp = align_down(sp); // sp of arm eabi is 8-byte aligned let sp = mut_offset(sp, -2);
unsafe { *sp = 0; } // ARM uses the same technique as x86_64 to have a landing pad for the start // of all new green tasks. Neither r1/r2 are saved on a context switch, so // the shim will copy r3/r4 into r1/r2 and then execute the function in r5 regs[0] = arg as uint; // r0 regs[3] = procedure.code as uint; // r3 regs[4] = procedure.env as uint; // r4 regs[5] = fptr as uint; // r5 regs[13] = sp as uint; // #52 sp, r13 regs[14] = rust_bootstrap_green_task as uint; // #56 pc, r14 --> lr } #[cfg(target_arch = "mips")] type Registers = [uint,..32]; #[cfg(target_arch = "mips")] fn new_regs() -> ~Registers { ~([0,.. 32]) } #[cfg(target_arch = "mips")] fn initialize_call_frame(regs: &mut Registers, fptr: InitFn, arg: uint, procedure: raw::Procedure, sp: *mut uint) { let sp = align_down(sp); // sp of mips o32 is 8-byte aligned let sp = mut_offset(sp, -2); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } regs[4] = arg as uint; regs[5] = procedure.code as uint; regs[6] = procedure.env as uint; regs[29] = sp as uint; regs[25] = fptr as uint; regs[31] = fptr as uint; } fn align_down(sp: *mut uint) -> *mut uint { let sp = (sp as uint) &!(16 - 1); sp as *mut uint } // ptr::mut_offset is positive ints only #[inline] pub fn mut_offset<T>(ptr: *mut T, count: int) -> *mut T { use std::mem::size_of; (ptr as int + count * (size_of::<T>() as int)) as *mut T }
// The final return address. 0 indicates the bottom of the stack
random_line_split
asm.rs
use super::BackendTypes; use crate::mir::operand::OperandRef; use crate::mir::place::PlaceRef; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_hir::def_id::DefId; use rustc_hir::LlvmInlineAsmInner; use rustc_middle::ty::Instance; use rustc_span::Span; use rustc_target::asm::InlineAsmRegOrRegClass; #[derive(Debug)] pub enum
<'tcx, B: BackendTypes +?Sized> { In { reg: InlineAsmRegOrRegClass, value: OperandRef<'tcx, B::Value>, }, Out { reg: InlineAsmRegOrRegClass, late: bool, place: Option<PlaceRef<'tcx, B::Value>>, }, InOut { reg: InlineAsmRegOrRegClass, late: bool, in_value: OperandRef<'tcx, B::Value>, out_place: Option<PlaceRef<'tcx, B::Value>>, }, Const { string: String, }, SymFn { instance: Instance<'tcx>, }, SymStatic { def_id: DefId, }, } #[derive(Debug)] pub enum GlobalAsmOperandRef { Const { string: String }, } pub trait AsmBuilderMethods<'tcx>: BackendTypes { /// Take an inline assembly expression and splat it out via LLVM fn codegen_llvm_inline_asm( &mut self, ia: &LlvmInlineAsmInner, outputs: Vec<PlaceRef<'tcx, Self::Value>>, inputs: Vec<Self::Value>, span: Span, ) -> bool; /// Take an inline assembly expression and splat it out via LLVM fn codegen_inline_asm( &mut self, template: &[InlineAsmTemplatePiece], operands: &[InlineAsmOperandRef<'tcx, Self>], options: InlineAsmOptions, line_spans: &[Span], instance: Instance<'_>, ); } pub trait AsmMethods { fn codegen_global_asm( &self, template: &[InlineAsmTemplatePiece], operands: &[GlobalAsmOperandRef], options: InlineAsmOptions, line_spans: &[Span], ); }
InlineAsmOperandRef
identifier_name
asm.rs
use super::BackendTypes; use crate::mir::operand::OperandRef; use crate::mir::place::PlaceRef; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_hir::def_id::DefId; use rustc_hir::LlvmInlineAsmInner; use rustc_middle::ty::Instance; use rustc_span::Span; use rustc_target::asm::InlineAsmRegOrRegClass; #[derive(Debug)] pub enum InlineAsmOperandRef<'tcx, B: BackendTypes +?Sized> { In { reg: InlineAsmRegOrRegClass, value: OperandRef<'tcx, B::Value>, }, Out { reg: InlineAsmRegOrRegClass, late: bool, place: Option<PlaceRef<'tcx, B::Value>>, }, InOut { reg: InlineAsmRegOrRegClass, late: bool, in_value: OperandRef<'tcx, B::Value>, out_place: Option<PlaceRef<'tcx, B::Value>>, }, Const { string: String, }, SymFn { instance: Instance<'tcx>, }, SymStatic { def_id: DefId, }, } #[derive(Debug)] pub enum GlobalAsmOperandRef { Const { string: String }, }
/// Take an inline assembly expression and splat it out via LLVM fn codegen_llvm_inline_asm( &mut self, ia: &LlvmInlineAsmInner, outputs: Vec<PlaceRef<'tcx, Self::Value>>, inputs: Vec<Self::Value>, span: Span, ) -> bool; /// Take an inline assembly expression and splat it out via LLVM fn codegen_inline_asm( &mut self, template: &[InlineAsmTemplatePiece], operands: &[InlineAsmOperandRef<'tcx, Self>], options: InlineAsmOptions, line_spans: &[Span], instance: Instance<'_>, ); } pub trait AsmMethods { fn codegen_global_asm( &self, template: &[InlineAsmTemplatePiece], operands: &[GlobalAsmOperandRef], options: InlineAsmOptions, line_spans: &[Span], ); }
pub trait AsmBuilderMethods<'tcx>: BackendTypes {
random_line_split
key_templates.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// //! This module contains pre-generated [`KeyTemplate`] instances for PRF. use tink_proto::{prost::Message, KeyTemplate}; /// Return a [`KeyTemplate`] that generates an HMAC key with the following parameters: /// - Key size: 32 bytes /// - Hash function: SHA256 pub fn hmac_sha256_prf_key_template() -> KeyTemplate { create_hmac_prf_key_template(32, tink_proto::HashType::Sha256) } /// Return a [`KeyTemplate`] that generates an HMAC key with the following parameters: /// - Key size: 64 bytes /// - Hash function: SHA512 pub fn hmac_sha512_prf_key_template() -> KeyTemplate { create_hmac_prf_key_template(64, tink_proto::HashType::Sha512) } /// Return a [`KeyTemplate`] that generates an HKDF key with the following parameters: /// - Key size: 32 bytes /// - Salt: empty /// - Hash function: SHA256 pub fn hkdf_sha256_prf_key_template() -> KeyTemplate
/// Return a [`KeyTemplate`] that generates an AES-CMAC key with the following parameters: /// - Key size: 32 bytes pub fn aes_cmac_prf_key_template() -> KeyTemplate { create_aes_cmac_prf_key_template(32) } /// Create a new [`KeyTemplate`] for HMAC using the given parameters. fn create_hmac_prf_key_template(key_size: u32, hash_type: tink_proto::HashType) -> KeyTemplate { let params = tink_proto::HmacPrfParams { hash: hash_type as i32, }; let format = tink_proto::HmacPrfKeyFormat { params: Some(params), key_size, version: super::HMAC_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::HMAC_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } } /// Creates a new [`KeyTemplate`] for HKDF using the given parameters. fn create_hkdf_prf_key_template( key_size: u32, hash_type: tink_proto::HashType, salt: &[u8], ) -> KeyTemplate { let params = tink_proto::HkdfPrfParams { hash: hash_type as i32, salt: salt.to_vec(), }; let format = tink_proto::HkdfPrfKeyFormat { params: Some(params), key_size, version: super::HKDF_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::HKDF_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } } // Create a new [`KeyTemplate`] for AES-CMAC using the given parameters. fn create_aes_cmac_prf_key_template(key_size: u32) -> KeyTemplate { let format = tink_proto::AesCmacPrfKeyFormat { key_size, version: super::AES_CMAC_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::AES_CMAC_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } }
{ create_hkdf_prf_key_template(32, tink_proto::HashType::Sha256, &[]) }
identifier_body
key_templates.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// //! This module contains pre-generated [`KeyTemplate`] instances for PRF. use tink_proto::{prost::Message, KeyTemplate}; /// Return a [`KeyTemplate`] that generates an HMAC key with the following parameters: /// - Key size: 32 bytes /// - Hash function: SHA256 pub fn hmac_sha256_prf_key_template() -> KeyTemplate { create_hmac_prf_key_template(32, tink_proto::HashType::Sha256) } /// Return a [`KeyTemplate`] that generates an HMAC key with the following parameters: /// - Key size: 64 bytes /// - Hash function: SHA512 pub fn hmac_sha512_prf_key_template() -> KeyTemplate { create_hmac_prf_key_template(64, tink_proto::HashType::Sha512) } /// Return a [`KeyTemplate`] that generates an HKDF key with the following parameters: /// - Key size: 32 bytes /// - Salt: empty /// - Hash function: SHA256 pub fn hkdf_sha256_prf_key_template() -> KeyTemplate { create_hkdf_prf_key_template(32, tink_proto::HashType::Sha256, &[]) } /// Return a [`KeyTemplate`] that generates an AES-CMAC key with the following parameters: /// - Key size: 32 bytes pub fn aes_cmac_prf_key_template() -> KeyTemplate { create_aes_cmac_prf_key_template(32) } /// Create a new [`KeyTemplate`] for HMAC using the given parameters. fn create_hmac_prf_key_template(key_size: u32, hash_type: tink_proto::HashType) -> KeyTemplate { let params = tink_proto::HmacPrfParams { hash: hash_type as i32, }; let format = tink_proto::HmacPrfKeyFormat { params: Some(params), key_size, version: super::HMAC_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::HMAC_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } } /// Creates a new [`KeyTemplate`] for HKDF using the given parameters. fn create_hkdf_prf_key_template( key_size: u32, hash_type: tink_proto::HashType, salt: &[u8], ) -> KeyTemplate { let params = tink_proto::HkdfPrfParams { hash: hash_type as i32, salt: salt.to_vec(), }; let format = tink_proto::HkdfPrfKeyFormat { params: Some(params), key_size,
format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::HKDF_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } } // Create a new [`KeyTemplate`] for AES-CMAC using the given parameters. fn create_aes_cmac_prf_key_template(key_size: u32) -> KeyTemplate { let format = tink_proto::AesCmacPrfKeyFormat { key_size, version: super::AES_CMAC_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::AES_CMAC_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } }
version: super::HKDF_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new();
random_line_split
key_templates.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// //! This module contains pre-generated [`KeyTemplate`] instances for PRF. use tink_proto::{prost::Message, KeyTemplate}; /// Return a [`KeyTemplate`] that generates an HMAC key with the following parameters: /// - Key size: 32 bytes /// - Hash function: SHA256 pub fn hmac_sha256_prf_key_template() -> KeyTemplate { create_hmac_prf_key_template(32, tink_proto::HashType::Sha256) } /// Return a [`KeyTemplate`] that generates an HMAC key with the following parameters: /// - Key size: 64 bytes /// - Hash function: SHA512 pub fn hmac_sha512_prf_key_template() -> KeyTemplate { create_hmac_prf_key_template(64, tink_proto::HashType::Sha512) } /// Return a [`KeyTemplate`] that generates an HKDF key with the following parameters: /// - Key size: 32 bytes /// - Salt: empty /// - Hash function: SHA256 pub fn
() -> KeyTemplate { create_hkdf_prf_key_template(32, tink_proto::HashType::Sha256, &[]) } /// Return a [`KeyTemplate`] that generates an AES-CMAC key with the following parameters: /// - Key size: 32 bytes pub fn aes_cmac_prf_key_template() -> KeyTemplate { create_aes_cmac_prf_key_template(32) } /// Create a new [`KeyTemplate`] for HMAC using the given parameters. fn create_hmac_prf_key_template(key_size: u32, hash_type: tink_proto::HashType) -> KeyTemplate { let params = tink_proto::HmacPrfParams { hash: hash_type as i32, }; let format = tink_proto::HmacPrfKeyFormat { params: Some(params), key_size, version: super::HMAC_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::HMAC_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } } /// Creates a new [`KeyTemplate`] for HKDF using the given parameters. fn create_hkdf_prf_key_template( key_size: u32, hash_type: tink_proto::HashType, salt: &[u8], ) -> KeyTemplate { let params = tink_proto::HkdfPrfParams { hash: hash_type as i32, salt: salt.to_vec(), }; let format = tink_proto::HkdfPrfKeyFormat { params: Some(params), key_size, version: super::HKDF_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::HKDF_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } } // Create a new [`KeyTemplate`] for AES-CMAC using the given parameters. fn create_aes_cmac_prf_key_template(key_size: u32) -> KeyTemplate { let format = tink_proto::AesCmacPrfKeyFormat { key_size, version: super::AES_CMAC_PRF_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: super::AES_CMAC_PRF_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Raw as i32, value: serialized_format, } }
hkdf_sha256_prf_key_template
identifier_name
clone_rope.rs
extern crate ropey; use std::iter::Iterator; use ropey::Rope; const TEXT: &str = include_str!("test_text.txt");
// Do identical insertions into both ropes rope1.insert(432, "Hello "); rope1.insert(2345, "world! "); rope1.insert(5256, "How are "); rope1.insert(53, "you "); rope1.insert(768, "doing?\r\n"); rope2.insert(432, "Hello "); rope2.insert(2345, "world! "); rope2.insert(5256, "How are "); rope2.insert(53, "you "); rope2.insert(768, "doing?\r\n"); // Make sure they match let matches = Iterator::zip(rope1.chars(), rope2.chars()) .map(|(a, b)| a == b) .all(|n| n); assert_eq!(matches, true); // Insert something into the clone, and make sure they don't match // afterwards. rope2.insert(3891, "I'm doing fine, thanks!"); let matches = Iterator::zip(rope1.chars(), rope2.chars()) .map(|(a, b)| a == b) .all(|n| n); assert_eq!(matches, false); }
#[test] fn clone_rope() { let mut rope1 = Rope::from_str(TEXT); let mut rope2 = rope1.clone();
random_line_split
clone_rope.rs
extern crate ropey; use std::iter::Iterator; use ropey::Rope; const TEXT: &str = include_str!("test_text.txt"); #[test] fn clone_rope()
.all(|n| n); assert_eq!(matches, true); // Insert something into the clone, and make sure they don't match // afterwards. rope2.insert(3891, "I'm doing fine, thanks!"); let matches = Iterator::zip(rope1.chars(), rope2.chars()) .map(|(a, b)| a == b) .all(|n| n); assert_eq!(matches, false); }
{ let mut rope1 = Rope::from_str(TEXT); let mut rope2 = rope1.clone(); // Do identical insertions into both ropes rope1.insert(432, "Hello "); rope1.insert(2345, "world! "); rope1.insert(5256, "How are "); rope1.insert(53, "you "); rope1.insert(768, "doing?\r\n"); rope2.insert(432, "Hello "); rope2.insert(2345, "world! "); rope2.insert(5256, "How are "); rope2.insert(53, "you "); rope2.insert(768, "doing?\r\n"); // Make sure they match let matches = Iterator::zip(rope1.chars(), rope2.chars()) .map(|(a, b)| a == b)
identifier_body
clone_rope.rs
extern crate ropey; use std::iter::Iterator; use ropey::Rope; const TEXT: &str = include_str!("test_text.txt"); #[test] fn
() { let mut rope1 = Rope::from_str(TEXT); let mut rope2 = rope1.clone(); // Do identical insertions into both ropes rope1.insert(432, "Hello "); rope1.insert(2345, "world! "); rope1.insert(5256, "How are "); rope1.insert(53, "you "); rope1.insert(768, "doing?\r\n"); rope2.insert(432, "Hello "); rope2.insert(2345, "world! "); rope2.insert(5256, "How are "); rope2.insert(53, "you "); rope2.insert(768, "doing?\r\n"); // Make sure they match let matches = Iterator::zip(rope1.chars(), rope2.chars()) .map(|(a, b)| a == b) .all(|n| n); assert_eq!(matches, true); // Insert something into the clone, and make sure they don't match // afterwards. rope2.insert(3891, "I'm doing fine, thanks!"); let matches = Iterator::zip(rope1.chars(), rope2.chars()) .map(|(a, b)| a == b) .all(|n| n); assert_eq!(matches, false); }
clone_rope
identifier_name
buttons-attribute.rs
/* * Copyright (c) 2017 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ Inhibit, prelude::ButtonExt, prelude::LabelExt, prelude::OrientableExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm::Widget; use relm_derive::{Msg, widget}; use self::Msg::*; // Define the structure of the model. pub struct Model { counter: i32, } // The messages that can be sent to the update function. #[derive(Msg)] pub enum Msg { #[cfg(test)] Test, Decrement, Increment, Quit, } #[widget] impl Widget for Win { // The initial model. fn model() -> Model { Model { counter: 0, } } // Update the model according to the message received. fn update(&mut self, event: Msg) { match event { #[cfg(test)] Test => (), Decrement => self.model.counter -= 1, Increment => self.model.counter += 1, Quit => gtk::main_quit(), } } view! { gtk::Window { gtk::Box { // Set the orientation property of the Box. orientation: Vertical, // Create a Button inside the Box. #[name="inc_button"] gtk::Button { // Send the message Increment when the button is clicked. clicked => Increment, // TODO: check if using two events of the same name work. label: "+", }, #[name="label"] gtk::Label { // Bind the text property of the label to the counter attribute of the model. text: &self.model.counter.to_string(), }, #[name="dec_button"] #[style_class="destructive-action"] #[style_class="linked"] gtk::Button { clicked => Decrement, label: "-", }, }, delete_event(_, _) => (Quit, Inhibit(false)), } } } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gtk::{prelude::ButtonExt, prelude::LabelExt}; use gtk_test::{assert_label, assert_text}; use relm_test::click; use crate::Win; #[test] fn label_change() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let inc_button = &widgets.inc_button; let dec_button = &widgets.dec_button; let label = &widgets.label; assert_label!(inc_button, "+"); assert_label!(dec_button, "-"); assert_text!(label, 0); click(inc_button); assert_text!(label, 1); click(inc_button);
assert_text!(label, 2); click(inc_button); assert_text!(label, 3); click(inc_button); assert_text!(label, 4); click(dec_button); assert_text!(label, 3); click(dec_button); assert_text!(label, 2); click(dec_button); assert_text!(label, 1); click(dec_button); assert_text!(label, 0); click(dec_button); assert_text!(label, -1); } }
random_line_split
buttons-attribute.rs
/* * Copyright (c) 2017 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ Inhibit, prelude::ButtonExt, prelude::LabelExt, prelude::OrientableExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm::Widget; use relm_derive::{Msg, widget}; use self::Msg::*; // Define the structure of the model. pub struct Model { counter: i32, } // The messages that can be sent to the update function. #[derive(Msg)] pub enum Msg { #[cfg(test)] Test, Decrement, Increment, Quit, } #[widget] impl Widget for Win { // The initial model. fn model() -> Model { Model { counter: 0, } } // Update the model according to the message received. fn update(&mut self, event: Msg) { match event { #[cfg(test)] Test => (), Decrement => self.model.counter -= 1, Increment => self.model.counter += 1, Quit => gtk::main_quit(), } } view! { gtk::Window { gtk::Box { // Set the orientation property of the Box. orientation: Vertical, // Create a Button inside the Box. #[name="inc_button"] gtk::Button { // Send the message Increment when the button is clicked. clicked => Increment, // TODO: check if using two events of the same name work. label: "+", }, #[name="label"] gtk::Label { // Bind the text property of the label to the counter attribute of the model. text: &self.model.counter.to_string(), }, #[name="dec_button"] #[style_class="destructive-action"] #[style_class="linked"] gtk::Button { clicked => Decrement, label: "-", }, }, delete_event(_, _) => (Quit, Inhibit(false)), } } } fn main()
#[cfg(test)] mod tests { use gtk::{prelude::ButtonExt, prelude::LabelExt}; use gtk_test::{assert_label, assert_text}; use relm_test::click; use crate::Win; #[test] fn label_change() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let inc_button = &widgets.inc_button; let dec_button = &widgets.dec_button; let label = &widgets.label; assert_label!(inc_button, "+"); assert_label!(dec_button, "-"); assert_text!(label, 0); click(inc_button); assert_text!(label, 1); click(inc_button); assert_text!(label, 2); click(inc_button); assert_text!(label, 3); click(inc_button); assert_text!(label, 4); click(dec_button); assert_text!(label, 3); click(dec_button); assert_text!(label, 2); click(dec_button); assert_text!(label, 1); click(dec_button); assert_text!(label, 0); click(dec_button); assert_text!(label, -1); } }
{ Win::run(()).expect("Win::run failed"); }
identifier_body
buttons-attribute.rs
/* * Copyright (c) 2017 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ Inhibit, prelude::ButtonExt, prelude::LabelExt, prelude::OrientableExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm::Widget; use relm_derive::{Msg, widget}; use self::Msg::*; // Define the structure of the model. pub struct Model { counter: i32, } // The messages that can be sent to the update function. #[derive(Msg)] pub enum
{ #[cfg(test)] Test, Decrement, Increment, Quit, } #[widget] impl Widget for Win { // The initial model. fn model() -> Model { Model { counter: 0, } } // Update the model according to the message received. fn update(&mut self, event: Msg) { match event { #[cfg(test)] Test => (), Decrement => self.model.counter -= 1, Increment => self.model.counter += 1, Quit => gtk::main_quit(), } } view! { gtk::Window { gtk::Box { // Set the orientation property of the Box. orientation: Vertical, // Create a Button inside the Box. #[name="inc_button"] gtk::Button { // Send the message Increment when the button is clicked. clicked => Increment, // TODO: check if using two events of the same name work. label: "+", }, #[name="label"] gtk::Label { // Bind the text property of the label to the counter attribute of the model. text: &self.model.counter.to_string(), }, #[name="dec_button"] #[style_class="destructive-action"] #[style_class="linked"] gtk::Button { clicked => Decrement, label: "-", }, }, delete_event(_, _) => (Quit, Inhibit(false)), } } } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gtk::{prelude::ButtonExt, prelude::LabelExt}; use gtk_test::{assert_label, assert_text}; use relm_test::click; use crate::Win; #[test] fn label_change() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let inc_button = &widgets.inc_button; let dec_button = &widgets.dec_button; let label = &widgets.label; assert_label!(inc_button, "+"); assert_label!(dec_button, "-"); assert_text!(label, 0); click(inc_button); assert_text!(label, 1); click(inc_button); assert_text!(label, 2); click(inc_button); assert_text!(label, 3); click(inc_button); assert_text!(label, 4); click(dec_button); assert_text!(label, 3); click(dec_button); assert_text!(label, 2); click(dec_button); assert_text!(label, 1); click(dec_button); assert_text!(label, 0); click(dec_button); assert_text!(label, -1); } }
Msg
identifier_name
release.rs
use std::any::Any; use input::Button; use { GenericEvent, RELEASE }; /// The release of a button pub trait ReleaseEvent { /// Creates a release event. fn from_button(button: Button, old_event: &Self) -> Option<Self>; /// Calls closure if this is a release event. fn release<U, F>(&self, f: F) -> Option<U> where F: FnMut(Button) -> U; /// Returns release arguments. fn release_args(&self) -> Option<Button> { self.release(|button| button) } } impl<T: GenericEvent> ReleaseEvent for T { fn from_button(button: Button, old_event: &Self) -> Option<Self> { GenericEvent::from_args(RELEASE, &button as &Any, old_event) } fn release<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(Button) -> U { if self.event_id()!= RELEASE { return None; } self.with_args(|any| { if let Some(&button) = any.downcast_ref::<Button>() { Some(f(button)) } else { panic!("Expected Button") } }) } } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn test_input_release() { use input::{ Button, Key, Input }; let e = Input::Release(Button::Keyboard(Key::S)); let button = Button::Keyboard(Key::A); let x: Option<Input> = ReleaseEvent::from_button(button, &e); let y: Option<Input> = x.clone().unwrap().release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[bench] fn
(bencher: &mut Bencher) { use input::{ Button, Input, Key }; let e = Input::Release(Button::Keyboard(Key::S)); let button = Button::Keyboard(Key::A); bencher.iter(|| { let _: Option<Input> = ReleaseEvent::from_button(button, &e); }); } #[test] fn test_event_release() { use Event; use input::{ Button, Key, Input }; let e = Event::Input(Input::Release(Button::Keyboard(Key::S))); let button = Button::Keyboard(Key::A); let x: Option<Event> = ReleaseEvent::from_button(button, &e); let y: Option<Event> = x.clone().unwrap().release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[bench] fn bench_event_release(bencher: &mut Bencher) { use Event; use input::{ Button, Key, Input }; let e = Event::Input(Input::Release(Button::Keyboard(Key::S))); let button = Button::Keyboard(Key::A); bencher.iter(|| { let _: Option<Event> = ReleaseEvent::from_button(button, &e); }); } }
bench_input_release
identifier_name
release.rs
use std::any::Any; use input::Button; use { GenericEvent, RELEASE }; /// The release of a button pub trait ReleaseEvent { /// Creates a release event. fn from_button(button: Button, old_event: &Self) -> Option<Self>; /// Calls closure if this is a release event. fn release<U, F>(&self, f: F) -> Option<U> where F: FnMut(Button) -> U; /// Returns release arguments. fn release_args(&self) -> Option<Button> { self.release(|button| button) } } impl<T: GenericEvent> ReleaseEvent for T { fn from_button(button: Button, old_event: &Self) -> Option<Self>
fn release<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(Button) -> U { if self.event_id()!= RELEASE { return None; } self.with_args(|any| { if let Some(&button) = any.downcast_ref::<Button>() { Some(f(button)) } else { panic!("Expected Button") } }) } } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn test_input_release() { use input::{ Button, Key, Input }; let e = Input::Release(Button::Keyboard(Key::S)); let button = Button::Keyboard(Key::A); let x: Option<Input> = ReleaseEvent::from_button(button, &e); let y: Option<Input> = x.clone().unwrap().release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[bench] fn bench_input_release(bencher: &mut Bencher) { use input::{ Button, Input, Key }; let e = Input::Release(Button::Keyboard(Key::S)); let button = Button::Keyboard(Key::A); bencher.iter(|| { let _: Option<Input> = ReleaseEvent::from_button(button, &e); }); } #[test] fn test_event_release() { use Event; use input::{ Button, Key, Input }; let e = Event::Input(Input::Release(Button::Keyboard(Key::S))); let button = Button::Keyboard(Key::A); let x: Option<Event> = ReleaseEvent::from_button(button, &e); let y: Option<Event> = x.clone().unwrap().release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[bench] fn bench_event_release(bencher: &mut Bencher) { use Event; use input::{ Button, Key, Input }; let e = Event::Input(Input::Release(Button::Keyboard(Key::S))); let button = Button::Keyboard(Key::A); bencher.iter(|| { let _: Option<Event> = ReleaseEvent::from_button(button, &e); }); } }
{ GenericEvent::from_args(RELEASE, &button as &Any, old_event) }
identifier_body
release.rs
use std::any::Any; use input::Button; use { GenericEvent, RELEASE }; /// The release of a button pub trait ReleaseEvent { /// Creates a release event. fn from_button(button: Button, old_event: &Self) -> Option<Self>; /// Calls closure if this is a release event. fn release<U, F>(&self, f: F) -> Option<U> where F: FnMut(Button) -> U; /// Returns release arguments. fn release_args(&self) -> Option<Button> { self.release(|button| button) } } impl<T: GenericEvent> ReleaseEvent for T { fn from_button(button: Button, old_event: &Self) -> Option<Self> { GenericEvent::from_args(RELEASE, &button as &Any, old_event) } fn release<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(Button) -> U { if self.event_id()!= RELEASE { return None; } self.with_args(|any| { if let Some(&button) = any.downcast_ref::<Button>() { Some(f(button)) } else { panic!("Expected Button") } }) } } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn test_input_release() { use input::{ Button, Key, Input }; let e = Input::Release(Button::Keyboard(Key::S)); let button = Button::Keyboard(Key::A); let x: Option<Input> = ReleaseEvent::from_button(button, &e); let y: Option<Input> = x.clone().unwrap().release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[bench] fn bench_input_release(bencher: &mut Bencher) { use input::{ Button, Input, Key }; let e = Input::Release(Button::Keyboard(Key::S)); let button = Button::Keyboard(Key::A); bencher.iter(|| { let _: Option<Input> = ReleaseEvent::from_button(button, &e); }); } #[test] fn test_event_release() { use Event; use input::{ Button, Key, Input }; let e = Event::Input(Input::Release(Button::Keyboard(Key::S))); let button = Button::Keyboard(Key::A); let x: Option<Event> = ReleaseEvent::from_button(button, &e);
#[bench] fn bench_event_release(bencher: &mut Bencher) { use Event; use input::{ Button, Key, Input }; let e = Event::Input(Input::Release(Button::Keyboard(Key::S))); let button = Button::Keyboard(Key::A); bencher.iter(|| { let _: Option<Event> = ReleaseEvent::from_button(button, &e); }); } }
let y: Option<Event> = x.clone().unwrap().release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); }
random_line_split
release.rs
use std::any::Any; use input::Button; use { GenericEvent, RELEASE }; /// The release of a button pub trait ReleaseEvent { /// Creates a release event. fn from_button(button: Button, old_event: &Self) -> Option<Self>; /// Calls closure if this is a release event. fn release<U, F>(&self, f: F) -> Option<U> where F: FnMut(Button) -> U; /// Returns release arguments. fn release_args(&self) -> Option<Button> { self.release(|button| button) } } impl<T: GenericEvent> ReleaseEvent for T { fn from_button(button: Button, old_event: &Self) -> Option<Self> { GenericEvent::from_args(RELEASE, &button as &Any, old_event) } fn release<U, F>(&self, mut f: F) -> Option<U> where F: FnMut(Button) -> U { if self.event_id()!= RELEASE { return None; } self.with_args(|any| { if let Some(&button) = any.downcast_ref::<Button>()
else { panic!("Expected Button") } }) } } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn test_input_release() { use input::{ Button, Key, Input }; let e = Input::Release(Button::Keyboard(Key::S)); let button = Button::Keyboard(Key::A); let x: Option<Input> = ReleaseEvent::from_button(button, &e); let y: Option<Input> = x.clone().unwrap().release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[bench] fn bench_input_release(bencher: &mut Bencher) { use input::{ Button, Input, Key }; let e = Input::Release(Button::Keyboard(Key::S)); let button = Button::Keyboard(Key::A); bencher.iter(|| { let _: Option<Input> = ReleaseEvent::from_button(button, &e); }); } #[test] fn test_event_release() { use Event; use input::{ Button, Key, Input }; let e = Event::Input(Input::Release(Button::Keyboard(Key::S))); let button = Button::Keyboard(Key::A); let x: Option<Event> = ReleaseEvent::from_button(button, &e); let y: Option<Event> = x.clone().unwrap().release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap())).unwrap(); assert_eq!(x, y); } #[bench] fn bench_event_release(bencher: &mut Bencher) { use Event; use input::{ Button, Key, Input }; let e = Event::Input(Input::Release(Button::Keyboard(Key::S))); let button = Button::Keyboard(Key::A); bencher.iter(|| { let _: Option<Event> = ReleaseEvent::from_button(button, &e); }); } }
{ Some(f(button)) }
conditional_block
matcher_api.rs
// 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. // // Implementation of the matcher API using the regular expressions in the PhoneNumberDesc // proto message to match numbers. // pub struct MatcherApi { regexCache : RegexCache } impl MatcherApi { fn new() -> MatcherApi { MatcherApi { regexCache: RegexCache::new(100) } } pub fn matches_national_number(&self, nationalNumber: &str, numberDesc: PhoneNumberDesc, allowPrefixMatch: bool) -> bool
pub fn matches_possible_number(&self, nationalNumber: &str, numberDesc: PhoneNumberDesc) -> bool { let nationalNumberPatternMatcher : Matcher = self.regexCache.get_pattern_for_regex( numberDesc.get_national_number_pattern()).matcher(nationalNumber); possibleNumberPatternMatcher.matches() } }
{ let nationalNumberPatternMatcher : Matcher = self.regexCache.get_pattern_for_regex( numberDesc.get_national_number_pattern()).matcher(nationalNumber); nationalNumberPatternMatcher.matches() || (allowPrefixMatch && nationalNumberPatternMatcher.looking_at()); }
identifier_body
matcher_api.rs
// 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. // // Implementation of the matcher API using the regular expressions in the PhoneNumberDesc // proto message to match numbers. // pub struct MatcherApi { regexCache : RegexCache } impl MatcherApi { fn new() -> MatcherApi { MatcherApi { regexCache: RegexCache::new(100) } } pub fn matches_national_number(&self, nationalNumber: &str, numberDesc: PhoneNumberDesc, allowPrefixMatch: bool) -> bool { let nationalNumberPatternMatcher : Matcher = self.regexCache.get_pattern_for_regex( numberDesc.get_national_number_pattern()).matcher(nationalNumber); nationalNumberPatternMatcher.matches() || (allowPrefixMatch && nationalNumberPatternMatcher.looking_at()); } pub fn
(&self, nationalNumber: &str, numberDesc: PhoneNumberDesc) -> bool { let nationalNumberPatternMatcher : Matcher = self.regexCache.get_pattern_for_regex( numberDesc.get_national_number_pattern()).matcher(nationalNumber); possibleNumberPatternMatcher.matches() } }
matches_possible_number
identifier_name
matcher_api.rs
// 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. // // Implementation of the matcher API using the regular expressions in the PhoneNumberDesc // proto message to match numbers. // pub struct MatcherApi { regexCache : RegexCache } impl MatcherApi { fn new() -> MatcherApi { MatcherApi { regexCache: RegexCache::new(100) } }
pub fn matches_national_number(&self, nationalNumber: &str, numberDesc: PhoneNumberDesc, allowPrefixMatch: bool) -> bool { let nationalNumberPatternMatcher : Matcher = self.regexCache.get_pattern_for_regex( numberDesc.get_national_number_pattern()).matcher(nationalNumber); nationalNumberPatternMatcher.matches() || (allowPrefixMatch && nationalNumberPatternMatcher.looking_at()); } pub fn matches_possible_number(&self, nationalNumber: &str, numberDesc: PhoneNumberDesc) -> bool { let nationalNumberPatternMatcher : Matcher = self.regexCache.get_pattern_for_regex( numberDesc.get_national_number_pattern()).matcher(nationalNumber); possibleNumberPatternMatcher.matches() } }
random_line_split
combinations_with_replacement.rs
use std::fmt; use super::lazy_buffer::LazyBuffer; /// An iterator to iterate through all the `n`-length combinations in an iterator, with replacement. /// /// See [`.combinations_with_replacement()`](../trait.Itertools.html#method.combinations_with_replacement) for more information. #[derive(Clone)] pub struct CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { k: usize, indices: Vec<usize>, // The current known max index value. This increases as pool grows. max_index: usize, pool: LazyBuffer<I>, first: bool, } impl<I> fmt::Debug for CombinationsWithReplacement<I> where I: Iterator + fmt::Debug, I::Item: fmt::Debug + Clone, { debug_fmt_fields!(Combinations, k, indices, max_index, pool, first); } impl<I> CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { /// Map the current mask over the pool to get an output combination fn current(&self) -> Vec<I::Item> { self.indices.iter().map(|i| self.pool[*i].clone()).collect() } } /// Create a new `CombinationsWithReplacement` from a clonable iterator. pub fn
<I>(iter: I, k: usize) -> CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { let indices: Vec<usize> = vec![0; k]; let pool: LazyBuffer<I> = LazyBuffer::new(iter); CombinationsWithReplacement { k, indices, max_index: 0, pool, first: true, } } impl<I> Iterator for CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { type Item = Vec<I::Item>; fn next(&mut self) -> Option<Self::Item> { // If this is the first iteration, return early if self.first { // In empty edge cases, stop iterating immediately return if self.k!= 0 &&!self.pool.get_next() { None // Otherwise, yield the initial state } else { self.first = false; Some(self.current()) }; } // Check if we need to consume more from the iterator // This will run while we increment our first index digit if self.pool.get_next() { self.max_index = self.pool.len() - 1; } // Work out where we need to update our indices let mut increment: Option<(usize, usize)> = None; for (i, indices_int) in self.indices.iter().enumerate().rev() { if indices_int < &self.max_index { increment = Some((i, indices_int + 1)); break; } } match increment { // If we can update the indices further Some((increment_from, increment_value)) => { // We need to update the rightmost non-max value // and all those to the right for indices_index in increment_from..self.indices.len() { self.indices[indices_index] = increment_value } Some(self.current()) } // Otherwise, we're done None => None, } } }
combinations_with_replacement
identifier_name
combinations_with_replacement.rs
use std::fmt; use super::lazy_buffer::LazyBuffer; /// An iterator to iterate through all the `n`-length combinations in an iterator, with replacement. /// /// See [`.combinations_with_replacement()`](../trait.Itertools.html#method.combinations_with_replacement) for more information. #[derive(Clone)] pub struct CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { k: usize, indices: Vec<usize>, // The current known max index value. This increases as pool grows. max_index: usize, pool: LazyBuffer<I>, first: bool, } impl<I> fmt::Debug for CombinationsWithReplacement<I> where I: Iterator + fmt::Debug, I::Item: fmt::Debug + Clone, { debug_fmt_fields!(Combinations, k, indices, max_index, pool, first); } impl<I> CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { /// Map the current mask over the pool to get an output combination fn current(&self) -> Vec<I::Item> { self.indices.iter().map(|i| self.pool[*i].clone()).collect() } } /// Create a new `CombinationsWithReplacement` from a clonable iterator. pub fn combinations_with_replacement<I>(iter: I, k: usize) -> CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { let indices: Vec<usize> = vec![0; k]; let pool: LazyBuffer<I> = LazyBuffer::new(iter); CombinationsWithReplacement { k, indices, max_index: 0, pool, first: true, } } impl<I> Iterator for CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { type Item = Vec<I::Item>; fn next(&mut self) -> Option<Self::Item> { // If this is the first iteration, return early if self.first { // In empty edge cases, stop iterating immediately return if self.k!= 0 &&!self.pool.get_next() { None // Otherwise, yield the initial state } else
; } // Check if we need to consume more from the iterator // This will run while we increment our first index digit if self.pool.get_next() { self.max_index = self.pool.len() - 1; } // Work out where we need to update our indices let mut increment: Option<(usize, usize)> = None; for (i, indices_int) in self.indices.iter().enumerate().rev() { if indices_int < &self.max_index { increment = Some((i, indices_int + 1)); break; } } match increment { // If we can update the indices further Some((increment_from, increment_value)) => { // We need to update the rightmost non-max value // and all those to the right for indices_index in increment_from..self.indices.len() { self.indices[indices_index] = increment_value } Some(self.current()) } // Otherwise, we're done None => None, } } }
{ self.first = false; Some(self.current()) }
conditional_block
combinations_with_replacement.rs
use std::fmt; use super::lazy_buffer::LazyBuffer; /// An iterator to iterate through all the `n`-length combinations in an iterator, with replacement. /// /// See [`.combinations_with_replacement()`](../trait.Itertools.html#method.combinations_with_replacement) for more information. #[derive(Clone)] pub struct CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { k: usize, indices: Vec<usize>, // The current known max index value. This increases as pool grows. max_index: usize, pool: LazyBuffer<I>, first: bool, } impl<I> fmt::Debug for CombinationsWithReplacement<I> where I: Iterator + fmt::Debug, I::Item: fmt::Debug + Clone, { debug_fmt_fields!(Combinations, k, indices, max_index, pool, first); } impl<I> CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { /// Map the current mask over the pool to get an output combination fn current(&self) -> Vec<I::Item> { self.indices.iter().map(|i| self.pool[*i].clone()).collect() } } /// Create a new `CombinationsWithReplacement` from a clonable iterator. pub fn combinations_with_replacement<I>(iter: I, k: usize) -> CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { let indices: Vec<usize> = vec![0; k]; let pool: LazyBuffer<I> = LazyBuffer::new(iter); CombinationsWithReplacement { k, indices, max_index: 0, pool, first: true, } } impl<I> Iterator for CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { type Item = Vec<I::Item>; fn next(&mut self) -> Option<Self::Item> { // If this is the first iteration, return early if self.first { // In empty edge cases, stop iterating immediately return if self.k!= 0 &&!self.pool.get_next() { None // Otherwise, yield the initial state } else { self.first = false; Some(self.current()) }; } // Check if we need to consume more from the iterator // This will run while we increment our first index digit if self.pool.get_next() { self.max_index = self.pool.len() - 1; } // Work out where we need to update our indices
let mut increment: Option<(usize, usize)> = None; for (i, indices_int) in self.indices.iter().enumerate().rev() { if indices_int < &self.max_index { increment = Some((i, indices_int + 1)); break; } } match increment { // If we can update the indices further Some((increment_from, increment_value)) => { // We need to update the rightmost non-max value // and all those to the right for indices_index in increment_from..self.indices.len() { self.indices[indices_index] = increment_value } Some(self.current()) } // Otherwise, we're done None => None, } } }
random_line_split
combinations_with_replacement.rs
use std::fmt; use super::lazy_buffer::LazyBuffer; /// An iterator to iterate through all the `n`-length combinations in an iterator, with replacement. /// /// See [`.combinations_with_replacement()`](../trait.Itertools.html#method.combinations_with_replacement) for more information. #[derive(Clone)] pub struct CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { k: usize, indices: Vec<usize>, // The current known max index value. This increases as pool grows. max_index: usize, pool: LazyBuffer<I>, first: bool, } impl<I> fmt::Debug for CombinationsWithReplacement<I> where I: Iterator + fmt::Debug, I::Item: fmt::Debug + Clone, { debug_fmt_fields!(Combinations, k, indices, max_index, pool, first); } impl<I> CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { /// Map the current mask over the pool to get an output combination fn current(&self) -> Vec<I::Item> { self.indices.iter().map(|i| self.pool[*i].clone()).collect() } } /// Create a new `CombinationsWithReplacement` from a clonable iterator. pub fn combinations_with_replacement<I>(iter: I, k: usize) -> CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { let indices: Vec<usize> = vec![0; k]; let pool: LazyBuffer<I> = LazyBuffer::new(iter); CombinationsWithReplacement { k, indices, max_index: 0, pool, first: true, } } impl<I> Iterator for CombinationsWithReplacement<I> where I: Iterator, I::Item: Clone, { type Item = Vec<I::Item>; fn next(&mut self) -> Option<Self::Item>
let mut increment: Option<(usize, usize)> = None; for (i, indices_int) in self.indices.iter().enumerate().rev() { if indices_int < &self.max_index { increment = Some((i, indices_int + 1)); break; } } match increment { // If we can update the indices further Some((increment_from, increment_value)) => { // We need to update the rightmost non-max value // and all those to the right for indices_index in increment_from..self.indices.len() { self.indices[indices_index] = increment_value } Some(self.current()) } // Otherwise, we're done None => None, } } }
{ // If this is the first iteration, return early if self.first { // In empty edge cases, stop iterating immediately return if self.k != 0 && !self.pool.get_next() { None // Otherwise, yield the initial state } else { self.first = false; Some(self.current()) }; } // Check if we need to consume more from the iterator // This will run while we increment our first index digit if self.pool.get_next() { self.max_index = self.pool.len() - 1; } // Work out where we need to update our indices
identifier_body
mod.rs
/*! In order to draw, you need to provide a source of indices which is used to link the vertices together into *primitives*. There are eleven types of primitives, each one with a corresponding struct: - `PointsList` - `LinesList` - `LinesListAdjacency` - `LineStrip` - `LineStripAdjacency` - `TrianglesList` - `TrianglesListAdjacency` - `TriangleStrip` - `TriangleStripAdjacency` - `TriangleFan` - `Patches` These structs can be turned into an `IndexBuffer`, which uploads the data in video memory. There are three ways to specify the indices that must be used: - Passing a reference to one of these structs. - Passing a reference to an `IndexBuffer`. - `NoIndices`, which is equivalent to `(0, 1, 2, 3, 4, 5, 6, 7,..)`. For performances it is highly recommended to use either an `IndexBuffer` or `NoIndices`, and to avoid passing indices in RAM. When you draw something, a draw command is sent to the GPU and the execution continues immediatly after. But if you pass indices in RAM, the execution has to block until the GPU has finished drawing in order to make sure that the indices are not free'd. */ use gl; use ToGlEnum; use std::mem; use buffer::BufferViewAnySlice; pub use self::buffer::{IndexBuffer, IndexBufferSlice, IndexBufferAny}; pub use self::multidraw::{DrawCommandsNoIndicesBuffer, DrawCommandNoIndices}; mod buffer; mod multidraw; /// Describes a source of indices used for drawing. #[derive(Clone)] pub enum IndicesSource<'a> { /// A buffer uploaded in video memory. IndexBuffer { /// The buffer. buffer: BufferViewAnySlice<'a>, /// Type of indices in the buffer. data_type: IndexType, /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, /// Use a multidraw indirect buffer without indices. MultidrawArray { /// The buffer. buffer: BufferViewAnySlice<'a>, /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, /// Don't use indices. Assemble primitives by using the order in which the vertices are in /// the vertices source. NoIndices { /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, } impl<'a> IndicesSource<'a> { /// Returns the type of the primitives. pub fn get_primitives_type(&self) -> PrimitiveType { match self { &IndicesSource::IndexBuffer { primitives,.. } => primitives, &IndicesSource::MultidrawArray { primitives,.. } => primitives, &IndicesSource::NoIndices { primitives } => primitives, } } } /// List of available primitives. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PrimitiveType { /// Points, /// LinesList, /// LinesListAdjacency, /// LineStrip, /// LineStripAdjacency, /// TrianglesList, /// TrianglesListAdjacency, /// TriangleStrip, /// TriangleStripAdjacency, /// TriangleFan, /// Patches { /// Number of vertices per patch. vertices_per_patch: u16, }, } impl ToGlEnum for PrimitiveType { fn to_glenum(&self) -> gl::types::GLenum { match self { &PrimitiveType::Points => gl::POINTS, &PrimitiveType::LinesList => gl::LINES, &PrimitiveType::LinesListAdjacency => gl::LINES_ADJACENCY, &PrimitiveType::LineStrip => gl::LINE_STRIP, &PrimitiveType::LineStripAdjacency => gl::LINE_STRIP_ADJACENCY, &PrimitiveType::TrianglesList => gl::TRIANGLES, &PrimitiveType::TrianglesListAdjacency => gl::TRIANGLES_ADJACENCY, &PrimitiveType::TriangleStrip => gl::TRIANGLE_STRIP, &PrimitiveType::TriangleStripAdjacency => gl::TRIANGLE_STRIP_ADJACENCY, &PrimitiveType::TriangleFan => gl::TRIANGLE_FAN, &PrimitiveType::Patches {.. } => gl::PATCHES, } } } /// Marker that can be used as an indices source when you don't need indices. /// /// If you use this, then the primitives will be constructed using the order in which the /// vertices are in the vertices sources. #[derive(Copy, Clone, Debug)] pub struct NoIndices(pub PrimitiveType); impl<'a> From<NoIndices> for IndicesSource<'a> { fn from(marker: NoIndices) -> IndicesSource<'a> { IndicesSource::NoIndices { primitives: marker.0 } } } impl<'a, 'b> From<&'b NoIndices> for IndicesSource<'a> { fn from(marker: &'b NoIndices) -> IndicesSource<'a> { IndicesSource::NoIndices { primitives: marker.0 } } } /// Type of the indices in an index source. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u32)] // GLenum pub enum IndexType { /// u8 U8 = gl::UNSIGNED_BYTE, /// u16 U16 = gl::UNSIGNED_SHORT, /// u32 U32 = gl::UNSIGNED_INT, } impl IndexType { /// Returns the size in bytes of each index of this type. pub fn get_size(&self) -> usize { match *self { IndexType::U8 => mem::size_of::<u8>(), IndexType::U16 => mem::size_of::<u16>(), IndexType::U32 => mem::size_of::<u32>(), } } } impl ToGlEnum for IndexType { fn to_glenum(&self) -> gl::types::GLenum { *self as gl::types::GLenum } } /// An index from the index buffer. pub unsafe trait Index: Copy + Send +'static { /// Returns the `IndexType` corresponding to this type. fn get_type() -> IndexType; } unsafe impl Index for u8 { fn get_type() -> IndexType { IndexType::U8 } } unsafe impl Index for u16 { fn get_type() -> IndexType
} unsafe impl Index for u32 { fn get_type() -> IndexType { IndexType::U32 } }
{ IndexType::U16 }
identifier_body
mod.rs
/*! In order to draw, you need to provide a source of indices which is used to link the vertices together into *primitives*. There are eleven types of primitives, each one with a corresponding struct: - `PointsList` - `LinesList` - `LinesListAdjacency` - `LineStrip` - `LineStripAdjacency` - `TrianglesList` - `TrianglesListAdjacency` - `TriangleStrip` - `TriangleStripAdjacency` - `TriangleFan` - `Patches` These structs can be turned into an `IndexBuffer`, which uploads the data in video memory. There are three ways to specify the indices that must be used: - Passing a reference to one of these structs. - Passing a reference to an `IndexBuffer`. - `NoIndices`, which is equivalent to `(0, 1, 2, 3, 4, 5, 6, 7,..)`. For performances it is highly recommended to use either an `IndexBuffer` or `NoIndices`, and to avoid passing indices in RAM. When you draw something, a draw command is sent to the GPU and the execution continues immediatly after. But if you pass indices in RAM, the execution has to block until the GPU has finished drawing in order to make sure that the indices are not free'd. */ use gl; use ToGlEnum; use std::mem; use buffer::BufferViewAnySlice; pub use self::buffer::{IndexBuffer, IndexBufferSlice, IndexBufferAny}; pub use self::multidraw::{DrawCommandsNoIndicesBuffer, DrawCommandNoIndices}; mod buffer; mod multidraw; /// Describes a source of indices used for drawing. #[derive(Clone)] pub enum IndicesSource<'a> { /// A buffer uploaded in video memory. IndexBuffer { /// The buffer. buffer: BufferViewAnySlice<'a>, /// Type of indices in the buffer. data_type: IndexType, /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, /// Use a multidraw indirect buffer without indices. MultidrawArray { /// The buffer. buffer: BufferViewAnySlice<'a>, /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, /// Don't use indices. Assemble primitives by using the order in which the vertices are in /// the vertices source. NoIndices { /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, } impl<'a> IndicesSource<'a> { /// Returns the type of the primitives. pub fn get_primitives_type(&self) -> PrimitiveType { match self { &IndicesSource::IndexBuffer { primitives,.. } => primitives, &IndicesSource::MultidrawArray { primitives,.. } => primitives, &IndicesSource::NoIndices { primitives } => primitives, } } } /// List of available primitives. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PrimitiveType { /// Points, /// LinesList, /// LinesListAdjacency, /// LineStrip, /// LineStripAdjacency, /// TrianglesList, /// TrianglesListAdjacency, /// TriangleStrip, /// TriangleStripAdjacency, /// TriangleFan, /// Patches { /// Number of vertices per patch. vertices_per_patch: u16, }, } impl ToGlEnum for PrimitiveType { fn to_glenum(&self) -> gl::types::GLenum { match self { &PrimitiveType::Points => gl::POINTS, &PrimitiveType::LinesList => gl::LINES, &PrimitiveType::LinesListAdjacency => gl::LINES_ADJACENCY, &PrimitiveType::LineStrip => gl::LINE_STRIP, &PrimitiveType::LineStripAdjacency => gl::LINE_STRIP_ADJACENCY, &PrimitiveType::TrianglesList => gl::TRIANGLES, &PrimitiveType::TrianglesListAdjacency => gl::TRIANGLES_ADJACENCY, &PrimitiveType::TriangleStrip => gl::TRIANGLE_STRIP, &PrimitiveType::TriangleStripAdjacency => gl::TRIANGLE_STRIP_ADJACENCY, &PrimitiveType::TriangleFan => gl::TRIANGLE_FAN, &PrimitiveType::Patches {.. } => gl::PATCHES, } } } /// Marker that can be used as an indices source when you don't need indices. /// /// If you use this, then the primitives will be constructed using the order in which the /// vertices are in the vertices sources. #[derive(Copy, Clone, Debug)] pub struct NoIndices(pub PrimitiveType); impl<'a> From<NoIndices> for IndicesSource<'a> { fn from(marker: NoIndices) -> IndicesSource<'a> { IndicesSource::NoIndices { primitives: marker.0 } } } impl<'a, 'b> From<&'b NoIndices> for IndicesSource<'a> { fn from(marker: &'b NoIndices) -> IndicesSource<'a> { IndicesSource::NoIndices { primitives: marker.0 } } } /// Type of the indices in an index source. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u32)] // GLenum pub enum IndexType { /// u8 U8 = gl::UNSIGNED_BYTE, /// u16 U16 = gl::UNSIGNED_SHORT, /// u32 U32 = gl::UNSIGNED_INT, } impl IndexType { /// Returns the size in bytes of each index of this type. pub fn get_size(&self) -> usize {
} } } impl ToGlEnum for IndexType { fn to_glenum(&self) -> gl::types::GLenum { *self as gl::types::GLenum } } /// An index from the index buffer. pub unsafe trait Index: Copy + Send +'static { /// Returns the `IndexType` corresponding to this type. fn get_type() -> IndexType; } unsafe impl Index for u8 { fn get_type() -> IndexType { IndexType::U8 } } unsafe impl Index for u16 { fn get_type() -> IndexType { IndexType::U16 } } unsafe impl Index for u32 { fn get_type() -> IndexType { IndexType::U32 } }
match *self { IndexType::U8 => mem::size_of::<u8>(), IndexType::U16 => mem::size_of::<u16>(), IndexType::U32 => mem::size_of::<u32>(),
random_line_split
mod.rs
/*! In order to draw, you need to provide a source of indices which is used to link the vertices together into *primitives*. There are eleven types of primitives, each one with a corresponding struct: - `PointsList` - `LinesList` - `LinesListAdjacency` - `LineStrip` - `LineStripAdjacency` - `TrianglesList` - `TrianglesListAdjacency` - `TriangleStrip` - `TriangleStripAdjacency` - `TriangleFan` - `Patches` These structs can be turned into an `IndexBuffer`, which uploads the data in video memory. There are three ways to specify the indices that must be used: - Passing a reference to one of these structs. - Passing a reference to an `IndexBuffer`. - `NoIndices`, which is equivalent to `(0, 1, 2, 3, 4, 5, 6, 7,..)`. For performances it is highly recommended to use either an `IndexBuffer` or `NoIndices`, and to avoid passing indices in RAM. When you draw something, a draw command is sent to the GPU and the execution continues immediatly after. But if you pass indices in RAM, the execution has to block until the GPU has finished drawing in order to make sure that the indices are not free'd. */ use gl; use ToGlEnum; use std::mem; use buffer::BufferViewAnySlice; pub use self::buffer::{IndexBuffer, IndexBufferSlice, IndexBufferAny}; pub use self::multidraw::{DrawCommandsNoIndicesBuffer, DrawCommandNoIndices}; mod buffer; mod multidraw; /// Describes a source of indices used for drawing. #[derive(Clone)] pub enum
<'a> { /// A buffer uploaded in video memory. IndexBuffer { /// The buffer. buffer: BufferViewAnySlice<'a>, /// Type of indices in the buffer. data_type: IndexType, /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, /// Use a multidraw indirect buffer without indices. MultidrawArray { /// The buffer. buffer: BufferViewAnySlice<'a>, /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, /// Don't use indices. Assemble primitives by using the order in which the vertices are in /// the vertices source. NoIndices { /// Type of primitives contained in the vertex source. primitives: PrimitiveType, }, } impl<'a> IndicesSource<'a> { /// Returns the type of the primitives. pub fn get_primitives_type(&self) -> PrimitiveType { match self { &IndicesSource::IndexBuffer { primitives,.. } => primitives, &IndicesSource::MultidrawArray { primitives,.. } => primitives, &IndicesSource::NoIndices { primitives } => primitives, } } } /// List of available primitives. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PrimitiveType { /// Points, /// LinesList, /// LinesListAdjacency, /// LineStrip, /// LineStripAdjacency, /// TrianglesList, /// TrianglesListAdjacency, /// TriangleStrip, /// TriangleStripAdjacency, /// TriangleFan, /// Patches { /// Number of vertices per patch. vertices_per_patch: u16, }, } impl ToGlEnum for PrimitiveType { fn to_glenum(&self) -> gl::types::GLenum { match self { &PrimitiveType::Points => gl::POINTS, &PrimitiveType::LinesList => gl::LINES, &PrimitiveType::LinesListAdjacency => gl::LINES_ADJACENCY, &PrimitiveType::LineStrip => gl::LINE_STRIP, &PrimitiveType::LineStripAdjacency => gl::LINE_STRIP_ADJACENCY, &PrimitiveType::TrianglesList => gl::TRIANGLES, &PrimitiveType::TrianglesListAdjacency => gl::TRIANGLES_ADJACENCY, &PrimitiveType::TriangleStrip => gl::TRIANGLE_STRIP, &PrimitiveType::TriangleStripAdjacency => gl::TRIANGLE_STRIP_ADJACENCY, &PrimitiveType::TriangleFan => gl::TRIANGLE_FAN, &PrimitiveType::Patches {.. } => gl::PATCHES, } } } /// Marker that can be used as an indices source when you don't need indices. /// /// If you use this, then the primitives will be constructed using the order in which the /// vertices are in the vertices sources. #[derive(Copy, Clone, Debug)] pub struct NoIndices(pub PrimitiveType); impl<'a> From<NoIndices> for IndicesSource<'a> { fn from(marker: NoIndices) -> IndicesSource<'a> { IndicesSource::NoIndices { primitives: marker.0 } } } impl<'a, 'b> From<&'b NoIndices> for IndicesSource<'a> { fn from(marker: &'b NoIndices) -> IndicesSource<'a> { IndicesSource::NoIndices { primitives: marker.0 } } } /// Type of the indices in an index source. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u32)] // GLenum pub enum IndexType { /// u8 U8 = gl::UNSIGNED_BYTE, /// u16 U16 = gl::UNSIGNED_SHORT, /// u32 U32 = gl::UNSIGNED_INT, } impl IndexType { /// Returns the size in bytes of each index of this type. pub fn get_size(&self) -> usize { match *self { IndexType::U8 => mem::size_of::<u8>(), IndexType::U16 => mem::size_of::<u16>(), IndexType::U32 => mem::size_of::<u32>(), } } } impl ToGlEnum for IndexType { fn to_glenum(&self) -> gl::types::GLenum { *self as gl::types::GLenum } } /// An index from the index buffer. pub unsafe trait Index: Copy + Send +'static { /// Returns the `IndexType` corresponding to this type. fn get_type() -> IndexType; } unsafe impl Index for u8 { fn get_type() -> IndexType { IndexType::U8 } } unsafe impl Index for u16 { fn get_type() -> IndexType { IndexType::U16 } } unsafe impl Index for u32 { fn get_type() -> IndexType { IndexType::U32 } }
IndicesSource
identifier_name
borrowed-enum.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. // xfail-android: FIXME(#10381) // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print *the_a_ref // check:$1 = {{TheA, x = 0, y = 8970181431921507452}, {TheA, 0, 2088533116, 2088533116}} // debugger:print *the_b_ref // check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}} // debugger:print *univariant_ref // check:$3 = {4820353753753434} #[allow(unused_variable)]; #[feature(struct_variant)]; // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn
() { // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b = TheB (0, 286331153, 286331153); let the_b_ref: &ABC = &the_b; let univariant = TheOnlyCase(4820353753753434); let univariant_ref: &Univariant = &univariant; zzz(); } fn zzz() {()}
main
identifier_name
borrowed-enum.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. // xfail-android: FIXME(#10381) // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print *the_a_ref // check:$1 = {{TheA, x = 0, y = 8970181431921507452}, {TheA, 0, 2088533116, 2088533116}} // debugger:print *the_b_ref // check:$2 = {{TheB, x = 0, y = 1229782938247303441}, {TheB, 0, 286331153, 286331153}} // debugger:print *univariant_ref // check:$3 = {4820353753753434} #[allow(unused_variable)]; #[feature(struct_variant)]; // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum ABC { TheA { x: i64, y: i64 }, TheB (i64, i32, i32), } // This is a special case since it does not have the implicit discriminant field. enum Univariant { TheOnlyCase(i64) } fn main() { // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let the_a = TheA { x: 0, y: 8970181431921507452 }; let the_a_ref: &ABC = &the_a; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let the_b = TheB (0, 286331153, 286331153); let the_b_ref: &ABC = &the_b; let univariant = TheOnlyCase(4820353753753434); let univariant_ref: &Univariant = &univariant; zzz(); } fn zzz() {()}
//
random_line_split
loan_ends_mid_block_pair.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. // compile-flags:-Zborrowck=compare #![allow(warnings)] #![feature(rustc_attrs)] fn main() { } fn nll_fail() { let mut data = ('a', 'b', 'c'); let c = &mut data.0; capitalize(c); data.0 = 'e'; //~^ ERROR (Ast) [E0506] //~| ERROR (Mir) [E0506] data.0 = 'f'; //~^ ERROR (Ast) [E0506] //~| ERROR (Mir) [E0506] data.0 = 'g'; //~^ ERROR (Ast) [E0506] //~| ERROR (Mir) [E0506] capitalize(c); } fn nll_ok() { let mut data = ('a', 'b', 'c'); let c = &mut data.0; capitalize(c); data.0 = 'e'; //~^ ERROR (Ast) [E0506] data.0 = 'f'; //~^ ERROR (Ast) [E0506] data.0 = 'g'; //~^ ERROR (Ast) [E0506] } fn
(_: &mut char) { }
capitalize
identifier_name
loan_ends_mid_block_pair.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. // compile-flags:-Zborrowck=compare #![allow(warnings)] #![feature(rustc_attrs)] fn main() { } fn nll_fail() { let mut data = ('a', 'b', 'c'); let c = &mut data.0; capitalize(c); data.0 = 'e'; //~^ ERROR (Ast) [E0506] //~| ERROR (Mir) [E0506] data.0 = 'f'; //~^ ERROR (Ast) [E0506] //~| ERROR (Mir) [E0506] data.0 = 'g'; //~^ ERROR (Ast) [E0506] //~| ERROR (Mir) [E0506] capitalize(c); } fn nll_ok()
fn capitalize(_: &mut char) { }
{ let mut data = ('a', 'b', 'c'); let c = &mut data.0; capitalize(c); data.0 = 'e'; //~^ ERROR (Ast) [E0506] data.0 = 'f'; //~^ ERROR (Ast) [E0506] data.0 = 'g'; //~^ ERROR (Ast) [E0506] }
identifier_body
loan_ends_mid_block_pair.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. // compile-flags:-Zborrowck=compare #![allow(warnings)] #![feature(rustc_attrs)] fn main() { } fn nll_fail() { let mut data = ('a', 'b', 'c'); let c = &mut data.0; capitalize(c); data.0 = 'e'; //~^ ERROR (Ast) [E0506] //~| ERROR (Mir) [E0506] data.0 = 'f'; //~^ ERROR (Ast) [E0506] //~| ERROR (Mir) [E0506] data.0 = 'g'; //~^ ERROR (Ast) [E0506]
//~| ERROR (Mir) [E0506] capitalize(c); } fn nll_ok() { let mut data = ('a', 'b', 'c'); let c = &mut data.0; capitalize(c); data.0 = 'e'; //~^ ERROR (Ast) [E0506] data.0 = 'f'; //~^ ERROR (Ast) [E0506] data.0 = 'g'; //~^ ERROR (Ast) [E0506] } fn capitalize(_: &mut char) { }
random_line_split
lib.rs
//! A serialization/deserialization library for [CSA] format. //! //! [CSA] format is a plaintext format for recording Shogi games. //! This library supports parsing CSA-formatted string as well as composing CSA-formatted string from structs. //! Detail about CSA format is found at http://www.computer-shogi.org/protocol/record_v22.html. //! //! # Examples //! Below is an example of parsing CSA-formatted string into structs. //! //! ``` //! use std::time::Duration; //! use csa::{parse_csa, Action, Color, GameRecord, MoveRecord, PieceType, Square}; //! //! let csa_str = "\ //! V2.2 //! N+NAKAHARA //! N-YONENAGA //! $EVENT:13th World Computer Shogi Championship //! PI //! + //! +2726FU //! T12 //! "; //! //! let game = parse_csa(csa_str).expect("failed to parse the csa content"); //! assert_eq!(game.black_player, Some("NAKAHARA".to_string()));
//! assert_eq!(game.event, Some("13th World Computer Shogi Championship".to_string())); //! assert_eq!(game.moves[0], MoveRecord{ //! action: Action::Move(Color::Black, Square::new(2, 7), Square::new(2, 6), PieceType::Pawn), //! time: Some(Duration::from_secs(12)) //! }); //! ``` //! //! In contrast, structs can be composed into CSA-formatted string. //! //! ``` //! use std::time::Duration; //! use csa::{ Action, Color, GameRecord, MoveRecord, PieceType, Square}; //! //! let mut g = GameRecord::default(); //! g.black_player = Some("NAKAHARA".to_string()); //! g.white_player = Some("YONENAGA".to_string()); //! g.event = Some("13th World Computer Shogi Championship".to_string()); //! g.moves.push(MoveRecord { //! action: Action::Move( //! Color::Black, //! Square::new(2, 7), //! Square::new(2, 6), //! PieceType::Pawn, //! ), //! time: Some(Duration::from_secs(5)), //! }); //! g.moves.push(MoveRecord { //! action: Action::Toryo, //! time: None, //! }); //! //! let csa_str = "\ //! V2.2 //! N+NAKAHARA //! N-YONENAGA //! $EVENT:13th World Computer Shogi Championship //! PI //! + //! +2726FU //! T5 //! %TORYO //! "; //! //! assert_eq!(csa_str, g.to_string()); //! ``` //! //! [CSA]: http://www2.computer-shogi.org/protocol/record_v22.html pub mod parser; pub mod value; pub use parser::*; pub use value::*;
//! assert_eq!(game.white_player, Some("YONENAGA".to_string()));
random_line_split
assets.rs
#[cfg(not(feature="dynamic-assets"))] mod static_assets { use std::collections::HashMap; use futures::Future; use web::{Resource, ResponseFuture}; // The CSS should be built to a single CSS file at compile time #[derive(StaticResource)] #[filename = "assets/themes.css"] #[mime = "text/css"] pub struct ThemesCss; #[derive(StaticResource)] #[filename = "assets/style.css"] #[mime = "text/css"] pub struct StyleCss; #[derive(StaticResource)] #[filename = "assets/script.js"] #[mime = "application/javascript"] pub struct ScriptJs; #[derive(StaticResource)] #[filename = "assets/search.js"] #[mime = "application/javascript"] pub struct SearchJs; // SIL Open Font License 1.1: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL // Copyright 2015 The Amatic SC Project Authors ([email protected]) // #[derive(StaticResource)] // #[filename = "assets/amatic-sc-v9-latin-regular.woff"] // #[mime = "application/font-woff"] // pub struct AmaticFont; type BoxResource = Box<Resource + Sync + Send>; type ResourceFn = Box<Fn() -> BoxResource + Sync + Send>; lazy_static! { pub static ref ASSETS_MAP: HashMap<&'static str, ResourceFn> = hashmap!{ // The CSS should be built to a single CSS file at compile time ThemesCss::resource_name() => Box::new(|| Box::new(ThemesCss) as BoxResource) as ResourceFn, StyleCss::resource_name() => Box::new(|| Box::new(StyleCss) as BoxResource) as ResourceFn, ScriptJs::resource_name() => Box::new(|| Box::new(ScriptJs) as BoxResource) as ResourceFn, SearchJs::resource_name() => Box::new(|| Box::new(SearchJs) as BoxResource) as ResourceFn, }; } } #[cfg(not(feature="dynamic-assets"))] pub use self::static_assets::*; #[cfg(feature="dynamic-assets")] mod dynamic_assets { pub struct ThemesCss;
impl StyleCss { pub fn resource_name() -> &'static str { "style.css" } } pub struct ScriptJs; impl ScriptJs { pub fn resource_name() -> &'static str { "script.js" } } pub struct SearchJs; impl SearchJs { pub fn resource_name() -> &'static str { "search.js" } } } #[cfg(feature="dynamic-assets")] pub use self::dynamic_assets::*;
impl ThemesCss { pub fn resource_name() -> &'static str { "themes.css" } } pub struct StyleCss;
random_line_split
assets.rs
#[cfg(not(feature="dynamic-assets"))] mod static_assets { use std::collections::HashMap; use futures::Future; use web::{Resource, ResponseFuture}; // The CSS should be built to a single CSS file at compile time #[derive(StaticResource)] #[filename = "assets/themes.css"] #[mime = "text/css"] pub struct ThemesCss; #[derive(StaticResource)] #[filename = "assets/style.css"] #[mime = "text/css"] pub struct StyleCss; #[derive(StaticResource)] #[filename = "assets/script.js"] #[mime = "application/javascript"] pub struct ScriptJs; #[derive(StaticResource)] #[filename = "assets/search.js"] #[mime = "application/javascript"] pub struct SearchJs; // SIL Open Font License 1.1: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL // Copyright 2015 The Amatic SC Project Authors ([email protected]) // #[derive(StaticResource)] // #[filename = "assets/amatic-sc-v9-latin-regular.woff"] // #[mime = "application/font-woff"] // pub struct AmaticFont; type BoxResource = Box<Resource + Sync + Send>; type ResourceFn = Box<Fn() -> BoxResource + Sync + Send>; lazy_static! { pub static ref ASSETS_MAP: HashMap<&'static str, ResourceFn> = hashmap!{ // The CSS should be built to a single CSS file at compile time ThemesCss::resource_name() => Box::new(|| Box::new(ThemesCss) as BoxResource) as ResourceFn, StyleCss::resource_name() => Box::new(|| Box::new(StyleCss) as BoxResource) as ResourceFn, ScriptJs::resource_name() => Box::new(|| Box::new(ScriptJs) as BoxResource) as ResourceFn, SearchJs::resource_name() => Box::new(|| Box::new(SearchJs) as BoxResource) as ResourceFn, }; } } #[cfg(not(feature="dynamic-assets"))] pub use self::static_assets::*; #[cfg(feature="dynamic-assets")] mod dynamic_assets { pub struct ThemesCss; impl ThemesCss { pub fn resource_name() -> &'static str { "themes.css" } } pub struct StyleCss; impl StyleCss { pub fn resource_name() -> &'static str { "style.css" } } pub struct ScriptJs; impl ScriptJs { pub fn resource_name() -> &'static str { "script.js" } } pub struct
; impl SearchJs { pub fn resource_name() -> &'static str { "search.js" } } } #[cfg(feature="dynamic-assets")] pub use self::dynamic_assets::*;
SearchJs
identifier_name
assets.rs
#[cfg(not(feature="dynamic-assets"))] mod static_assets { use std::collections::HashMap; use futures::Future; use web::{Resource, ResponseFuture}; // The CSS should be built to a single CSS file at compile time #[derive(StaticResource)] #[filename = "assets/themes.css"] #[mime = "text/css"] pub struct ThemesCss; #[derive(StaticResource)] #[filename = "assets/style.css"] #[mime = "text/css"] pub struct StyleCss; #[derive(StaticResource)] #[filename = "assets/script.js"] #[mime = "application/javascript"] pub struct ScriptJs; #[derive(StaticResource)] #[filename = "assets/search.js"] #[mime = "application/javascript"] pub struct SearchJs; // SIL Open Font License 1.1: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL // Copyright 2015 The Amatic SC Project Authors ([email protected]) // #[derive(StaticResource)] // #[filename = "assets/amatic-sc-v9-latin-regular.woff"] // #[mime = "application/font-woff"] // pub struct AmaticFont; type BoxResource = Box<Resource + Sync + Send>; type ResourceFn = Box<Fn() -> BoxResource + Sync + Send>; lazy_static! { pub static ref ASSETS_MAP: HashMap<&'static str, ResourceFn> = hashmap!{ // The CSS should be built to a single CSS file at compile time ThemesCss::resource_name() => Box::new(|| Box::new(ThemesCss) as BoxResource) as ResourceFn, StyleCss::resource_name() => Box::new(|| Box::new(StyleCss) as BoxResource) as ResourceFn, ScriptJs::resource_name() => Box::new(|| Box::new(ScriptJs) as BoxResource) as ResourceFn, SearchJs::resource_name() => Box::new(|| Box::new(SearchJs) as BoxResource) as ResourceFn, }; } } #[cfg(not(feature="dynamic-assets"))] pub use self::static_assets::*; #[cfg(feature="dynamic-assets")] mod dynamic_assets { pub struct ThemesCss; impl ThemesCss { pub fn resource_name() -> &'static str
} pub struct StyleCss; impl StyleCss { pub fn resource_name() -> &'static str { "style.css" } } pub struct ScriptJs; impl ScriptJs { pub fn resource_name() -> &'static str { "script.js" } } pub struct SearchJs; impl SearchJs { pub fn resource_name() -> &'static str { "search.js" } } } #[cfg(feature="dynamic-assets")] pub use self::dynamic_assets::*;
{ "themes.css" }
identifier_body
main.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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. // // Serkr 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 Serkr. If not, see <http://www.gnu.org/licenses/>. // //! Serkr is an automated theorem prover for first order logic. // Some lints which are pretty useful. #![deny(fat_ptr_transmutes, unused_extern_crates, variant_size_differences, missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces, unused_qualifications)] // Might as well make the warnings errors. #![deny(warnings)] // Clippy lints turned to the max. #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy", deny(clippy))] #![cfg_attr(feature="clippy", deny(clippy_pedantic))] #![cfg_attr(feature="clippy", allow(indexing_slicing, similar_names, many_single_char_names, doc_markdown, stutter, type_complexity, missing_docs_in_private_items))] #[macro_use] extern crate clap; extern crate num; #[macro_use] pub mod utils; pub mod tptp_parser; pub mod cnf; pub mod prover; use prover::proof_statistics::*; use prover::proof_result::ProofResult; use utils::stopwatch::Stopwatch; #[cfg_attr(feature="clippy", allow(print_stdout))] fn print_proof_result(proof_result: &ProofResult, input_file: &str) { println_szs!("SZS status {} for {}", proof_result.display_type(), input_file); if proof_result.is_successful()
println!(""); } #[cfg_attr(feature="clippy", allow(print_stdout))] fn print_statistics(sw: &Stopwatch) { println_szs!("Time elapsed (in ms): {}", sw.elapsed_ms()); println_szs!("Initial clauses: {}", get_initial_clauses()); println_szs!("Analyzed clauses: {}", get_iteration_count()); println_szs!(" Trivial: {}", get_trivial_count()); println_szs!(" Forward subsumed: {}", get_forward_subsumed_count()); println_szs!(" Nonredundant: {}", get_nonredundant_analyzed_count()); println_szs!("Backward subsumptions: {}", get_backward_subsumed_count()); println_szs!("Inferred clauses: {}", get_inferred_count()); println_szs!(" Superposition: {}", get_superposition_inferred_count()); println_szs!(" Equality factoring: {}", get_equality_factoring_inferred_count()); println_szs!(" Equality resolution: {}", get_equality_resolution_inferred_count()); println_szs!("Nontrivial inferred clauses: {}", get_nontrivial_inferred_count()); } fn main() { let matches = clap::App::new("Serkr") .version(crate_version!()) .author("Mikko Aarnos <[email protected]>") .about("An automated theorem prover for first order logic with equality") .args_from_usage("<INPUT> 'The TPTP file the program should analyze'") .arg(clap::Arg::with_name("time-limit") .help("Time limit for the prover (default=300s)") .short("t") .long("time-limit") .value_name("arg")) .arg(clap::Arg::with_name("lpo") .help("Use LPO as the term ordering") .short("l") .long("lpo") .conflicts_with("kbo")) .arg(clap::Arg::with_name("kbo") .help("Use KBO as the term ordering (default)") .short("k") .long("kbo") .conflicts_with("lpo")) .arg(clap::Arg::with_name("formula-renaming") .help("Adjust the limit for renaming subformulae to avoid \ exponential blowup in the CNF transformer. The default \ (=32) seems to work pretty well. 0 disables formula \ renaming.") .long("formula-renaming") .value_name("arg")) .get_matches(); // Hack to get around lifetime issues. let input_file_name = matches.value_of("INPUT") .expect("This should always be OK") .to_owned(); let time_limit_ms = value_t!(matches, "time-limit", u64).unwrap_or(300) * 1000; // The stack size is a hack to get around the parser/CNF transformer from crashing with very large files. let _ = std::thread::Builder::new() .stack_size(32 * 1024 * 1024) .spawn(move || { let input_file = matches.value_of("INPUT") .expect("This should always be OK"); let use_lpo = matches.is_present("lpo"); let renaming_limit = value_t!(matches, "formula-renaming", u64) .unwrap_or(32); prover::proof_search::prove(input_file, use_lpo, renaming_limit) }) .expect("Creating a new thread shouldn't fail"); let mut sw = Stopwatch::new(); let resolution = std::time::Duration::from_millis(10); sw.start(); while sw.elapsed_ms() < time_limit_ms &&!has_search_finished() { std::thread::sleep(resolution); } sw.stop(); let proof_result = get_proof_result(); print_proof_result(&proof_result, &input_file_name); if!proof_result.is_err() { print_statistics(&sw); } }
{ println_szs!("SZS output None for {} : Proof output is not yet supported", input_file); }
conditional_block
main.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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. // // Serkr 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 Serkr. If not, see <http://www.gnu.org/licenses/>. // //! Serkr is an automated theorem prover for first order logic. // Some lints which are pretty useful. #![deny(fat_ptr_transmutes, unused_extern_crates, variant_size_differences, missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces, unused_qualifications)] // Might as well make the warnings errors. #![deny(warnings)] // Clippy lints turned to the max. #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy", deny(clippy))] #![cfg_attr(feature="clippy", deny(clippy_pedantic))] #![cfg_attr(feature="clippy", allow(indexing_slicing, similar_names, many_single_char_names, doc_markdown, stutter, type_complexity, missing_docs_in_private_items))] #[macro_use] extern crate clap; extern crate num; #[macro_use] pub mod utils; pub mod tptp_parser; pub mod cnf; pub mod prover; use prover::proof_statistics::*; use prover::proof_result::ProofResult; use utils::stopwatch::Stopwatch; #[cfg_attr(feature="clippy", allow(print_stdout))] fn print_proof_result(proof_result: &ProofResult, input_file: &str) { println_szs!("SZS status {} for {}", proof_result.display_type(), input_file); if proof_result.is_successful() { println_szs!("SZS output None for {} : Proof output is not yet supported", input_file); } println!(""); } #[cfg_attr(feature="clippy", allow(print_stdout))] fn print_statistics(sw: &Stopwatch)
fn main() { let matches = clap::App::new("Serkr") .version(crate_version!()) .author("Mikko Aarnos <[email protected]>") .about("An automated theorem prover for first order logic with equality") .args_from_usage("<INPUT> 'The TPTP file the program should analyze'") .arg(clap::Arg::with_name("time-limit") .help("Time limit for the prover (default=300s)") .short("t") .long("time-limit") .value_name("arg")) .arg(clap::Arg::with_name("lpo") .help("Use LPO as the term ordering") .short("l") .long("lpo") .conflicts_with("kbo")) .arg(clap::Arg::with_name("kbo") .help("Use KBO as the term ordering (default)") .short("k") .long("kbo") .conflicts_with("lpo")) .arg(clap::Arg::with_name("formula-renaming") .help("Adjust the limit for renaming subformulae to avoid \ exponential blowup in the CNF transformer. The default \ (=32) seems to work pretty well. 0 disables formula \ renaming.") .long("formula-renaming") .value_name("arg")) .get_matches(); // Hack to get around lifetime issues. let input_file_name = matches.value_of("INPUT") .expect("This should always be OK") .to_owned(); let time_limit_ms = value_t!(matches, "time-limit", u64).unwrap_or(300) * 1000; // The stack size is a hack to get around the parser/CNF transformer from crashing with very large files. let _ = std::thread::Builder::new() .stack_size(32 * 1024 * 1024) .spawn(move || { let input_file = matches.value_of("INPUT") .expect("This should always be OK"); let use_lpo = matches.is_present("lpo"); let renaming_limit = value_t!(matches, "formula-renaming", u64) .unwrap_or(32); prover::proof_search::prove(input_file, use_lpo, renaming_limit) }) .expect("Creating a new thread shouldn't fail"); let mut sw = Stopwatch::new(); let resolution = std::time::Duration::from_millis(10); sw.start(); while sw.elapsed_ms() < time_limit_ms &&!has_search_finished() { std::thread::sleep(resolution); } sw.stop(); let proof_result = get_proof_result(); print_proof_result(&proof_result, &input_file_name); if!proof_result.is_err() { print_statistics(&sw); } }
{ println_szs!("Time elapsed (in ms): {}", sw.elapsed_ms()); println_szs!("Initial clauses: {}", get_initial_clauses()); println_szs!("Analyzed clauses: {}", get_iteration_count()); println_szs!(" Trivial: {}", get_trivial_count()); println_szs!(" Forward subsumed: {}", get_forward_subsumed_count()); println_szs!(" Nonredundant: {}", get_nonredundant_analyzed_count()); println_szs!("Backward subsumptions: {}", get_backward_subsumed_count()); println_szs!("Inferred clauses: {}", get_inferred_count()); println_szs!(" Superposition: {}", get_superposition_inferred_count()); println_szs!(" Equality factoring: {}", get_equality_factoring_inferred_count()); println_szs!(" Equality resolution: {}", get_equality_resolution_inferred_count()); println_szs!("Nontrivial inferred clauses: {}", get_nontrivial_inferred_count()); }
identifier_body