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
init.rs
use std::sync::{Arc, Mutex}; use std::io; use std::ptr; use std::mem; use std::thread; use super::callback; use super::Window; use super::MonitorId; use super::WindowWrapper; use super::Context; use Api; use CreationError; use CreationError::OsError; use CursorState; use GlAttributes; use GlRequest; use PixelFormatRequirements; use WindowAttributes; use std::ffi::{OsStr}; use std::os::windows::ffi::OsStrExt; use std::sync::mpsc::channel; use winapi; use kernel32; use dwmapi; use user32; use api::wgl::Context as WglContext; use api::egl; use api::egl::Context as EglContext; use api::egl::ffi::egl::Egl; #[derive(Clone)] pub enum RawContext { Egl(egl::ffi::egl::types::EGLContext), Wgl(winapi::HGLRC), } unsafe impl Send for RawContext {} unsafe impl Sync for RawContext {} pub fn new_window(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<RawContext>, egl: Option<&Egl>) -> Result<Window, CreationError> { let egl = egl.map(|e| e.clone()); let window = window.clone(); let pf_reqs = pf_reqs.clone(); let opengl = opengl.clone(); // initializing variables to be sent to the task let title = OsStr::new(&window.title).encode_wide().chain(Some(0).into_iter()) .collect::<Vec<_>>(); let (tx, rx) = channel(); // `GetMessage` must be called in the same thread as CreateWindow, so we create a new thread // dedicated to this window. thread::spawn(move || { unsafe { // creating and sending the `Window` match init(title, &window, &pf_reqs, &opengl, egl) { Ok(w) => tx.send(Ok(w)).ok(), Err(e) => { tx.send(Err(e)).ok(); return; } }; // now that the `Window` struct is initialized, the main `Window::new()` function will // return and this events loop will run in parallel loop { let mut msg = mem::uninitialized(); if user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 {
user32::TranslateMessage(&msg); user32::DispatchMessageW(&msg); // calls `callback` (see the callback module) } } }); rx.recv().unwrap() } unsafe fn init(title: Vec<u16>, window: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<RawContext>, egl: Option<Egl>) -> Result<Window, CreationError> { let opengl = opengl.clone().map_sharing(|sharelists| { match sharelists { RawContext::Wgl(c) => c, _ => unimplemented!() } }); // registering the window class let class_name = register_window_class(); // building a RECT object with coordinates let mut rect = winapi::RECT { left: 0, right: window.dimensions.unwrap_or((1024, 768)).0 as winapi::LONG, top: 0, bottom: window.dimensions.unwrap_or((1024, 768)).1 as winapi::LONG, }; // switching to fullscreen if necessary // this means adjusting the window's position so that it overlaps the right monitor, // and change the monitor's resolution if necessary if window.monitor.is_some() { let monitor = window.monitor.as_ref().unwrap(); try!(switch_to_fullscreen(&mut rect, monitor)); } // computing the style and extended style of the window let (ex_style, style) = if window.monitor.is_some() || window.decorations == false { (winapi::WS_EX_APPWINDOW, winapi::WS_POPUP | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN) } else { (winapi::WS_EX_APPWINDOW | winapi::WS_EX_WINDOWEDGE, winapi::WS_OVERLAPPEDWINDOW | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN) }; // adjusting the window coordinates using the style user32::AdjustWindowRectEx(&mut rect, style, 0, ex_style); // creating the real window this time, by using the functions in `extra_functions` let real_window = { let (width, height) = if window.monitor.is_some() || window.dimensions.is_some() { (Some(rect.right - rect.left), Some(rect.bottom - rect.top)) } else { (None, None) }; let (x, y) = if window.monitor.is_some() { (Some(rect.left), Some(rect.top)) } else { (None, None) }; let style = if!window.visible { style } else { style | winapi::WS_VISIBLE }; let handle = user32::CreateWindowExW(ex_style | winapi::WS_EX_ACCEPTFILES, class_name.as_ptr(), title.as_ptr() as winapi::LPCWSTR, style | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN, x.unwrap_or(winapi::CW_USEDEFAULT), y.unwrap_or(winapi::CW_USEDEFAULT), width.unwrap_or(winapi::CW_USEDEFAULT), height.unwrap_or(winapi::CW_USEDEFAULT), ptr::null_mut(), ptr::null_mut(), kernel32::GetModuleHandleW(ptr::null()), ptr::null_mut()); if handle.is_null() { return Err(OsError(format!("CreateWindowEx function failed: {}", format!("{}", io::Error::last_os_error())))); } let hdc = user32::GetDC(handle); if hdc.is_null() { return Err(OsError(format!("GetDC function failed: {}", format!("{}", io::Error::last_os_error())))); } WindowWrapper(handle, hdc) }; // creating the OpenGL context let context = match opengl.version { GlRequest::Specific(Api::OpenGlEs, (_major, _minor)) => { if let Some(egl) = egl { if let Ok(c) = EglContext::new(egl, &pf_reqs, &opengl.clone().map_sharing(|_| unimplemented!()), egl::NativeDisplay::Other(Some(ptr::null()))) .and_then(|p| p.finish(real_window.0)) { Context::Egl(c) } else { try!(WglContext::new(&pf_reqs, &opengl, real_window.0) .map(Context::Wgl)) } } else { // falling back to WGL, which is always available try!(WglContext::new(&pf_reqs, &opengl, real_window.0) .map(Context::Wgl)) } }, _ => { try!(WglContext::new(&pf_reqs, &opengl, real_window.0).map(Context::Wgl)) } }; // making the window transparent if window.transparent { let bb = winapi::DWM_BLURBEHIND { dwFlags: 0x1, // FIXME: DWM_BB_ENABLE; fEnable: 1, hRgnBlur: ptr::null_mut(), fTransitionOnMaximized: 0, }; dwmapi::DwmEnableBlurBehindWindow(real_window.0, &bb); } // calling SetForegroundWindow if fullscreen if window.monitor.is_some() { user32::SetForegroundWindow(real_window.0); } // Creating a mutex to track the current cursor state let cursor_state = Arc::new(Mutex::new(CursorState::Normal)); // filling the CONTEXT_STASH task-local storage so that we can start receiving events let events_receiver = { let (tx, rx) = channel(); let mut tx = Some(tx); callback::CONTEXT_STASH.with(|context_stash| { let data = callback::ThreadLocalData { win: real_window.0, sender: tx.take().unwrap(), cursor_state: cursor_state.clone() }; (*context_stash.borrow_mut()) = Some(data); }); rx }; // building the struct Ok(Window { window: real_window, context: context, events_receiver: events_receiver, cursor_state: cursor_state, }) } unsafe fn register_window_class() -> Vec<u16> { let class_name = OsStr::new("Window Class").encode_wide().chain(Some(0).into_iter()) .collect::<Vec<_>>(); let class = winapi::WNDCLASSEXW { cbSize: mem::size_of::<winapi::WNDCLASSEXW>() as winapi::UINT, style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC, lpfnWndProc: Some(callback::callback), cbClsExtra: 0, cbWndExtra: 0, hInstance: kernel32::GetModuleHandleW(ptr::null()), hIcon: ptr::null_mut(), hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly hbrBackground: ptr::null_mut(), lpszMenuName: ptr::null(), lpszClassName: class_name.as_ptr(), hIconSm: ptr::null_mut(), }; // We ignore errors because registering the same window class twice would trigger // an error, and because errors here are detected during CreateWindowEx anyway. // Also since there is no weird element in the struct, there is no reason for this // call to fail. user32::RegisterClassExW(&class); class_name } unsafe fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorId) -> Result<(), CreationError> { // adjusting the rect { let pos = monitor.get_position(); rect.left += pos.0 as winapi::LONG; rect.right += pos.0 as winapi::LONG; rect.top += pos.1 as winapi::LONG; rect.bottom += pos.1 as winapi::LONG; } // changing device settings let mut screen_settings: winapi::DEVMODEW = mem::zeroed(); screen_settings.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD; screen_settings.dmPelsWidth = (rect.right - rect.left) as winapi::DWORD; screen_settings.dmPelsHeight = (rect.bottom - rect.top) as winapi::DWORD; screen_settings.dmBitsPerPel = 32; // TODO:? screen_settings.dmFields = winapi::DM_BITSPERPEL | winapi::DM_PELSWIDTH | winapi::DM_PELSHEIGHT; let result = user32::ChangeDisplaySettingsExW(monitor.get_adapter_name().as_ptr(), &mut screen_settings, ptr::null_mut(), winapi::CDS_FULLSCREEN, ptr::null_mut()); if result!= winapi::DISP_CHANGE_SUCCESSFUL { return Err(OsError(format!("ChangeDisplaySettings failed: {}", result))); } Ok(()) }
break; }
random_line_split
init.rs
use std::sync::{Arc, Mutex}; use std::io; use std::ptr; use std::mem; use std::thread; use super::callback; use super::Window; use super::MonitorId; use super::WindowWrapper; use super::Context; use Api; use CreationError; use CreationError::OsError; use CursorState; use GlAttributes; use GlRequest; use PixelFormatRequirements; use WindowAttributes; use std::ffi::{OsStr}; use std::os::windows::ffi::OsStrExt; use std::sync::mpsc::channel; use winapi; use kernel32; use dwmapi; use user32; use api::wgl::Context as WglContext; use api::egl; use api::egl::Context as EglContext; use api::egl::ffi::egl::Egl; #[derive(Clone)] pub enum RawContext { Egl(egl::ffi::egl::types::EGLContext), Wgl(winapi::HGLRC), } unsafe impl Send for RawContext {} unsafe impl Sync for RawContext {} pub fn new_window(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<RawContext>, egl: Option<&Egl>) -> Result<Window, CreationError>
Err(e) => { tx.send(Err(e)).ok(); return; } }; // now that the `Window` struct is initialized, the main `Window::new()` function will // return and this events loop will run in parallel loop { let mut msg = mem::uninitialized(); if user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 { break; } user32::TranslateMessage(&msg); user32::DispatchMessageW(&msg); // calls `callback` (see the callback module) } } }); rx.recv().unwrap() } unsafe fn init(title: Vec<u16>, window: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<RawContext>, egl: Option<Egl>) -> Result<Window, CreationError> { let opengl = opengl.clone().map_sharing(|sharelists| { match sharelists { RawContext::Wgl(c) => c, _ => unimplemented!() } }); // registering the window class let class_name = register_window_class(); // building a RECT object with coordinates let mut rect = winapi::RECT { left: 0, right: window.dimensions.unwrap_or((1024, 768)).0 as winapi::LONG, top: 0, bottom: window.dimensions.unwrap_or((1024, 768)).1 as winapi::LONG, }; // switching to fullscreen if necessary // this means adjusting the window's position so that it overlaps the right monitor, // and change the monitor's resolution if necessary if window.monitor.is_some() { let monitor = window.monitor.as_ref().unwrap(); try!(switch_to_fullscreen(&mut rect, monitor)); } // computing the style and extended style of the window let (ex_style, style) = if window.monitor.is_some() || window.decorations == false { (winapi::WS_EX_APPWINDOW, winapi::WS_POPUP | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN) } else { (winapi::WS_EX_APPWINDOW | winapi::WS_EX_WINDOWEDGE, winapi::WS_OVERLAPPEDWINDOW | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN) }; // adjusting the window coordinates using the style user32::AdjustWindowRectEx(&mut rect, style, 0, ex_style); // creating the real window this time, by using the functions in `extra_functions` let real_window = { let (width, height) = if window.monitor.is_some() || window.dimensions.is_some() { (Some(rect.right - rect.left), Some(rect.bottom - rect.top)) } else { (None, None) }; let (x, y) = if window.monitor.is_some() { (Some(rect.left), Some(rect.top)) } else { (None, None) }; let style = if!window.visible { style } else { style | winapi::WS_VISIBLE }; let handle = user32::CreateWindowExW(ex_style | winapi::WS_EX_ACCEPTFILES, class_name.as_ptr(), title.as_ptr() as winapi::LPCWSTR, style | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN, x.unwrap_or(winapi::CW_USEDEFAULT), y.unwrap_or(winapi::CW_USEDEFAULT), width.unwrap_or(winapi::CW_USEDEFAULT), height.unwrap_or(winapi::CW_USEDEFAULT), ptr::null_mut(), ptr::null_mut(), kernel32::GetModuleHandleW(ptr::null()), ptr::null_mut()); if handle.is_null() { return Err(OsError(format!("CreateWindowEx function failed: {}", format!("{}", io::Error::last_os_error())))); } let hdc = user32::GetDC(handle); if hdc.is_null() { return Err(OsError(format!("GetDC function failed: {}", format!("{}", io::Error::last_os_error())))); } WindowWrapper(handle, hdc) }; // creating the OpenGL context let context = match opengl.version { GlRequest::Specific(Api::OpenGlEs, (_major, _minor)) => { if let Some(egl) = egl { if let Ok(c) = EglContext::new(egl, &pf_reqs, &opengl.clone().map_sharing(|_| unimplemented!()), egl::NativeDisplay::Other(Some(ptr::null()))) .and_then(|p| p.finish(real_window.0)) { Context::Egl(c) } else { try!(WglContext::new(&pf_reqs, &opengl, real_window.0) .map(Context::Wgl)) } } else { // falling back to WGL, which is always available try!(WglContext::new(&pf_reqs, &opengl, real_window.0) .map(Context::Wgl)) } }, _ => { try!(WglContext::new(&pf_reqs, &opengl, real_window.0).map(Context::Wgl)) } }; // making the window transparent if window.transparent { let bb = winapi::DWM_BLURBEHIND { dwFlags: 0x1, // FIXME: DWM_BB_ENABLE; fEnable: 1, hRgnBlur: ptr::null_mut(), fTransitionOnMaximized: 0, }; dwmapi::DwmEnableBlurBehindWindow(real_window.0, &bb); } // calling SetForegroundWindow if fullscreen if window.monitor.is_some() { user32::SetForegroundWindow(real_window.0); } // Creating a mutex to track the current cursor state let cursor_state = Arc::new(Mutex::new(CursorState::Normal)); // filling the CONTEXT_STASH task-local storage so that we can start receiving events let events_receiver = { let (tx, rx) = channel(); let mut tx = Some(tx); callback::CONTEXT_STASH.with(|context_stash| { let data = callback::ThreadLocalData { win: real_window.0, sender: tx.take().unwrap(), cursor_state: cursor_state.clone() }; (*context_stash.borrow_mut()) = Some(data); }); rx }; // building the struct Ok(Window { window: real_window, context: context, events_receiver: events_receiver, cursor_state: cursor_state, }) } unsafe fn register_window_class() -> Vec<u16> { let class_name = OsStr::new("Window Class").encode_wide().chain(Some(0).into_iter()) .collect::<Vec<_>>(); let class = winapi::WNDCLASSEXW { cbSize: mem::size_of::<winapi::WNDCLASSEXW>() as winapi::UINT, style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC, lpfnWndProc: Some(callback::callback), cbClsExtra: 0, cbWndExtra: 0, hInstance: kernel32::GetModuleHandleW(ptr::null()), hIcon: ptr::null_mut(), hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly hbrBackground: ptr::null_mut(), lpszMenuName: ptr::null(), lpszClassName: class_name.as_ptr(), hIconSm: ptr::null_mut(), }; // We ignore errors because registering the same window class twice would trigger // an error, and because errors here are detected during CreateWindowEx anyway. // Also since there is no weird element in the struct, there is no reason for this // call to fail. user32::RegisterClassExW(&class); class_name } unsafe fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorId) -> Result<(), CreationError> { // adjusting the rect { let pos = monitor.get_position(); rect.left += pos.0 as winapi::LONG; rect.right += pos.0 as winapi::LONG; rect.top += pos.1 as winapi::LONG; rect.bottom += pos.1 as winapi::LONG; } // changing device settings let mut screen_settings: winapi::DEVMODEW = mem::zeroed(); screen_settings.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD; screen_settings.dmPelsWidth = (rect.right - rect.left) as winapi::DWORD; screen_settings.dmPelsHeight = (rect.bottom - rect.top) as winapi::DWORD; screen_settings.dmBitsPerPel = 32; // TODO:? screen_settings.dmFields = winapi::DM_BITSPERPEL | winapi::DM_PELSWIDTH | winapi::DM_PELSHEIGHT; let result = user32::ChangeDisplaySettingsExW(monitor.get_adapter_name().as_ptr(), &mut screen_settings, ptr::null_mut(), winapi::CDS_FULLSCREEN, ptr::null_mut()); if result!= winapi::DISP_CHANGE_SUCCESSFUL { return Err(OsError(format!("ChangeDisplaySettings failed: {}", result))); } Ok(()) }
{ let egl = egl.map(|e| e.clone()); let window = window.clone(); let pf_reqs = pf_reqs.clone(); let opengl = opengl.clone(); // initializing variables to be sent to the task let title = OsStr::new(&window.title).encode_wide().chain(Some(0).into_iter()) .collect::<Vec<_>>(); let (tx, rx) = channel(); // `GetMessage` must be called in the same thread as CreateWindow, so we create a new thread // dedicated to this window. thread::spawn(move || { unsafe { // creating and sending the `Window` match init(title, &window, &pf_reqs, &opengl, egl) { Ok(w) => tx.send(Ok(w)).ok(),
identifier_body
TestNativeExp2.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh. #pragma version(1) #pragma rs java_package_name(android.renderscript.cts) float __attribute__((kernel)) testNativeExp2FloatFloat(float inV) { return native_exp2(inV); } float2 __attribute__((kernel)) testNativeExp2Float2Float2(float2 inV) { return native_exp2(inV); } float3 __attribute__((kernel)) testNativeExp2Float3Float3(float3 inV) { return native_exp2(inV); }
float4 __attribute__((kernel)) testNativeExp2Float4Float4(float4 inV) { return native_exp2(inV); } half __attribute__((kernel)) testNativeExp2HalfHalf(half inV) { return native_exp2(inV); } half2 __attribute__((kernel)) testNativeExp2Half2Half2(half2 inV) { return native_exp2(inV); } half3 __attribute__((kernel)) testNativeExp2Half3Half3(half3 inV) { return native_exp2(inV); } half4 __attribute__((kernel)) testNativeExp2Half4Half4(half4 inV) { return native_exp2(inV); }
random_line_split
reader.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. use client::Client; use crypto::shared_secretbox; use futures::Future; use nfs::{File, NfsError, NfsFuture, data_map}; use self_encryption::SelfEncryptor; use self_encryption_storage::SelfEncryptionStorage; use utils::FutureExt; /// Reader is used to read contents of a File. It can read in chunks if the /// file happens to be very large #[allow(dead_code)] pub struct Reader<T> { client: Client<T>, self_encryptor: SelfEncryptor<SelfEncryptionStorage<T>>, } impl<T:'static> Reader<T> { /// Create a new instance of Reader pub fn new( client: Client<T>, storage: SelfEncryptionStorage<T>, file: &File, encryption_key: Option<shared_secretbox::Key>, ) -> Box<NfsFuture<Reader<T>>> { data_map::get(&client, file.data_map_name(), encryption_key) .and_then(move |data_map| { let self_encryptor = SelfEncryptor::new(storage, data_map)?; Ok(Reader { client: client, self_encryptor: self_encryptor, }) }) .into_box() } /// Returns the total size of the file/blob pub fn size(&self) -> u64 { self.self_encryptor.len() } /// Read data from file/blob pub fn read(&self, position: u64, length: u64) -> Box<NfsFuture<Vec<u8>>> { trace!( "Reader reading from pos: {} and size: {}.", position, length ); if (position + length) > self.size() { err!(NfsError::InvalidRange) } else
} }
{ debug!( "Reading {len} bytes of data from file starting at offset of {pos} bytes ...", len = length, pos = position ); self.self_encryptor .read(position, length) .map_err(From::from) .into_box() }
conditional_block
reader.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. use client::Client; use crypto::shared_secretbox; use futures::Future; use nfs::{File, NfsError, NfsFuture, data_map}; use self_encryption::SelfEncryptor; use self_encryption_storage::SelfEncryptionStorage; use utils::FutureExt; /// Reader is used to read contents of a File. It can read in chunks if the /// file happens to be very large #[allow(dead_code)] pub struct Reader<T> { client: Client<T>, self_encryptor: SelfEncryptor<SelfEncryptionStorage<T>>, } impl<T:'static> Reader<T> { /// Create a new instance of Reader pub fn new( client: Client<T>, storage: SelfEncryptionStorage<T>, file: &File, encryption_key: Option<shared_secretbox::Key>, ) -> Box<NfsFuture<Reader<T>>> { data_map::get(&client, file.data_map_name(), encryption_key) .and_then(move |data_map| { let self_encryptor = SelfEncryptor::new(storage, data_map)?; Ok(Reader { client: client, self_encryptor: self_encryptor, }) }) .into_box() } /// Returns the total size of the file/blob pub fn size(&self) -> u64 { self.self_encryptor.len() } /// Read data from file/blob pub fn read(&self, position: u64, length: u64) -> Box<NfsFuture<Vec<u8>>> { trace!( "Reader reading from pos: {} and size: {}.",
position, length ); if (position + length) > self.size() { err!(NfsError::InvalidRange) } else { debug!( "Reading {len} bytes of data from file starting at offset of {pos} bytes...", len = length, pos = position ); self.self_encryptor .read(position, length) .map_err(From::from) .into_box() } } }
random_line_split
reader.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. use client::Client; use crypto::shared_secretbox; use futures::Future; use nfs::{File, NfsError, NfsFuture, data_map}; use self_encryption::SelfEncryptor; use self_encryption_storage::SelfEncryptionStorage; use utils::FutureExt; /// Reader is used to read contents of a File. It can read in chunks if the /// file happens to be very large #[allow(dead_code)] pub struct
<T> { client: Client<T>, self_encryptor: SelfEncryptor<SelfEncryptionStorage<T>>, } impl<T:'static> Reader<T> { /// Create a new instance of Reader pub fn new( client: Client<T>, storage: SelfEncryptionStorage<T>, file: &File, encryption_key: Option<shared_secretbox::Key>, ) -> Box<NfsFuture<Reader<T>>> { data_map::get(&client, file.data_map_name(), encryption_key) .and_then(move |data_map| { let self_encryptor = SelfEncryptor::new(storage, data_map)?; Ok(Reader { client: client, self_encryptor: self_encryptor, }) }) .into_box() } /// Returns the total size of the file/blob pub fn size(&self) -> u64 { self.self_encryptor.len() } /// Read data from file/blob pub fn read(&self, position: u64, length: u64) -> Box<NfsFuture<Vec<u8>>> { trace!( "Reader reading from pos: {} and size: {}.", position, length ); if (position + length) > self.size() { err!(NfsError::InvalidRange) } else { debug!( "Reading {len} bytes of data from file starting at offset of {pos} bytes...", len = length, pos = position ); self.self_encryptor .read(position, length) .map_err(From::from) .into_box() } } }
Reader
identifier_name
flush.rs
use core::marker::PhantomData; use core::pin::Pin; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_sink::Sink; /// Future for the [`flush`](super::SinkExt::flush) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, Si:?Sized, Item> { sink: &'a mut Si, _phantom: PhantomData<fn(Item)>, } // Pin is never projected to a field. impl<Si: Unpin +?Sized, Item> Unpin for Flush<'_, Si, Item> {} /// A future that completes when the sink has finished processing all /// pending requests. /// /// The sink itself is returned after flushing is complete; this adapter is /// intended to be used when you want to stop sending to the sink until /// all current requests are processed. impl<'a, Si: Sink<Item> + Unpin +?Sized, Item> Flush<'a, Si, Item> { pub(super) fn new(sink: &'a mut Si) -> Self { Flush { sink, _phantom: PhantomData, } } } impl<Si: Sink<Item> + Unpin +?Sized, Item> Future for Flush<'_, Si, Item> { type Output = Result<(), Si::Error>; fn
( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::new(&mut self.sink).poll_flush(cx) } }
poll
identifier_name
flush.rs
use core::marker::PhantomData; use core::pin::Pin; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_sink::Sink; /// Future for the [`flush`](super::SinkExt::flush) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, Si:?Sized, Item> { sink: &'a mut Si, _phantom: PhantomData<fn(Item)>, } // Pin is never projected to a field. impl<Si: Unpin +?Sized, Item> Unpin for Flush<'_, Si, Item> {} /// A future that completes when the sink has finished processing all /// pending requests. /// /// The sink itself is returned after flushing is complete; this adapter is /// intended to be used when you want to stop sending to the sink until /// all current requests are processed. impl<'a, Si: Sink<Item> + Unpin +?Sized, Item> Flush<'a, Si, Item> { pub(super) fn new(sink: &'a mut Si) -> Self
} impl<Si: Sink<Item> + Unpin +?Sized, Item> Future for Flush<'_, Si, Item> { type Output = Result<(), Si::Error>; fn poll( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::new(&mut self.sink).poll_flush(cx) } }
{ Flush { sink, _phantom: PhantomData, } }
identifier_body
flush.rs
use core::marker::PhantomData; use core::pin::Pin; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_sink::Sink; /// Future for the [`flush`](super::SinkExt::flush) method.
} // Pin is never projected to a field. impl<Si: Unpin +?Sized, Item> Unpin for Flush<'_, Si, Item> {} /// A future that completes when the sink has finished processing all /// pending requests. /// /// The sink itself is returned after flushing is complete; this adapter is /// intended to be used when you want to stop sending to the sink until /// all current requests are processed. impl<'a, Si: Sink<Item> + Unpin +?Sized, Item> Flush<'a, Si, Item> { pub(super) fn new(sink: &'a mut Si) -> Self { Flush { sink, _phantom: PhantomData, } } } impl<Si: Sink<Item> + Unpin +?Sized, Item> Future for Flush<'_, Si, Item> { type Output = Result<(), Si::Error>; fn poll( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::new(&mut self.sink).poll_flush(cx) } }
#[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, Si: ?Sized, Item> { sink: &'a mut Si, _phantom: PhantomData<fn(Item)>,
random_line_split
body_exp_euler_integrator.rs
//! Explicit Euler integrator. use na::Transformation; use math::Scalar; use object::RigidBody; use integration::Integrator; use integration::euler; /// An explicit Euler integrator. /// /// Do not use this, prefer the `BodySmpEulerIntegrator` instead. pub struct BodyExpEulerIntegrator; impl BodyExpEulerIntegrator { /// Creates a new `BodyExpEulerIntegrator`. #[inline] pub fn new() -> BodyExpEulerIntegrator { BodyExpEulerIntegrator } } impl Integrator<RigidBody> for BodyExpEulerIntegrator { #[inline] fn update(&mut self, dt: Scalar, rb: &mut RigidBody)
}
{ if rb.can_move() { let (t, lv, av) = euler::explicit_integrate( dt.clone(), rb.position(), rb.center_of_mass(), &rb.lin_vel(), &rb.ang_vel(), &rb.lin_acc(), &rb.ang_acc()); rb.append_transformation(&t); rb.set_lin_vel(lv); rb.set_ang_vel(av); } }
identifier_body
body_exp_euler_integrator.rs
//! Explicit Euler integrator. use na::Transformation; use math::Scalar; use object::RigidBody; use integration::Integrator; use integration::euler; /// An explicit Euler integrator. /// /// Do not use this, prefer the `BodySmpEulerIntegrator` instead. pub struct BodyExpEulerIntegrator; impl BodyExpEulerIntegrator { /// Creates a new `BodyExpEulerIntegrator`. #[inline] pub fn new() -> BodyExpEulerIntegrator { BodyExpEulerIntegrator } } impl Integrator<RigidBody> for BodyExpEulerIntegrator { #[inline] fn update(&mut self, dt: Scalar, rb: &mut RigidBody) { if rb.can_move()
} }
{ let (t, lv, av) = euler::explicit_integrate( dt.clone(), rb.position(), rb.center_of_mass(), &rb.lin_vel(), &rb.ang_vel(), &rb.lin_acc(), &rb.ang_acc()); rb.append_transformation(&t); rb.set_lin_vel(lv); rb.set_ang_vel(av); }
conditional_block
body_exp_euler_integrator.rs
//! Explicit Euler integrator. use na::Transformation;
use object::RigidBody; use integration::Integrator; use integration::euler; /// An explicit Euler integrator. /// /// Do not use this, prefer the `BodySmpEulerIntegrator` instead. pub struct BodyExpEulerIntegrator; impl BodyExpEulerIntegrator { /// Creates a new `BodyExpEulerIntegrator`. #[inline] pub fn new() -> BodyExpEulerIntegrator { BodyExpEulerIntegrator } } impl Integrator<RigidBody> for BodyExpEulerIntegrator { #[inline] fn update(&mut self, dt: Scalar, rb: &mut RigidBody) { if rb.can_move() { let (t, lv, av) = euler::explicit_integrate( dt.clone(), rb.position(), rb.center_of_mass(), &rb.lin_vel(), &rb.ang_vel(), &rb.lin_acc(), &rb.ang_acc()); rb.append_transformation(&t); rb.set_lin_vel(lv); rb.set_ang_vel(av); } } }
use math::Scalar;
random_line_split
body_exp_euler_integrator.rs
//! Explicit Euler integrator. use na::Transformation; use math::Scalar; use object::RigidBody; use integration::Integrator; use integration::euler; /// An explicit Euler integrator. /// /// Do not use this, prefer the `BodySmpEulerIntegrator` instead. pub struct BodyExpEulerIntegrator; impl BodyExpEulerIntegrator { /// Creates a new `BodyExpEulerIntegrator`. #[inline] pub fn
() -> BodyExpEulerIntegrator { BodyExpEulerIntegrator } } impl Integrator<RigidBody> for BodyExpEulerIntegrator { #[inline] fn update(&mut self, dt: Scalar, rb: &mut RigidBody) { if rb.can_move() { let (t, lv, av) = euler::explicit_integrate( dt.clone(), rb.position(), rb.center_of_mass(), &rb.lin_vel(), &rb.ang_vel(), &rb.lin_acc(), &rb.ang_acc()); rb.append_transformation(&t); rb.set_lin_vel(lv); rb.set_ang_vel(av); } } }
new
identifier_name
iterable.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/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<...,...>` WebIDL declarations. use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use crate::dom::globalscope::GlobalScope; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; use js::jsapi::{Heap, JSObject}; use js::jsval::UndefinedValue; use js::rust::{HandleValue, MutableHandleObject}; use std::cell::Cell; use std::ptr; use std::ptr::NonNull; /// The values that an iterator will iterate over. #[derive(JSTraceable, MallocSizeOf)] pub enum IteratorType { /// The keys of the iterable object. Keys, /// The values of the iterable object. Values, /// The keys and values of the iterable object combined. Entries, } /// A DOM object that can be iterated over using a pair value iterator. pub trait Iterable { /// The type of the key of the iterator pair. type Key: ToJSValConvertible; /// The type of the value of the iterator pair. type Value: ToJSValConvertible; /// Return the number of entries that can be iterated over. fn get_iterable_length(&self) -> u32; /// Return the value at the provided index. fn get_value_at_index(&self, index: u32) -> Self::Value; /// Return the key at the provided index. fn get_key_at_index(&self, index: u32) -> Self::Key; } /// An iterator over the iterable entries of a given DOM interface. //FIXME: #12811 prevents dom_struct with type parameters #[dom_struct] pub struct IterableIterator<T: DomObject + JSTraceable + Iterable> { reflector: Reflector, iterable: Dom<T>, type_: IteratorType, index: Cell<u32>, } impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new( iterable: &T, type_: IteratorType, wrap: unsafe fn(JSContext, &GlobalScope, Box<IterableIterator<T>>) -> DomRoot<Self>, ) -> DomRoot<Self> { let iterator = Box::new(IterableIterator { reflector: Reflector::new(), type_: type_, iterable: Dom::from_ref(iterable), index: Cell::new(0), }); reflect_dom_object(iterator, &*iterable.global(), wrap) } /// Return the next value from the iterable object. #[allow(non_snake_case)] pub fn Next(&self, cx: JSContext) -> Fallible<NonNull<JSObject>> { let index = self.index.get(); rooted!(in(*cx) let mut value = UndefinedValue()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>()); let result = if index >= self.iterable.get_iterable_length() { dict_return(cx, rval.handle_mut(), true, value.handle()) } else
unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, key.handle_mut()); self.iterable .get_value_at_index(index) .to_jsval(*cx, value.handle_mut()); } key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle()) }, } } ; self.index.set(index + 1); result.map(|_| NonNull::new(rval.get()).expect("got a null pointer")) } } fn dict_return( cx: JSContext, mut result: MutableHandleObject, done: bool, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyOrValueResult::empty(); dict.done = done; dict.value.set(value.get()); rooted!(in(*cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(*cx, dict_value.handle_mut()); } result.set(dict_value.to_object()); Ok(()) } fn key_and_value_return( cx: JSContext, mut result: MutableHandleObject, key: HandleValue, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyAndValueResult::empty(); dict.done = false; dict.value = Some( vec![key, value] .into_iter() .map(|handle| RootedTraceableBox::from_box(Heap::boxed(handle.get()))) .collect(), ); rooted!(in(*cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(*cx, dict_value.handle_mut()); } result.set(dict_value.to_object()); Ok(()) }
{ match self.type_ { IteratorType::Keys => { unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Values => { unsafe { self.iterable .get_value_at_index(index) .to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Entries => { rooted!(in(*cx) let mut key = UndefinedValue());
conditional_block
iterable.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/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<...,...>` WebIDL declarations. use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use crate::dom::globalscope::GlobalScope; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; use js::jsapi::{Heap, JSObject}; use js::jsval::UndefinedValue; use js::rust::{HandleValue, MutableHandleObject}; use std::cell::Cell; use std::ptr; use std::ptr::NonNull; /// The values that an iterator will iterate over. #[derive(JSTraceable, MallocSizeOf)] pub enum IteratorType { /// The keys of the iterable object. Keys, /// The values of the iterable object. Values, /// The keys and values of the iterable object combined. Entries, } /// A DOM object that can be iterated over using a pair value iterator. pub trait Iterable { /// The type of the key of the iterator pair. type Key: ToJSValConvertible; /// The type of the value of the iterator pair. type Value: ToJSValConvertible; /// Return the number of entries that can be iterated over. fn get_iterable_length(&self) -> u32; /// Return the value at the provided index. fn get_value_at_index(&self, index: u32) -> Self::Value; /// Return the key at the provided index. fn get_key_at_index(&self, index: u32) -> Self::Key; } /// An iterator over the iterable entries of a given DOM interface. //FIXME: #12811 prevents dom_struct with type parameters #[dom_struct] pub struct IterableIterator<T: DomObject + JSTraceable + Iterable> { reflector: Reflector, iterable: Dom<T>, type_: IteratorType, index: Cell<u32>, } impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new( iterable: &T, type_: IteratorType, wrap: unsafe fn(JSContext, &GlobalScope, Box<IterableIterator<T>>) -> DomRoot<Self>, ) -> DomRoot<Self> { let iterator = Box::new(IterableIterator { reflector: Reflector::new(), type_: type_, iterable: Dom::from_ref(iterable), index: Cell::new(0), }); reflect_dom_object(iterator, &*iterable.global(), wrap) } /// Return the next value from the iterable object. #[allow(non_snake_case)] pub fn Next(&self, cx: JSContext) -> Fallible<NonNull<JSObject>>
.to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Entries => { rooted!(in(*cx) let mut key = UndefinedValue()); unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, key.handle_mut()); self.iterable .get_value_at_index(index) .to_jsval(*cx, value.handle_mut()); } key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle()) }, } }; self.index.set(index + 1); result.map(|_| NonNull::new(rval.get()).expect("got a null pointer")) } } fn dict_return( cx: JSContext, mut result: MutableHandleObject, done: bool, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyOrValueResult::empty(); dict.done = done; dict.value.set(value.get()); rooted!(in(*cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(*cx, dict_value.handle_mut()); } result.set(dict_value.to_object()); Ok(()) } fn key_and_value_return( cx: JSContext, mut result: MutableHandleObject, key: HandleValue, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyAndValueResult::empty(); dict.done = false; dict.value = Some( vec![key, value] .into_iter() .map(|handle| RootedTraceableBox::from_box(Heap::boxed(handle.get()))) .collect(), ); rooted!(in(*cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(*cx, dict_value.handle_mut()); } result.set(dict_value.to_object()); Ok(()) }
{ let index = self.index.get(); rooted!(in(*cx) let mut value = UndefinedValue()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>()); let result = if index >= self.iterable.get_iterable_length() { dict_return(cx, rval.handle_mut(), true, value.handle()) } else { match self.type_ { IteratorType::Keys => { unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Values => { unsafe { self.iterable .get_value_at_index(index)
identifier_body
iterable.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/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<...,...>` WebIDL declarations. use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use crate::dom::globalscope::GlobalScope; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; use js::jsapi::{Heap, JSObject}; use js::jsval::UndefinedValue; use js::rust::{HandleValue, MutableHandleObject};
/// The values that an iterator will iterate over. #[derive(JSTraceable, MallocSizeOf)] pub enum IteratorType { /// The keys of the iterable object. Keys, /// The values of the iterable object. Values, /// The keys and values of the iterable object combined. Entries, } /// A DOM object that can be iterated over using a pair value iterator. pub trait Iterable { /// The type of the key of the iterator pair. type Key: ToJSValConvertible; /// The type of the value of the iterator pair. type Value: ToJSValConvertible; /// Return the number of entries that can be iterated over. fn get_iterable_length(&self) -> u32; /// Return the value at the provided index. fn get_value_at_index(&self, index: u32) -> Self::Value; /// Return the key at the provided index. fn get_key_at_index(&self, index: u32) -> Self::Key; } /// An iterator over the iterable entries of a given DOM interface. //FIXME: #12811 prevents dom_struct with type parameters #[dom_struct] pub struct IterableIterator<T: DomObject + JSTraceable + Iterable> { reflector: Reflector, iterable: Dom<T>, type_: IteratorType, index: Cell<u32>, } impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new( iterable: &T, type_: IteratorType, wrap: unsafe fn(JSContext, &GlobalScope, Box<IterableIterator<T>>) -> DomRoot<Self>, ) -> DomRoot<Self> { let iterator = Box::new(IterableIterator { reflector: Reflector::new(), type_: type_, iterable: Dom::from_ref(iterable), index: Cell::new(0), }); reflect_dom_object(iterator, &*iterable.global(), wrap) } /// Return the next value from the iterable object. #[allow(non_snake_case)] pub fn Next(&self, cx: JSContext) -> Fallible<NonNull<JSObject>> { let index = self.index.get(); rooted!(in(*cx) let mut value = UndefinedValue()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>()); let result = if index >= self.iterable.get_iterable_length() { dict_return(cx, rval.handle_mut(), true, value.handle()) } else { match self.type_ { IteratorType::Keys => { unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Values => { unsafe { self.iterable .get_value_at_index(index) .to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Entries => { rooted!(in(*cx) let mut key = UndefinedValue()); unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, key.handle_mut()); self.iterable .get_value_at_index(index) .to_jsval(*cx, value.handle_mut()); } key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle()) }, } }; self.index.set(index + 1); result.map(|_| NonNull::new(rval.get()).expect("got a null pointer")) } } fn dict_return( cx: JSContext, mut result: MutableHandleObject, done: bool, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyOrValueResult::empty(); dict.done = done; dict.value.set(value.get()); rooted!(in(*cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(*cx, dict_value.handle_mut()); } result.set(dict_value.to_object()); Ok(()) } fn key_and_value_return( cx: JSContext, mut result: MutableHandleObject, key: HandleValue, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyAndValueResult::empty(); dict.done = false; dict.value = Some( vec![key, value] .into_iter() .map(|handle| RootedTraceableBox::from_box(Heap::boxed(handle.get()))) .collect(), ); rooted!(in(*cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(*cx, dict_value.handle_mut()); } result.set(dict_value.to_object()); Ok(()) }
use std::cell::Cell; use std::ptr; use std::ptr::NonNull;
random_line_split
iterable.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/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<...,...>` WebIDL declarations. use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use crate::dom::globalscope::GlobalScope; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; use js::jsapi::{Heap, JSObject}; use js::jsval::UndefinedValue; use js::rust::{HandleValue, MutableHandleObject}; use std::cell::Cell; use std::ptr; use std::ptr::NonNull; /// The values that an iterator will iterate over. #[derive(JSTraceable, MallocSizeOf)] pub enum IteratorType { /// The keys of the iterable object. Keys, /// The values of the iterable object. Values, /// The keys and values of the iterable object combined. Entries, } /// A DOM object that can be iterated over using a pair value iterator. pub trait Iterable { /// The type of the key of the iterator pair. type Key: ToJSValConvertible; /// The type of the value of the iterator pair. type Value: ToJSValConvertible; /// Return the number of entries that can be iterated over. fn get_iterable_length(&self) -> u32; /// Return the value at the provided index. fn get_value_at_index(&self, index: u32) -> Self::Value; /// Return the key at the provided index. fn get_key_at_index(&self, index: u32) -> Self::Key; } /// An iterator over the iterable entries of a given DOM interface. //FIXME: #12811 prevents dom_struct with type parameters #[dom_struct] pub struct IterableIterator<T: DomObject + JSTraceable + Iterable> { reflector: Reflector, iterable: Dom<T>, type_: IteratorType, index: Cell<u32>, } impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new( iterable: &T, type_: IteratorType, wrap: unsafe fn(JSContext, &GlobalScope, Box<IterableIterator<T>>) -> DomRoot<Self>, ) -> DomRoot<Self> { let iterator = Box::new(IterableIterator { reflector: Reflector::new(), type_: type_, iterable: Dom::from_ref(iterable), index: Cell::new(0), }); reflect_dom_object(iterator, &*iterable.global(), wrap) } /// Return the next value from the iterable object. #[allow(non_snake_case)] pub fn
(&self, cx: JSContext) -> Fallible<NonNull<JSObject>> { let index = self.index.get(); rooted!(in(*cx) let mut value = UndefinedValue()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>()); let result = if index >= self.iterable.get_iterable_length() { dict_return(cx, rval.handle_mut(), true, value.handle()) } else { match self.type_ { IteratorType::Keys => { unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Values => { unsafe { self.iterable .get_value_at_index(index) .to_jsval(*cx, value.handle_mut()); } dict_return(cx, rval.handle_mut(), false, value.handle()) }, IteratorType::Entries => { rooted!(in(*cx) let mut key = UndefinedValue()); unsafe { self.iterable .get_key_at_index(index) .to_jsval(*cx, key.handle_mut()); self.iterable .get_value_at_index(index) .to_jsval(*cx, value.handle_mut()); } key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle()) }, } }; self.index.set(index + 1); result.map(|_| NonNull::new(rval.get()).expect("got a null pointer")) } } fn dict_return( cx: JSContext, mut result: MutableHandleObject, done: bool, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyOrValueResult::empty(); dict.done = done; dict.value.set(value.get()); rooted!(in(*cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(*cx, dict_value.handle_mut()); } result.set(dict_value.to_object()); Ok(()) } fn key_and_value_return( cx: JSContext, mut result: MutableHandleObject, key: HandleValue, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyAndValueResult::empty(); dict.done = false; dict.value = Some( vec![key, value] .into_iter() .map(|handle| RootedTraceableBox::from_box(Heap::boxed(handle.get()))) .collect(), ); rooted!(in(*cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_jsval(*cx, dict_value.handle_mut()); } result.set(dict_value.to_object()); Ok(()) }
Next
identifier_name
client.rs
extern crate env_logger; extern crate tokio_core; extern crate futures; extern crate tokio_solicit; use std::str; use std::io::{self}; use futures::{Future, Stream}; use futures::future::{self}; use tokio_core::reactor::{Core}; use tokio_solicit::client::H2Client; // Shows the usage of `H2Client` when establishing an HTTP/2 connection over cleartext TCP. // Also demonstrates how to stream the body of the response (i.e. get response body chunks as soon // as they are received on a `futures::Stream`. fn cleartext_example()
println!("receiving a new chunk of size {}", chunk.body.len()); vec.extend(chunk.body.into_iter()); future::ok::<_, io::Error>(vec) }) }); // Finally, yield a future that resolves once both requests are complete (and both bodies // are available). Future::join(get, post) }).map(|(get_response, post_response_body)| { // Convert the bodies to a UTF-8 string let get_res: String = str::from_utf8(&get_response.body).unwrap().into(); let post_res: String = str::from_utf8(&post_response_body).unwrap().into(); //...and yield a pair of bodies converted to a string. (get_res, post_res) }); let res = core.run(future_response).expect("responses!"); println!("{:?}", res); } /// Fetches the response of google.com over HTTP/2. /// /// The connection is negotiated during the TLS handshake using ALPN. fn alpn_example() { println!(); println!("---- ALPN example ----"); use std::net::{ToSocketAddrs}; let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "google.com:443" .to_socket_addrs() .expect("unable to resolve the domain name") .next() .expect("no matching ip addresses"); let future_response = H2Client::connect("google.com", &addr, &handle).and_then(|mut client| { // Ask for the homepage... client.get(b"/").into_full_body_response() }); let response = core.run(future_response).expect("unexpected failure"); // Print both the headers and the response body... println!("{:?}", response.headers); // (Recklessly assume it's utf-8!) let body = str::from_utf8(&response.body).unwrap(); println!("{}", body); println!("---- ALPN example end ----"); } fn main() { env_logger::init().expect("logger init is required"); // Establish an http/2 connection (over cleartext TCP), issue a couple of requests, and // stream the body of the response of one of them. Wait until both are ready and then // print the bodies. cleartext_example(); // Show how to estalbish a connection over TLS, while negotiating the use of http/2 over ALPN. alpn_example(); // An additional demo showing how to perform a streaming _request_ (i.e. the body of the // request is streamed out to the server). do_streaming_request(); } fn do_streaming_request() { println!(); println!("---- streaming request example ----"); use std::iter; use tokio_solicit::client::HttpRequestBody; use futures::Sink; let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address"); let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { let (post, tx) = client.streaming_request(b"POST", b"/post", iter::empty()); tx .send(Ok(HttpRequestBody::new(b"HELLO ".to_vec()))) .and_then(|tx| tx.send(Ok(HttpRequestBody::new(b" WORLD".to_vec())))) .and_then(|tx| tx.send(Ok(HttpRequestBody::new(b"!".to_vec())))) .map_err(|_err| io::Error::from(io::ErrorKind::BrokenPipe)) .and_then(|_tx| post.into_full_body_response()) }); let res = core.run(future_response).expect("response"); println!("{:?}", res); println!("---- streaming request example end ----"); }
{ let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address"); let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { println!("Connection established."); // For the first request, we simply want the full body, without streaming individual body // chunks... let get = client.get(b"/get").into_full_body_response(); let post = client.post(b"/post", b"Hello, world!".to_vec()); // ...for the other, we accumulate the body "manually" in order to do some more // processing for each chunk (for demo purposes). Also, discards the headers. let post = post.and_then(|(_headers, body)| { body.fold(Vec::<u8>::new(), |mut vec, chunk| {
identifier_body
client.rs
extern crate env_logger; extern crate tokio_core; extern crate futures; extern crate tokio_solicit; use std::str; use std::io::{self}; use futures::{Future, Stream}; use futures::future::{self}; use tokio_core::reactor::{Core}; use tokio_solicit::client::H2Client; // Shows the usage of `H2Client` when establishing an HTTP/2 connection over cleartext TCP. // Also demonstrates how to stream the body of the response (i.e. get response body chunks as soon // as they are received on a `futures::Stream`. fn cleartext_example() { let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address"); let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { println!("Connection established."); // For the first request, we simply want the full body, without streaming individual body // chunks... let get = client.get(b"/get").into_full_body_response(); let post = client.post(b"/post", b"Hello, world!".to_vec()); //...for the other, we accumulate the body "manually" in order to do some more // processing for each chunk (for demo purposes). Also, discards the headers. let post = post.and_then(|(_headers, body)| { body.fold(Vec::<u8>::new(), |mut vec, chunk| { println!("receiving a new chunk of size {}", chunk.body.len()); vec.extend(chunk.body.into_iter()); future::ok::<_, io::Error>(vec) }) }); // Finally, yield a future that resolves once both requests are complete (and both bodies // are available). Future::join(get, post) }).map(|(get_response, post_response_body)| { // Convert the bodies to a UTF-8 string let get_res: String = str::from_utf8(&get_response.body).unwrap().into(); let post_res: String = str::from_utf8(&post_response_body).unwrap().into(); //...and yield a pair of bodies converted to a string. (get_res, post_res) }); let res = core.run(future_response).expect("responses!"); println!("{:?}", res); } /// Fetches the response of google.com over HTTP/2. /// /// The connection is negotiated during the TLS handshake using ALPN. fn alpn_example() { println!(); println!("---- ALPN example ----"); use std::net::{ToSocketAddrs}; let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "google.com:443" .to_socket_addrs() .expect("unable to resolve the domain name") .next() .expect("no matching ip addresses"); let future_response = H2Client::connect("google.com", &addr, &handle).and_then(|mut client| { // Ask for the homepage... client.get(b"/").into_full_body_response() }); let response = core.run(future_response).expect("unexpected failure"); // Print both the headers and the response body... println!("{:?}", response.headers); // (Recklessly assume it's utf-8!) let body = str::from_utf8(&response.body).unwrap(); println!("{}", body); println!("---- ALPN example end ----"); } fn main() { env_logger::init().expect("logger init is required"); // Establish an http/2 connection (over cleartext TCP), issue a couple of requests, and // stream the body of the response of one of them. Wait until both are ready and then // print the bodies. cleartext_example(); // Show how to estalbish a connection over TLS, while negotiating the use of http/2 over ALPN. alpn_example(); // An additional demo showing how to perform a streaming _request_ (i.e. the body of the // request is streamed out to the server). do_streaming_request(); } fn
() { println!(); println!("---- streaming request example ----"); use std::iter; use tokio_solicit::client::HttpRequestBody; use futures::Sink; let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address"); let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { let (post, tx) = client.streaming_request(b"POST", b"/post", iter::empty()); tx .send(Ok(HttpRequestBody::new(b"HELLO ".to_vec()))) .and_then(|tx| tx.send(Ok(HttpRequestBody::new(b" WORLD".to_vec())))) .and_then(|tx| tx.send(Ok(HttpRequestBody::new(b"!".to_vec())))) .map_err(|_err| io::Error::from(io::ErrorKind::BrokenPipe)) .and_then(|_tx| post.into_full_body_response()) }); let res = core.run(future_response).expect("response"); println!("{:?}", res); println!("---- streaming request example end ----"); }
do_streaming_request
identifier_name
client.rs
extern crate env_logger; extern crate tokio_core; extern crate futures; extern crate tokio_solicit; use std::str; use std::io::{self}; use futures::{Future, Stream}; use futures::future::{self}; use tokio_core::reactor::{Core}; use tokio_solicit::client::H2Client; // Shows the usage of `H2Client` when establishing an HTTP/2 connection over cleartext TCP. // Also demonstrates how to stream the body of the response (i.e. get response body chunks as soon // as they are received on a `futures::Stream`. fn cleartext_example() { let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address"); let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { println!("Connection established."); // For the first request, we simply want the full body, without streaming individual body // chunks... let get = client.get(b"/get").into_full_body_response(); let post = client.post(b"/post", b"Hello, world!".to_vec()); //...for the other, we accumulate the body "manually" in order to do some more // processing for each chunk (for demo purposes). Also, discards the headers. let post = post.and_then(|(_headers, body)| { body.fold(Vec::<u8>::new(), |mut vec, chunk| { println!("receiving a new chunk of size {}", chunk.body.len()); vec.extend(chunk.body.into_iter()); future::ok::<_, io::Error>(vec) }) }); // Finally, yield a future that resolves once both requests are complete (and both bodies // are available). Future::join(get, post) }).map(|(get_response, post_response_body)| { // Convert the bodies to a UTF-8 string let get_res: String = str::from_utf8(&get_response.body).unwrap().into(); let post_res: String = str::from_utf8(&post_response_body).unwrap().into(); //...and yield a pair of bodies converted to a string. (get_res, post_res) }); let res = core.run(future_response).expect("responses!"); println!("{:?}", res); } /// Fetches the response of google.com over HTTP/2. /// /// The connection is negotiated during the TLS handshake using ALPN. fn alpn_example() { println!(); println!("---- ALPN example ----"); use std::net::{ToSocketAddrs}; let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "google.com:443" .to_socket_addrs() .expect("unable to resolve the domain name") .next() .expect("no matching ip addresses"); let future_response = H2Client::connect("google.com", &addr, &handle).and_then(|mut client| { // Ask for the homepage... client.get(b"/").into_full_body_response() }); let response = core.run(future_response).expect("unexpected failure"); // Print both the headers and the response body... println!("{:?}", response.headers); // (Recklessly assume it's utf-8!) let body = str::from_utf8(&response.body).unwrap(); println!("{}", body); println!("---- ALPN example end ----"); } fn main() { env_logger::init().expect("logger init is required"); // Establish an http/2 connection (over cleartext TCP), issue a couple of requests, and // stream the body of the response of one of them. Wait until both are ready and then // print the bodies. cleartext_example(); // Show how to estalbish a connection over TLS, while negotiating the use of http/2 over ALPN. alpn_example(); // An additional demo showing how to perform a streaming _request_ (i.e. the body of the // request is streamed out to the server). do_streaming_request(); } fn do_streaming_request() { println!(); println!("---- streaming request example ----"); use std::iter; use tokio_solicit::client::HttpRequestBody; use futures::Sink; let mut core = Core::new().expect("event loop required");
let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { let (post, tx) = client.streaming_request(b"POST", b"/post", iter::empty()); tx .send(Ok(HttpRequestBody::new(b"HELLO ".to_vec()))) .and_then(|tx| tx.send(Ok(HttpRequestBody::new(b" WORLD".to_vec())))) .and_then(|tx| tx.send(Ok(HttpRequestBody::new(b"!".to_vec())))) .map_err(|_err| io::Error::from(io::ErrorKind::BrokenPipe)) .and_then(|_tx| post.into_full_body_response()) }); let res = core.run(future_response).expect("response"); println!("{:?}", res); println!("---- streaming request example end ----"); }
let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address");
random_line_split
pslldq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pslldq_1()
fn pslldq_2() { run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM6)), operand2: Some(Literal8(32)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 254, 32], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Literal8(90)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 252, 90], OperandSize::Dword) }
identifier_body
pslldq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pslldq_1() { run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Literal8(90)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 252, 90], OperandSize::Dword) } fn
() { run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM6)), operand2: Some(Literal8(32)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 254, 32], OperandSize::Qword) }
pslldq_2
identifier_name
pslldq.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pslldq_1() { run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM4)), operand2: Some(Literal8(90)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 252, 90], OperandSize::Dword)
run_test(&Instruction { mnemonic: Mnemonic::PSLLDQ, operand1: Some(Direct(XMM6)), operand2: Some(Literal8(32)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 115, 254, 32], OperandSize::Qword) }
} fn pslldq_2() {
random_line_split
legacy.rs
use core::char; use core::fmt; /// Representation of a demangled symbol name. pub struct Demangle<'a> { inner: &'a str, /// The number of ::-separated elements in the original name. elements: usize, } /// De-mangles a Rust symbol into a more readable version /// /// All Rust symbols by default are mangled as they contain characters that /// cannot be represented in all object files. The mangling mechanism is similar /// to C++'s, but Rust has a few specifics to handle items like lifetimes in /// symbols. /// /// This function will take a **mangled** symbol and return a value. When printed, /// the de-mangled version will be written. If the symbol does not look like /// a mangled symbol, the original value will be written instead. /// /// # Examples /// /// ``` /// use rustc_demangle::demangle; /// /// assert_eq!(demangle("_ZN4testE").to_string(), "test"); /// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); /// assert_eq!(demangle("foo").to_string(), "foo"); /// ``` // All Rust symbols are in theory lists of "::"-separated identifiers. Some // assemblers, however, can't handle these characters in symbol names. To get // around this, we use C++-style mangling. The mangling method is: // // 1. Prefix the symbol with "_ZN" // 2. For each element of the path, emit the length plus the element // 3. End the path with "E" // // For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar". //
// // Note that this demangler isn't quite as fancy as it could be. We have lots // of other information in our symbols like hashes, version, type information, // etc. Additionally, this doesn't handle glue symbols at all. pub fn demangle(s: &str) -> Result<(Demangle, &str), ()> { // First validate the symbol. If it doesn't look like anything we're // expecting, we just print it literally. Note that we must handle non-Rust // symbols because we could have any function in the backtrace. let inner = if s.starts_with("_ZN") { &s[3..] } else if s.starts_with("ZN") { // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" // form too. &s[2..] } else if s.starts_with("__ZN") { // On OSX, symbols are prefixed with an extra _ &s[4..] } else { return Err(()); }; // only work with ascii text if inner.bytes().any(|c| c & 0x80!= 0) { return Err(()); } let mut elements = 0; let mut chars = inner.chars(); let mut c = chars.next().ok_or(())?; while c!= 'E' { // Decode an identifier element's length. if!c.is_digit(10) { return Err(()); } let mut len = 0usize; while let Some(d) = c.to_digit(10) { len = len .checked_mul(10) .and_then(|len| len.checked_add(d as usize)) .ok_or(())?; c = chars.next().ok_or(())?; } // `c` already contains the first character of this identifier, skip it and // all the other characters of this identifier, to reach the next element. for _ in 0..len { c = chars.next().ok_or(())?; } elements += 1; } Ok((Demangle { inner, elements }, chars.as_str())) } // Rust hashes are hex digits with an `h` prepended. fn is_rust_hash(s: &str) -> bool { s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16)) } impl<'a> fmt::Display for Demangle<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Alright, let's do this. let mut inner = self.inner; for element in 0..self.elements { let mut rest = inner; while rest.chars().next().unwrap().is_digit(10) { rest = &rest[1..]; } let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap(); inner = &rest[i..]; rest = &rest[..i]; // Skip printing the hash if alternate formatting // was requested. if f.alternate() && element + 1 == self.elements && is_rust_hash(&rest) { break; } if element!= 0 { f.write_str("::")?; } if rest.starts_with("_$") { rest = &rest[1..]; } loop { if rest.starts_with('.') { if let Some('.') = rest[1..].chars().next() { f.write_str("::")?; rest = &rest[2..]; } else { f.write_str(".")?; rest = &rest[1..]; } } else if rest.starts_with('$') { let (escape, after_escape) = if let Some(end) = rest[1..].find('$') { (&rest[1..=end], &rest[end + 2..]) } else { break; }; // see src/librustc_codegen_utils/symbol_names/legacy.rs for these mappings let unescaped = match escape { "SP" => "@", "BP" => "*", "RF" => "&", "LT" => "<", "GT" => ">", "LP" => "(", "RP" => ")", "C" => ",", _ => { if escape.starts_with('u') { let digits = &escape[1..]; let all_lower_hex = digits.chars().all(|c| match c { '0'..='9' | 'a'..='f' => true, _ => false, }); let c = u32::from_str_radix(digits, 16) .ok() .and_then(char::from_u32); if let (true, Some(c)) = (all_lower_hex, c) { // FIXME(eddyb) do we need to filter out control codepoints? if!c.is_control() { c.fmt(f)?; rest = after_escape; continue; } } } break; } }; f.write_str(unescaped)?; rest = after_escape; } else if let Some(i) = rest.find(|c| c == '$' || c == '.') { f.write_str(&rest[..i])?; rest = &rest[i..]; } else { break; } } f.write_str(rest)?; } Ok(()) } } #[cfg(test)] mod tests { use std::prelude::v1::*; macro_rules! t { ($a:expr, $b:expr) => { assert!(ok($a, $b)) }; } macro_rules! t_err { ($a:expr) => { assert!(ok_err($a)) }; } macro_rules! t_nohash { ($a:expr, $b:expr) => {{ assert_eq!(format!("{:#}", ::demangle($a)), $b); }}; } fn ok(sym: &str, expected: &str) -> bool { match ::try_demangle(sym) { Ok(s) => { if s.to_string() == expected { true } else { println!("\n{}\n!=\n{}\n", s, expected); false } } Err(_) => { println!("error demangling"); false } } } fn ok_err(sym: &str) -> bool { match ::try_demangle(sym) { Ok(_) => { println!("succeeded in demangling"); false } Err(_) => ::demangle(sym).to_string() == sym, } } #[test] fn demangle() { t_err!("test"); t!("_ZN4testE", "test"); t_err!("_ZN4test"); t!("_ZN4test1a2bcE", "test::a::bc"); } #[test] fn demangle_dollars() { t!("_ZN4$RP$E", ")"); t!("_ZN8$RF$testE", "&test"); t!("_ZN8$BP$test4foobE", "*test::foob"); t!("_ZN9$u20$test4foobE", " test::foob"); t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); } #[test] fn demangle_many_dollars() { t!("_ZN13test$u20$test4foobE", "test test::foob"); t!("_ZN12test$BP$test4foobE", "test*test::foob"); } #[test] fn demangle_osx() { t!( "__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011" ); t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170"); } #[test] fn demangle_windows() { t!("ZN4testE", "test"); t!("ZN13test$u20$test4foobE", "test test::foob"); t!("ZN12test$RF$test4foobE", "test&test::foob"); } #[test] fn demangle_elements_beginning_with_underscore() { t!("_ZN13_$LT$test$GT$E", "<test>"); t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}"); t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR"); } #[test] fn demangle_trait_impls() { t!( "_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", "<Test +'static as foo::Bar<Test>>::bar" ); } #[test] fn demangle_without_hash() { let s = "_ZN3foo17h05af221e174051e9E"; t!(s, "foo::h05af221e174051e9"); t_nohash!(s, "foo"); } #[test] fn demangle_without_hash_edgecases() { // One element, no hash. t_nohash!("_ZN3fooE", "foo"); // Two elements, no hash. t_nohash!("_ZN3foo3barE", "foo::bar"); // Longer-than-normal hash. t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo"); // Shorter-than-normal hash. t_nohash!("_ZN3foo5h05afE", "foo"); // Valid hash, but not at the end. t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo"); // Not a valid hash, missing the 'h'. t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9"); // Not a valid hash, has a non-hex-digit. t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9"); } #[test] fn demangle_thinlto() { // One element, no hash. t!("_ZN3fooE.llvm.9D1C9369", "foo"); t!("_ZN3fooE.llvm.9D1C9369@@16", "foo"); t_nohash!( "_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo" ); } #[test] fn demangle_llvm_ir_branch_labels() { t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i"); t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut.exit.i.i"); } #[test] fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() { t_err!("_ZN3fooE.llvm moocow"); } #[test] fn dont_panic() { ::demangle("_ZN2222222222222222222222EE").to_string(); ::demangle("_ZN5*70527e27.ll34csaғE").to_string(); ::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); ::demangle( "\ _ZN5~saäb4e\n\ 2734cOsbE\n\ 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ ", ) .to_string(); } #[test] fn invalid_no_chop() { t_err!("_ZNfooE"); } #[test] fn handle_assoc_types() { t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", "<alloc::boxed::Box<alloc::boxed::FnBox<A, Output=R> + 'a> as core::ops::function::FnOnce<A>>::call_once::h69e8f44b3723e1ca"); } #[test] fn handle_bang() { t!( "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E", "<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8" ); } #[test] fn demangle_utf8_idents() { t_nohash!( "_ZN11utf8_idents157_$u10e1$$u10d0$$u10ed$$u10db$$u10d4$$u10da$$u10d0$$u10d3$_$u10d2$$u10d4$$u10db$$u10e0$$u10d8$$u10d4$$u10da$$u10d8$_$u10e1$$u10d0$$u10d3$$u10d8$$u10da$$u10d8$17h21634fd5714000aaE", "utf8_idents::საჭმელად_გემრიელი_სადილი" ); } #[test] fn demangle_issue_60925() { t_nohash!( "_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h059a991a004536adE", "issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo" ); } }
// We're the ones printing our backtraces, so we can't rely on anything else to // demangle our symbols. It's *much* nicer to look at demangled symbols, so // this function is implemented to give us nice pretty output.
random_line_split
legacy.rs
use core::char; use core::fmt; /// Representation of a demangled symbol name. pub struct Demangle<'a> { inner: &'a str, /// The number of ::-separated elements in the original name. elements: usize, } /// De-mangles a Rust symbol into a more readable version /// /// All Rust symbols by default are mangled as they contain characters that /// cannot be represented in all object files. The mangling mechanism is similar /// to C++'s, but Rust has a few specifics to handle items like lifetimes in /// symbols. /// /// This function will take a **mangled** symbol and return a value. When printed, /// the de-mangled version will be written. If the symbol does not look like /// a mangled symbol, the original value will be written instead. /// /// # Examples /// /// ``` /// use rustc_demangle::demangle; /// /// assert_eq!(demangle("_ZN4testE").to_string(), "test"); /// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); /// assert_eq!(demangle("foo").to_string(), "foo"); /// ``` // All Rust symbols are in theory lists of "::"-separated identifiers. Some // assemblers, however, can't handle these characters in symbol names. To get // around this, we use C++-style mangling. The mangling method is: // // 1. Prefix the symbol with "_ZN" // 2. For each element of the path, emit the length plus the element // 3. End the path with "E" // // For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar". // // We're the ones printing our backtraces, so we can't rely on anything else to // demangle our symbols. It's *much* nicer to look at demangled symbols, so // this function is implemented to give us nice pretty output. // // Note that this demangler isn't quite as fancy as it could be. We have lots // of other information in our symbols like hashes, version, type information, // etc. Additionally, this doesn't handle glue symbols at all. pub fn demangle(s: &str) -> Result<(Demangle, &str), ()> { // First validate the symbol. If it doesn't look like anything we're // expecting, we just print it literally. Note that we must handle non-Rust // symbols because we could have any function in the backtrace. let inner = if s.starts_with("_ZN") { &s[3..] } else if s.starts_with("ZN") { // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" // form too. &s[2..] } else if s.starts_with("__ZN") { // On OSX, symbols are prefixed with an extra _ &s[4..] } else { return Err(()); }; // only work with ascii text if inner.bytes().any(|c| c & 0x80!= 0) { return Err(()); } let mut elements = 0; let mut chars = inner.chars(); let mut c = chars.next().ok_or(())?; while c!= 'E' { // Decode an identifier element's length. if!c.is_digit(10) { return Err(()); } let mut len = 0usize; while let Some(d) = c.to_digit(10) { len = len .checked_mul(10) .and_then(|len| len.checked_add(d as usize)) .ok_or(())?; c = chars.next().ok_or(())?; } // `c` already contains the first character of this identifier, skip it and // all the other characters of this identifier, to reach the next element. for _ in 0..len { c = chars.next().ok_or(())?; } elements += 1; } Ok((Demangle { inner, elements }, chars.as_str())) } // Rust hashes are hex digits with an `h` prepended. fn is_rust_hash(s: &str) -> bool { s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16)) } impl<'a> fmt::Display for Demangle<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Alright, let's do this. let mut inner = self.inner; for element in 0..self.elements { let mut rest = inner; while rest.chars().next().unwrap().is_digit(10) { rest = &rest[1..]; } let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap(); inner = &rest[i..]; rest = &rest[..i]; // Skip printing the hash if alternate formatting // was requested. if f.alternate() && element + 1 == self.elements && is_rust_hash(&rest) { break; } if element!= 0 { f.write_str("::")?; } if rest.starts_with("_$") { rest = &rest[1..]; } loop { if rest.starts_with('.') { if let Some('.') = rest[1..].chars().next() { f.write_str("::")?; rest = &rest[2..]; } else { f.write_str(".")?; rest = &rest[1..]; } } else if rest.starts_with('$')
let digits = &escape[1..]; let all_lower_hex = digits.chars().all(|c| match c { '0'..='9' | 'a'..='f' => true, _ => false, }); let c = u32::from_str_radix(digits, 16) .ok() .and_then(char::from_u32); if let (true, Some(c)) = (all_lower_hex, c) { // FIXME(eddyb) do we need to filter out control codepoints? if!c.is_control() { c.fmt(f)?; rest = after_escape; continue; } } } break; } }; f.write_str(unescaped)?; rest = after_escape; } else if let Some(i) = rest.find(|c| c == '$' || c == '.') { f.write_str(&rest[..i])?; rest = &rest[i..]; } else { break; } } f.write_str(rest)?; } Ok(()) } } #[cfg(test)] mod tests { use std::prelude::v1::*; macro_rules! t { ($a:expr, $b:expr) => { assert!(ok($a, $b)) }; } macro_rules! t_err { ($a:expr) => { assert!(ok_err($a)) }; } macro_rules! t_nohash { ($a:expr, $b:expr) => {{ assert_eq!(format!("{:#}", ::demangle($a)), $b); }}; } fn ok(sym: &str, expected: &str) -> bool { match ::try_demangle(sym) { Ok(s) => { if s.to_string() == expected { true } else { println!("\n{}\n!=\n{}\n", s, expected); false } } Err(_) => { println!("error demangling"); false } } } fn ok_err(sym: &str) -> bool { match ::try_demangle(sym) { Ok(_) => { println!("succeeded in demangling"); false } Err(_) => ::demangle(sym).to_string() == sym, } } #[test] fn demangle() { t_err!("test"); t!("_ZN4testE", "test"); t_err!("_ZN4test"); t!("_ZN4test1a2bcE", "test::a::bc"); } #[test] fn demangle_dollars() { t!("_ZN4$RP$E", ")"); t!("_ZN8$RF$testE", "&test"); t!("_ZN8$BP$test4foobE", "*test::foob"); t!("_ZN9$u20$test4foobE", " test::foob"); t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); } #[test] fn demangle_many_dollars() { t!("_ZN13test$u20$test4foobE", "test test::foob"); t!("_ZN12test$BP$test4foobE", "test*test::foob"); } #[test] fn demangle_osx() { t!( "__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011" ); t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170"); } #[test] fn demangle_windows() { t!("ZN4testE", "test"); t!("ZN13test$u20$test4foobE", "test test::foob"); t!("ZN12test$RF$test4foobE", "test&test::foob"); } #[test] fn demangle_elements_beginning_with_underscore() { t!("_ZN13_$LT$test$GT$E", "<test>"); t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}"); t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR"); } #[test] fn demangle_trait_impls() { t!( "_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", "<Test +'static as foo::Bar<Test>>::bar" ); } #[test] fn demangle_without_hash() { let s = "_ZN3foo17h05af221e174051e9E"; t!(s, "foo::h05af221e174051e9"); t_nohash!(s, "foo"); } #[test] fn demangle_without_hash_edgecases() { // One element, no hash. t_nohash!("_ZN3fooE", "foo"); // Two elements, no hash. t_nohash!("_ZN3foo3barE", "foo::bar"); // Longer-than-normal hash. t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo"); // Shorter-than-normal hash. t_nohash!("_ZN3foo5h05afE", "foo"); // Valid hash, but not at the end. t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo"); // Not a valid hash, missing the 'h'. t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9"); // Not a valid hash, has a non-hex-digit. t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9"); } #[test] fn demangle_thinlto() { // One element, no hash. t!("_ZN3fooE.llvm.9D1C9369", "foo"); t!("_ZN3fooE.llvm.9D1C9369@@16", "foo"); t_nohash!( "_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo" ); } #[test] fn demangle_llvm_ir_branch_labels() { t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i"); t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut.exit.i.i"); } #[test] fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() { t_err!("_ZN3fooE.llvm moocow"); } #[test] fn dont_panic() { ::demangle("_ZN2222222222222222222222EE").to_string(); ::demangle("_ZN5*70527e27.ll34csaғE").to_string(); ::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); ::demangle( "\ _ZN5~saäb4e\n\ 2734cOsbE\n\ 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ ", ) .to_string(); } #[test] fn invalid_no_chop() { t_err!("_ZNfooE"); } #[test] fn handle_assoc_types() { t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", "<alloc::boxed::Box<alloc::boxed::FnBox<A, Output=R> + 'a> as core::ops::function::FnOnce<A>>::call_once::h69e8f44b3723e1ca"); } #[test] fn handle_bang() { t!( "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E", "<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8" ); } #[test] fn demangle_utf8_idents() { t_nohash!( "_ZN11utf8_idents157_$u10e1$$u10d0$$u10ed$$u10db$$u10d4$$u10da$$u10d0$$u10d3$_$u10d2$$u10d4$$u10db$$u10e0$$u10d8$$u10d4$$u10da$$u10d8$_$u10e1$$u10d0$$u10d3$$u10d8$$u10da$$u10d8$17h21634fd5714000aaE", "utf8_idents::საჭმელად_გემრიელი_სადილი" ); } #[test] fn demangle_issue_60925() { t_nohash!( "_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h059a991a004536adE", "issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo" ); } }
{ let (escape, after_escape) = if let Some(end) = rest[1..].find('$') { (&rest[1..=end], &rest[end + 2..]) } else { break; }; // see src/librustc_codegen_utils/symbol_names/legacy.rs for these mappings let unescaped = match escape { "SP" => "@", "BP" => "*", "RF" => "&", "LT" => "<", "GT" => ">", "LP" => "(", "RP" => ")", "C" => ",", _ => { if escape.starts_with('u') {
conditional_block
legacy.rs
use core::char; use core::fmt; /// Representation of a demangled symbol name. pub struct Demangle<'a> { inner: &'a str, /// The number of ::-separated elements in the original name. elements: usize, } /// De-mangles a Rust symbol into a more readable version /// /// All Rust symbols by default are mangled as they contain characters that /// cannot be represented in all object files. The mangling mechanism is similar /// to C++'s, but Rust has a few specifics to handle items like lifetimes in /// symbols. /// /// This function will take a **mangled** symbol and return a value. When printed, /// the de-mangled version will be written. If the symbol does not look like /// a mangled symbol, the original value will be written instead. /// /// # Examples /// /// ``` /// use rustc_demangle::demangle; /// /// assert_eq!(demangle("_ZN4testE").to_string(), "test"); /// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); /// assert_eq!(demangle("foo").to_string(), "foo"); /// ``` // All Rust symbols are in theory lists of "::"-separated identifiers. Some // assemblers, however, can't handle these characters in symbol names. To get // around this, we use C++-style mangling. The mangling method is: // // 1. Prefix the symbol with "_ZN" // 2. For each element of the path, emit the length plus the element // 3. End the path with "E" // // For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar". // // We're the ones printing our backtraces, so we can't rely on anything else to // demangle our symbols. It's *much* nicer to look at demangled symbols, so // this function is implemented to give us nice pretty output. // // Note that this demangler isn't quite as fancy as it could be. We have lots // of other information in our symbols like hashes, version, type information, // etc. Additionally, this doesn't handle glue symbols at all. pub fn demangle(s: &str) -> Result<(Demangle, &str), ()> { // First validate the symbol. If it doesn't look like anything we're // expecting, we just print it literally. Note that we must handle non-Rust // symbols because we could have any function in the backtrace. let inner = if s.starts_with("_ZN") { &s[3..] } else if s.starts_with("ZN") { // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" // form too. &s[2..] } else if s.starts_with("__ZN") { // On OSX, symbols are prefixed with an extra _ &s[4..] } else { return Err(()); }; // only work with ascii text if inner.bytes().any(|c| c & 0x80!= 0) { return Err(()); } let mut elements = 0; let mut chars = inner.chars(); let mut c = chars.next().ok_or(())?; while c!= 'E' { // Decode an identifier element's length. if!c.is_digit(10) { return Err(()); } let mut len = 0usize; while let Some(d) = c.to_digit(10) { len = len .checked_mul(10) .and_then(|len| len.checked_add(d as usize)) .ok_or(())?; c = chars.next().ok_or(())?; } // `c` already contains the first character of this identifier, skip it and // all the other characters of this identifier, to reach the next element. for _ in 0..len { c = chars.next().ok_or(())?; } elements += 1; } Ok((Demangle { inner, elements }, chars.as_str())) } // Rust hashes are hex digits with an `h` prepended. fn is_rust_hash(s: &str) -> bool { s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16)) } impl<'a> fmt::Display for Demangle<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Alright, let's do this. let mut inner = self.inner; for element in 0..self.elements { let mut rest = inner; while rest.chars().next().unwrap().is_digit(10) { rest = &rest[1..]; } let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap(); inner = &rest[i..]; rest = &rest[..i]; // Skip printing the hash if alternate formatting // was requested. if f.alternate() && element + 1 == self.elements && is_rust_hash(&rest) { break; } if element!= 0 { f.write_str("::")?; } if rest.starts_with("_$") { rest = &rest[1..]; } loop { if rest.starts_with('.') { if let Some('.') = rest[1..].chars().next() { f.write_str("::")?; rest = &rest[2..]; } else { f.write_str(".")?; rest = &rest[1..]; } } else if rest.starts_with('$') { let (escape, after_escape) = if let Some(end) = rest[1..].find('$') { (&rest[1..=end], &rest[end + 2..]) } else { break; }; // see src/librustc_codegen_utils/symbol_names/legacy.rs for these mappings let unescaped = match escape { "SP" => "@", "BP" => "*", "RF" => "&", "LT" => "<", "GT" => ">", "LP" => "(", "RP" => ")", "C" => ",", _ => { if escape.starts_with('u') { let digits = &escape[1..]; let all_lower_hex = digits.chars().all(|c| match c { '0'..='9' | 'a'..='f' => true, _ => false, }); let c = u32::from_str_radix(digits, 16) .ok() .and_then(char::from_u32); if let (true, Some(c)) = (all_lower_hex, c) { // FIXME(eddyb) do we need to filter out control codepoints? if!c.is_control() { c.fmt(f)?; rest = after_escape; continue; } } } break; } }; f.write_str(unescaped)?; rest = after_escape; } else if let Some(i) = rest.find(|c| c == '$' || c == '.') { f.write_str(&rest[..i])?; rest = &rest[i..]; } else { break; } } f.write_str(rest)?; } Ok(()) } } #[cfg(test)] mod tests { use std::prelude::v1::*; macro_rules! t { ($a:expr, $b:expr) => { assert!(ok($a, $b)) }; } macro_rules! t_err { ($a:expr) => { assert!(ok_err($a)) }; } macro_rules! t_nohash { ($a:expr, $b:expr) => {{ assert_eq!(format!("{:#}", ::demangle($a)), $b); }}; } fn ok(sym: &str, expected: &str) -> bool { match ::try_demangle(sym) { Ok(s) => { if s.to_string() == expected { true } else { println!("\n{}\n!=\n{}\n", s, expected); false } } Err(_) => { println!("error demangling"); false } } } fn ok_err(sym: &str) -> bool { match ::try_demangle(sym) { Ok(_) => { println!("succeeded in demangling"); false } Err(_) => ::demangle(sym).to_string() == sym, } } #[test] fn demangle() { t_err!("test"); t!("_ZN4testE", "test"); t_err!("_ZN4test"); t!("_ZN4test1a2bcE", "test::a::bc"); } #[test] fn demangle_dollars() { t!("_ZN4$RP$E", ")"); t!("_ZN8$RF$testE", "&test"); t!("_ZN8$BP$test4foobE", "*test::foob"); t!("_ZN9$u20$test4foobE", " test::foob"); t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); } #[test] fn demangle_many_dollars() { t!("_ZN13test$u20$test4foobE", "test test::foob"); t!("_ZN12test$BP$test4foobE", "test*test::foob"); } #[test] fn demangle_osx() { t!( "__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011" ); t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170"); } #[test] fn demangle_windows() { t!("ZN4testE", "test"); t!("ZN13test$u20$test4foobE", "test test::foob"); t!("ZN12test$RF$test4foobE", "test&test::foob"); } #[test] fn demangle_elements_beginning_with_underscore() { t!("_ZN13_$LT$test$GT$E", "<test>"); t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}"); t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR"); } #[test] fn demangle_trait_impls() { t!( "_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", "<Test +'static as foo::Bar<Test>>::bar" ); } #[test] fn demangle_without_hash() { let s = "_ZN3foo17h05af221e174051e9E"; t!(s, "foo::h05af221e174051e9"); t_nohash!(s, "foo"); } #[test] fn demangle_without_hash_edgecases() { // One element, no hash. t_nohash!("_ZN3fooE", "foo"); // Two elements, no hash. t_nohash!("_ZN3foo3barE", "foo::bar"); // Longer-than-normal hash. t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo"); // Shorter-than-normal hash. t_nohash!("_ZN3foo5h05afE", "foo"); // Valid hash, but not at the end. t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo"); // Not a valid hash, missing the 'h'. t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9"); // Not a valid hash, has a non-hex-digit. t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9"); } #[test] fn demangle_thinlto() { // One element, no hash. t!("_ZN3fooE.llvm.9D1C9369", "foo"); t!("_ZN3fooE.llvm.9D1C9369@@16", "foo"); t_nohash!( "_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo" ); } #[test] fn demangle_llvm_ir_branch_labels() { t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i"); t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut.exit.i.i"); } #[test] fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() { t_err!("_ZN3fooE.llvm moocow"); } #[test] fn dont_panic() { ::demangle("_ZN2222222222222222222222EE").to_string(); ::demangle("_ZN5*70527e27.ll34csaғE").to_string(); ::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); ::demangle( "\ _ZN5~saäb4e\n\ 2734cOsbE\n\ 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ ", ) .to_string(); } #[test] fn invalid_no_chop() { t_err!("_ZNfooE"); } #[test] fn handle_assoc_types() { t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", "<alloc::boxed::Box<alloc::boxed::FnBox<A, Output=R> + 'a> as core::ops::function::FnOnce<A>>::call_once::h69e8f44b3723e1ca"); } #[test] fn handle_bang() { t!( "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E", "<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8" ); } #[test] fn demangle_utf8_idents() { t_nohash!( "_ZN11utf8_idents157_$u10e1$$u10d0$$u10ed$$u10db$$u10d4$$u10da$$u10d0$$u10d3$_$u10d2$$u10d4$$u10db$$u10e0$$u10d8$$u10d4$$u10da$$u10d8$_$u10e1$$u10d0$$u10d3$$u10d8$$u10da$$u10d8$17h21634fd5714000aaE", "utf8_idents::საჭმელად_გემრიელი_სადილი" ); } #[test] fn demangle_issue_60925() { t_nohash!(
e_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h059a991a004536adE", "issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo" ); } }
"_ZN11issu
identifier_name
legacy.rs
use core::char; use core::fmt; /// Representation of a demangled symbol name. pub struct Demangle<'a> { inner: &'a str, /// The number of ::-separated elements in the original name. elements: usize, } /// De-mangles a Rust symbol into a more readable version /// /// All Rust symbols by default are mangled as they contain characters that /// cannot be represented in all object files. The mangling mechanism is similar /// to C++'s, but Rust has a few specifics to handle items like lifetimes in /// symbols. /// /// This function will take a **mangled** symbol and return a value. When printed, /// the de-mangled version will be written. If the symbol does not look like /// a mangled symbol, the original value will be written instead. /// /// # Examples /// /// ``` /// use rustc_demangle::demangle; /// /// assert_eq!(demangle("_ZN4testE").to_string(), "test"); /// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); /// assert_eq!(demangle("foo").to_string(), "foo"); /// ``` // All Rust symbols are in theory lists of "::"-separated identifiers. Some // assemblers, however, can't handle these characters in symbol names. To get // around this, we use C++-style mangling. The mangling method is: // // 1. Prefix the symbol with "_ZN" // 2. For each element of the path, emit the length plus the element // 3. End the path with "E" // // For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar". // // We're the ones printing our backtraces, so we can't rely on anything else to // demangle our symbols. It's *much* nicer to look at demangled symbols, so // this function is implemented to give us nice pretty output. // // Note that this demangler isn't quite as fancy as it could be. We have lots // of other information in our symbols like hashes, version, type information, // etc. Additionally, this doesn't handle glue symbols at all. pub fn demangle(s: &str) -> Result<(Demangle, &str), ()> { // First validate the symbol. If it doesn't look like anything we're // expecting, we just print it literally. Note that we must handle non-Rust // symbols because we could have any function in the backtrace. let inner = if s.starts_with("_ZN") { &s[3..] } else if s.starts_with("ZN") { // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" // form too. &s[2..] } else if s.starts_with("__ZN") { // On OSX, symbols are prefixed with an extra _ &s[4..] } else { return Err(()); }; // only work with ascii text if inner.bytes().any(|c| c & 0x80!= 0) { return Err(()); } let mut elements = 0; let mut chars = inner.chars(); let mut c = chars.next().ok_or(())?; while c!= 'E' { // Decode an identifier element's length. if!c.is_digit(10) { return Err(()); } let mut len = 0usize; while let Some(d) = c.to_digit(10) { len = len .checked_mul(10) .and_then(|len| len.checked_add(d as usize)) .ok_or(())?; c = chars.next().ok_or(())?; } // `c` already contains the first character of this identifier, skip it and // all the other characters of this identifier, to reach the next element. for _ in 0..len { c = chars.next().ok_or(())?; } elements += 1; } Ok((Demangle { inner, elements }, chars.as_str())) } // Rust hashes are hex digits with an `h` prepended. fn is_rust_hash(s: &str) -> bool { s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16)) } impl<'a> fmt::Display for Demangle<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Alright, let's do this. let mut inner = self.inner; for element in 0..self.elements { let mut rest = inner; while rest.chars().next().unwrap().is_digit(10) { rest = &rest[1..]; } let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap(); inner = &rest[i..]; rest = &rest[..i]; // Skip printing the hash if alternate formatting // was requested. if f.alternate() && element + 1 == self.elements && is_rust_hash(&rest) { break; } if element!= 0 { f.write_str("::")?; } if rest.starts_with("_$") { rest = &rest[1..]; } loop { if rest.starts_with('.') { if let Some('.') = rest[1..].chars().next() { f.write_str("::")?; rest = &rest[2..]; } else { f.write_str(".")?; rest = &rest[1..]; } } else if rest.starts_with('$') { let (escape, after_escape) = if let Some(end) = rest[1..].find('$') { (&rest[1..=end], &rest[end + 2..]) } else { break; }; // see src/librustc_codegen_utils/symbol_names/legacy.rs for these mappings let unescaped = match escape { "SP" => "@", "BP" => "*", "RF" => "&", "LT" => "<", "GT" => ">", "LP" => "(", "RP" => ")", "C" => ",", _ => { if escape.starts_with('u') { let digits = &escape[1..]; let all_lower_hex = digits.chars().all(|c| match c { '0'..='9' | 'a'..='f' => true, _ => false, }); let c = u32::from_str_radix(digits, 16) .ok() .and_then(char::from_u32); if let (true, Some(c)) = (all_lower_hex, c) { // FIXME(eddyb) do we need to filter out control codepoints? if!c.is_control() { c.fmt(f)?; rest = after_escape; continue; } } } break; } }; f.write_str(unescaped)?; rest = after_escape; } else if let Some(i) = rest.find(|c| c == '$' || c == '.') { f.write_str(&rest[..i])?; rest = &rest[i..]; } else { break; } } f.write_str(rest)?; } Ok(()) } } #[cfg(test)] mod tests { use std::prelude::v1::*; macro_rules! t { ($a:expr, $b:expr) => { assert!(ok($a, $b)) }; } macro_rules! t_err { ($a:expr) => { assert!(ok_err($a)) }; } macro_rules! t_nohash { ($a:expr, $b:expr) => {{ assert_eq!(format!("{:#}", ::demangle($a)), $b); }}; } fn ok(sym: &str, expected: &str) -> bool { match ::try_demangle(sym) { Ok(s) => { if s.to_string() == expected { true } else { println!("\n{}\n!=\n{}\n", s, expected); false } } Err(_) => { println!("error demangling"); false } } } fn ok_err(sym: &str) -> bool { match ::try_demangle(sym) { Ok(_) => { println!("succeeded in demangling"); false } Err(_) => ::demangle(sym).to_string() == sym, } } #[test] fn demangle() { t_err!("test"); t!("_ZN4testE", "test"); t_err!("_ZN4test"); t!("_ZN4test1a2bcE", "test::a::bc"); } #[test] fn demangle_dollars() { t!("_ZN4$RP$E", ")"); t!("_ZN8$RF$testE", "&test"); t!("_ZN8$BP$test4foobE", "*test::foob"); t!("_ZN9$u20$test4foobE", " test::foob"); t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); } #[test] fn demangle_many_dollars() { t!("_ZN13test$u20$test4foobE", "test test::foob"); t!("_ZN12test$BP$test4foobE", "test*test::foob"); } #[test] fn demangle_osx() { t!( "__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011" ); t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170"); } #[test] fn demangle_windows() { t!("ZN4testE", "test"); t!("ZN13test$u20$test4foobE", "test test::foob"); t!("ZN12test$RF$test4foobE", "test&test::foob"); } #[test] fn demangle_elements_beginning_with_underscore() { t!("_ZN13_$LT$test$GT$E", "<test>"); t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}"); t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR"); } #[test] fn demangle_trait_impls() { t!( "_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", "<Test +'static as foo::Bar<Test>>::bar" ); } #[test] fn demangle_without_hash() { let s = "_ZN3foo17h05af221e174051e9E"; t!(s, "foo::h05af221e174051e9"); t_nohash!(s, "foo"); } #[test] fn demangle_without_hash_edgecases() { // One element, no hash. t_nohash!("_ZN3fooE", "foo"); // Two elements, no hash. t_nohash!("_ZN3foo3barE", "foo::bar"); // Longer-than-normal hash. t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo"); // Shorter-than-normal hash. t_nohash!("_ZN3foo5h05afE", "foo"); // Valid hash, but not at the end. t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo"); // Not a valid hash, missing the 'h'. t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9"); // Not a valid hash, has a non-hex-digit. t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9"); } #[test] fn demangle_thinlto() { // One element, no hash. t!("_ZN3fooE.llvm.9D1C9369", "foo"); t!("_ZN3fooE.llvm.9D1C9369@@16", "foo"); t_nohash!( "_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo" ); } #[test] fn demangle_llvm_ir_branch_labels() { t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i"); t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice::<impl core::ops::index::IndexMut<I> for [T]>::index_mut.exit.i.i"); } #[test] fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() { t_err!("_ZN3fooE.llvm moocow"); } #[test] fn dont_panic() { ::demangle("_ZN2222222222222222222222EE").to_string(); ::demangle("_ZN5*70527e27.ll34csaғE").to_string(); ::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); ::demangle( "\ _ZN5~saäb4e\n\ 2734cOsbE\n\ 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ ", ) .to_string(); } #[test] fn invalid_no_chop() { t_err!("_ZNfooE"); } #[test] fn handle_assoc_types() { t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", "<alloc::boxed::Box<alloc::boxed::FnBox<A, Output=R> + 'a> as core::ops::function::FnOnce<A>>::call_once::h69e8f44b3723e1ca"); } #[test] fn handle_bang() {
#[test] fn demangle_utf8_idents() { t_nohash!( "_ZN11utf8_idents157_$u10e1$$u10d0$$u10ed$$u10db$$u10d4$$u10da$$u10d0$$u10d3$_$u10d2$$u10d4$$u10db$$u10e0$$u10d8$$u10d4$$u10da$$u10d8$_$u10e1$$u10d0$$u10d3$$u10d8$$u10da$$u10d8$17h21634fd5714000aaE", "utf8_idents::საჭმელად_გემრიელი_სადილი" ); } #[test] fn demangle_issue_60925() { t_nohash!( "_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h059a991a004536adE", "issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo" ); } }
t!( "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E", "<core::result::Result<!, E> as std::process::Termination>::report::hfc41d0da4a40b3e8" ); }
identifier_body
build.rs
extern crate rustc_version; extern crate semver; use std::fs::File; use std::io::Write; use std::{env, path}; use semver::Identifier; use rustc_version::{version_meta, Channel}; fn identifier_to_source(id: &Identifier) -> String { match *id { Identifier::Numeric(ref n) => format!("semver::Identifier::Numeric({})", n), Identifier::AlphaNumeric(ref n) => format!("semver::Identifier::AlphaNumeric({:?}.to_owned())", n), } } fn
(ids: &Vec<Identifier>) -> String { let mut r = "vec![".as_bytes().to_vec(); for id in ids { write!(r, "{}, ", identifier_to_source(id)).unwrap(); } write!(r, "]").unwrap(); String::from_utf8(r).unwrap() } fn main() { let mut path = path::PathBuf::from(env::var_os("OUT_DIR").unwrap()); path.push("version.rs"); let mut f = File::create(&path).unwrap(); let version = version_meta().expect("Failed to read rustc version."); write!(f, " /// Returns the `rustc` SemVer version and additional metadata /// like the git short hash and build date. pub fn version_meta() -> VersionMeta {{ VersionMeta {{ semver: Version {{ major: {major}, minor: {minor}, patch: {patch}, pre: {pre}, build: {build}, }}, host: \"{host}\".to_owned(), short_version_string: \"{short_version_string}\".to_owned(), commit_hash: {commit_hash}, commit_date: {commit_date}, build_date: {build_date}, channel: Channel::{channel}, }} }} ", major = version.semver.major, minor = version.semver.minor, patch = version.semver.patch, pre = identifiers_to_source(&version.semver.pre), build = identifiers_to_source(&version.semver.build), commit_hash = version.commit_hash.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), commit_date = version.commit_date.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), build_date = version.build_date.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), host = version.host, short_version_string = version.short_version_string, channel = match version.channel { Channel::Dev => "Dev", Channel::Nightly => "Nightly", Channel::Beta => "Beta", Channel::Stable => "Stable", } ).unwrap(); }
identifiers_to_source
identifier_name
build.rs
extern crate rustc_version; extern crate semver; use std::fs::File; use std::io::Write; use std::{env, path}; use semver::Identifier; use rustc_version::{version_meta, Channel}; fn identifier_to_source(id: &Identifier) -> String
fn identifiers_to_source(ids: &Vec<Identifier>) -> String { let mut r = "vec![".as_bytes().to_vec(); for id in ids { write!(r, "{}, ", identifier_to_source(id)).unwrap(); } write!(r, "]").unwrap(); String::from_utf8(r).unwrap() } fn main() { let mut path = path::PathBuf::from(env::var_os("OUT_DIR").unwrap()); path.push("version.rs"); let mut f = File::create(&path).unwrap(); let version = version_meta().expect("Failed to read rustc version."); write!(f, " /// Returns the `rustc` SemVer version and additional metadata /// like the git short hash and build date. pub fn version_meta() -> VersionMeta {{ VersionMeta {{ semver: Version {{ major: {major}, minor: {minor}, patch: {patch}, pre: {pre}, build: {build}, }}, host: \"{host}\".to_owned(), short_version_string: \"{short_version_string}\".to_owned(), commit_hash: {commit_hash}, commit_date: {commit_date}, build_date: {build_date}, channel: Channel::{channel}, }} }} ", major = version.semver.major, minor = version.semver.minor, patch = version.semver.patch, pre = identifiers_to_source(&version.semver.pre), build = identifiers_to_source(&version.semver.build), commit_hash = version.commit_hash.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), commit_date = version.commit_date.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), build_date = version.build_date.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), host = version.host, short_version_string = version.short_version_string, channel = match version.channel { Channel::Dev => "Dev", Channel::Nightly => "Nightly", Channel::Beta => "Beta", Channel::Stable => "Stable", } ).unwrap(); }
{ match *id { Identifier::Numeric(ref n) => format!("semver::Identifier::Numeric({})", n), Identifier::AlphaNumeric(ref n) => format!("semver::Identifier::AlphaNumeric({:?}.to_owned())", n), } }
identifier_body
build.rs
extern crate rustc_version; extern crate semver; use std::fs::File; use std::io::Write; use std::{env, path}; use semver::Identifier; use rustc_version::{version_meta, Channel}; fn identifier_to_source(id: &Identifier) -> String { match *id { Identifier::Numeric(ref n) => format!("semver::Identifier::Numeric({})", n), Identifier::AlphaNumeric(ref n) => format!("semver::Identifier::AlphaNumeric({:?}.to_owned())", n), } } fn identifiers_to_source(ids: &Vec<Identifier>) -> String { let mut r = "vec![".as_bytes().to_vec(); for id in ids { write!(r, "{}, ", identifier_to_source(id)).unwrap(); } write!(r, "]").unwrap(); String::from_utf8(r).unwrap() } fn main() { let mut path = path::PathBuf::from(env::var_os("OUT_DIR").unwrap()); path.push("version.rs"); let mut f = File::create(&path).unwrap(); let version = version_meta().expect("Failed to read rustc version."); write!(f, " /// Returns the `rustc` SemVer version and additional metadata /// like the git short hash and build date. pub fn version_meta() -> VersionMeta {{ VersionMeta {{ semver: Version {{ major: {major}, minor: {minor}, patch: {patch}, pre: {pre}, build: {build}, }}, host: \"{host}\".to_owned(), short_version_string: \"{short_version_string}\".to_owned(), commit_hash: {commit_hash}, commit_date: {commit_date}, build_date: {build_date}, channel: Channel::{channel}, }} }} ", major = version.semver.major, minor = version.semver.minor, patch = version.semver.patch, pre = identifiers_to_source(&version.semver.pre), build = identifiers_to_source(&version.semver.build), commit_hash = version.commit_hash.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), commit_date = version.commit_date.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), build_date = version.build_date.map(|h| format!("Some(\"{}\".to_owned())", h)).unwrap_or("None".to_owned()), host = version.host, short_version_string = version.short_version_string, channel = match version.channel { Channel::Dev => "Dev", Channel::Nightly => "Nightly", Channel::Beta => "Beta", Channel::Stable => "Stable", } ).unwrap();
}
random_line_split
vm_config.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::on_chain_config::OnChainConfig; use anyhow::{format_err, Result}; use move_core_types::gas_schedule::{CostTable, GasConstants}; use serde::{Deserialize, Serialize}; /// Defines all the on chain configuration data needed by VM. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub struct VMConfig { pub gas_schedule: CostTable, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct CostTableInner { pub instruction_table: Vec<u8>, pub native_table: Vec<u8>, pub gas_constants: GasConstants, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct VMConfigInner { pub gas_schedule: CostTableInner, } impl CostTableInner { pub fn as_cost_table(&self) -> Result<CostTable> { let instruction_table = bcs::from_bytes(&self.instruction_table)?; let native_table = bcs::from_bytes(&self.native_table)?; Ok(CostTable { instruction_table, native_table, gas_constants: self.gas_constants.clone(), }) } } impl OnChainConfig for VMConfig { const IDENTIFIER: &'static str = "DiemVMConfig"; fn
(bytes: &[u8]) -> Result<Self> { let raw_vm_config = bcs::from_bytes::<VMConfigInner>(&bytes).map_err(|e| { format_err!( "Failed first round of deserialization for VMConfigInner: {}", e ) })?; let gas_schedule = raw_vm_config.gas_schedule.as_cost_table()?; Ok(VMConfig { gas_schedule }) } }
deserialize_into_config
identifier_name
vm_config.rs
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0 use crate::on_chain_config::OnChainConfig; use anyhow::{format_err, Result}; use move_core_types::gas_schedule::{CostTable, GasConstants}; use serde::{Deserialize, Serialize}; /// Defines all the on chain configuration data needed by VM. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub struct VMConfig { pub gas_schedule: CostTable, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct CostTableInner { pub instruction_table: Vec<u8>, pub native_table: Vec<u8>, pub gas_constants: GasConstants, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] struct VMConfigInner { pub gas_schedule: CostTableInner, } impl CostTableInner { pub fn as_cost_table(&self) -> Result<CostTable> { let instruction_table = bcs::from_bytes(&self.instruction_table)?; let native_table = bcs::from_bytes(&self.native_table)?; Ok(CostTable { instruction_table, native_table, gas_constants: self.gas_constants.clone(), }) } } impl OnChainConfig for VMConfig { const IDENTIFIER: &'static str = "DiemVMConfig"; fn deserialize_into_config(bytes: &[u8]) -> Result<Self> { let raw_vm_config = bcs::from_bytes::<VMConfigInner>(&bytes).map_err(|e| { format_err!( "Failed first round of deserialization for VMConfigInner: {}", e ) })?; let gas_schedule = raw_vm_config.gas_schedule.as_cost_table()?; Ok(VMConfig { gas_schedule }) } }
random_line_split
ps.rs
extern crate arg_parser; extern crate extra; use std::env; use std::fs::File; use std::io::{stdout, stderr, copy, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{ps} */ r#" NAME ps - report a snapshot of the current processes SYNOPSIS ps [ -h | --help] DESCRIPTION Displays information about processes and threads that are currently active OPTIONS -h --help display this help and exit "#; /* @MANEND */ fn main()
{ let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } let mut file = File::open("sys:/context").try(&mut stderr); copy(&mut file, &mut stdout).try(&mut stderr); }
identifier_body
ps.rs
extern crate arg_parser; extern crate extra; use std::env; use std::fs::File; use std::io::{stdout, stderr, copy, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{ps} */ r#" NAME ps - report a snapshot of the current processes SYNOPSIS ps [ -h | --help] DESCRIPTION Displays information about processes and threads that are currently active OPTIONS -h --help display this help and exit "#; /* @MANEND */ fn
() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } let mut file = File::open("sys:/context").try(&mut stderr); copy(&mut file, &mut stdout).try(&mut stderr); }
main
identifier_name
ps.rs
extern crate arg_parser; extern crate extra; use std::env; use std::fs::File; use std::io::{stdout, stderr, copy, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt;
SYNOPSIS ps [ -h | --help] DESCRIPTION Displays information about processes and threads that are currently active OPTIONS -h --help display this help and exit "#; /* @MANEND */ fn main() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } let mut file = File::open("sys:/context").try(&mut stderr); copy(&mut file, &mut stdout).try(&mut stderr); }
const MAN_PAGE: &'static str = /* @MANSTART{ps} */ r#" NAME ps - report a snapshot of the current processes
random_line_split
ps.rs
extern crate arg_parser; extern crate extra; use std::env; use std::fs::File; use std::io::{stdout, stderr, copy, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; const MAN_PAGE: &'static str = /* @MANSTART{ps} */ r#" NAME ps - report a snapshot of the current processes SYNOPSIS ps [ -h | --help] DESCRIPTION Displays information about processes and threads that are currently active OPTIONS -h --help display this help and exit "#; /* @MANEND */ fn main() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]); parser.parse(env::args()); if parser.found("help")
let mut file = File::open("sys:/context").try(&mut stderr); copy(&mut file, &mut stdout).try(&mut stderr); }
{ stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); }
conditional_block
text.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/. */ //! Text layout. #![deny(unsafe_block)] use fragment::{Fragment, ScannedTextFragmentInfo, UnscannedTextFragment}; use inline::InlineFragments; use gfx::font::{FontMetrics,RunMetrics}; use gfx::font_context::FontContext; use gfx::text::glyph::CharIndex; use gfx::text::text_run::TextRun; use gfx::text::util::{mod, CompressWhitespaceNewline, CompressNone}; use servo_util::dlist; use servo_util::geometry::Au; use servo_util::logical_geometry::{LogicalSize, WritingMode}; use servo_util::range::Range; use servo_util::smallvec::{SmallVec, SmallVec1}; use std::collections::{DList, Deque}; use std::mem; use style::ComputedValues; use style::computed_values::{line_height, text_orientation, white_space}; use style::style_structs::Font as FontStyle; use sync::Arc; /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextFragment`s. pub struct TextRunScanner { pub clump: DList<Fragment>, } impl TextRunScanner { pub fn new() -> TextRunScanner { TextRunScanner { clump: DList::new(), } } pub fn scan_for_runs(&mut self, font_context: &mut FontContext, mut fragments: DList<Fragment>) -> InlineFragments { debug!("TextRunScanner: scanning {:u} fragments for text runs...", fragments.len()); // FIXME(pcwalton): We want to be sure not to allocate multiple times, since this is a // performance-critical spot, but this may overestimate and allocate too much memory. let mut new_fragments = Vec::with_capacity(fragments.len()); let mut last_whitespace = true; while!fragments.is_empty() { // Create a clump. self.clump.append(dlist::split(&mut fragments)); while!fragments.is_empty() && self.clump .back() .unwrap() .can_merge_with_fragment(fragments.front() .unwrap()) { self.clump.append(dlist::split(&mut fragments)); } // Flush that clump to the list of fragments we're building up. last_whitespace = self.flush_clump_to_list(font_context, &mut new_fragments, last_whitespace); } debug!("TextRunScanner: complete."); InlineFragments { fragments: new_fragments, } } /// A "clump" is a range of inline flow leaves that can be merged together into a single /// fragment. Adjacent text with the same style can be merged, and nothing else can. /// /// The flow keeps track of the fragments contained by all non-leaf DOM nodes. This is necessary /// for correct painting order. Since we compress several leaf fragments here, the mapping must /// be adjusted. fn flush_clump_to_list(&mut self, font_context: &mut FontContext, out_fragments: &mut Vec<Fragment>, mut last_whitespace: bool) -> bool { debug!("TextRunScanner: flushing {} fragments in range", self.clump.len()); debug_assert!(!self.clump.is_empty()); match self.clump.front().unwrap().specific { UnscannedTextFragment(_) => {} _ => { debug_assert!(self.clump.len() == 1, "WAT: can't coalesce non-text nodes in flush_clump_to_list()!"); out_fragments.push(self.clump.pop_front().unwrap()); return last_whitespace } } // TODO(#177): Text run creation must account for the renderability of text by font group // fonts. This is probably achieved by creating the font group above and then letting // `FontGroup` decide which `Font` to stick into the text run. // // Concatenate all of the transformed strings together, saving the new character indices. let mut new_ranges: SmallVec1<Range<CharIndex>> = SmallVec1::new(); let mut new_line_positions: SmallVec1<NewLinePositions> = SmallVec1::new(); let mut char_total = CharIndex(0); let run = { let fontgroup; let compression; { let in_fragment = self.clump.front().unwrap(); let font_style = in_fragment.style().get_font_arc(); fontgroup = font_context.get_layout_font_group_for_style(font_style); compression = match in_fragment.white_space() { white_space::normal | white_space::nowrap => CompressWhitespaceNewline, white_space::pre => CompressNone, } } // First, transform/compress text of all the nodes. let mut run_text = String::new(); for in_fragment in self.clump.iter() { let in_fragment = match in_fragment.specific { UnscannedTextFragment(ref text_fragment_info) => &text_fragment_info.text, _ => fail!("Expected an unscanned text fragment!"), }; let mut new_line_pos = Vec::new(); let old_length = CharIndex(run_text.as_slice().char_len() as int); last_whitespace = util::transform_text(in_fragment.as_slice(), compression, last_whitespace, &mut run_text, &mut new_line_pos); new_line_positions.push(NewLinePositions(new_line_pos)); let added_chars = CharIndex(run_text.as_slice().char_len() as int) - old_length; new_ranges.push(Range::new(char_total, added_chars)); char_total = char_total + added_chars; } // Now create the run. // // TextRuns contain a cycle which is usually resolved by the teardown sequence. // If no clump takes ownership, however, it will leak. if run_text.len() == 0 { self.clump = DList::new(); return last_whitespace } Arc::new(box TextRun::new(&mut *fontgroup.fonts.get(0).borrow_mut(), run_text)) }; // Make new fragments with the run and adjusted text indices. debug!("TextRunScanner: pushing {} fragment(s)", self.clump.len()); for (logical_offset, old_fragment) in mem::replace(&mut self.clump, DList::new()).into_iter().enumerate() { let range = *new_ranges.get(logical_offset); if range.is_empty() { debug!("Elided an `UnscannedTextFragment` because it was zero-length after \ compression; {}", old_fragment); continue } let text_size = old_fragment.border_box.size; let &NewLinePositions(ref mut new_line_positions) = new_line_positions.get_mut(logical_offset); let new_text_fragment_info = box ScannedTextFragmentInfo::new(run.clone(), range, mem::replace(new_line_positions, Vec::new()), text_size); let new_metrics = new_text_fragment_info.run.metrics_for_range(&range); let bounding_box_size = bounding_box_for_run_metrics(&new_metrics, old_fragment.style.writing_mode); let new_fragment = old_fragment.transform(bounding_box_size, new_text_fragment_info); out_fragments.push(new_fragment) } last_whitespace } } struct NewLinePositions(Vec<CharIndex>); #[inline] fn bounding_box_for_run_metrics(metrics: &RunMetrics, writing_mode: WritingMode) -> LogicalSize<Au>
} /// Returns the metrics of the font represented by the given `FontStyle`, respectively. /// /// `#[inline]` because often the caller only needs a few fields from the font metrics. #[inline] pub fn font_metrics_for_style(font_context: &mut FontContext, font_style: Arc<FontStyle>) -> FontMetrics { let fontgroup = font_context.get_layout_font_group_for_style(font_style); fontgroup.fonts.get(0).borrow().metrics.clone() } /// Returns the line block-size needed by the given computed style and font size. pub fn line_height_from_style(style: &ComputedValues, metrics: &FontMetrics) -> Au { let font_size = style.get_font().font_size; match style.get_inheritedbox().line_height { line_height::Normal => metrics.line_gap, line_height::Number(l) => font_size.scale_by(l), line_height::Length(l) => l } }
{ // This does nothing, but it will fail to build // when more values are added to the `text-orientation` CSS property. // This will be a reminder to update the code below. let dummy: Option<text_orientation::T> = None; match dummy { Some(text_orientation::sideways_right) | Some(text_orientation::sideways_left) | Some(text_orientation::sideways) | None => {} } // In vertical sideways or horizontal upgright text, // the "width" of text metrics is always inline // This will need to be updated when other text orientations are supported. LogicalSize::new( writing_mode, metrics.bounding_box.size.width, metrics.bounding_box.size.height)
identifier_body
text.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/. */ //! Text layout. #![deny(unsafe_block)] use fragment::{Fragment, ScannedTextFragmentInfo, UnscannedTextFragment}; use inline::InlineFragments; use gfx::font::{FontMetrics,RunMetrics}; use gfx::font_context::FontContext; use gfx::text::glyph::CharIndex; use gfx::text::text_run::TextRun; use gfx::text::util::{mod, CompressWhitespaceNewline, CompressNone}; use servo_util::dlist; use servo_util::geometry::Au; use servo_util::logical_geometry::{LogicalSize, WritingMode}; use servo_util::range::Range; use servo_util::smallvec::{SmallVec, SmallVec1}; use std::collections::{DList, Deque}; use std::mem; use style::ComputedValues; use style::computed_values::{line_height, text_orientation, white_space}; use style::style_structs::Font as FontStyle; use sync::Arc; /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextFragment`s. pub struct TextRunScanner { pub clump: DList<Fragment>, } impl TextRunScanner { pub fn new() -> TextRunScanner { TextRunScanner { clump: DList::new(), } } pub fn scan_for_runs(&mut self, font_context: &mut FontContext, mut fragments: DList<Fragment>) -> InlineFragments { debug!("TextRunScanner: scanning {:u} fragments for text runs...", fragments.len()); // FIXME(pcwalton): We want to be sure not to allocate multiple times, since this is a // performance-critical spot, but this may overestimate and allocate too much memory. let mut new_fragments = Vec::with_capacity(fragments.len()); let mut last_whitespace = true; while!fragments.is_empty() { // Create a clump. self.clump.append(dlist::split(&mut fragments)); while!fragments.is_empty() && self.clump .back() .unwrap() .can_merge_with_fragment(fragments.front() .unwrap()) { self.clump.append(dlist::split(&mut fragments)); } // Flush that clump to the list of fragments we're building up. last_whitespace = self.flush_clump_to_list(font_context, &mut new_fragments, last_whitespace); } debug!("TextRunScanner: complete."); InlineFragments { fragments: new_fragments, } } /// A "clump" is a range of inline flow leaves that can be merged together into a single /// fragment. Adjacent text with the same style can be merged, and nothing else can. /// /// The flow keeps track of the fragments contained by all non-leaf DOM nodes. This is necessary /// for correct painting order. Since we compress several leaf fragments here, the mapping must /// be adjusted. fn flush_clump_to_list(&mut self, font_context: &mut FontContext, out_fragments: &mut Vec<Fragment>, mut last_whitespace: bool) -> bool { debug!("TextRunScanner: flushing {} fragments in range", self.clump.len()); debug_assert!(!self.clump.is_empty()); match self.clump.front().unwrap().specific { UnscannedTextFragment(_) => {} _ => { debug_assert!(self.clump.len() == 1, "WAT: can't coalesce non-text nodes in flush_clump_to_list()!"); out_fragments.push(self.clump.pop_front().unwrap()); return last_whitespace } } // TODO(#177): Text run creation must account for the renderability of text by font group // fonts. This is probably achieved by creating the font group above and then letting // `FontGroup` decide which `Font` to stick into the text run. // // Concatenate all of the transformed strings together, saving the new character indices. let mut new_ranges: SmallVec1<Range<CharIndex>> = SmallVec1::new(); let mut new_line_positions: SmallVec1<NewLinePositions> = SmallVec1::new(); let mut char_total = CharIndex(0); let run = { let fontgroup; let compression; { let in_fragment = self.clump.front().unwrap(); let font_style = in_fragment.style().get_font_arc(); fontgroup = font_context.get_layout_font_group_for_style(font_style); compression = match in_fragment.white_space() {
// First, transform/compress text of all the nodes. let mut run_text = String::new(); for in_fragment in self.clump.iter() { let in_fragment = match in_fragment.specific { UnscannedTextFragment(ref text_fragment_info) => &text_fragment_info.text, _ => fail!("Expected an unscanned text fragment!"), }; let mut new_line_pos = Vec::new(); let old_length = CharIndex(run_text.as_slice().char_len() as int); last_whitespace = util::transform_text(in_fragment.as_slice(), compression, last_whitespace, &mut run_text, &mut new_line_pos); new_line_positions.push(NewLinePositions(new_line_pos)); let added_chars = CharIndex(run_text.as_slice().char_len() as int) - old_length; new_ranges.push(Range::new(char_total, added_chars)); char_total = char_total + added_chars; } // Now create the run. // // TextRuns contain a cycle which is usually resolved by the teardown sequence. // If no clump takes ownership, however, it will leak. if run_text.len() == 0 { self.clump = DList::new(); return last_whitespace } Arc::new(box TextRun::new(&mut *fontgroup.fonts.get(0).borrow_mut(), run_text)) }; // Make new fragments with the run and adjusted text indices. debug!("TextRunScanner: pushing {} fragment(s)", self.clump.len()); for (logical_offset, old_fragment) in mem::replace(&mut self.clump, DList::new()).into_iter().enumerate() { let range = *new_ranges.get(logical_offset); if range.is_empty() { debug!("Elided an `UnscannedTextFragment` because it was zero-length after \ compression; {}", old_fragment); continue } let text_size = old_fragment.border_box.size; let &NewLinePositions(ref mut new_line_positions) = new_line_positions.get_mut(logical_offset); let new_text_fragment_info = box ScannedTextFragmentInfo::new(run.clone(), range, mem::replace(new_line_positions, Vec::new()), text_size); let new_metrics = new_text_fragment_info.run.metrics_for_range(&range); let bounding_box_size = bounding_box_for_run_metrics(&new_metrics, old_fragment.style.writing_mode); let new_fragment = old_fragment.transform(bounding_box_size, new_text_fragment_info); out_fragments.push(new_fragment) } last_whitespace } } struct NewLinePositions(Vec<CharIndex>); #[inline] fn bounding_box_for_run_metrics(metrics: &RunMetrics, writing_mode: WritingMode) -> LogicalSize<Au> { // This does nothing, but it will fail to build // when more values are added to the `text-orientation` CSS property. // This will be a reminder to update the code below. let dummy: Option<text_orientation::T> = None; match dummy { Some(text_orientation::sideways_right) | Some(text_orientation::sideways_left) | Some(text_orientation::sideways) | None => {} } // In vertical sideways or horizontal upgright text, // the "width" of text metrics is always inline // This will need to be updated when other text orientations are supported. LogicalSize::new( writing_mode, metrics.bounding_box.size.width, metrics.bounding_box.size.height) } /// Returns the metrics of the font represented by the given `FontStyle`, respectively. /// /// `#[inline]` because often the caller only needs a few fields from the font metrics. #[inline] pub fn font_metrics_for_style(font_context: &mut FontContext, font_style: Arc<FontStyle>) -> FontMetrics { let fontgroup = font_context.get_layout_font_group_for_style(font_style); fontgroup.fonts.get(0).borrow().metrics.clone() } /// Returns the line block-size needed by the given computed style and font size. pub fn line_height_from_style(style: &ComputedValues, metrics: &FontMetrics) -> Au { let font_size = style.get_font().font_size; match style.get_inheritedbox().line_height { line_height::Normal => metrics.line_gap, line_height::Number(l) => font_size.scale_by(l), line_height::Length(l) => l } }
white_space::normal | white_space::nowrap => CompressWhitespaceNewline, white_space::pre => CompressNone, } }
random_line_split
text.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/. */ //! Text layout. #![deny(unsafe_block)] use fragment::{Fragment, ScannedTextFragmentInfo, UnscannedTextFragment}; use inline::InlineFragments; use gfx::font::{FontMetrics,RunMetrics}; use gfx::font_context::FontContext; use gfx::text::glyph::CharIndex; use gfx::text::text_run::TextRun; use gfx::text::util::{mod, CompressWhitespaceNewline, CompressNone}; use servo_util::dlist; use servo_util::geometry::Au; use servo_util::logical_geometry::{LogicalSize, WritingMode}; use servo_util::range::Range; use servo_util::smallvec::{SmallVec, SmallVec1}; use std::collections::{DList, Deque}; use std::mem; use style::ComputedValues; use style::computed_values::{line_height, text_orientation, white_space}; use style::style_structs::Font as FontStyle; use sync::Arc; /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextFragment`s. pub struct TextRunScanner { pub clump: DList<Fragment>, } impl TextRunScanner { pub fn new() -> TextRunScanner { TextRunScanner { clump: DList::new(), } } pub fn scan_for_runs(&mut self, font_context: &mut FontContext, mut fragments: DList<Fragment>) -> InlineFragments { debug!("TextRunScanner: scanning {:u} fragments for text runs...", fragments.len()); // FIXME(pcwalton): We want to be sure not to allocate multiple times, since this is a // performance-critical spot, but this may overestimate and allocate too much memory. let mut new_fragments = Vec::with_capacity(fragments.len()); let mut last_whitespace = true; while!fragments.is_empty() { // Create a clump. self.clump.append(dlist::split(&mut fragments)); while!fragments.is_empty() && self.clump .back() .unwrap() .can_merge_with_fragment(fragments.front() .unwrap()) { self.clump.append(dlist::split(&mut fragments)); } // Flush that clump to the list of fragments we're building up. last_whitespace = self.flush_clump_to_list(font_context, &mut new_fragments, last_whitespace); } debug!("TextRunScanner: complete."); InlineFragments { fragments: new_fragments, } } /// A "clump" is a range of inline flow leaves that can be merged together into a single /// fragment. Adjacent text with the same style can be merged, and nothing else can. /// /// The flow keeps track of the fragments contained by all non-leaf DOM nodes. This is necessary /// for correct painting order. Since we compress several leaf fragments here, the mapping must /// be adjusted. fn flush_clump_to_list(&mut self, font_context: &mut FontContext, out_fragments: &mut Vec<Fragment>, mut last_whitespace: bool) -> bool { debug!("TextRunScanner: flushing {} fragments in range", self.clump.len()); debug_assert!(!self.clump.is_empty()); match self.clump.front().unwrap().specific { UnscannedTextFragment(_) => {} _ => { debug_assert!(self.clump.len() == 1, "WAT: can't coalesce non-text nodes in flush_clump_to_list()!"); out_fragments.push(self.clump.pop_front().unwrap()); return last_whitespace } } // TODO(#177): Text run creation must account for the renderability of text by font group // fonts. This is probably achieved by creating the font group above and then letting // `FontGroup` decide which `Font` to stick into the text run. // // Concatenate all of the transformed strings together, saving the new character indices. let mut new_ranges: SmallVec1<Range<CharIndex>> = SmallVec1::new(); let mut new_line_positions: SmallVec1<NewLinePositions> = SmallVec1::new(); let mut char_total = CharIndex(0); let run = { let fontgroup; let compression; { let in_fragment = self.clump.front().unwrap(); let font_style = in_fragment.style().get_font_arc(); fontgroup = font_context.get_layout_font_group_for_style(font_style); compression = match in_fragment.white_space() { white_space::normal | white_space::nowrap => CompressWhitespaceNewline, white_space::pre => CompressNone, } } // First, transform/compress text of all the nodes. let mut run_text = String::new(); for in_fragment in self.clump.iter() { let in_fragment = match in_fragment.specific { UnscannedTextFragment(ref text_fragment_info) => &text_fragment_info.text, _ => fail!("Expected an unscanned text fragment!"), }; let mut new_line_pos = Vec::new(); let old_length = CharIndex(run_text.as_slice().char_len() as int); last_whitespace = util::transform_text(in_fragment.as_slice(), compression, last_whitespace, &mut run_text, &mut new_line_pos); new_line_positions.push(NewLinePositions(new_line_pos)); let added_chars = CharIndex(run_text.as_slice().char_len() as int) - old_length; new_ranges.push(Range::new(char_total, added_chars)); char_total = char_total + added_chars; } // Now create the run. // // TextRuns contain a cycle which is usually resolved by the teardown sequence. // If no clump takes ownership, however, it will leak. if run_text.len() == 0 { self.clump = DList::new(); return last_whitespace } Arc::new(box TextRun::new(&mut *fontgroup.fonts.get(0).borrow_mut(), run_text)) }; // Make new fragments with the run and adjusted text indices. debug!("TextRunScanner: pushing {} fragment(s)", self.clump.len()); for (logical_offset, old_fragment) in mem::replace(&mut self.clump, DList::new()).into_iter().enumerate() { let range = *new_ranges.get(logical_offset); if range.is_empty() { debug!("Elided an `UnscannedTextFragment` because it was zero-length after \ compression; {}", old_fragment); continue } let text_size = old_fragment.border_box.size; let &NewLinePositions(ref mut new_line_positions) = new_line_positions.get_mut(logical_offset); let new_text_fragment_info = box ScannedTextFragmentInfo::new(run.clone(), range, mem::replace(new_line_positions, Vec::new()), text_size); let new_metrics = new_text_fragment_info.run.metrics_for_range(&range); let bounding_box_size = bounding_box_for_run_metrics(&new_metrics, old_fragment.style.writing_mode); let new_fragment = old_fragment.transform(bounding_box_size, new_text_fragment_info); out_fragments.push(new_fragment) } last_whitespace } } struct NewLinePositions(Vec<CharIndex>); #[inline] fn
(metrics: &RunMetrics, writing_mode: WritingMode) -> LogicalSize<Au> { // This does nothing, but it will fail to build // when more values are added to the `text-orientation` CSS property. // This will be a reminder to update the code below. let dummy: Option<text_orientation::T> = None; match dummy { Some(text_orientation::sideways_right) | Some(text_orientation::sideways_left) | Some(text_orientation::sideways) | None => {} } // In vertical sideways or horizontal upgright text, // the "width" of text metrics is always inline // This will need to be updated when other text orientations are supported. LogicalSize::new( writing_mode, metrics.bounding_box.size.width, metrics.bounding_box.size.height) } /// Returns the metrics of the font represented by the given `FontStyle`, respectively. /// /// `#[inline]` because often the caller only needs a few fields from the font metrics. #[inline] pub fn font_metrics_for_style(font_context: &mut FontContext, font_style: Arc<FontStyle>) -> FontMetrics { let fontgroup = font_context.get_layout_font_group_for_style(font_style); fontgroup.fonts.get(0).borrow().metrics.clone() } /// Returns the line block-size needed by the given computed style and font size. pub fn line_height_from_style(style: &ComputedValues, metrics: &FontMetrics) -> Au { let font_size = style.get_font().font_size; match style.get_inheritedbox().line_height { line_height::Normal => metrics.line_gap, line_height::Number(l) => font_size.scale_by(l), line_height::Length(l) => l } }
bounding_box_for_run_metrics
identifier_name
interval_timer.rs
//! Timer to keep track of repeating intervals. /// This struct keeps track of passage of repeated intervals (like bars of music). pub struct IntervalTimer { every: u64, next: u64, } impl IntervalTimer { #[allow(missing_docs)] pub fn new(every: u64, next: u64) -> IntervalTimer { IntervalTimer { every: every, next: next,
#[inline] /// Returns the number of intervals that have elapsed since last `update`. pub fn update(&mut self, current: u64) -> u64 { if current < self.next { 0 } else { let r = 1 + (current - self.next) / self.every; self.next += self.every * r; r } } } #[test] fn simple() { let mut timer = IntervalTimer::new(3, 3); let mut time = 2; assert_eq!(timer.update(time), 0); time += 2; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(timer.update(time), 1); time += 6; assert_eq!(timer.update(time), 2); time += 3; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(timer.update(time), 0); }
} }
random_line_split
interval_timer.rs
//! Timer to keep track of repeating intervals. /// This struct keeps track of passage of repeated intervals (like bars of music). pub struct IntervalTimer { every: u64, next: u64, } impl IntervalTimer { #[allow(missing_docs)] pub fn
(every: u64, next: u64) -> IntervalTimer { IntervalTimer { every: every, next: next, } } #[inline] /// Returns the number of intervals that have elapsed since last `update`. pub fn update(&mut self, current: u64) -> u64 { if current < self.next { 0 } else { let r = 1 + (current - self.next) / self.every; self.next += self.every * r; r } } } #[test] fn simple() { let mut timer = IntervalTimer::new(3, 3); let mut time = 2; assert_eq!(timer.update(time), 0); time += 2; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(timer.update(time), 1); time += 6; assert_eq!(timer.update(time), 2); time += 3; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(timer.update(time), 0); }
new
identifier_name
interval_timer.rs
//! Timer to keep track of repeating intervals. /// This struct keeps track of passage of repeated intervals (like bars of music). pub struct IntervalTimer { every: u64, next: u64, } impl IntervalTimer { #[allow(missing_docs)] pub fn new(every: u64, next: u64) -> IntervalTimer { IntervalTimer { every: every, next: next, } } #[inline] /// Returns the number of intervals that have elapsed since last `update`. pub fn update(&mut self, current: u64) -> u64 { if current < self.next
else { let r = 1 + (current - self.next) / self.every; self.next += self.every * r; r } } } #[test] fn simple() { let mut timer = IntervalTimer::new(3, 3); let mut time = 2; assert_eq!(timer.update(time), 0); time += 2; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(timer.update(time), 1); time += 6; assert_eq!(timer.update(time), 2); time += 3; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(timer.update(time), 0); }
{ 0 }
conditional_block
issue-2111.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
match (a,b) { //~^ ERROR: non-exhaustive patterns: `(None, None)` not covered (Some(a), Some(b)) if a == b => { } (Some(_), None) | (None, Some(_)) => { } } } fn main() { foo(None, None); }
// <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. fn foo(a: Option<uint>, b: Option<uint>) {
random_line_split
issue-2111.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. fn foo(a: Option<uint>, b: Option<uint>) { match (a,b) { //~^ ERROR: non-exhaustive patterns: `(None, None)` not covered (Some(a), Some(b)) if a == b => { } (Some(_), None) | (None, Some(_)) => { } } } fn
() { foo(None, None); }
main
identifier_name
issue-2111.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. fn foo(a: Option<uint>, b: Option<uint>) { match (a,b) { //~^ ERROR: non-exhaustive patterns: `(None, None)` not covered (Some(a), Some(b)) if a == b => { } (Some(_), None) | (None, Some(_)) => { } } } fn main()
{ foo(None, None); }
identifier_body
custom_stream.rs
use std::io::Result as IoResult; use std::io::{Read, Write}; pub struct
<R, W> { reader: R, writer: W, } impl<R, W> CustomStream<R, W> where R: Read, W: Write, { pub fn new(reader: R, writer: W) -> CustomStream<R, W> { CustomStream { reader, writer } } } impl<R, W> Read for CustomStream<R, W> where R: Read, { fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { self.reader.read(buf) } } impl<R, W> Write for CustomStream<R, W> where W: Write, { fn write(&mut self, buf: &[u8]) -> IoResult<usize> { self.writer.write(buf) } fn flush(&mut self) -> IoResult<()> { self.writer.flush() } }
CustomStream
identifier_name
custom_stream.rs
use std::io::Result as IoResult; use std::io::{Read, Write}; pub struct CustomStream<R, W> { reader: R, writer: W, } impl<R, W> CustomStream<R, W> where R: Read, W: Write, { pub fn new(reader: R, writer: W) -> CustomStream<R, W> { CustomStream { reader, writer } } } impl<R, W> Read for CustomStream<R, W> where R: Read, { fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { self.reader.read(buf) } } impl<R, W> Write for CustomStream<R, W> where W: Write, { fn write(&mut self, buf: &[u8]) -> IoResult<usize> { self.writer.write(buf)
}
} fn flush(&mut self) -> IoResult<()> { self.writer.flush() }
random_line_split
expander.rs
// Our use cases use super::stream; pub const WAVE_FORMAT_PCM: usize = 1; #[derive(Default)] pub struct WaveFormatEx { pub format_tag: u16, pub channels: u16, pub samples_per_second: i32, pub average_bytes_per_second: i32, pub block_align: u16, pub bits_per_sample: u16, pub cb_size: u16, } pub struct SoundExpander { pub memb_20: i32, pub memb_24: i32, pub memb_28: i32, pub memb_30: i32, pub memb_34: i32, pub memb_40: i32, pub memb_48: i32, pub memb_4C: i32, pub memb_54: i32, pub memb_58: i32, pub memb_5C: i32, pub memb_64: i32, pub memb_68: i32, pub memb_70: i32, pub memb_74: i32, pub memb_80: i32, pub memb_8C: i32, pub memb_90: i32, pub file_reader: stream::FileReader, pub wave_format_ex: WaveFormatEx, pub flags0: i32, pub flags1: i32, pub flags2: i32, pub loop_point: i32, pub file_length: i32, pub read_limit: i32, pub some_var_6680EC: i32, pub some_var_6680E8: i32, pub previous: Box<SoundExpander>, pub next: Box<SoundExpander>, } impl SoundExpander { pub fn
() -> SoundExpander { let wave_format: WaveFormatEx = Default::default(); SoundExpander { memb_20: 0, memb_24: 0, memb_28: 0, memb_30: 0, memb_34: 0, memb_40: 0, memb_48: 0, memb_4C: 0, memb_54: 0, memb_58: 0, memb_5C: 0, memb_64: 0, memb_68: 0, memb_70: 0, memb_74: 0, memb_80: 0, memb_8C: 0, memb_90: 0, file_reader: stream::FileReader::new(), wave_format_ex: wave_format, flags0: 0, flags1: 0, flags2: 0, loop_point: 0, file_length: 0, read_limit: 0, some_var_6680EC: 0, some_var_6680E8: 0, previous: Box::new(SoundExpander::new()), next: Box::new(SoundExpander::new()), } } }
new
identifier_name
expander.rs
// Our use cases use super::stream; pub const WAVE_FORMAT_PCM: usize = 1; #[derive(Default)] pub struct WaveFormatEx { pub format_tag: u16, pub channels: u16, pub samples_per_second: i32, pub average_bytes_per_second: i32, pub block_align: u16, pub bits_per_sample: u16, pub cb_size: u16, } pub struct SoundExpander { pub memb_20: i32, pub memb_24: i32, pub memb_28: i32, pub memb_30: i32, pub memb_34: i32, pub memb_40: i32, pub memb_48: i32, pub memb_4C: i32, pub memb_54: i32, pub memb_58: i32, pub memb_5C: i32, pub memb_64: i32, pub memb_68: i32, pub memb_70: i32, pub memb_74: i32, pub memb_80: i32, pub memb_8C: i32, pub memb_90: i32, pub file_reader: stream::FileReader, pub wave_format_ex: WaveFormatEx, pub flags0: i32, pub flags1: i32, pub flags2: i32, pub loop_point: i32, pub file_length: i32, pub read_limit: i32, pub some_var_6680EC: i32, pub some_var_6680E8: i32, pub previous: Box<SoundExpander>, pub next: Box<SoundExpander>, } impl SoundExpander { pub fn new() -> SoundExpander { let wave_format: WaveFormatEx = Default::default(); SoundExpander { memb_20: 0, memb_24: 0, memb_28: 0, memb_30: 0, memb_34: 0, memb_40: 0, memb_48: 0, memb_4C: 0, memb_54: 0, memb_58: 0, memb_5C: 0, memb_64: 0, memb_68: 0, memb_70: 0, memb_74: 0, memb_80: 0, memb_8C: 0, memb_90: 0, file_reader: stream::FileReader::new(), wave_format_ex: wave_format, flags0: 0, flags1: 0, flags2: 0, loop_point: 0, file_length: 0, read_limit: 0,
} }
some_var_6680EC: 0, some_var_6680E8: 0, previous: Box::new(SoundExpander::new()), next: Box::new(SoundExpander::new()), }
random_line_split
record.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 api::{ApiMsg, FrameMsg, SceneMsg}; use bincode::serialize; use byteorder::{LittleEndian, WriteBytesExt}; use std::any::TypeId; use std::fmt::Debug; use std::fs::File; use std::io::Write; use std::mem; use std::path::PathBuf; pub static WEBRENDER_RECORDING_HEADER: u64 = 0xbeefbeefbeefbe01u64; pub trait ApiRecordingReceiver: Send + Debug { fn write_msg(&mut self, frame: u32, msg: &ApiMsg); fn write_payload(&mut self, frame: u32, data: &[u8]); } #[derive(Debug)] pub struct BinaryRecorder { file: File, } impl BinaryRecorder { pub fn new(dest: &PathBuf) -> BinaryRecorder
fn write_length_and_data(&mut self, data: &[u8]) { self.file.write_u32::<LittleEndian>(data.len() as u32).ok(); self.file.write(data).ok(); } } impl ApiRecordingReceiver for BinaryRecorder { fn write_msg(&mut self, _: u32, msg: &ApiMsg) { if should_record_msg(msg) { let buf = serialize(msg).unwrap(); self.write_length_and_data(&buf); } } fn write_payload(&mut self, _: u32, data: &[u8]) { // signal payload with a 0 length self.file.write_u32::<LittleEndian>(0).ok(); self.write_length_and_data(data); } } pub fn should_record_msg(msg: &ApiMsg) -> bool { match *msg { ApiMsg::UpdateResources(..) | ApiMsg::AddDocument {.. } | ApiMsg::DeleteDocument(..) => true, ApiMsg::UpdateDocument(_, ref msgs) => { if msgs.generate_frame { return true; } for msg in &msgs.scene_ops { match *msg { SceneMsg::SetDisplayList {.. } | SceneMsg::SetRootPipeline {.. } => return true, _ => {} } } for msg in &msgs.frame_ops { match *msg { FrameMsg::GetScrollNodeState(..) | FrameMsg::HitTest(..) => {} _ => return true, } } false } _ => false, } }
{ let mut file = File::create(dest).unwrap(); // write the header let apimsg_type_id = unsafe { assert!(mem::size_of::<TypeId>() == mem::size_of::<u64>()); mem::transmute::<TypeId, u64>(TypeId::of::<ApiMsg>()) }; file.write_u64::<LittleEndian>(WEBRENDER_RECORDING_HEADER) .ok(); file.write_u64::<LittleEndian>(apimsg_type_id).ok(); BinaryRecorder { file } }
identifier_body
record.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 api::{ApiMsg, FrameMsg, SceneMsg}; use bincode::serialize; use byteorder::{LittleEndian, WriteBytesExt}; use std::any::TypeId; use std::fmt::Debug; use std::fs::File; use std::io::Write; use std::mem; use std::path::PathBuf; pub static WEBRENDER_RECORDING_HEADER: u64 = 0xbeefbeefbeefbe01u64; pub trait ApiRecordingReceiver: Send + Debug { fn write_msg(&mut self, frame: u32, msg: &ApiMsg); fn write_payload(&mut self, frame: u32, data: &[u8]); } #[derive(Debug)] pub struct BinaryRecorder { file: File, } impl BinaryRecorder { pub fn new(dest: &PathBuf) -> BinaryRecorder { let mut file = File::create(dest).unwrap(); // write the header let apimsg_type_id = unsafe { assert!(mem::size_of::<TypeId>() == mem::size_of::<u64>()); mem::transmute::<TypeId, u64>(TypeId::of::<ApiMsg>()) }; file.write_u64::<LittleEndian>(WEBRENDER_RECORDING_HEADER) .ok(); file.write_u64::<LittleEndian>(apimsg_type_id).ok(); BinaryRecorder { file } } fn write_length_and_data(&mut self, data: &[u8]) { self.file.write_u32::<LittleEndian>(data.len() as u32).ok(); self.file.write(data).ok(); } } impl ApiRecordingReceiver for BinaryRecorder { fn
(&mut self, _: u32, msg: &ApiMsg) { if should_record_msg(msg) { let buf = serialize(msg).unwrap(); self.write_length_and_data(&buf); } } fn write_payload(&mut self, _: u32, data: &[u8]) { // signal payload with a 0 length self.file.write_u32::<LittleEndian>(0).ok(); self.write_length_and_data(data); } } pub fn should_record_msg(msg: &ApiMsg) -> bool { match *msg { ApiMsg::UpdateResources(..) | ApiMsg::AddDocument {.. } | ApiMsg::DeleteDocument(..) => true, ApiMsg::UpdateDocument(_, ref msgs) => { if msgs.generate_frame { return true; } for msg in &msgs.scene_ops { match *msg { SceneMsg::SetDisplayList {.. } | SceneMsg::SetRootPipeline {.. } => return true, _ => {} } } for msg in &msgs.frame_ops { match *msg { FrameMsg::GetScrollNodeState(..) | FrameMsg::HitTest(..) => {} _ => return true, } } false } _ => false, } }
write_msg
identifier_name
record.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 api::{ApiMsg, FrameMsg, SceneMsg}; use bincode::serialize; use byteorder::{LittleEndian, WriteBytesExt}; use std::any::TypeId; use std::fmt::Debug; use std::fs::File; use std::io::Write; use std::mem; use std::path::PathBuf; pub static WEBRENDER_RECORDING_HEADER: u64 = 0xbeefbeefbeefbe01u64; pub trait ApiRecordingReceiver: Send + Debug { fn write_msg(&mut self, frame: u32, msg: &ApiMsg); fn write_payload(&mut self, frame: u32, data: &[u8]); } #[derive(Debug)] pub struct BinaryRecorder { file: File, } impl BinaryRecorder { pub fn new(dest: &PathBuf) -> BinaryRecorder { let mut file = File::create(dest).unwrap(); // write the header let apimsg_type_id = unsafe { assert!(mem::size_of::<TypeId>() == mem::size_of::<u64>()); mem::transmute::<TypeId, u64>(TypeId::of::<ApiMsg>()) }; file.write_u64::<LittleEndian>(WEBRENDER_RECORDING_HEADER) .ok(); file.write_u64::<LittleEndian>(apimsg_type_id).ok(); BinaryRecorder { file } } fn write_length_and_data(&mut self, data: &[u8]) { self.file.write_u32::<LittleEndian>(data.len() as u32).ok(); self.file.write(data).ok(); } } impl ApiRecordingReceiver for BinaryRecorder { fn write_msg(&mut self, _: u32, msg: &ApiMsg) { if should_record_msg(msg) { let buf = serialize(msg).unwrap(); self.write_length_and_data(&buf); } } fn write_payload(&mut self, _: u32, data: &[u8]) { // signal payload with a 0 length self.file.write_u32::<LittleEndian>(0).ok(); self.write_length_and_data(data); } } pub fn should_record_msg(msg: &ApiMsg) -> bool { match *msg { ApiMsg::UpdateResources(..) | ApiMsg::AddDocument {.. } | ApiMsg::DeleteDocument(..) => true, ApiMsg::UpdateDocument(_, ref msgs) => { if msgs.generate_frame { return true;
SceneMsg::SetDisplayList {.. } | SceneMsg::SetRootPipeline {.. } => return true, _ => {} } } for msg in &msgs.frame_ops { match *msg { FrameMsg::GetScrollNodeState(..) | FrameMsg::HitTest(..) => {} _ => return true, } } false } _ => false, } }
} for msg in &msgs.scene_ops { match *msg {
random_line_split
gamepad.rs
//! Gamepad utility functions. //! //! This is going to be a bit of a work-in-progress as gamepad input //! gets fleshed out. The `gilrs` crate needs help to add better //! cross-platform support. Why not give it a hand? //! //! TODO: All of this. use std::fmt; use gilrs::{Event, Gamepad, Gilrs}; use crate::context::Context; use crate::error::GameResult; /// Trait object defining a gamepad/joystick context. pub trait GamepadContext { /// Returns a gamepad event. fn next_event(&mut self) -> Option<Event>; /// returns the `Gamepad` associated with an id. fn gamepad(&self, id: usize) -> Option<&Gamepad>; } /// A structure that contains gamepad state using `gilrs`. pub struct GilrsGamepadContext { pub(crate) gilrs: Gilrs, } impl fmt::Debug for GilrsGamepadContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GilrsGamepadContext: {:p}>", self) } } impl GilrsGamepadContext { pub(crate) fn new() -> GameResult<Self> { let gilrs = Gilrs::new()?; Ok(GilrsGamepadContext { gilrs }) } } impl GamepadContext for GilrsGamepadContext { fn next_event(&mut self) -> Option<Event> { self.gilrs.next_event() } fn gamepad(&self, id: usize) -> Option<&Gamepad> { self.gilrs.get(id) } } /// A structure that implements [`GamepadContext`](trait.GamepadContext.html) /// but does nothing; a stub for when you don't need it or are /// on a platform that `gilrs` doesn't support. #[derive(Debug, Clone, Copy, Default)] pub struct NullGamepadContext {} impl GamepadContext for NullGamepadContext { fn next_event(&mut self) -> Option<Event> { panic!("Gamepad module disabled") } fn gamepad(&self, _id: usize) -> Option<&Gamepad> { panic!("Gamepad module disabled") } } /// Returns the `Gamepad` associated with an `id`. pub fn gamepad(ctx: &Context, id: usize) -> Option<&Gamepad> { ctx.gamepad_context.gamepad(id) } // Properties gamepads might want: // Number of buttons // Number of axes // Name/ID // Is it connected? (For consoles?) // Whether or not they support vibration /// Lists all gamepads. With metainfo, maybe? pub fn list_gamepads() { unimplemented!() } /// Returns the state of the given axis on a gamepad. pub fn axis() { unimplemented!() } /// Returns the state of the given button on a gamepad. pub fn button_pressed() { unimplemented!() } #[cfg(test)]
assert!(GilrsGamepadContext::new().is_ok()); } }
mod tests { use super::*; #[test] fn gilrs_init() {
random_line_split
gamepad.rs
//! Gamepad utility functions. //! //! This is going to be a bit of a work-in-progress as gamepad input //! gets fleshed out. The `gilrs` crate needs help to add better //! cross-platform support. Why not give it a hand? //! //! TODO: All of this. use std::fmt; use gilrs::{Event, Gamepad, Gilrs}; use crate::context::Context; use crate::error::GameResult; /// Trait object defining a gamepad/joystick context. pub trait GamepadContext { /// Returns a gamepad event. fn next_event(&mut self) -> Option<Event>; /// returns the `Gamepad` associated with an id. fn gamepad(&self, id: usize) -> Option<&Gamepad>; } /// A structure that contains gamepad state using `gilrs`. pub struct GilrsGamepadContext { pub(crate) gilrs: Gilrs, } impl fmt::Debug for GilrsGamepadContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GilrsGamepadContext: {:p}>", self) } } impl GilrsGamepadContext { pub(crate) fn
() -> GameResult<Self> { let gilrs = Gilrs::new()?; Ok(GilrsGamepadContext { gilrs }) } } impl GamepadContext for GilrsGamepadContext { fn next_event(&mut self) -> Option<Event> { self.gilrs.next_event() } fn gamepad(&self, id: usize) -> Option<&Gamepad> { self.gilrs.get(id) } } /// A structure that implements [`GamepadContext`](trait.GamepadContext.html) /// but does nothing; a stub for when you don't need it or are /// on a platform that `gilrs` doesn't support. #[derive(Debug, Clone, Copy, Default)] pub struct NullGamepadContext {} impl GamepadContext for NullGamepadContext { fn next_event(&mut self) -> Option<Event> { panic!("Gamepad module disabled") } fn gamepad(&self, _id: usize) -> Option<&Gamepad> { panic!("Gamepad module disabled") } } /// Returns the `Gamepad` associated with an `id`. pub fn gamepad(ctx: &Context, id: usize) -> Option<&Gamepad> { ctx.gamepad_context.gamepad(id) } // Properties gamepads might want: // Number of buttons // Number of axes // Name/ID // Is it connected? (For consoles?) // Whether or not they support vibration /// Lists all gamepads. With metainfo, maybe? pub fn list_gamepads() { unimplemented!() } /// Returns the state of the given axis on a gamepad. pub fn axis() { unimplemented!() } /// Returns the state of the given button on a gamepad. pub fn button_pressed() { unimplemented!() } #[cfg(test)] mod tests { use super::*; #[test] fn gilrs_init() { assert!(GilrsGamepadContext::new().is_ok()); } }
new
identifier_name
c_types.rs
#![allow(dead_code, non_camel_case_types)] extern crate libc; use self::libc::{ c_char, c_int, uid_t, time_t }; use self::libc::funcs::posix88::unistd::getgroups; use std::vec::Vec; use std::ptr::read; use std::str::raw::from_c_str; pub struct c_passwd { pub pw_name: *c_char, /* user name */ pub pw_passwd: *c_char, /* user name */ pub pw_uid: c_int, /* user uid */ pub pw_gid: c_int, /* user gid */ pub pw_change: time_t, pub pw_class: *c_char, pub pw_gecos: *c_char, pub pw_dir: *c_char, pub pw_shell: *c_char, pub pw_expire: time_t } #[cfg(target_os = "macos")]
pub struct utsname { pub sysname: [c_char,..256], pub nodename: [c_char,..256], pub release: [c_char,..256], pub version: [c_char,..256], pub machine: [c_char,..256] } #[cfg(target_os = "linux")] pub struct utsname { pub sysname: [c_char,..65], pub nodename: [c_char,..65], pub release: [c_char,..65], pub version: [c_char,..65], pub machine: [c_char,..65], pub domainame: [c_char,..65] } pub struct c_group { pub gr_name: *c_char /* group name */ } pub struct c_tm { pub tm_sec: c_int, /* seconds */ pub tm_min: c_int, /* minutes */ pub tm_hour: c_int, /* hours */ pub tm_mday: c_int, /* day of the month */ pub tm_mon: c_int, /* month */ pub tm_year: c_int, /* year */ pub tm_wday: c_int, /* day of the week */ pub tm_yday: c_int, /* day in the year */ pub tm_isdst: c_int /* daylight saving time */ } extern { pub fn getpwuid(uid: c_int) -> *c_passwd; pub fn getpwnam(login: *c_char) -> *c_passwd; pub fn getgrouplist(name: *c_char, basegid: c_int, groups: *c_int, ngroups: *mut c_int) -> c_int; pub fn getgrgid(gid: uid_t) -> *c_group; } pub fn get_pw_from_args(free: &Vec<String>) -> Option<c_passwd> { if free.len() == 1 { let username = free.get(0).as_slice(); // Passed user as id if username.chars().all(|c| c.is_digit()) { let id = from_str::<i32>(username).unwrap(); let pw_pointer = unsafe { getpwuid(id) }; if pw_pointer.is_not_null() { Some(unsafe { read(pw_pointer) }) } else { crash!(1, "{:s}: no such user", username); } // Passed the username as a string } else { let pw_pointer = unsafe { getpwnam(username.as_slice().as_ptr() as *i8) }; if pw_pointer.is_not_null() { Some(unsafe { read(pw_pointer) }) } else { crash!(1, "{:s}: no such user", username); } } } else { None } } static NGROUPS: i32 = 20; pub fn group(possible_pw: Option<c_passwd>, nflag: bool) { let mut groups = Vec::with_capacity(NGROUPS as uint); let mut ngroups; if possible_pw.is_some() { ngroups = NGROUPS; unsafe { getgrouplist( possible_pw.unwrap().pw_name, possible_pw.unwrap().pw_gid, groups.as_ptr(), &mut ngroups); } } else { ngroups = unsafe { getgroups(NGROUPS, groups.as_mut_ptr() as *mut u32) }; } unsafe { groups.set_len(ngroups as uint) }; for &g in groups.iter() { if nflag { let group = unsafe { getgrgid(g as u32) }; if group.is_not_null() { let name = unsafe { from_c_str(read(group).gr_name) }; print!("{:s} ", name); } } else { print!("{:d} ", g); } } println!(""); }
random_line_split
c_types.rs
#![allow(dead_code, non_camel_case_types)] extern crate libc; use self::libc::{ c_char, c_int, uid_t, time_t }; use self::libc::funcs::posix88::unistd::getgroups; use std::vec::Vec; use std::ptr::read; use std::str::raw::from_c_str; pub struct c_passwd { pub pw_name: *c_char, /* user name */ pub pw_passwd: *c_char, /* user name */ pub pw_uid: c_int, /* user uid */ pub pw_gid: c_int, /* user gid */ pub pw_change: time_t, pub pw_class: *c_char, pub pw_gecos: *c_char, pub pw_dir: *c_char, pub pw_shell: *c_char, pub pw_expire: time_t } #[cfg(target_os = "macos")] pub struct utsname { pub sysname: [c_char,..256], pub nodename: [c_char,..256], pub release: [c_char,..256], pub version: [c_char,..256], pub machine: [c_char,..256] } #[cfg(target_os = "linux")] pub struct utsname { pub sysname: [c_char,..65], pub nodename: [c_char,..65], pub release: [c_char,..65], pub version: [c_char,..65], pub machine: [c_char,..65], pub domainame: [c_char,..65] } pub struct c_group { pub gr_name: *c_char /* group name */ } pub struct c_tm { pub tm_sec: c_int, /* seconds */ pub tm_min: c_int, /* minutes */ pub tm_hour: c_int, /* hours */ pub tm_mday: c_int, /* day of the month */ pub tm_mon: c_int, /* month */ pub tm_year: c_int, /* year */ pub tm_wday: c_int, /* day of the week */ pub tm_yday: c_int, /* day in the year */ pub tm_isdst: c_int /* daylight saving time */ } extern { pub fn getpwuid(uid: c_int) -> *c_passwd; pub fn getpwnam(login: *c_char) -> *c_passwd; pub fn getgrouplist(name: *c_char, basegid: c_int, groups: *c_int, ngroups: *mut c_int) -> c_int; pub fn getgrgid(gid: uid_t) -> *c_group; } pub fn get_pw_from_args(free: &Vec<String>) -> Option<c_passwd> { if free.len() == 1 { let username = free.get(0).as_slice(); // Passed user as id if username.chars().all(|c| c.is_digit()) { let id = from_str::<i32>(username).unwrap(); let pw_pointer = unsafe { getpwuid(id) }; if pw_pointer.is_not_null() { Some(unsafe { read(pw_pointer) }) } else { crash!(1, "{:s}: no such user", username); } // Passed the username as a string } else { let pw_pointer = unsafe { getpwnam(username.as_slice().as_ptr() as *i8) }; if pw_pointer.is_not_null() { Some(unsafe { read(pw_pointer) }) } else { crash!(1, "{:s}: no such user", username); } } } else { None } } static NGROUPS: i32 = 20; pub fn group(possible_pw: Option<c_passwd>, nflag: bool) { let mut groups = Vec::with_capacity(NGROUPS as uint); let mut ngroups; if possible_pw.is_some()
else { ngroups = unsafe { getgroups(NGROUPS, groups.as_mut_ptr() as *mut u32) }; } unsafe { groups.set_len(ngroups as uint) }; for &g in groups.iter() { if nflag { let group = unsafe { getgrgid(g as u32) }; if group.is_not_null() { let name = unsafe { from_c_str(read(group).gr_name) }; print!("{:s} ", name); } } else { print!("{:d} ", g); } } println!(""); }
{ ngroups = NGROUPS; unsafe { getgrouplist( possible_pw.unwrap().pw_name, possible_pw.unwrap().pw_gid, groups.as_ptr(), &mut ngroups); } }
conditional_block
c_types.rs
#![allow(dead_code, non_camel_case_types)] extern crate libc; use self::libc::{ c_char, c_int, uid_t, time_t }; use self::libc::funcs::posix88::unistd::getgroups; use std::vec::Vec; use std::ptr::read; use std::str::raw::from_c_str; pub struct c_passwd { pub pw_name: *c_char, /* user name */ pub pw_passwd: *c_char, /* user name */ pub pw_uid: c_int, /* user uid */ pub pw_gid: c_int, /* user gid */ pub pw_change: time_t, pub pw_class: *c_char, pub pw_gecos: *c_char, pub pw_dir: *c_char, pub pw_shell: *c_char, pub pw_expire: time_t } #[cfg(target_os = "macos")] pub struct
{ pub sysname: [c_char,..256], pub nodename: [c_char,..256], pub release: [c_char,..256], pub version: [c_char,..256], pub machine: [c_char,..256] } #[cfg(target_os = "linux")] pub struct utsname { pub sysname: [c_char,..65], pub nodename: [c_char,..65], pub release: [c_char,..65], pub version: [c_char,..65], pub machine: [c_char,..65], pub domainame: [c_char,..65] } pub struct c_group { pub gr_name: *c_char /* group name */ } pub struct c_tm { pub tm_sec: c_int, /* seconds */ pub tm_min: c_int, /* minutes */ pub tm_hour: c_int, /* hours */ pub tm_mday: c_int, /* day of the month */ pub tm_mon: c_int, /* month */ pub tm_year: c_int, /* year */ pub tm_wday: c_int, /* day of the week */ pub tm_yday: c_int, /* day in the year */ pub tm_isdst: c_int /* daylight saving time */ } extern { pub fn getpwuid(uid: c_int) -> *c_passwd; pub fn getpwnam(login: *c_char) -> *c_passwd; pub fn getgrouplist(name: *c_char, basegid: c_int, groups: *c_int, ngroups: *mut c_int) -> c_int; pub fn getgrgid(gid: uid_t) -> *c_group; } pub fn get_pw_from_args(free: &Vec<String>) -> Option<c_passwd> { if free.len() == 1 { let username = free.get(0).as_slice(); // Passed user as id if username.chars().all(|c| c.is_digit()) { let id = from_str::<i32>(username).unwrap(); let pw_pointer = unsafe { getpwuid(id) }; if pw_pointer.is_not_null() { Some(unsafe { read(pw_pointer) }) } else { crash!(1, "{:s}: no such user", username); } // Passed the username as a string } else { let pw_pointer = unsafe { getpwnam(username.as_slice().as_ptr() as *i8) }; if pw_pointer.is_not_null() { Some(unsafe { read(pw_pointer) }) } else { crash!(1, "{:s}: no such user", username); } } } else { None } } static NGROUPS: i32 = 20; pub fn group(possible_pw: Option<c_passwd>, nflag: bool) { let mut groups = Vec::with_capacity(NGROUPS as uint); let mut ngroups; if possible_pw.is_some() { ngroups = NGROUPS; unsafe { getgrouplist( possible_pw.unwrap().pw_name, possible_pw.unwrap().pw_gid, groups.as_ptr(), &mut ngroups); } } else { ngroups = unsafe { getgroups(NGROUPS, groups.as_mut_ptr() as *mut u32) }; } unsafe { groups.set_len(ngroups as uint) }; for &g in groups.iter() { if nflag { let group = unsafe { getgrgid(g as u32) }; if group.is_not_null() { let name = unsafe { from_c_str(read(group).gr_name) }; print!("{:s} ", name); } } else { print!("{:d} ", g); } } println!(""); }
utsname
identifier_name
ffi.rs
use std::fmt; // this extern block links to the libm library #[link(name = "m")] extern { // this is a foreign function // that computes the square root of a single precision complex number fn csqrtf(z: Complex) -> Complex; } fn main() { // z = -1 + 0i let z = Complex { re: -1., im: 0. }; // calling a foreign function is an unsafe operation let z_sqrt = unsafe { csqrtf(z) }; println!("the square root of {} is {}", z, z_sqrt); } // Minimal implementation of single precision complex numbers #[repr(C)] struct
{ re: f32, im: f32, } impl fmt::Show for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self.im) } else { write!(f, "{}+{}i", self.re, self.im) } } }
Complex
identifier_name
ffi.rs
use std::fmt; // this extern block links to the libm library #[link(name = "m")] extern { // this is a foreign function // that computes the square root of a single precision complex number fn csqrtf(z: Complex) -> Complex; } fn main() { // z = -1 + 0i let z = Complex { re: -1., im: 0. }; // calling a foreign function is an unsafe operation let z_sqrt = unsafe { csqrtf(z) }; println!("the square root of {} is {}", z, z_sqrt); } // Minimal implementation of single precision complex numbers #[repr(C)] struct Complex { re: f32, im: f32, } impl fmt::Show for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}-{}i", self.re, -self.im) } else { write!(f, "{}+{}i", self.re, self.im) } } }
if self.im < 0. {
random_line_split
ffi.rs
use std::fmt; // this extern block links to the libm library #[link(name = "m")] extern { // this is a foreign function // that computes the square root of a single precision complex number fn csqrtf(z: Complex) -> Complex; } fn main() { // z = -1 + 0i let z = Complex { re: -1., im: 0. }; // calling a foreign function is an unsafe operation let z_sqrt = unsafe { csqrtf(z) }; println!("the square root of {} is {}", z, z_sqrt); } // Minimal implementation of single precision complex numbers #[repr(C)] struct Complex { re: f32, im: f32, } impl fmt::Show for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self.im) } else
} }
{ write!(f, "{}+{}i", self.re, self.im) }
conditional_block
ffi.rs
use std::fmt; // this extern block links to the libm library #[link(name = "m")] extern { // this is a foreign function // that computes the square root of a single precision complex number fn csqrtf(z: Complex) -> Complex; } fn main()
// Minimal implementation of single precision complex numbers #[repr(C)] struct Complex { re: f32, im: f32, } impl fmt::Show for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self.im) } else { write!(f, "{}+{}i", self.re, self.im) } } }
{ // z = -1 + 0i let z = Complex { re: -1., im: 0. }; // calling a foreign function is an unsafe operation let z_sqrt = unsafe { csqrtf(z) }; println!("the square root of {} is {}", z, z_sqrt); }
identifier_body
main.rs
#![feature(slice_patterns, convert, vec_push_all)] extern crate md5; mod keys; use keys::*; fn
() { // capture arguments let key = match get_key_from_args() { Ok(k) => k, Err(why) => { handle_errors(why); return; }, }; // separate key into segments xxxxx-xxxxx-xxxxx let segments = match get_key_segments(key.as_ref()) { Ok(s) => s, Err(why) => { handle_errors(why); return; }, }; // check segment1 and create modified key let mut mod_key = match check_segment1(segments.as_ref()) { Ok(s) => s, Err(why) => { handle_errors(why); return; }, }; // check segment 2 and store result in seg let _ = match check_segment2(segments.as_ref(), &mut mod_key) { Ok(_) => {}, Err(why) => { handle_errors(why); return; }, }; // check segment 3 let _ = match check_segment3(segments.as_ref(), &mut mod_key) { Ok(_) => {}, Err(why) => { handle_errors(why); return; }, }; if check_final(mod_key.as_ref()) { print_key(&segments); print_key(&mod_key); } else { println!("You failed to enter the correct key"); } }
main
identifier_name
main.rs
#![feature(slice_patterns, convert, vec_push_all)] extern crate md5; mod keys; use keys::*; fn main() { // capture arguments let key = match get_key_from_args() { Ok(k) => k, Err(why) => { handle_errors(why); return; }, }; // separate key into segments xxxxx-xxxxx-xxxxx let segments = match get_key_segments(key.as_ref()) { Ok(s) => s, Err(why) => { handle_errors(why); return; }, }; // check segment1 and create modified key let mut mod_key = match check_segment1(segments.as_ref()) { Ok(s) => s, Err(why) => { handle_errors(why); return; }, }; // check segment 2 and store result in seg let _ = match check_segment2(segments.as_ref(), &mut mod_key) {
}, }; // check segment 3 let _ = match check_segment3(segments.as_ref(), &mut mod_key) { Ok(_) => {}, Err(why) => { handle_errors(why); return; }, }; if check_final(mod_key.as_ref()) { print_key(&segments); print_key(&mod_key); } else { println!("You failed to enter the correct key"); } }
Ok(_) => {}, Err(why) => { handle_errors(why); return;
random_line_split
main.rs
#![feature(slice_patterns, convert, vec_push_all)] extern crate md5; mod keys; use keys::*; fn main()
let mut mod_key = match check_segment1(segments.as_ref()) { Ok(s) => s, Err(why) => { handle_errors(why); return; }, }; // check segment 2 and store result in seg let _ = match check_segment2(segments.as_ref(), &mut mod_key) { Ok(_) => {}, Err(why) => { handle_errors(why); return; }, }; // check segment 3 let _ = match check_segment3(segments.as_ref(), &mut mod_key) { Ok(_) => {}, Err(why) => { handle_errors(why); return; }, }; if check_final(mod_key.as_ref()) { print_key(&segments); print_key(&mod_key); } else { println!("You failed to enter the correct key"); } }
{ // capture arguments let key = match get_key_from_args() { Ok(k) => k, Err(why) => { handle_errors(why); return; }, }; // separate key into segments xxxxx-xxxxx-xxxxx let segments = match get_key_segments(key.as_ref()) { Ok(s) => s, Err(why) => { handle_errors(why); return; }, }; // check segment1 and create modified key
identifier_body
apic.rs
use common::*; use arch::init::{LOCAL_APIC_PAGE_VADDR, IO_APIC_PAGE_VADDR}; use util::{Mutex}; use super::{InterruptVector}; /// Local APIC pointer. #[derive(Debug)] pub struct LocalAPIC { address: VAddr, } /// I/O APIC pointer. #[derive(Debug)] pub struct IOAPIC { address: VAddr, } /// The local APIC static. pub static LOCAL_APIC: Mutex<LocalAPIC> = Mutex::new(LocalAPIC { address: LOCAL_APIC_PAGE_VADDR }); /// The I/O APIC static. pub static IO_APIC: Mutex<IOAPIC> = Mutex::new(IOAPIC { address: IO_APIC_PAGE_VADDR }); #[allow(dead_code)] impl LocalAPIC { /// Read a value from the local APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn read(&self, reg: u32) -> u32 { use core::intrinsics::{volatile_load}; volatile_load((self.address.into(): usize + reg as usize) as *const u32) }
/// `reg` must be valid. unsafe fn write(&mut self, reg: u32, value: u32) { use core::intrinsics::{volatile_store}; volatile_store((self.address.into(): usize + reg as usize) as *mut u32, value); } /// APIC id. pub fn id(&self) -> u32 { unsafe { self.read(0x20) } } /// APIC version. pub fn version(&self) -> u32 { unsafe { self.read(0x30) } } /// Spurious interrupt vector. pub fn siv(&self) -> u32 { unsafe { self.read(0xF0) } } /// Set the spurious interrupt vector. pub fn set_siv(&mut self, value: u32) { unsafe { self.write(0xF0, value) } } /// Send End of Interrupt. pub fn eoi(&mut self) { unsafe { self.write(0xB0, 0) } } /// Enable timer with a specific value. pub fn enable_timer(&mut self) { unsafe { self.write(0x3E0, 0x3); self.write(0x380, 0x10000); self.write(0x320, (1<<17) | 0x40); log!("timer register is 0b{:b}", self.read(0x320)); } } /// Current error status. pub fn error_status(&self) -> u32 { unsafe { self.read(0x280) } } } #[allow(dead_code)] impl IOAPIC { /// Read a value from the I/O APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn read(&self, reg: u32) -> u32 { use core::intrinsics::{volatile_load, volatile_store}; volatile_store((self.address.into(): usize + 0x0 as usize) as *mut u32, reg); volatile_load((self.address.into(): usize + 0x10 as usize) as *const u32) } /// Write a value to the I/O APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn write(&mut self, reg: u32, value: u32) { use core::intrinsics::volatile_store; volatile_store((self.address.into(): usize + 0x0 as usize) as *mut u32, reg); volatile_store((self.address.into(): usize + 0x10 as usize) as *mut u32, value); } /// I/O APIC id. pub fn id(&self) -> u32 { unsafe { self.read(0x0) } } /// I/O APIC version. pub fn version(&self) -> u32 { unsafe { self.read(0x1) } } /// I/O APIC arbitration id. pub fn arbitration_id(&self) -> u32 { unsafe { self.read(0x2) } } /// Set IRQ to an interrupt vector. pub fn set_irq(&mut self, irq: u8, apic_id: u8, vector: InterruptVector) { let vector = vector as u8; let low_index: u32 = 0x10 + (irq as u32) * 2; let high_index: u32 = 0x10 + (irq as u32) * 2 + 1; let mut high = unsafe { self.read(high_index) }; high &=!0xff000000; high |= (apic_id as u32) << 24; unsafe { self.write(high_index, high) }; let mut low = unsafe { self.read(low_index) }; low &=!(1<<16); low &=!(1<<11); low &=!0x700; low &=!0xff; low |= vector as u32; unsafe { self.write(low_index, low) }; } }
/// Write a value to the local APIC. /// /// # Safety ///
random_line_split
apic.rs
use common::*; use arch::init::{LOCAL_APIC_PAGE_VADDR, IO_APIC_PAGE_VADDR}; use util::{Mutex}; use super::{InterruptVector}; /// Local APIC pointer. #[derive(Debug)] pub struct LocalAPIC { address: VAddr, } /// I/O APIC pointer. #[derive(Debug)] pub struct IOAPIC { address: VAddr, } /// The local APIC static. pub static LOCAL_APIC: Mutex<LocalAPIC> = Mutex::new(LocalAPIC { address: LOCAL_APIC_PAGE_VADDR }); /// The I/O APIC static. pub static IO_APIC: Mutex<IOAPIC> = Mutex::new(IOAPIC { address: IO_APIC_PAGE_VADDR }); #[allow(dead_code)] impl LocalAPIC { /// Read a value from the local APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn read(&self, reg: u32) -> u32 { use core::intrinsics::{volatile_load}; volatile_load((self.address.into(): usize + reg as usize) as *const u32) } /// Write a value to the local APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn write(&mut self, reg: u32, value: u32) { use core::intrinsics::{volatile_store}; volatile_store((self.address.into(): usize + reg as usize) as *mut u32, value); } /// APIC id. pub fn id(&self) -> u32 { unsafe { self.read(0x20) } } /// APIC version. pub fn version(&self) -> u32 { unsafe { self.read(0x30) } } /// Spurious interrupt vector. pub fn siv(&self) -> u32 { unsafe { self.read(0xF0) } } /// Set the spurious interrupt vector. pub fn set_siv(&mut self, value: u32) { unsafe { self.write(0xF0, value) } } /// Send End of Interrupt. pub fn eoi(&mut self) { unsafe { self.write(0xB0, 0) } } /// Enable timer with a specific value. pub fn enable_timer(&mut self) { unsafe { self.write(0x3E0, 0x3); self.write(0x380, 0x10000); self.write(0x320, (1<<17) | 0x40); log!("timer register is 0b{:b}", self.read(0x320)); } } /// Current error status. pub fn error_status(&self) -> u32 { unsafe { self.read(0x280) } } } #[allow(dead_code)] impl IOAPIC { /// Read a value from the I/O APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn read(&self, reg: u32) -> u32 { use core::intrinsics::{volatile_load, volatile_store}; volatile_store((self.address.into(): usize + 0x0 as usize) as *mut u32, reg); volatile_load((self.address.into(): usize + 0x10 as usize) as *const u32) } /// Write a value to the I/O APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn write(&mut self, reg: u32, value: u32) { use core::intrinsics::volatile_store; volatile_store((self.address.into(): usize + 0x0 as usize) as *mut u32, reg); volatile_store((self.address.into(): usize + 0x10 as usize) as *mut u32, value); } /// I/O APIC id. pub fn id(&self) -> u32 { unsafe { self.read(0x0) } } /// I/O APIC version. pub fn
(&self) -> u32 { unsafe { self.read(0x1) } } /// I/O APIC arbitration id. pub fn arbitration_id(&self) -> u32 { unsafe { self.read(0x2) } } /// Set IRQ to an interrupt vector. pub fn set_irq(&mut self, irq: u8, apic_id: u8, vector: InterruptVector) { let vector = vector as u8; let low_index: u32 = 0x10 + (irq as u32) * 2; let high_index: u32 = 0x10 + (irq as u32) * 2 + 1; let mut high = unsafe { self.read(high_index) }; high &=!0xff000000; high |= (apic_id as u32) << 24; unsafe { self.write(high_index, high) }; let mut low = unsafe { self.read(low_index) }; low &=!(1<<16); low &=!(1<<11); low &=!0x700; low &=!0xff; low |= vector as u32; unsafe { self.write(low_index, low) }; } }
version
identifier_name
apic.rs
use common::*; use arch::init::{LOCAL_APIC_PAGE_VADDR, IO_APIC_PAGE_VADDR}; use util::{Mutex}; use super::{InterruptVector}; /// Local APIC pointer. #[derive(Debug)] pub struct LocalAPIC { address: VAddr, } /// I/O APIC pointer. #[derive(Debug)] pub struct IOAPIC { address: VAddr, } /// The local APIC static. pub static LOCAL_APIC: Mutex<LocalAPIC> = Mutex::new(LocalAPIC { address: LOCAL_APIC_PAGE_VADDR }); /// The I/O APIC static. pub static IO_APIC: Mutex<IOAPIC> = Mutex::new(IOAPIC { address: IO_APIC_PAGE_VADDR }); #[allow(dead_code)] impl LocalAPIC { /// Read a value from the local APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn read(&self, reg: u32) -> u32 { use core::intrinsics::{volatile_load}; volatile_load((self.address.into(): usize + reg as usize) as *const u32) } /// Write a value to the local APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn write(&mut self, reg: u32, value: u32) { use core::intrinsics::{volatile_store}; volatile_store((self.address.into(): usize + reg as usize) as *mut u32, value); } /// APIC id. pub fn id(&self) -> u32 { unsafe { self.read(0x20) } } /// APIC version. pub fn version(&self) -> u32 { unsafe { self.read(0x30) } } /// Spurious interrupt vector. pub fn siv(&self) -> u32 { unsafe { self.read(0xF0) } } /// Set the spurious interrupt vector. pub fn set_siv(&mut self, value: u32) { unsafe { self.write(0xF0, value) } } /// Send End of Interrupt. pub fn eoi(&mut self) { unsafe { self.write(0xB0, 0) } } /// Enable timer with a specific value. pub fn enable_timer(&mut self) { unsafe { self.write(0x3E0, 0x3); self.write(0x380, 0x10000); self.write(0x320, (1<<17) | 0x40); log!("timer register is 0b{:b}", self.read(0x320)); } } /// Current error status. pub fn error_status(&self) -> u32 { unsafe { self.read(0x280) } } } #[allow(dead_code)] impl IOAPIC { /// Read a value from the I/O APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn read(&self, reg: u32) -> u32 { use core::intrinsics::{volatile_load, volatile_store}; volatile_store((self.address.into(): usize + 0x0 as usize) as *mut u32, reg); volatile_load((self.address.into(): usize + 0x10 as usize) as *const u32) } /// Write a value to the I/O APIC. /// /// # Safety /// /// `reg` must be valid. unsafe fn write(&mut self, reg: u32, value: u32) { use core::intrinsics::volatile_store; volatile_store((self.address.into(): usize + 0x0 as usize) as *mut u32, reg); volatile_store((self.address.into(): usize + 0x10 as usize) as *mut u32, value); } /// I/O APIC id. pub fn id(&self) -> u32 { unsafe { self.read(0x0) } } /// I/O APIC version. pub fn version(&self) -> u32
/// I/O APIC arbitration id. pub fn arbitration_id(&self) -> u32 { unsafe { self.read(0x2) } } /// Set IRQ to an interrupt vector. pub fn set_irq(&mut self, irq: u8, apic_id: u8, vector: InterruptVector) { let vector = vector as u8; let low_index: u32 = 0x10 + (irq as u32) * 2; let high_index: u32 = 0x10 + (irq as u32) * 2 + 1; let mut high = unsafe { self.read(high_index) }; high &=!0xff000000; high |= (apic_id as u32) << 24; unsafe { self.write(high_index, high) }; let mut low = unsafe { self.read(low_index) }; low &=!(1<<16); low &=!(1<<11); low &=!0x700; low &=!0xff; low |= vector as u32; unsafe { self.write(low_index, low) }; } }
{ unsafe { self.read(0x1) } }
identifier_body
issue-29037.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] // This test ensures that each pointer type `P<X>` is covariant in `X`. use std::rc::Rc; use std::sync::Arc; fn a<'r>(x: Box<&'static str>) -> Box<&'r str> {
fn b<'r, 'w>(x: &'w &'static str) -> &'w &'r str { x } fn c<'r>(x: Arc<&'static str>) -> Arc<&'r str> { x } fn d<'r>(x: Rc<&'static str>) -> Rc<&'r str> { x } fn main() {}
x }
random_line_split
issue-29037.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] // This test ensures that each pointer type `P<X>` is covariant in `X`. use std::rc::Rc; use std::sync::Arc; fn a<'r>(x: Box<&'static str>) -> Box<&'r str> { x } fn b<'r, 'w>(x: &'w &'static str) -> &'w &'r str { x } fn c<'r>(x: Arc<&'static str>) -> Arc<&'r str> { x } fn d<'r>(x: Rc<&'static str>) -> Rc<&'r str>
fn main() {}
{ x }
identifier_body
issue-29037.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] // This test ensures that each pointer type `P<X>` is covariant in `X`. use std::rc::Rc; use std::sync::Arc; fn a<'r>(x: Box<&'static str>) -> Box<&'r str> { x } fn b<'r, 'w>(x: &'w &'static str) -> &'w &'r str { x } fn c<'r>(x: Arc<&'static str>) -> Arc<&'r str> { x } fn d<'r>(x: Rc<&'static str>) -> Rc<&'r str> { x } fn
() {}
main
identifier_name
main.rs
// Copyright 2015 Google Inc. All rights reserved. // // 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. //! Command line tool to exercise pulldown-cmark. extern crate getopts; extern crate pulldown_cmark; use pulldown_cmark::Parser; use pulldown_cmark::{Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES}; use pulldown_cmark::html; use std::env; use std::io; use std::io::{Read, Write}; use std::path::Path; use std::fs::File; fn
(text: &str, opts: Options) -> String { let mut s = String::with_capacity(text.len() * 3 / 2); let p = Parser::new_ext(&text, opts); html::push_html(&mut s, p); s } fn dry_run(text:&str, opts: Options) { let p = Parser::new_ext(&text, opts); /* let events = p.collect::<Vec<_>>(); let count = events.len(); */ let count = p.count(); println!("{} events", count); } fn print_events(text: &str, opts: Options) { let mut p = Parser::new_ext(&text, opts); loop { print!("{}: ", p.get_offset()); if let Some(event) = p.next() { println!("{:?}", event); } else { break; } } println!("EOF"); } fn read_file(filename: &str) -> String { let path = Path::new(filename); let mut file = match File::open(&path) { Err(why) => panic!("couldn't open {}: {}", path.display(), why), Ok(file) => file }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(why) => panic!("couldn't open {}: {}", path.display(), why), Ok(_) => s } } fn find_test_delim(text: &str) -> Option<usize> { if text.starts_with(".\n") { Some(0) } else { text.find("\n.\n").map(|pos| pos + 1) } } fn run_spec(spec_text: &str, args: &[String], opts: Options) { //println!("spec length={}, args={:?}", spec_text.len(), args); let (first, last) = if args.is_empty() { (None, None) } else { let mut iter = args[0].split(".."); let first = iter.next().and_then(|s| s.parse().ok()); let last = match iter.next() { Some(s) => s.parse().ok(), None => first }; (first, last) }; let mut test_number = 1; let mut tests_failed = 0; let mut tests_run = 0; let mut line_count = 0; let mut tail = spec_text; loop { let rest = match find_test_delim(tail) { Some(pos) => &tail[pos + 2..], None => break }; let (source, rest) = match find_test_delim(rest) { Some(pos) => (&rest[..pos], &rest[pos + 2..]), None => break }; let (html, rest) = match find_test_delim(rest) { Some(pos) => (&rest[.. pos], &rest[pos + 2..]), None => break }; if first.map(|fst| fst <= test_number).unwrap_or(true) && last.map(|lst| test_number <= lst).unwrap_or(true) { if tests_run == 0 || line_count == 0 || (test_number % 10 == 0) { if line_count > 30 { println!(""); line_count = 0; } else if line_count > 0 { print!(" "); } print!("[{}]", test_number); } else if line_count > 0 && (test_number % 10) == 5 { print!(" "); } let our_html = render_html(&source.replace("→", "\t").replace("\n", "\r\n"), opts); if our_html == html { print!("."); } else { if tests_failed == 0 { print!("FAIL {}:\n---input---\n{}\n---wanted---\n{}\n---got---\n{}", test_number, source, html, our_html); } else { print!("X"); } tests_failed += 1; } let _ = io::stdout().flush(); tests_run += 1; line_count += 1; } tail = rest; test_number += 1; } println!("\n{}/{} tests passed", tests_run - tests_failed, tests_run) } pub fn main() { let args: Vec<_> = env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("d", "dry-run", "dry run, produce no output"); opts.optflag("e", "events", "print event sequence instead of rendering"); opts.optflag("T", "enable-tables", "enable GitHub-style tables"); opts.optflag("F", "enable-footnotes", "enable Hoedown-style footnotes"); opts.optopt("s", "spec", "run tests from spec file", "FILE"); opts.optopt("b", "bench", "run benchmark", "FILE"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()) }; let mut opts = Options::empty(); if matches.opt_present("enable-tables") { opts.insert(OPTION_ENABLE_TABLES); } if matches.opt_present("enable-footnotes") { opts.insert(OPTION_ENABLE_FOOTNOTES); } if let Some(filename) = matches.opt_str("spec") { run_spec(&read_file(&filename), &matches.free, opts); } else if let Some(filename) = matches.opt_str("bench") { let inp = read_file(&filename); for _ in 0..1000 { let _ = render_html(&inp, opts); } } else { let mut input = String::new(); match io::stdin().read_to_string(&mut input) { Err(why) => panic!("couldn't read from stdin: {}", why), Ok(_) => () } if matches.opt_present("events") { print_events(&input, opts); } else if matches.opt_present("dry-run") { dry_run(&input, opts); } else { print!("{}", render_html(&input, opts)); } } }
render_html
identifier_name
main.rs
// Copyright 2015 Google Inc. All rights reserved. // // 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. //! Command line tool to exercise pulldown-cmark. extern crate getopts; extern crate pulldown_cmark; use pulldown_cmark::Parser; use pulldown_cmark::{Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES}; use pulldown_cmark::html; use std::env; use std::io; use std::io::{Read, Write}; use std::path::Path; use std::fs::File; fn render_html(text: &str, opts: Options) -> String { let mut s = String::with_capacity(text.len() * 3 / 2); let p = Parser::new_ext(&text, opts); html::push_html(&mut s, p); s } fn dry_run(text:&str, opts: Options) { let p = Parser::new_ext(&text, opts); /* let events = p.collect::<Vec<_>>(); let count = events.len(); */ let count = p.count(); println!("{} events", count); } fn print_events(text: &str, opts: Options) { let mut p = Parser::new_ext(&text, opts); loop { print!("{}: ", p.get_offset()); if let Some(event) = p.next() { println!("{:?}", event); } else { break; } } println!("EOF"); } fn read_file(filename: &str) -> String { let path = Path::new(filename); let mut file = match File::open(&path) { Err(why) => panic!("couldn't open {}: {}", path.display(), why), Ok(file) => file }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(why) => panic!("couldn't open {}: {}", path.display(), why), Ok(_) => s } } fn find_test_delim(text: &str) -> Option<usize> { if text.starts_with(".\n") { Some(0) } else { text.find("\n.\n").map(|pos| pos + 1) } } fn run_spec(spec_text: &str, args: &[String], opts: Options) { //println!("spec length={}, args={:?}", spec_text.len(), args); let (first, last) = if args.is_empty() { (None, None) } else { let mut iter = args[0].split(".."); let first = iter.next().and_then(|s| s.parse().ok()); let last = match iter.next() { Some(s) => s.parse().ok(), None => first }; (first, last) }; let mut test_number = 1; let mut tests_failed = 0; let mut tests_run = 0; let mut line_count = 0; let mut tail = spec_text; loop { let rest = match find_test_delim(tail) { Some(pos) => &tail[pos + 2..], None => break }; let (source, rest) = match find_test_delim(rest) { Some(pos) => (&rest[..pos], &rest[pos + 2..]), None => break }; let (html, rest) = match find_test_delim(rest) { Some(pos) => (&rest[.. pos], &rest[pos + 2..]), None => break }; if first.map(|fst| fst <= test_number).unwrap_or(true) && last.map(|lst| test_number <= lst).unwrap_or(true) { if tests_run == 0 || line_count == 0 || (test_number % 10 == 0) { if line_count > 30
else if line_count > 0 { print!(" "); } print!("[{}]", test_number); } else if line_count > 0 && (test_number % 10) == 5 { print!(" "); } let our_html = render_html(&source.replace("→", "\t").replace("\n", "\r\n"), opts); if our_html == html { print!("."); } else { if tests_failed == 0 { print!("FAIL {}:\n---input---\n{}\n---wanted---\n{}\n---got---\n{}", test_number, source, html, our_html); } else { print!("X"); } tests_failed += 1; } let _ = io::stdout().flush(); tests_run += 1; line_count += 1; } tail = rest; test_number += 1; } println!("\n{}/{} tests passed", tests_run - tests_failed, tests_run) } pub fn main() { let args: Vec<_> = env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("d", "dry-run", "dry run, produce no output"); opts.optflag("e", "events", "print event sequence instead of rendering"); opts.optflag("T", "enable-tables", "enable GitHub-style tables"); opts.optflag("F", "enable-footnotes", "enable Hoedown-style footnotes"); opts.optopt("s", "spec", "run tests from spec file", "FILE"); opts.optopt("b", "bench", "run benchmark", "FILE"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()) }; let mut opts = Options::empty(); if matches.opt_present("enable-tables") { opts.insert(OPTION_ENABLE_TABLES); } if matches.opt_present("enable-footnotes") { opts.insert(OPTION_ENABLE_FOOTNOTES); } if let Some(filename) = matches.opt_str("spec") { run_spec(&read_file(&filename), &matches.free, opts); } else if let Some(filename) = matches.opt_str("bench") { let inp = read_file(&filename); for _ in 0..1000 { let _ = render_html(&inp, opts); } } else { let mut input = String::new(); match io::stdin().read_to_string(&mut input) { Err(why) => panic!("couldn't read from stdin: {}", why), Ok(_) => () } if matches.opt_present("events") { print_events(&input, opts); } else if matches.opt_present("dry-run") { dry_run(&input, opts); } else { print!("{}", render_html(&input, opts)); } } }
{ println!(""); line_count = 0; }
conditional_block
main.rs
// Copyright 2015 Google Inc. All rights reserved. // // 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. //! Command line tool to exercise pulldown-cmark. extern crate getopts; extern crate pulldown_cmark; use pulldown_cmark::Parser; use pulldown_cmark::{Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES}; use pulldown_cmark::html; use std::env; use std::io; use std::io::{Read, Write}; use std::path::Path; use std::fs::File; fn render_html(text: &str, opts: Options) -> String { let mut s = String::with_capacity(text.len() * 3 / 2); let p = Parser::new_ext(&text, opts); html::push_html(&mut s, p); s } fn dry_run(text:&str, opts: Options) { let p = Parser::new_ext(&text, opts); /* let events = p.collect::<Vec<_>>(); let count = events.len(); */ let count = p.count(); println!("{} events", count); } fn print_events(text: &str, opts: Options) { let mut p = Parser::new_ext(&text, opts); loop { print!("{}: ", p.get_offset()); if let Some(event) = p.next() { println!("{:?}", event); } else { break; } } println!("EOF"); } fn read_file(filename: &str) -> String { let path = Path::new(filename); let mut file = match File::open(&path) { Err(why) => panic!("couldn't open {}: {}", path.display(), why), Ok(file) => file }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(why) => panic!("couldn't open {}: {}", path.display(), why), Ok(_) => s } } fn find_test_delim(text: &str) -> Option<usize> { if text.starts_with(".\n") { Some(0) } else { text.find("\n.\n").map(|pos| pos + 1) } } fn run_spec(spec_text: &str, args: &[String], opts: Options) { //println!("spec length={}, args={:?}", spec_text.len(), args); let (first, last) = if args.is_empty() { (None, None) } else { let mut iter = args[0].split(".."); let first = iter.next().and_then(|s| s.parse().ok()); let last = match iter.next() { Some(s) => s.parse().ok(), None => first }; (first, last) }; let mut test_number = 1; let mut tests_failed = 0; let mut tests_run = 0; let mut line_count = 0; let mut tail = spec_text; loop { let rest = match find_test_delim(tail) { Some(pos) => &tail[pos + 2..], None => break }; let (source, rest) = match find_test_delim(rest) { Some(pos) => (&rest[..pos], &rest[pos + 2..]), None => break }; let (html, rest) = match find_test_delim(rest) { Some(pos) => (&rest[.. pos], &rest[pos + 2..]), None => break }; if first.map(|fst| fst <= test_number).unwrap_or(true) && last.map(|lst| test_number <= lst).unwrap_or(true) { if tests_run == 0 || line_count == 0 || (test_number % 10 == 0) { if line_count > 30 { println!(""); line_count = 0; } else if line_count > 0 { print!(" "); } print!("[{}]", test_number); } else if line_count > 0 && (test_number % 10) == 5 { print!(" "); } let our_html = render_html(&source.replace("→", "\t").replace("\n", "\r\n"), opts); if our_html == html { print!("."); } else { if tests_failed == 0 { print!("FAIL {}:\n---input---\n{}\n---wanted---\n{}\n---got---\n{}", test_number, source, html, our_html); } else { print!("X"); } tests_failed += 1; } let _ = io::stdout().flush(); tests_run += 1; line_count += 1; } tail = rest; test_number += 1; } println!("\n{}/{} tests passed", tests_run - tests_failed, tests_run) } pub fn main() {
run_spec(&read_file(&filename), &matches.free, opts); } else if let Some(filename) = matches.opt_str("bench") { let inp = read_file(&filename); for _ in 0..1000 { let _ = render_html(&inp, opts); } } else { let mut input = String::new(); match io::stdin().read_to_string(&mut input) { Err(why) => panic!("couldn't read from stdin: {}", why), Ok(_) => () } if matches.opt_present("events") { print_events(&input, opts); } else if matches.opt_present("dry-run") { dry_run(&input, opts); } else { print!("{}", render_html(&input, opts)); } } }
let args: Vec<_> = env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("d", "dry-run", "dry run, produce no output"); opts.optflag("e", "events", "print event sequence instead of rendering"); opts.optflag("T", "enable-tables", "enable GitHub-style tables"); opts.optflag("F", "enable-footnotes", "enable Hoedown-style footnotes"); opts.optopt("s", "spec", "run tests from spec file", "FILE"); opts.optopt("b", "bench", "run benchmark", "FILE"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()) }; let mut opts = Options::empty(); if matches.opt_present("enable-tables") { opts.insert(OPTION_ENABLE_TABLES); } if matches.opt_present("enable-footnotes") { opts.insert(OPTION_ENABLE_FOOTNOTES); } if let Some(filename) = matches.opt_str("spec") {
identifier_body
main.rs
// Copyright 2015 Google Inc. All rights reserved. // // 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. //! Command line tool to exercise pulldown-cmark. extern crate getopts; extern crate pulldown_cmark; use pulldown_cmark::Parser; use pulldown_cmark::{Options, OPTION_ENABLE_TABLES, OPTION_ENABLE_FOOTNOTES}; use pulldown_cmark::html; use std::env; use std::io; use std::io::{Read, Write}; use std::path::Path; use std::fs::File; fn render_html(text: &str, opts: Options) -> String { let mut s = String::with_capacity(text.len() * 3 / 2); let p = Parser::new_ext(&text, opts); html::push_html(&mut s, p); s } fn dry_run(text:&str, opts: Options) { let p = Parser::new_ext(&text, opts); /* let events = p.collect::<Vec<_>>(); let count = events.len(); */ let count = p.count(); println!("{} events", count); } fn print_events(text: &str, opts: Options) { let mut p = Parser::new_ext(&text, opts); loop { print!("{}: ", p.get_offset()); if let Some(event) = p.next() { println!("{:?}", event); } else { break; } } println!("EOF"); } fn read_file(filename: &str) -> String { let path = Path::new(filename); let mut file = match File::open(&path) { Err(why) => panic!("couldn't open {}: {}", path.display(), why), Ok(file) => file }; let mut s = String::new(); match file.read_to_string(&mut s) { Err(why) => panic!("couldn't open {}: {}", path.display(), why), Ok(_) => s } } fn find_test_delim(text: &str) -> Option<usize> { if text.starts_with(".\n") { Some(0) } else { text.find("\n.\n").map(|pos| pos + 1) } } fn run_spec(spec_text: &str, args: &[String], opts: Options) { //println!("spec length={}, args={:?}", spec_text.len(), args); let (first, last) = if args.is_empty() { (None, None) } else { let mut iter = args[0].split(".."); let first = iter.next().and_then(|s| s.parse().ok()); let last = match iter.next() { Some(s) => s.parse().ok(), None => first }; (first, last) }; let mut test_number = 1; let mut tests_failed = 0; let mut tests_run = 0; let mut line_count = 0; let mut tail = spec_text; loop { let rest = match find_test_delim(tail) { Some(pos) => &tail[pos + 2..], None => break }; let (source, rest) = match find_test_delim(rest) { Some(pos) => (&rest[..pos], &rest[pos + 2..]), None => break }; let (html, rest) = match find_test_delim(rest) { Some(pos) => (&rest[.. pos], &rest[pos + 2..]), None => break }; if first.map(|fst| fst <= test_number).unwrap_or(true) && last.map(|lst| test_number <= lst).unwrap_or(true) { if tests_run == 0 || line_count == 0 || (test_number % 10 == 0) { if line_count > 30 { println!(""); line_count = 0; } else if line_count > 0 { print!(" "); } print!("[{}]", test_number); } else if line_count > 0 && (test_number % 10) == 5 { print!(" "); } let our_html = render_html(&source.replace("→", "\t").replace("\n", "\r\n"), opts); if our_html == html { print!("."); } else {
} else { print!("X"); } tests_failed += 1; } let _ = io::stdout().flush(); tests_run += 1; line_count += 1; } tail = rest; test_number += 1; } println!("\n{}/{} tests passed", tests_run - tests_failed, tests_run) } pub fn main() { let args: Vec<_> = env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("d", "dry-run", "dry run, produce no output"); opts.optflag("e", "events", "print event sequence instead of rendering"); opts.optflag("T", "enable-tables", "enable GitHub-style tables"); opts.optflag("F", "enable-footnotes", "enable Hoedown-style footnotes"); opts.optopt("s", "spec", "run tests from spec file", "FILE"); opts.optopt("b", "bench", "run benchmark", "FILE"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()) }; let mut opts = Options::empty(); if matches.opt_present("enable-tables") { opts.insert(OPTION_ENABLE_TABLES); } if matches.opt_present("enable-footnotes") { opts.insert(OPTION_ENABLE_FOOTNOTES); } if let Some(filename) = matches.opt_str("spec") { run_spec(&read_file(&filename), &matches.free, opts); } else if let Some(filename) = matches.opt_str("bench") { let inp = read_file(&filename); for _ in 0..1000 { let _ = render_html(&inp, opts); } } else { let mut input = String::new(); match io::stdin().read_to_string(&mut input) { Err(why) => panic!("couldn't read from stdin: {}", why), Ok(_) => () } if matches.opt_present("events") { print_events(&input, opts); } else if matches.opt_present("dry-run") { dry_run(&input, opts); } else { print!("{}", render_html(&input, opts)); } } }
if tests_failed == 0 { print!("FAIL {}:\n---input---\n{}\n---wanted---\n{}\n---got---\n{}", test_number, source, html, our_html);
random_line_split
chunks.rs
use std::ops::{ Index, IndexMut }; use std::collections::HashMap; use cgmath::{ Point, Point3 }; use super::chunk::Chunk; pub type ChunkPos = Point3<i32>; #[derive(Debug)] pub struct Chunks { chunks: HashMap<ChunkPos, Chunk>, empty: Chunk, } impl Chunks { pub fn new() -> Chunks { Chunks { chunks: HashMap::new(), empty: Chunk::new(), } } pub fn around(dist: u8, center: ChunkPos) -> Vec<ChunkPos> { let mut res = Vec::new(); let dist = dist as i32; for x in -dist + 1..dist { for y in -dist + 1..dist { for z in -dist + 1..dist { let rel = Point3::new(x, y, z); res.push(center + rel.to_vec()); } } } res } } impl Index<ChunkPos> for Chunks { type Output = Chunk; fn index(&self, index: ChunkPos) -> &Chunk { self.chunks.get(&index).unwrap_or(&self.empty) } } impl IndexMut<ChunkPos> for Chunks { fn index_mut(&mut self, index: ChunkPos) -> &mut Chunk
}
{ self.chunks.entry(index).or_insert_with(Chunk::new) }
identifier_body
chunks.rs
use std::ops::{ Index, IndexMut }; use std::collections::HashMap; use cgmath::{ Point, Point3 }; use super::chunk::Chunk; pub type ChunkPos = Point3<i32>; #[derive(Debug)] pub struct Chunks { chunks: HashMap<ChunkPos, Chunk>, empty: Chunk, } impl Chunks { pub fn
() -> Chunks { Chunks { chunks: HashMap::new(), empty: Chunk::new(), } } pub fn around(dist: u8, center: ChunkPos) -> Vec<ChunkPos> { let mut res = Vec::new(); let dist = dist as i32; for x in -dist + 1..dist { for y in -dist + 1..dist { for z in -dist + 1..dist { let rel = Point3::new(x, y, z); res.push(center + rel.to_vec()); } } } res } } impl Index<ChunkPos> for Chunks { type Output = Chunk; fn index(&self, index: ChunkPos) -> &Chunk { self.chunks.get(&index).unwrap_or(&self.empty) } } impl IndexMut<ChunkPos> for Chunks { fn index_mut(&mut self, index: ChunkPos) -> &mut Chunk { self.chunks.entry(index).or_insert_with(Chunk::new) } }
new
identifier_name
chunks.rs
use std::ops::{ Index, IndexMut }; use std::collections::HashMap; use cgmath::{ Point, Point3 }; use super::chunk::Chunk; pub type ChunkPos = Point3<i32>; #[derive(Debug)] pub struct Chunks { chunks: HashMap<ChunkPos, Chunk>, empty: Chunk, }
Chunks { chunks: HashMap::new(), empty: Chunk::new(), } } pub fn around(dist: u8, center: ChunkPos) -> Vec<ChunkPos> { let mut res = Vec::new(); let dist = dist as i32; for x in -dist + 1..dist { for y in -dist + 1..dist { for z in -dist + 1..dist { let rel = Point3::new(x, y, z); res.push(center + rel.to_vec()); } } } res } } impl Index<ChunkPos> for Chunks { type Output = Chunk; fn index(&self, index: ChunkPos) -> &Chunk { self.chunks.get(&index).unwrap_or(&self.empty) } } impl IndexMut<ChunkPos> for Chunks { fn index_mut(&mut self, index: ChunkPos) -> &mut Chunk { self.chunks.entry(index).or_insert_with(Chunk::new) } }
impl Chunks { pub fn new() -> Chunks {
random_line_split
build.rs
use std::env; use std::process::Command; fn main() { if std::env::var("DOCS_RS").is_ok() { // Skip everything when building docs on docs.rs return; } // On Windows Rust always links against release version of MSVC runtime, thus requires Release // build here. let build_type = if cfg!(all(debug_assertions, not(windows))) { "Debug" } else { "Release" }; let out_dir = env::var("OUT_DIR").unwrap(); // Force forward slashes on Windows too so that is plays well with our dumb `Makefile` let mediasoup_out_dir = format!("{}/out", out_dir.replace('\\', "/")); // Add C++ std lib #[cfg(target_os = "linux")] { let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string())) .arg("--print-file-name=libstdc++.a") .output() .expect("Failed to start") .stdout; println!( "cargo:rustc-link-search=native={}", String::from_utf8_lossy(&path) .trim() .strip_suffix("libstdc++.a") .expect("Failed to strip suffix"), ); println!("cargo:rustc-link-lib=static=stdc++"); } #[cfg(any( target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd" ))] { let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string())) .arg("--print-file-name=libc++.a") .output() .expect("Failed to start") .stdout; println!( "cargo:rustc-link-search=native={}", String::from_utf8_lossy(&path) .trim() .strip_suffix("libc++.a") .expect("Failed to strip suffix"), ); println!("cargo:rustc-link-lib=static=c++"); } #[cfg(target_os = "macos")] { let path = Command::new("xcrun") .args(&["--show-sdk-path"]) .output() .expect("Failed to start") .stdout; let libpath = format!( "{}/usr/lib", String::from_utf8(path) .expect("Failed to decode path") .trim() ); println!("cargo:rustc-link-search={}", libpath); println!("cargo:rustc-link-lib=dylib=c++"); println!("cargo:rustc-link-lib=dylib=c++abi"); } #[cfg(target_os = "windows")] { // Nothing special is needed so far } // Build if!Command::new("make") .arg("libmediasoup-worker") .env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir) .env("MEDIASOUP_BUILDTYPE", &build_type) // Force forward slashes on Windows too, otherwise Meson thinks path is not absolute 🤷 .env("INSTALL_DIR", &out_dir.replace('\\', "/")) .spawn() .expect("Failed to start") .wait() .expect("Wasn't running") .success() { panic!("Failed to build libmediasoup-worker") } #[cfg(target_os = "windows")] { let dot_a = format!("{}/libmediasoup-worker.a", out_dir); let dot_lib = format!("{}/mediasoup-worker.lib", out_dir); // Meson builds `libmediasoup-worker.a` on Windows instead of `*.lib` file under MinGW if std::path::Path::new(&dot_a).exists() { std::fs::copy(&dot_a, &dot_lib).unwrap_or_else(|error| { panic!( "Failed to copy static library from {} to {}: {}", dot_a, dot_lib, error ) }); } // These are required by libuv on Windows println!("cargo:rustc-link-lib=psapi"); println!("cargo:rustc-link-lib=user32"); println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=iphlpapi"); println!("cargo:rustc-link-lib=userenv"); println!("cargo:rustc-link-lib=ws2_32"); // These are required by OpenSSL on Windows println!("cargo:rustc-link-lib=ws2_32"); println!("cargo:rustc-link-lib=gdi32"); println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=crypt32"); println!("cargo:rustc-link-lib=user32"); } if env::var("KEEP_BUILD_ARTIFACTS")!= Ok("1".to_string()) {
println!("cargo:rustc-link-lib=static=mediasoup-worker"); println!("cargo:rustc-link-search=native={}", out_dir); }
// Clean if !Command::new("make") .arg("clean-all") .env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir) .spawn() .expect("Failed to start") .wait() .expect("Wasn't running") .success() { panic!("Failed to clean libmediasoup-worker") } }
conditional_block
build.rs
use std::env; use std::process::Command; fn
() { if std::env::var("DOCS_RS").is_ok() { // Skip everything when building docs on docs.rs return; } // On Windows Rust always links against release version of MSVC runtime, thus requires Release // build here. let build_type = if cfg!(all(debug_assertions, not(windows))) { "Debug" } else { "Release" }; let out_dir = env::var("OUT_DIR").unwrap(); // Force forward slashes on Windows too so that is plays well with our dumb `Makefile` let mediasoup_out_dir = format!("{}/out", out_dir.replace('\\', "/")); // Add C++ std lib #[cfg(target_os = "linux")] { let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string())) .arg("--print-file-name=libstdc++.a") .output() .expect("Failed to start") .stdout; println!( "cargo:rustc-link-search=native={}", String::from_utf8_lossy(&path) .trim() .strip_suffix("libstdc++.a") .expect("Failed to strip suffix"), ); println!("cargo:rustc-link-lib=static=stdc++"); } #[cfg(any( target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd" ))] { let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string())) .arg("--print-file-name=libc++.a") .output() .expect("Failed to start") .stdout; println!( "cargo:rustc-link-search=native={}", String::from_utf8_lossy(&path) .trim() .strip_suffix("libc++.a") .expect("Failed to strip suffix"), ); println!("cargo:rustc-link-lib=static=c++"); } #[cfg(target_os = "macos")] { let path = Command::new("xcrun") .args(&["--show-sdk-path"]) .output() .expect("Failed to start") .stdout; let libpath = format!( "{}/usr/lib", String::from_utf8(path) .expect("Failed to decode path") .trim() ); println!("cargo:rustc-link-search={}", libpath); println!("cargo:rustc-link-lib=dylib=c++"); println!("cargo:rustc-link-lib=dylib=c++abi"); } #[cfg(target_os = "windows")] { // Nothing special is needed so far } // Build if!Command::new("make") .arg("libmediasoup-worker") .env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir) .env("MEDIASOUP_BUILDTYPE", &build_type) // Force forward slashes on Windows too, otherwise Meson thinks path is not absolute 🤷 .env("INSTALL_DIR", &out_dir.replace('\\', "/")) .spawn() .expect("Failed to start") .wait() .expect("Wasn't running") .success() { panic!("Failed to build libmediasoup-worker") } #[cfg(target_os = "windows")] { let dot_a = format!("{}/libmediasoup-worker.a", out_dir); let dot_lib = format!("{}/mediasoup-worker.lib", out_dir); // Meson builds `libmediasoup-worker.a` on Windows instead of `*.lib` file under MinGW if std::path::Path::new(&dot_a).exists() { std::fs::copy(&dot_a, &dot_lib).unwrap_or_else(|error| { panic!( "Failed to copy static library from {} to {}: {}", dot_a, dot_lib, error ) }); } // These are required by libuv on Windows println!("cargo:rustc-link-lib=psapi"); println!("cargo:rustc-link-lib=user32"); println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=iphlpapi"); println!("cargo:rustc-link-lib=userenv"); println!("cargo:rustc-link-lib=ws2_32"); // These are required by OpenSSL on Windows println!("cargo:rustc-link-lib=ws2_32"); println!("cargo:rustc-link-lib=gdi32"); println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=crypt32"); println!("cargo:rustc-link-lib=user32"); } if env::var("KEEP_BUILD_ARTIFACTS")!= Ok("1".to_string()) { // Clean if!Command::new("make") .arg("clean-all") .env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir) .spawn() .expect("Failed to start") .wait() .expect("Wasn't running") .success() { panic!("Failed to clean libmediasoup-worker") } } println!("cargo:rustc-link-lib=static=mediasoup-worker"); println!("cargo:rustc-link-search=native={}", out_dir); }
main
identifier_name
build.rs
use std::env; use std::process::Command; fn main()
{ let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string())) .arg("--print-file-name=libstdc++.a") .output() .expect("Failed to start") .stdout; println!( "cargo:rustc-link-search=native={}", String::from_utf8_lossy(&path) .trim() .strip_suffix("libstdc++.a") .expect("Failed to strip suffix"), ); println!("cargo:rustc-link-lib=static=stdc++"); } #[cfg(any( target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd" ))] { let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string())) .arg("--print-file-name=libc++.a") .output() .expect("Failed to start") .stdout; println!( "cargo:rustc-link-search=native={}", String::from_utf8_lossy(&path) .trim() .strip_suffix("libc++.a") .expect("Failed to strip suffix"), ); println!("cargo:rustc-link-lib=static=c++"); } #[cfg(target_os = "macos")] { let path = Command::new("xcrun") .args(&["--show-sdk-path"]) .output() .expect("Failed to start") .stdout; let libpath = format!( "{}/usr/lib", String::from_utf8(path) .expect("Failed to decode path") .trim() ); println!("cargo:rustc-link-search={}", libpath); println!("cargo:rustc-link-lib=dylib=c++"); println!("cargo:rustc-link-lib=dylib=c++abi"); } #[cfg(target_os = "windows")] { // Nothing special is needed so far } // Build if!Command::new("make") .arg("libmediasoup-worker") .env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir) .env("MEDIASOUP_BUILDTYPE", &build_type) // Force forward slashes on Windows too, otherwise Meson thinks path is not absolute 🤷 .env("INSTALL_DIR", &out_dir.replace('\\', "/")) .spawn() .expect("Failed to start") .wait() .expect("Wasn't running") .success() { panic!("Failed to build libmediasoup-worker") } #[cfg(target_os = "windows")] { let dot_a = format!("{}/libmediasoup-worker.a", out_dir); let dot_lib = format!("{}/mediasoup-worker.lib", out_dir); // Meson builds `libmediasoup-worker.a` on Windows instead of `*.lib` file under MinGW if std::path::Path::new(&dot_a).exists() { std::fs::copy(&dot_a, &dot_lib).unwrap_or_else(|error| { panic!( "Failed to copy static library from {} to {}: {}", dot_a, dot_lib, error ) }); } // These are required by libuv on Windows println!("cargo:rustc-link-lib=psapi"); println!("cargo:rustc-link-lib=user32"); println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=iphlpapi"); println!("cargo:rustc-link-lib=userenv"); println!("cargo:rustc-link-lib=ws2_32"); // These are required by OpenSSL on Windows println!("cargo:rustc-link-lib=ws2_32"); println!("cargo:rustc-link-lib=gdi32"); println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=crypt32"); println!("cargo:rustc-link-lib=user32"); } if env::var("KEEP_BUILD_ARTIFACTS")!= Ok("1".to_string()) { // Clean if!Command::new("make") .arg("clean-all") .env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir) .spawn() .expect("Failed to start") .wait() .expect("Wasn't running") .success() { panic!("Failed to clean libmediasoup-worker") } } println!("cargo:rustc-link-lib=static=mediasoup-worker"); println!("cargo:rustc-link-search=native={}", out_dir); }
{ if std::env::var("DOCS_RS").is_ok() { // Skip everything when building docs on docs.rs return; } // On Windows Rust always links against release version of MSVC runtime, thus requires Release // build here. let build_type = if cfg!(all(debug_assertions, not(windows))) { "Debug" } else { "Release" }; let out_dir = env::var("OUT_DIR").unwrap(); // Force forward slashes on Windows too so that is plays well with our dumb `Makefile` let mediasoup_out_dir = format!("{}/out", out_dir.replace('\\', "/")); // Add C++ std lib #[cfg(target_os = "linux")]
identifier_body
build.rs
use std::env;
fn main() { if std::env::var("DOCS_RS").is_ok() { // Skip everything when building docs on docs.rs return; } // On Windows Rust always links against release version of MSVC runtime, thus requires Release // build here. let build_type = if cfg!(all(debug_assertions, not(windows))) { "Debug" } else { "Release" }; let out_dir = env::var("OUT_DIR").unwrap(); // Force forward slashes on Windows too so that is plays well with our dumb `Makefile` let mediasoup_out_dir = format!("{}/out", out_dir.replace('\\', "/")); // Add C++ std lib #[cfg(target_os = "linux")] { let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string())) .arg("--print-file-name=libstdc++.a") .output() .expect("Failed to start") .stdout; println!( "cargo:rustc-link-search=native={}", String::from_utf8_lossy(&path) .trim() .strip_suffix("libstdc++.a") .expect("Failed to strip suffix"), ); println!("cargo:rustc-link-lib=static=stdc++"); } #[cfg(any( target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd" ))] { let path = Command::new(env::var("CXX").unwrap_or_else(|_| "c++".to_string())) .arg("--print-file-name=libc++.a") .output() .expect("Failed to start") .stdout; println!( "cargo:rustc-link-search=native={}", String::from_utf8_lossy(&path) .trim() .strip_suffix("libc++.a") .expect("Failed to strip suffix"), ); println!("cargo:rustc-link-lib=static=c++"); } #[cfg(target_os = "macos")] { let path = Command::new("xcrun") .args(&["--show-sdk-path"]) .output() .expect("Failed to start") .stdout; let libpath = format!( "{}/usr/lib", String::from_utf8(path) .expect("Failed to decode path") .trim() ); println!("cargo:rustc-link-search={}", libpath); println!("cargo:rustc-link-lib=dylib=c++"); println!("cargo:rustc-link-lib=dylib=c++abi"); } #[cfg(target_os = "windows")] { // Nothing special is needed so far } // Build if!Command::new("make") .arg("libmediasoup-worker") .env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir) .env("MEDIASOUP_BUILDTYPE", &build_type) // Force forward slashes on Windows too, otherwise Meson thinks path is not absolute 🤷 .env("INSTALL_DIR", &out_dir.replace('\\', "/")) .spawn() .expect("Failed to start") .wait() .expect("Wasn't running") .success() { panic!("Failed to build libmediasoup-worker") } #[cfg(target_os = "windows")] { let dot_a = format!("{}/libmediasoup-worker.a", out_dir); let dot_lib = format!("{}/mediasoup-worker.lib", out_dir); // Meson builds `libmediasoup-worker.a` on Windows instead of `*.lib` file under MinGW if std::path::Path::new(&dot_a).exists() { std::fs::copy(&dot_a, &dot_lib).unwrap_or_else(|error| { panic!( "Failed to copy static library from {} to {}: {}", dot_a, dot_lib, error ) }); } // These are required by libuv on Windows println!("cargo:rustc-link-lib=psapi"); println!("cargo:rustc-link-lib=user32"); println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=iphlpapi"); println!("cargo:rustc-link-lib=userenv"); println!("cargo:rustc-link-lib=ws2_32"); // These are required by OpenSSL on Windows println!("cargo:rustc-link-lib=ws2_32"); println!("cargo:rustc-link-lib=gdi32"); println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=crypt32"); println!("cargo:rustc-link-lib=user32"); } if env::var("KEEP_BUILD_ARTIFACTS")!= Ok("1".to_string()) { // Clean if!Command::new("make") .arg("clean-all") .env("MEDIASOUP_OUT_DIR", &mediasoup_out_dir) .spawn() .expect("Failed to start") .wait() .expect("Wasn't running") .success() { panic!("Failed to clean libmediasoup-worker") } } println!("cargo:rustc-link-lib=static=mediasoup-worker"); println!("cargo:rustc-link-search=native={}", out_dir); }
use std::process::Command;
random_line_split
config.rs
// Copyright 2020 The Exonum Team // // 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 exonum::runtime::{CoreError, ErrorMatch, ExecutionError, InstanceId, SUPERVISOR_INSTANCE_ID}; use exonum_supervisor::{ConfigPropose, Supervisor, SupervisorInterface}; use exonum_testkit::{ApiKind, Spec, TestKit, TestKitBuilder}; use exonum_time::{MockTimeProvider, TimeServiceFactory}; use std::time::SystemTime; use exonum_timestamping::{Config, TimestampingService}; const TIME_SERVICE_ID: InstanceId = 102; const TIME_SERVICE_NAME: &str = "time"; const SERVICE_ID: InstanceId = 103; const SERVICE_NAME: &str = "timestamping"; const SECOND_TIME_SERVICE_ID: InstanceId = 104; const SECOND_TIME_SERVICE_NAME: &str = "time2"; fn init_testkit(second_time_service: bool) -> (TestKit, MockTimeProvider)
.build(); (testkit, mock_provider) } /// Creates block with `ConfigPropose` tx and returns `Result` with new /// configuration or corresponding `ExecutionError`. async fn propose_configuration( testkit: &mut TestKit, config: Config, ) -> Result<(), ExecutionError> { let tx = ConfigPropose::immediate(0).service_config(SERVICE_ID, config.clone()); let keypair = testkit.network().us().service_keypair(); let tx = keypair.propose_config_change(SUPERVISOR_INSTANCE_ID, tx); let block = testkit.create_block_with_transaction(tx); if let Err(e) = block[0].status() { return Err(e.clone()); } let new_config: Config = testkit .api() .public(ApiKind::Service(SERVICE_NAME)) .get("v1/timestamps/config") .await .expect("Failed to get service configuration"); assert_eq!(config.time_service_name, new_config.time_service_name); Ok(()) } #[tokio::test] async fn test_propose_configuration() { let (mut testkit, _) = init_testkit(true); let config = Config { time_service_name: SECOND_TIME_SERVICE_NAME.to_string(), }; // Propose valid configuration. propose_configuration(&mut testkit, config) .await .expect("Configuration proposal failed."); } #[tokio::test] async fn test_propose_invalid_configuration() { let (mut testkit, _) = init_testkit(false); let incorrect_names = vec!["", " ", "illegal.illegal", "not_service", SERVICE_NAME]; for name in incorrect_names { let config = Config { time_service_name: name.to_string(), }; // Propose configuration with invalid time service name. let err = propose_configuration(&mut testkit, config) .await .expect_err("Configuration proposal should fail."); let expected_err = ErrorMatch::from_fail(&CoreError::IncorrectInstanceId).with_any_description(); assert_eq!(err, expected_err); } }
{ let mock_provider = MockTimeProvider::new(SystemTime::now().into()); let time_service = TimeServiceFactory::with_provider(mock_provider.clone()); let mut time_service = Spec::new(time_service).with_instance(TIME_SERVICE_ID, TIME_SERVICE_NAME, ()); if second_time_service { time_service = time_service.with_instance(SECOND_TIME_SERVICE_ID, SECOND_TIME_SERVICE_NAME, ()); } let config = Config { time_service_name: TIME_SERVICE_NAME.to_owned(), }; let timestamping = Spec::new(TimestampingService).with_instance(SERVICE_ID, SERVICE_NAME, config); let testkit = TestKitBuilder::validator() .with(Supervisor::simple()) .with(time_service) .with(timestamping)
identifier_body
config.rs
// Copyright 2020 The Exonum Team // // 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 exonum::runtime::{CoreError, ErrorMatch, ExecutionError, InstanceId, SUPERVISOR_INSTANCE_ID}; use exonum_supervisor::{ConfigPropose, Supervisor, SupervisorInterface}; use exonum_testkit::{ApiKind, Spec, TestKit, TestKitBuilder}; use exonum_time::{MockTimeProvider, TimeServiceFactory}; use std::time::SystemTime; use exonum_timestamping::{Config, TimestampingService}; const TIME_SERVICE_ID: InstanceId = 102; const TIME_SERVICE_NAME: &str = "time"; const SERVICE_ID: InstanceId = 103; const SERVICE_NAME: &str = "timestamping"; const SECOND_TIME_SERVICE_ID: InstanceId = 104; const SECOND_TIME_SERVICE_NAME: &str = "time2"; fn
(second_time_service: bool) -> (TestKit, MockTimeProvider) { let mock_provider = MockTimeProvider::new(SystemTime::now().into()); let time_service = TimeServiceFactory::with_provider(mock_provider.clone()); let mut time_service = Spec::new(time_service).with_instance(TIME_SERVICE_ID, TIME_SERVICE_NAME, ()); if second_time_service { time_service = time_service.with_instance(SECOND_TIME_SERVICE_ID, SECOND_TIME_SERVICE_NAME, ()); } let config = Config { time_service_name: TIME_SERVICE_NAME.to_owned(), }; let timestamping = Spec::new(TimestampingService).with_instance(SERVICE_ID, SERVICE_NAME, config); let testkit = TestKitBuilder::validator() .with(Supervisor::simple()) .with(time_service) .with(timestamping) .build(); (testkit, mock_provider) } /// Creates block with `ConfigPropose` tx and returns `Result` with new /// configuration or corresponding `ExecutionError`. async fn propose_configuration( testkit: &mut TestKit, config: Config, ) -> Result<(), ExecutionError> { let tx = ConfigPropose::immediate(0).service_config(SERVICE_ID, config.clone()); let keypair = testkit.network().us().service_keypair(); let tx = keypair.propose_config_change(SUPERVISOR_INSTANCE_ID, tx); let block = testkit.create_block_with_transaction(tx); if let Err(e) = block[0].status() { return Err(e.clone()); } let new_config: Config = testkit .api() .public(ApiKind::Service(SERVICE_NAME)) .get("v1/timestamps/config") .await .expect("Failed to get service configuration"); assert_eq!(config.time_service_name, new_config.time_service_name); Ok(()) } #[tokio::test] async fn test_propose_configuration() { let (mut testkit, _) = init_testkit(true); let config = Config { time_service_name: SECOND_TIME_SERVICE_NAME.to_string(), }; // Propose valid configuration. propose_configuration(&mut testkit, config) .await .expect("Configuration proposal failed."); } #[tokio::test] async fn test_propose_invalid_configuration() { let (mut testkit, _) = init_testkit(false); let incorrect_names = vec!["", " ", "illegal.illegal", "not_service", SERVICE_NAME]; for name in incorrect_names { let config = Config { time_service_name: name.to_string(), }; // Propose configuration with invalid time service name. let err = propose_configuration(&mut testkit, config) .await .expect_err("Configuration proposal should fail."); let expected_err = ErrorMatch::from_fail(&CoreError::IncorrectInstanceId).with_any_description(); assert_eq!(err, expected_err); } }
init_testkit
identifier_name
config.rs
// Copyright 2020 The Exonum Team // // 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 exonum::runtime::{CoreError, ErrorMatch, ExecutionError, InstanceId, SUPERVISOR_INSTANCE_ID}; use exonum_supervisor::{ConfigPropose, Supervisor, SupervisorInterface}; use exonum_testkit::{ApiKind, Spec, TestKit, TestKitBuilder}; use exonum_time::{MockTimeProvider, TimeServiceFactory}; use std::time::SystemTime; use exonum_timestamping::{Config, TimestampingService}; const TIME_SERVICE_ID: InstanceId = 102; const TIME_SERVICE_NAME: &str = "time"; const SERVICE_ID: InstanceId = 103; const SERVICE_NAME: &str = "timestamping"; const SECOND_TIME_SERVICE_ID: InstanceId = 104; const SECOND_TIME_SERVICE_NAME: &str = "time2"; fn init_testkit(second_time_service: bool) -> (TestKit, MockTimeProvider) { let mock_provider = MockTimeProvider::new(SystemTime::now().into()); let time_service = TimeServiceFactory::with_provider(mock_provider.clone()); let mut time_service = Spec::new(time_service).with_instance(TIME_SERVICE_ID, TIME_SERVICE_NAME, ()); if second_time_service { time_service = time_service.with_instance(SECOND_TIME_SERVICE_ID, SECOND_TIME_SERVICE_NAME, ()); } let config = Config { time_service_name: TIME_SERVICE_NAME.to_owned(), }; let timestamping = Spec::new(TimestampingService).with_instance(SERVICE_ID, SERVICE_NAME, config); let testkit = TestKitBuilder::validator() .with(Supervisor::simple()) .with(time_service) .with(timestamping) .build(); (testkit, mock_provider) } /// Creates block with `ConfigPropose` tx and returns `Result` with new /// configuration or corresponding `ExecutionError`. async fn propose_configuration( testkit: &mut TestKit, config: Config, ) -> Result<(), ExecutionError> { let tx = ConfigPropose::immediate(0).service_config(SERVICE_ID, config.clone()); let keypair = testkit.network().us().service_keypair(); let tx = keypair.propose_config_change(SUPERVISOR_INSTANCE_ID, tx); let block = testkit.create_block_with_transaction(tx); if let Err(e) = block[0].status() { return Err(e.clone()); } let new_config: Config = testkit .api() .public(ApiKind::Service(SERVICE_NAME)) .get("v1/timestamps/config") .await .expect("Failed to get service configuration"); assert_eq!(config.time_service_name, new_config.time_service_name); Ok(()) } #[tokio::test] async fn test_propose_configuration() { let (mut testkit, _) = init_testkit(true); let config = Config { time_service_name: SECOND_TIME_SERVICE_NAME.to_string(), }; // Propose valid configuration. propose_configuration(&mut testkit, config) .await .expect("Configuration proposal failed."); } #[tokio::test] async fn test_propose_invalid_configuration() { let (mut testkit, _) = init_testkit(false); let incorrect_names = vec!["", " ", "illegal.illegal", "not_service", SERVICE_NAME]; for name in incorrect_names { let config = Config { time_service_name: name.to_string(), };
// Propose configuration with invalid time service name. let err = propose_configuration(&mut testkit, config) .await .expect_err("Configuration proposal should fail."); let expected_err = ErrorMatch::from_fail(&CoreError::IncorrectInstanceId).with_any_description(); assert_eq!(err, expected_err); } }
random_line_split
config.rs
// Copyright 2020 The Exonum Team // // 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 exonum::runtime::{CoreError, ErrorMatch, ExecutionError, InstanceId, SUPERVISOR_INSTANCE_ID}; use exonum_supervisor::{ConfigPropose, Supervisor, SupervisorInterface}; use exonum_testkit::{ApiKind, Spec, TestKit, TestKitBuilder}; use exonum_time::{MockTimeProvider, TimeServiceFactory}; use std::time::SystemTime; use exonum_timestamping::{Config, TimestampingService}; const TIME_SERVICE_ID: InstanceId = 102; const TIME_SERVICE_NAME: &str = "time"; const SERVICE_ID: InstanceId = 103; const SERVICE_NAME: &str = "timestamping"; const SECOND_TIME_SERVICE_ID: InstanceId = 104; const SECOND_TIME_SERVICE_NAME: &str = "time2"; fn init_testkit(second_time_service: bool) -> (TestKit, MockTimeProvider) { let mock_provider = MockTimeProvider::new(SystemTime::now().into()); let time_service = TimeServiceFactory::with_provider(mock_provider.clone()); let mut time_service = Spec::new(time_service).with_instance(TIME_SERVICE_ID, TIME_SERVICE_NAME, ()); if second_time_service
let config = Config { time_service_name: TIME_SERVICE_NAME.to_owned(), }; let timestamping = Spec::new(TimestampingService).with_instance(SERVICE_ID, SERVICE_NAME, config); let testkit = TestKitBuilder::validator() .with(Supervisor::simple()) .with(time_service) .with(timestamping) .build(); (testkit, mock_provider) } /// Creates block with `ConfigPropose` tx and returns `Result` with new /// configuration or corresponding `ExecutionError`. async fn propose_configuration( testkit: &mut TestKit, config: Config, ) -> Result<(), ExecutionError> { let tx = ConfigPropose::immediate(0).service_config(SERVICE_ID, config.clone()); let keypair = testkit.network().us().service_keypair(); let tx = keypair.propose_config_change(SUPERVISOR_INSTANCE_ID, tx); let block = testkit.create_block_with_transaction(tx); if let Err(e) = block[0].status() { return Err(e.clone()); } let new_config: Config = testkit .api() .public(ApiKind::Service(SERVICE_NAME)) .get("v1/timestamps/config") .await .expect("Failed to get service configuration"); assert_eq!(config.time_service_name, new_config.time_service_name); Ok(()) } #[tokio::test] async fn test_propose_configuration() { let (mut testkit, _) = init_testkit(true); let config = Config { time_service_name: SECOND_TIME_SERVICE_NAME.to_string(), }; // Propose valid configuration. propose_configuration(&mut testkit, config) .await .expect("Configuration proposal failed."); } #[tokio::test] async fn test_propose_invalid_configuration() { let (mut testkit, _) = init_testkit(false); let incorrect_names = vec!["", " ", "illegal.illegal", "not_service", SERVICE_NAME]; for name in incorrect_names { let config = Config { time_service_name: name.to_string(), }; // Propose configuration with invalid time service name. let err = propose_configuration(&mut testkit, config) .await .expect_err("Configuration proposal should fail."); let expected_err = ErrorMatch::from_fail(&CoreError::IncorrectInstanceId).with_any_description(); assert_eq!(err, expected_err); } }
{ time_service = time_service.with_instance(SECOND_TIME_SERVICE_ID, SECOND_TIME_SERVICE_NAME, ()); }
conditional_block
regex.rs
#![allow(unused)] #![warn(clippy::invalid_regex, clippy::trivial_regex)] extern crate regex; use regex::bytes::{Regex as BRegex, RegexBuilder as BRegexBuilder, RegexSet as BRegexSet}; use regex::{Regex, RegexBuilder, RegexSet}; const OPENING_PAREN: &str = "("; const NOT_A_REAL_REGEX: &str = "foobar"; fn syntax_error() { let pipe_in_wrong_position = Regex::new("|"); let pipe_in_wrong_position_builder = RegexBuilder::new("|"); let wrong_char_ranice = Regex::new("[z-a]"); let some_unicode = Regex::new("[é-è]"); let some_regex = Regex::new(OPENING_PAREN); let binary_pipe_in_wrong_position = BRegex::new("|"); let some_binary_regex = BRegex::new(OPENING_PAREN); let some_binary_regex_builder = BRegexBuilder::new(OPENING_PAREN); let closing_paren = ")"; let not_linted = Regex::new(closing_paren); let set = RegexSet::new(&[r"[a-z]+@[a-z]+\.(com|org|net)", r"[a-z]+\.(com|org|net)"]); let bset = BRegexSet::new(&[ r"[a-z]+@[a-z]+\.(com|org|net)", r"[a-z]+\.(com|org|net)", r".", // regression test ]); let set_error = RegexSet::new(&[OPENING_PAREN, r"[a-z]+\.(com|org|net)"]); let bset_error = BRegexSet::new(&[OPENING_PAREN, r"[a-z]+\.(com|org|net)"]); let raw_string_error = Regex::new(r"[...\/...]"); let raw_string_error = Regex::new(r#"[...\/...]"#); } fn trivial_regex() { let trivial_eq = Regex::new("^foobar$"); let trivial_eq_builder = RegexBuilder::new("^foobar$"); let trivial_starts_with = Regex::new("^foobar"); let trivial_ends_with = Regex::new("foobar$"); let trivial_contains = Regex::new("foobar"); let trivial_contains = Regex::new(NOT_A_REAL_REGEX); let trivial_backslash = Regex::new("a\\.b"); // unlikely corner cases let trivial_empty = Regex::new(""); let trivial_empty = Regex::new("^"); let trivial_empty = Regex::new("^$"); let binary_trivial_empty = BRegex::new("^$"); // non-trivial regexes let non_trivial_dot = Regex::new("a.b"); let non_trivial_dot_builder = RegexBuilder::new("a.b"); let non_trivial_eq = Regex::new("^foo|bar$"); let non_trivial_starts_with = Regex::new("^foo|bar"); let non_trivial_ends_with = Regex::new("^foo|bar"); let non_trivial_ends_with = Regex::new("foo|bar"); let non_trivial_binary = BRegex::new("foo|bar"); let non_trivial_binary_builder = BRegexBuilder::new("foo|bar"); // #6005: unicode classes in bytes::Regex let a_byte_of_unicode = BRegex::new(r"\p{C}"); } fn ma
{ syntax_error(); trivial_regex(); }
in()
identifier_name
regex.rs
#![allow(unused)] #![warn(clippy::invalid_regex, clippy::trivial_regex)] extern crate regex; use regex::bytes::{Regex as BRegex, RegexBuilder as BRegexBuilder, RegexSet as BRegexSet}; use regex::{Regex, RegexBuilder, RegexSet}; const OPENING_PAREN: &str = "("; const NOT_A_REAL_REGEX: &str = "foobar"; fn syntax_error() { let pipe_in_wrong_position = Regex::new("|"); let pipe_in_wrong_position_builder = RegexBuilder::new("|"); let wrong_char_ranice = Regex::new("[z-a]"); let some_unicode = Regex::new("[é-è]"); let some_regex = Regex::new(OPENING_PAREN); let binary_pipe_in_wrong_position = BRegex::new("|"); let some_binary_regex = BRegex::new(OPENING_PAREN); let some_binary_regex_builder = BRegexBuilder::new(OPENING_PAREN); let closing_paren = ")"; let not_linted = Regex::new(closing_paren); let set = RegexSet::new(&[r"[a-z]+@[a-z]+\.(com|org|net)", r"[a-z]+\.(com|org|net)"]); let bset = BRegexSet::new(&[ r"[a-z]+@[a-z]+\.(com|org|net)", r"[a-z]+\.(com|org|net)", r".", // regression test ]); let set_error = RegexSet::new(&[OPENING_PAREN, r"[a-z]+\.(com|org|net)"]); let bset_error = BRegexSet::new(&[OPENING_PAREN, r"[a-z]+\.(com|org|net)"]); let raw_string_error = Regex::new(r"[...\/...]"); let raw_string_error = Regex::new(r#"[...\/...]"#); }
let trivial_eq_builder = RegexBuilder::new("^foobar$"); let trivial_starts_with = Regex::new("^foobar"); let trivial_ends_with = Regex::new("foobar$"); let trivial_contains = Regex::new("foobar"); let trivial_contains = Regex::new(NOT_A_REAL_REGEX); let trivial_backslash = Regex::new("a\\.b"); // unlikely corner cases let trivial_empty = Regex::new(""); let trivial_empty = Regex::new("^"); let trivial_empty = Regex::new("^$"); let binary_trivial_empty = BRegex::new("^$"); // non-trivial regexes let non_trivial_dot = Regex::new("a.b"); let non_trivial_dot_builder = RegexBuilder::new("a.b"); let non_trivial_eq = Regex::new("^foo|bar$"); let non_trivial_starts_with = Regex::new("^foo|bar"); let non_trivial_ends_with = Regex::new("^foo|bar"); let non_trivial_ends_with = Regex::new("foo|bar"); let non_trivial_binary = BRegex::new("foo|bar"); let non_trivial_binary_builder = BRegexBuilder::new("foo|bar"); // #6005: unicode classes in bytes::Regex let a_byte_of_unicode = BRegex::new(r"\p{C}"); } fn main() { syntax_error(); trivial_regex(); }
fn trivial_regex() { let trivial_eq = Regex::new("^foobar$");
random_line_split
regex.rs
#![allow(unused)] #![warn(clippy::invalid_regex, clippy::trivial_regex)] extern crate regex; use regex::bytes::{Regex as BRegex, RegexBuilder as BRegexBuilder, RegexSet as BRegexSet}; use regex::{Regex, RegexBuilder, RegexSet}; const OPENING_PAREN: &str = "("; const NOT_A_REAL_REGEX: &str = "foobar"; fn syntax_error()
]); let set_error = RegexSet::new(&[OPENING_PAREN, r"[a-z]+\.(com|org|net)"]); let bset_error = BRegexSet::new(&[OPENING_PAREN, r"[a-z]+\.(com|org|net)"]); let raw_string_error = Regex::new(r"[...\/...]"); let raw_string_error = Regex::new(r#"[...\/...]"#); } fn trivial_regex() { let trivial_eq = Regex::new("^foobar$"); let trivial_eq_builder = RegexBuilder::new("^foobar$"); let trivial_starts_with = Regex::new("^foobar"); let trivial_ends_with = Regex::new("foobar$"); let trivial_contains = Regex::new("foobar"); let trivial_contains = Regex::new(NOT_A_REAL_REGEX); let trivial_backslash = Regex::new("a\\.b"); // unlikely corner cases let trivial_empty = Regex::new(""); let trivial_empty = Regex::new("^"); let trivial_empty = Regex::new("^$"); let binary_trivial_empty = BRegex::new("^$"); // non-trivial regexes let non_trivial_dot = Regex::new("a.b"); let non_trivial_dot_builder = RegexBuilder::new("a.b"); let non_trivial_eq = Regex::new("^foo|bar$"); let non_trivial_starts_with = Regex::new("^foo|bar"); let non_trivial_ends_with = Regex::new("^foo|bar"); let non_trivial_ends_with = Regex::new("foo|bar"); let non_trivial_binary = BRegex::new("foo|bar"); let non_trivial_binary_builder = BRegexBuilder::new("foo|bar"); // #6005: unicode classes in bytes::Regex let a_byte_of_unicode = BRegex::new(r"\p{C}"); } fn main() { syntax_error(); trivial_regex(); }
{ let pipe_in_wrong_position = Regex::new("|"); let pipe_in_wrong_position_builder = RegexBuilder::new("|"); let wrong_char_ranice = Regex::new("[z-a]"); let some_unicode = Regex::new("[é-è]"); let some_regex = Regex::new(OPENING_PAREN); let binary_pipe_in_wrong_position = BRegex::new("|"); let some_binary_regex = BRegex::new(OPENING_PAREN); let some_binary_regex_builder = BRegexBuilder::new(OPENING_PAREN); let closing_paren = ")"; let not_linted = Regex::new(closing_paren); let set = RegexSet::new(&[r"[a-z]+@[a-z]+\.(com|org|net)", r"[a-z]+\.(com|org|net)"]); let bset = BRegexSet::new(&[ r"[a-z]+@[a-z]+\.(com|org|net)", r"[a-z]+\.(com|org|net)", r".", // regression test
identifier_body
htmlstyleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use script_layout_interface::message::Msg; use std::sync::Arc; use string_cache::Atom; use style::media_queries::parse_media_query_list; use style::parser::ParserContextExtraData; use style::stylesheets::{Stylesheet, Origin}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>, } impl HTMLStyleElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let win = window_from_node(node); let url = win.get_url(); let mq_attribute = element.get_attribute(&ns!(), &atom!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let mut sheet = Stylesheet::from_str(&data, url, Origin::Author, win.css_error_reporter(), ParserContextExtraData::default()); let mut css_parser = CssParser::new(&mq_str); let media = parse_media_query_list(&mut css_parser); sheet.set_media(Some(media)); let sheet = Arc::new(sheet); win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap(); *self.stylesheet.borrow_mut() = Some(sheet); let doc = document_from_node(self); doc.invalidate_stylesheets(); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } } impl VirtualMethods for HTMLStyleElement {
fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { self.parse_own_css(); } } }
random_line_split
htmlstyleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use script_layout_interface::message::Msg; use std::sync::Arc; use string_cache::Atom; use style::media_queries::parse_media_query_list; use style::parser::ParserContextExtraData; use style::stylesheets::{Stylesheet, Origin}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>, } impl HTMLStyleElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let win = window_from_node(node); let url = win.get_url(); let mq_attribute = element.get_attribute(&ns!(), &atom!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let mut sheet = Stylesheet::from_str(&data, url, Origin::Author, win.css_error_reporter(), ParserContextExtraData::default()); let mut css_parser = CssParser::new(&mq_str); let media = parse_media_query_list(&mut css_parser); sheet.set_media(Some(media)); let sheet = Arc::new(sheet); win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap(); *self.stylesheet.borrow_mut() = Some(sheet); let doc = document_from_node(self); doc.invalidate_stylesheets(); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type()
if tree_in_doc { self.parse_own_css(); } } }
{ s.bind_to_tree(tree_in_doc); }
conditional_block
htmlstyleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use script_layout_interface::message::Msg; use std::sync::Arc; use string_cache::Atom; use style::media_queries::parse_media_query_list; use style::parser::ParserContextExtraData; use style::stylesheets::{Stylesheet, Origin}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>, } impl HTMLStyleElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLStyleElement
#[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let win = window_from_node(node); let url = win.get_url(); let mq_attribute = element.get_attribute(&ns!(), &atom!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let mut sheet = Stylesheet::from_str(&data, url, Origin::Author, win.css_error_reporter(), ParserContextExtraData::default()); let mut css_parser = CssParser::new(&mq_str); let media = parse_media_query_list(&mut css_parser); sheet.set_media(Some(media)); let sheet = Arc::new(sheet); win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap(); *self.stylesheet.borrow_mut() = Some(sheet); let doc = document_from_node(self); doc.invalidate_stylesheets(); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { self.parse_own_css(); } } }
{ HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DOMRefCell::new(None), } }
identifier_body
htmlstyleelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use script_layout_interface::message::Msg; use std::sync::Arc; use string_cache::Atom; use style::media_queries::parse_media_query_list; use style::parser::ParserContextExtraData; use style::stylesheets::{Stylesheet, Origin}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_heap_size_of = "Arc"] stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>, } impl HTMLStyleElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document), document, HTMLStyleElementBinding::Wrap) } pub fn
(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let win = window_from_node(node); let url = win.get_url(); let mq_attribute = element.get_attribute(&ns!(), &atom!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let mut sheet = Stylesheet::from_str(&data, url, Origin::Author, win.css_error_reporter(), ParserContextExtraData::default()); let mut css_parser = CssParser::new(&mq_str); let media = parse_media_query_list(&mut css_parser); sheet.set_media(Some(media)); let sheet = Arc::new(sheet); win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap(); *self.stylesheet.borrow_mut() = Some(sheet); let doc = document_from_node(self); doc.invalidate_stylesheets(); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { self.parse_own_css(); } } }
parse_own_css
identifier_name
common.rs
use std::io::Read; use std::io::Write; use std::fs::File; use std::fs::OpenOptions; use std::fs; use std::path::PathBuf; use std::path::Path; const IT_PATH: &str = "it"; pub const BINARY_PATH: &str = "target/debug/prep"; pub fn get_file_content(file: &str) -> String { let path_buf = pb(file); let mut file = File::open(path_buf.clone()).expect(&format!("opening file {:?}", path_buf)); let mut text = String::new(); file.read_to_string(&mut text).expect("reading file"); text } pub fn set_file_content(file: &str, content: &str) { let path_buf = pb(file); let mut file = OpenOptions::new() .create(true) .write(true) .open(path_buf) .expect("set_file_content opening file"); file.write_all(content.as_bytes()).unwrap(); } #[derive(Debug)] pub enum FsEntity { Dir(PathBuf), File(PathBuf), } pub struct TestFs {} impl Drop for TestFs { fn drop(&mut self) { fs::remove_dir_all(IT_PATH).unwrap(); } } impl TestFs { fn create(entities: &[FsEntity]) -> TestFs { fs::create_dir_all(IT_PATH).expect("Failed during creation of it directory"); for entity in entities { match entity { &FsEntity::Dir(ref pb) => { fs::create_dir_all(pb).unwrap(); } &FsEntity::File(ref pb) => { File::create(pb).unwrap(); } } } TestFs {} } } pub fn pb<P: AsRef<Path>>(p: P) -> PathBuf { let mut pb = PathBuf::from("it/"); pb.push(p); pb } pub fn td<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::Dir(pb(p)) } pub fn tf<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::File(pb(p)) } pub fn setup(entities: &[FsEntity]) -> TestFs {
TestFs::create(&entities) }
random_line_split
common.rs
use std::io::Read; use std::io::Write; use std::fs::File; use std::fs::OpenOptions; use std::fs; use std::path::PathBuf; use std::path::Path; const IT_PATH: &str = "it"; pub const BINARY_PATH: &str = "target/debug/prep"; pub fn get_file_content(file: &str) -> String { let path_buf = pb(file); let mut file = File::open(path_buf.clone()).expect(&format!("opening file {:?}", path_buf)); let mut text = String::new(); file.read_to_string(&mut text).expect("reading file"); text } pub fn set_file_content(file: &str, content: &str) { let path_buf = pb(file); let mut file = OpenOptions::new() .create(true) .write(true) .open(path_buf) .expect("set_file_content opening file"); file.write_all(content.as_bytes()).unwrap(); } #[derive(Debug)] pub enum FsEntity { Dir(PathBuf), File(PathBuf), } pub struct TestFs {} impl Drop for TestFs { fn drop(&mut self) { fs::remove_dir_all(IT_PATH).unwrap(); } } impl TestFs { fn create(entities: &[FsEntity]) -> TestFs { fs::create_dir_all(IT_PATH).expect("Failed during creation of it directory"); for entity in entities { match entity { &FsEntity::Dir(ref pb) => { fs::create_dir_all(pb).unwrap(); } &FsEntity::File(ref pb) => { File::create(pb).unwrap(); } } } TestFs {} } } pub fn pb<P: AsRef<Path>>(p: P) -> PathBuf { let mut pb = PathBuf::from("it/"); pb.push(p); pb } pub fn td<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::Dir(pb(p)) } pub fn tf<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::File(pb(p)) } pub fn setup(entities: &[FsEntity]) -> TestFs
{ TestFs::create(&entities) }
identifier_body
common.rs
use std::io::Read; use std::io::Write; use std::fs::File; use std::fs::OpenOptions; use std::fs; use std::path::PathBuf; use std::path::Path; const IT_PATH: &str = "it"; pub const BINARY_PATH: &str = "target/debug/prep"; pub fn get_file_content(file: &str) -> String { let path_buf = pb(file); let mut file = File::open(path_buf.clone()).expect(&format!("opening file {:?}", path_buf)); let mut text = String::new(); file.read_to_string(&mut text).expect("reading file"); text } pub fn set_file_content(file: &str, content: &str) { let path_buf = pb(file); let mut file = OpenOptions::new() .create(true) .write(true) .open(path_buf) .expect("set_file_content opening file"); file.write_all(content.as_bytes()).unwrap(); } #[derive(Debug)] pub enum FsEntity { Dir(PathBuf), File(PathBuf), } pub struct TestFs {} impl Drop for TestFs { fn drop(&mut self) { fs::remove_dir_all(IT_PATH).unwrap(); } } impl TestFs { fn create(entities: &[FsEntity]) -> TestFs { fs::create_dir_all(IT_PATH).expect("Failed during creation of it directory"); for entity in entities { match entity { &FsEntity::Dir(ref pb) =>
&FsEntity::File(ref pb) => { File::create(pb).unwrap(); } } } TestFs {} } } pub fn pb<P: AsRef<Path>>(p: P) -> PathBuf { let mut pb = PathBuf::from("it/"); pb.push(p); pb } pub fn td<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::Dir(pb(p)) } pub fn tf<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::File(pb(p)) } pub fn setup(entities: &[FsEntity]) -> TestFs { TestFs::create(&entities) }
{ fs::create_dir_all(pb).unwrap(); }
conditional_block
common.rs
use std::io::Read; use std::io::Write; use std::fs::File; use std::fs::OpenOptions; use std::fs; use std::path::PathBuf; use std::path::Path; const IT_PATH: &str = "it"; pub const BINARY_PATH: &str = "target/debug/prep"; pub fn get_file_content(file: &str) -> String { let path_buf = pb(file); let mut file = File::open(path_buf.clone()).expect(&format!("opening file {:?}", path_buf)); let mut text = String::new(); file.read_to_string(&mut text).expect("reading file"); text } pub fn set_file_content(file: &str, content: &str) { let path_buf = pb(file); let mut file = OpenOptions::new() .create(true) .write(true) .open(path_buf) .expect("set_file_content opening file"); file.write_all(content.as_bytes()).unwrap(); } #[derive(Debug)] pub enum FsEntity { Dir(PathBuf), File(PathBuf), } pub struct TestFs {} impl Drop for TestFs { fn drop(&mut self) { fs::remove_dir_all(IT_PATH).unwrap(); } } impl TestFs { fn create(entities: &[FsEntity]) -> TestFs { fs::create_dir_all(IT_PATH).expect("Failed during creation of it directory"); for entity in entities { match entity { &FsEntity::Dir(ref pb) => { fs::create_dir_all(pb).unwrap(); } &FsEntity::File(ref pb) => { File::create(pb).unwrap(); } } } TestFs {} } } pub fn
<P: AsRef<Path>>(p: P) -> PathBuf { let mut pb = PathBuf::from("it/"); pb.push(p); pb } pub fn td<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::Dir(pb(p)) } pub fn tf<P: AsRef<Path>>(p: P) -> FsEntity { FsEntity::File(pb(p)) } pub fn setup(entities: &[FsEntity]) -> TestFs { TestFs::create(&entities) }
pb
identifier_name
msid.rs
#[doc = "Register `MSID[%s]` reader"] pub struct R(crate::R<MSID_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MSID_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MSID_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<MSID_SPEC>) -> Self { R(reader) } } #[doc = "Field `INDEX` reader - Message Pending Index"] pub struct INDEX_R(crate::FieldReader<u8, u8>); impl INDEX_R { pub(crate) fn new(bits: u8) -> Self { INDEX_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for INDEX_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:5 - Message Pending Index"] #[inline(always)] pub fn
(&self) -> INDEX_R { INDEX_R::new((self.bits & 0x3f) as u8) } } #[doc = "Message Index Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [msid](index.html) module"] pub struct MSID_SPEC; impl crate::RegisterSpec for MSID_SPEC { type Ux = u32; } #[doc = "`read()` method returns [msid::R](R) reader structure"] impl crate::Readable for MSID_SPEC { type Reader = R; } #[doc = "`reset()` method sets MSID[%s] to value 0x20"] impl crate::Resettable for MSID_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0x20 } }
index
identifier_name
msid.rs
#[doc = "Register `MSID[%s]` reader"] pub struct R(crate::R<MSID_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MSID_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MSID_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<MSID_SPEC>) -> Self { R(reader) } } #[doc = "Field `INDEX` reader - Message Pending Index"] pub struct INDEX_R(crate::FieldReader<u8, u8>); impl INDEX_R { pub(crate) fn new(bits: u8) -> Self { INDEX_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for INDEX_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:5 - Message Pending Index"]
INDEX_R::new((self.bits & 0x3f) as u8) } } #[doc = "Message Index Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [msid](index.html) module"] pub struct MSID_SPEC; impl crate::RegisterSpec for MSID_SPEC { type Ux = u32; } #[doc = "`read()` method returns [msid::R](R) reader structure"] impl crate::Readable for MSID_SPEC { type Reader = R; } #[doc = "`reset()` method sets MSID[%s] to value 0x20"] impl crate::Resettable for MSID_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0x20 } }
#[inline(always)] pub fn index(&self) -> INDEX_R {
random_line_split
main.rs
use std::error; use std::io; fn get_sum(input: String) -> Result<i32, Box<dyn error::Error>> { let numbers = input .split_whitespace() .map(|number| number.parse()) .collect::<Result<Vec<i32>, _>>()?; if numbers.len() == 2
else { Err("Please enter 2 integers".into()) } } fn main() -> Result<(), Box<dyn error::Error>> { let mut input = String::new(); io::stdin().read_line(&mut input)?; let sum = get_sum(input)?; println!("{}", sum); Ok(()) } #[cfg(test)] mod tests { use super::get_sum; #[test] fn integer_sum_test() { let input = "2 2".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 4); let input = "3 2".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 5); let input = "79 -1".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 78); let input = "-5 10".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 5); let input = "1000 -1000".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 0); } #[test] fn bad_parsing_test() { let input = "2 1T".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); let input = "2 2.4".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); } #[test] fn bad_length_test() { let input = "2 1 1".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); let input = "2".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); let input = "".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); } }
{ Ok(numbers.iter().sum()) }
conditional_block
main.rs
use std::error; use std::io; fn get_sum(input: String) -> Result<i32, Box<dyn error::Error>> { let numbers = input .split_whitespace() .map(|number| number.parse()) .collect::<Result<Vec<i32>, _>>()?; if numbers.len() == 2 { Ok(numbers.iter().sum()) } else { Err("Please enter 2 integers".into()) } } fn main() -> Result<(), Box<dyn error::Error>> { let mut input = String::new(); io::stdin().read_line(&mut input)?; let sum = get_sum(input)?; println!("{}", sum); Ok(()) } #[cfg(test)] mod tests { use super::get_sum; #[test] fn integer_sum_test() { let input = "2 2".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 4); let input = "3 2".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 5); let input = "79 -1".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 78); let input = "-5 10".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 5); let input = "1000 -1000".to_string(); let output = get_sum(input); assert_eq!(output.unwrap(), 0); } #[test] fn bad_parsing_test() { let input = "2 1T".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); let input = "2 2.4".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); } #[test] fn bad_length_test() { let input = "2 1 1".to_string(); let output = get_sum(input); assert_eq!(output.is_err(), true); let input = "2".to_string();
let output = get_sum(input); assert_eq!(output.is_err(), true); } }
let output = get_sum(input); assert_eq!(output.is_err(), true); let input = "".to_string();
random_line_split