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 |
---|---|---|---|---|
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
EditableSignals, | prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::{Horizontal, Vertical};
use relm::{Relm, Widget};
use relm_derive::{Msg, widget};
use self::Msg::*;
pub struct Model {
left_text: String,
relm: Relm<Win>,
right_text: String,
text: String,
}
#[derive(Clone, Msg)]
pub enum Msg {
Cancel,
Concat,
DataAvailable(String),
DataCleared,
LeftChanged(String),
RightChanged(String),
Quit,
}
#[widget]
impl Widget for Win {
fn model(relm: &Relm<Self>, (): ()) -> Model {
Model {
left_text: String::new(),
right_text: String::new(),
relm: relm.clone(),
text: String::new(),
}
}
fn update(&mut self, event: Msg) {
match event {
Cancel => {
self.model.left_text = String::new();
self.model.right_text = String::new();
self.model.text = String::new();
self.model.relm.stream().emit(DataCleared);
},
Concat => {
self.model.text = format!("{}{}", self.model.left_text, self.model.right_text);
self.model.relm.stream().emit(DataAvailable(self.model.text.clone()));
},
// To be listened to by the user.
DataAvailable(_) | DataCleared => (),
LeftChanged(text) => self.model.left_text = text,
RightChanged(text) => self.model.right_text = text,
Quit => gtk::main_quit(),
}
}
view! {
#[name="window"]
gtk::Window {
gtk::Box {
gtk::Box {
#[name="left_entry"]
gtk::Entry {
text: &self.model.left_text,
changed(entry) => LeftChanged(entry.text().to_string()),
},
#[name="right_entry"]
gtk::Entry {
text: &self.model.right_text,
changed(entry) => RightChanged(entry.text().to_string()),
},
orientation: Horizontal,
},
gtk::ButtonBox {
#[name="concat_button"]
gtk::Button {
clicked => Concat,
label: "Concat",
},
#[name="cancel_button"]
gtk::Button {
clicked => Cancel,
label: "Cancel",
},
orientation: Horizontal,
},
orientation: Vertical,
#[name="label"]
gtk::Label {
label: &self.model.text,
},
},
delete_event(_, _) => (Quit, Inhibit(false)),
}
}
}
#[cfg(test)]
mod tests {
use gdk::keys::constants as key;
use gtk::prelude::{
EntryExt,
GtkWindowExt,
LabelExt,
WidgetExt,
};
use gtk_test::{
assert_text,
focus,
};
use relm_test::{
enter_key,
enter_keys,
relm_observer_new,
relm_observer_wait,
};
use crate::Msg::{DataAvailable, DataCleared};
use crate::Win;
#[test]
fn label_change() {
let (component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let cancel_button = &widgets.cancel_button;
let concat_button = &widgets.concat_button;
let label = &widgets.label;
let left_entry = &widgets.left_entry;
let right_entry = &widgets.right_entry;
let window = &widgets.window;
let available_observer = relm_observer_new!(component, DataAvailable(_));
let cleared_observer = relm_observer_new!(component, DataCleared);
assert_text!(label, "");
enter_keys(&window.focused_widget().expect("focused widget"), "left");
enter_key(window, key::Tab);
assert!(right_entry.has_focus());
enter_keys(&window.focused_widget().expect("focused widget"), "right");
enter_key(window, key::Tab);
assert!(concat_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "leftright");
enter_key(window, key::Tab);
assert!(cancel_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "");
assert_text!(left_entry, "");
assert_text!(right_entry, "");
focus(left_entry);
assert!(left_entry.has_focus());
focus(right_entry);
assert!(right_entry.has_focus());
relm_observer_wait!(let DataAvailable(text) = available_observer);
assert_eq!(text, "leftright");
relm_observer_wait!(let DataCleared = cleared_observer);
}
} | Inhibit,
prelude::ButtonExt,
prelude::EntryExt, | random_line_split |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
EditableSignals,
Inhibit,
prelude::ButtonExt,
prelude::EntryExt,
prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::{Horizontal, Vertical};
use relm::{Relm, Widget};
use relm_derive::{Msg, widget};
use self::Msg::*;
pub struct Model {
left_text: String,
relm: Relm<Win>,
right_text: String,
text: String,
}
#[derive(Clone, Msg)]
pub enum Msg {
Cancel,
Concat,
DataAvailable(String),
DataCleared,
LeftChanged(String),
RightChanged(String),
Quit,
}
#[widget]
impl Widget for Win {
fn model(relm: &Relm<Self>, (): ()) -> Model |
fn update(&mut self, event: Msg) {
match event {
Cancel => {
self.model.left_text = String::new();
self.model.right_text = String::new();
self.model.text = String::new();
self.model.relm.stream().emit(DataCleared);
},
Concat => {
self.model.text = format!("{}{}", self.model.left_text, self.model.right_text);
self.model.relm.stream().emit(DataAvailable(self.model.text.clone()));
},
// To be listened to by the user.
DataAvailable(_) | DataCleared => (),
LeftChanged(text) => self.model.left_text = text,
RightChanged(text) => self.model.right_text = text,
Quit => gtk::main_quit(),
}
}
view! {
#[name="window"]
gtk::Window {
gtk::Box {
gtk::Box {
#[name="left_entry"]
gtk::Entry {
text: &self.model.left_text,
changed(entry) => LeftChanged(entry.text().to_string()),
},
#[name="right_entry"]
gtk::Entry {
text: &self.model.right_text,
changed(entry) => RightChanged(entry.text().to_string()),
},
orientation: Horizontal,
},
gtk::ButtonBox {
#[name="concat_button"]
gtk::Button {
clicked => Concat,
label: "Concat",
},
#[name="cancel_button"]
gtk::Button {
clicked => Cancel,
label: "Cancel",
},
orientation: Horizontal,
},
orientation: Vertical,
#[name="label"]
gtk::Label {
label: &self.model.text,
},
},
delete_event(_, _) => (Quit, Inhibit(false)),
}
}
}
#[cfg(test)]
mod tests {
use gdk::keys::constants as key;
use gtk::prelude::{
EntryExt,
GtkWindowExt,
LabelExt,
WidgetExt,
};
use gtk_test::{
assert_text,
focus,
};
use relm_test::{
enter_key,
enter_keys,
relm_observer_new,
relm_observer_wait,
};
use crate::Msg::{DataAvailable, DataCleared};
use crate::Win;
#[test]
fn label_change() {
let (component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let cancel_button = &widgets.cancel_button;
let concat_button = &widgets.concat_button;
let label = &widgets.label;
let left_entry = &widgets.left_entry;
let right_entry = &widgets.right_entry;
let window = &widgets.window;
let available_observer = relm_observer_new!(component, DataAvailable(_));
let cleared_observer = relm_observer_new!(component, DataCleared);
assert_text!(label, "");
enter_keys(&window.focused_widget().expect("focused widget"), "left");
enter_key(window, key::Tab);
assert!(right_entry.has_focus());
enter_keys(&window.focused_widget().expect("focused widget"), "right");
enter_key(window, key::Tab);
assert!(concat_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "leftright");
enter_key(window, key::Tab);
assert!(cancel_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "");
assert_text!(left_entry, "");
assert_text!(right_entry, "");
focus(left_entry);
assert!(left_entry.has_focus());
focus(right_entry);
assert!(right_entry.has_focus());
relm_observer_wait!(let DataAvailable(text) = available_observer);
assert_eq!(text, "leftright");
relm_observer_wait!(let DataCleared = cleared_observer);
}
}
| {
Model {
left_text: String::new(),
right_text: String::new(),
relm: relm.clone(),
text: String::new(),
}
} | identifier_body |
basic.rs | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
struct Test1(u64);
impl Test1 {
#[fn_mut]
fn test1(&self, text: &str) -> u64 |
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_const! {
println!("This is const fn: {}", text);
}
Some(ptr!(self.0))
}
}
#[test]
fn test1() {
let mut t = Test1(1);
assert_eq!(t.test2("const"), Some(&1));
let mut s = String::from("mut");
assert_eq!(t.test2_mut(&mut s), Some(&mut 1));
assert_eq!(t.test1("const"), 21);
assert_eq!(t.test1_mut("const"), 11);
}
| {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
} | identifier_body |
basic.rs | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
struct Test1(u64);
impl Test1 {
#[fn_mut]
fn | (&self, text: &str) -> u64 {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
}
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_const! {
println!("This is const fn: {}", text);
}
Some(ptr!(self.0))
}
}
#[test]
fn test1() {
let mut t = Test1(1);
assert_eq!(t.test2("const"), Some(&1));
let mut s = String::from("mut");
assert_eq!(t.test2_mut(&mut s), Some(&mut 1));
assert_eq!(t.test1("const"), 21);
assert_eq!(t.test1_mut("const"), 11);
}
| test1 | identifier_name |
basic.rs | struct Test1(u64);
impl Test1 {
#[fn_mut]
fn test1(&self, text: &str) -> u64 {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
}
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_const! {
println!("This is const fn: {}", text);
}
Some(ptr!(self.0))
}
}
#[test]
fn test1() {
let mut t = Test1(1);
assert_eq!(t.test2("const"), Some(&1));
let mut s = String::from("mut");
assert_eq!(t.test2_mut(&mut s), Some(&mut 1));
assert_eq!(t.test1("const"), 21);
assert_eq!(t.test1_mut("const"), 11);
} | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
| random_line_split |
|
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RTC_IMSC: u32 = 0x010;
static RTC_RIS: u32 = 0x014;
static RTC_MIS: u32 = 0x018;
static RTC_ICR: u32 = 0x01c;
static mut PL031_RTC: Pl031rtc = Pl031rtc {
address: 0,
};
pub unsafe fn init() {
PL031_RTC.init();
time::START.lock().0 = PL031_RTC.time();
}
struct Pl031rtc {
pub address: usize,
}
impl Pl031rtc {
unsafe fn init(&mut self) {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let start_frame = Frame::containing_address(PhysicalAddress::new(0x09010000));
let end_frame = Frame::containing_address(PhysicalAddress::new(0x09010000 + 0x1000 - 1));
for frame in Frame::range_inclusive(start_frame, end_frame) {
let page = Page::containing_address(VirtualAddress::new(frame.start_address().data() + crate::KERNEL_DEVMAP_OFFSET));
let result = active_table.map_to(page, frame, PageFlags::new().write(true));
result.flush();
}
self.address = crate::KERNEL_DEVMAP_OFFSET + 0x09010000;
}
unsafe fn read(&self, reg: u32) -> u32 |
unsafe fn write(&mut self, reg: u32, value: u32) {
volatile_store((self.address + reg as usize) as *mut u32, value);
}
pub fn time(&mut self) -> u64 {
let seconds = unsafe { self.read(RTC_DR) } as u64;
seconds
}
}
| {
let val = volatile_load((self.address + reg as usize) as *const u32);
val
} | identifier_body |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RTC_IMSC: u32 = 0x010;
static RTC_RIS: u32 = 0x014;
static RTC_MIS: u32 = 0x018;
static RTC_ICR: u32 = 0x01c;
static mut PL031_RTC: Pl031rtc = Pl031rtc {
address: 0,
};
pub unsafe fn init() {
PL031_RTC.init();
time::START.lock().0 = PL031_RTC.time();
}
struct Pl031rtc {
pub address: usize,
}
impl Pl031rtc {
unsafe fn init(&mut self) {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let start_frame = Frame::containing_address(PhysicalAddress::new(0x09010000));
let end_frame = Frame::containing_address(PhysicalAddress::new(0x09010000 + 0x1000 - 1)); | let result = active_table.map_to(page, frame, PageFlags::new().write(true));
result.flush();
}
self.address = crate::KERNEL_DEVMAP_OFFSET + 0x09010000;
}
unsafe fn read(&self, reg: u32) -> u32 {
let val = volatile_load((self.address + reg as usize) as *const u32);
val
}
unsafe fn write(&mut self, reg: u32, value: u32) {
volatile_store((self.address + reg as usize) as *mut u32, value);
}
pub fn time(&mut self) -> u64 {
let seconds = unsafe { self.read(RTC_DR) } as u64;
seconds
}
} |
for frame in Frame::range_inclusive(start_frame, end_frame) {
let page = Page::containing_address(VirtualAddress::new(frame.start_address().data() + crate::KERNEL_DEVMAP_OFFSET)); | random_line_split |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RTC_IMSC: u32 = 0x010;
static RTC_RIS: u32 = 0x014;
static RTC_MIS: u32 = 0x018;
static RTC_ICR: u32 = 0x01c;
static mut PL031_RTC: Pl031rtc = Pl031rtc {
address: 0,
};
pub unsafe fn init() {
PL031_RTC.init();
time::START.lock().0 = PL031_RTC.time();
}
struct Pl031rtc {
pub address: usize,
}
impl Pl031rtc {
unsafe fn | (&mut self) {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let start_frame = Frame::containing_address(PhysicalAddress::new(0x09010000));
let end_frame = Frame::containing_address(PhysicalAddress::new(0x09010000 + 0x1000 - 1));
for frame in Frame::range_inclusive(start_frame, end_frame) {
let page = Page::containing_address(VirtualAddress::new(frame.start_address().data() + crate::KERNEL_DEVMAP_OFFSET));
let result = active_table.map_to(page, frame, PageFlags::new().write(true));
result.flush();
}
self.address = crate::KERNEL_DEVMAP_OFFSET + 0x09010000;
}
unsafe fn read(&self, reg: u32) -> u32 {
let val = volatile_load((self.address + reg as usize) as *const u32);
val
}
unsafe fn write(&mut self, reg: u32, value: u32) {
volatile_store((self.address + reg as usize) as *mut u32, value);
}
pub fn time(&mut self) -> u64 {
let seconds = unsafe { self.read(RTC_DR) } as u64;
seconds
}
}
| init | identifier_name |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn | (&mut self) -> Option<Self::Item> {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Ordering::Acquire);
let val = slot.value.load(Ordering::Relaxed);
if key_ptr.is_null() {
panic!("Iterator found an active slot with a null key");
}
let key = unsafe { hashkey_to_string(&(*key_ptr)) };
self.index += 1;
ret = Some((key, val));
break;
},
_ => {
self.index += 1;
}
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
}
| next | identifier_name |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> | },
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
}
| {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Ordering::Acquire);
let val = slot.value.load(Ordering::Relaxed);
if key_ptr.is_null() {
panic!("Iterator found an active slot with a null key");
}
let key = unsafe { hashkey_to_string(&(*key_ptr)) };
self.index += 1;
ret = Some((key, val));
break;
},
_ => {
self.index += 1;
} | identifier_body |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Ordering::Acquire);
let val = slot.value.load(Ordering::Relaxed);
if key_ptr.is_null() {
panic!("Iterator found an active slot with a null key");
}
let key = unsafe { hashkey_to_string(&(*key_ptr)) };
self.index += 1;
ret = Some((key, val));
break;
},
_ => |
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
}
| {
self.index += 1;
} | conditional_block |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Ordering::Acquire);
let val = slot.value.load(Ordering::Relaxed);
if key_ptr.is_null() {
panic!("Iterator found an active slot with a null key");
}
let key = unsafe { hashkey_to_string(&(*key_ptr)) };
self.index += 1;
ret = Some((key, val));
break;
},
_ => { | self.index += 1;
}
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
} | random_line_split |
|
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!";
bitflags! {
/**
The label flags
* NONE: No flags. Equivalent to a invisible blank label.
* VISIBLE: The label is immediatly visible after creation
* DISABLED: The label cannot be interacted with by the user. It also has a grayed out look.
*/
pub struct LabelFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
/// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines.
const ELIPSIS = SS_WORDELLIPSIS;
}
}
/**
A label is a single line of static text. Use `\r\n` to split the text on multiple lines.
Label is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The label parent container.
* `text`: The label text.
* `size`: The label size.
* `position`: The label position.
* `enabled`: If the label is enabled. A disabled label won't trigger events
* `flags`: A combination of the LabelFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the label text
* `background_color`: The background color of the label
* `h_align`: The horizontal aligment of the label
**Control events:**
* `OnLabelClick`: When the user click the label
* `OnLabelDoubleClick`: When the user double click a label
* `MousePress(_)`: Generic mouse press events on the label
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
** Example **
```rust
use native_windows_gui as nwg;
fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {
nwg::Label::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(label);
}
```
*/
#[derive(Default)]
pub struct Label {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
handler1: RefCell<Option<RawEventHandler>>,
}
impl Label {
pub fn builder<'a>() -> LabelBuilder<'a> {
LabelBuilder {
text: "A label",
size: (130, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
font: None,
parent: None,
h_align: HTextAlign::Left,
v_align: VTextAlign::Center,
background_color: None
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the label in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the label in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the label text
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the label text
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"STATIC"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT};
WS_VISIBLE | SS_NOPREFIX | SS_LEFT
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOTIFY, WS_CHILD};
WS_CHILD | SS_NOTIFY
}
/// Center the text vertically.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT};
use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT};
use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let handle = self.handle.hwnd().expect(BAD_HANDLE);
let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle));
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
if bg.is_some() {
let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| {
match msg {
WM_CTLCOLORSTATIC => {
let child = l as HWND;
if child == handle {
return Some(brush as LRESULT);
}
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let mut newline_count = 1;
let buffer_size = GetWindowTextLengthW(handle) as usize;
match buffer_size == 0 {
true => {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
},
false => {
let mut buffer: Vec<u16> = vec![0; buffer_size + 1];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
}
}
}
|
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler1.borrow_mut() = Some(handler1.unwrap());
}
}
}
impl PartialEq for Label {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl Drop for Label {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
let handler = self.handler1.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct LabelBuilder<'a> {
text: &'a str,
size: (i32, i32),
position: (i32, i32),
background_color: Option<[u8; 3]>,
flags: Option<LabelFlags>,
ex_flags: u32,
font: Option<&'a Font>,
h_align: HTextAlign,
v_align: VTextAlign,
parent: Option<ControlHandle>
}
impl<'a> LabelBuilder<'a> {
pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> {
self.text = text;
self
}
pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> {
self.background_color = color;
self
}
pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> {
self.h_align = align;
self
}
pub fn v_align(mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER};
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.h_align {
HTextAlign::Left => { flags |= SS_LEFT; },
HTextAlign::Right => { flags |= SS_RIGHT; },
HTextAlign::Center => { flags |= SS_CENTER; },
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Label"))
}?;
// Drop the old object
*out = Label::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
out.hook_non_client_size(self.background_color, self.v_align);
Ok(())
}
} | let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc); | random_line_split |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!";
bitflags! {
/**
The label flags
* NONE: No flags. Equivalent to a invisible blank label.
* VISIBLE: The label is immediatly visible after creation
* DISABLED: The label cannot be interacted with by the user. It also has a grayed out look.
*/
pub struct LabelFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
/// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines.
const ELIPSIS = SS_WORDELLIPSIS;
}
}
/**
A label is a single line of static text. Use `\r\n` to split the text on multiple lines.
Label is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The label parent container.
* `text`: The label text.
* `size`: The label size.
* `position`: The label position.
* `enabled`: If the label is enabled. A disabled label won't trigger events
* `flags`: A combination of the LabelFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the label text
* `background_color`: The background color of the label
* `h_align`: The horizontal aligment of the label
**Control events:**
* `OnLabelClick`: When the user click the label
* `OnLabelDoubleClick`: When the user double click a label
* `MousePress(_)`: Generic mouse press events on the label
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
** Example **
```rust
use native_windows_gui as nwg;
fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {
nwg::Label::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(label);
}
```
*/
#[derive(Default)]
pub struct Label {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
handler1: RefCell<Option<RawEventHandler>>,
}
impl Label {
pub fn builder<'a>() -> LabelBuilder<'a> {
LabelBuilder {
text: "A label",
size: (130, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
font: None,
parent: None,
h_align: HTextAlign::Left,
v_align: VTextAlign::Center,
background_color: None
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the label in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the label in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the label text
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the label text
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"STATIC"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT};
WS_VISIBLE | SS_NOPREFIX | SS_LEFT
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOTIFY, WS_CHILD};
WS_CHILD | SS_NOTIFY
}
/// Center the text vertically.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT};
use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT};
use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let handle = self.handle.hwnd().expect(BAD_HANDLE);
let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle));
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
if bg.is_some() {
let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| {
match msg {
WM_CTLCOLORSTATIC => {
let child = l as HWND;
if child == handle {
return Some(brush as LRESULT);
}
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let mut newline_count = 1;
let buffer_size = GetWindowTextLengthW(handle) as usize;
match buffer_size == 0 {
true => {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
},
false => {
let mut buffer: Vec<u16> = vec![0; buffer_size + 1];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
}
}
}
let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc);
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler1.borrow_mut() = Some(handler1.unwrap());
}
}
}
impl PartialEq for Label {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl Drop for Label {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
let handler = self.handler1.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct LabelBuilder<'a> {
text: &'a str,
size: (i32, i32),
position: (i32, i32),
background_color: Option<[u8; 3]>,
flags: Option<LabelFlags>,
ex_flags: u32,
font: Option<&'a Font>,
h_align: HTextAlign,
v_align: VTextAlign,
parent: Option<ControlHandle>
}
impl<'a> LabelBuilder<'a> {
pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> {
self.text = text;
self
}
pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> {
self.background_color = color;
self
}
pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> {
self.h_align = align;
self
}
pub fn | (mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER};
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.h_align {
HTextAlign::Left => { flags |= SS_LEFT; },
HTextAlign::Right => { flags |= SS_RIGHT; },
HTextAlign::Center => { flags |= SS_CENTER; },
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Label"))
}?;
// Drop the old object
*out = Label::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
out.hook_non_client_size(self.background_color, self.v_align);
Ok(())
}
}
| v_align | identifier_name |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!";
bitflags! {
/**
The label flags
* NONE: No flags. Equivalent to a invisible blank label.
* VISIBLE: The label is immediatly visible after creation
* DISABLED: The label cannot be interacted with by the user. It also has a grayed out look.
*/
pub struct LabelFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
/// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines.
const ELIPSIS = SS_WORDELLIPSIS;
}
}
/**
A label is a single line of static text. Use `\r\n` to split the text on multiple lines.
Label is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The label parent container.
* `text`: The label text.
* `size`: The label size.
* `position`: The label position.
* `enabled`: If the label is enabled. A disabled label won't trigger events
* `flags`: A combination of the LabelFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the label text
* `background_color`: The background color of the label
* `h_align`: The horizontal aligment of the label
**Control events:**
* `OnLabelClick`: When the user click the label
* `OnLabelDoubleClick`: When the user double click a label
* `MousePress(_)`: Generic mouse press events on the label
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
** Example **
```rust
use native_windows_gui as nwg;
fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {
nwg::Label::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(label);
}
```
*/
#[derive(Default)]
pub struct Label {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
handler1: RefCell<Option<RawEventHandler>>,
}
impl Label {
pub fn builder<'a>() -> LabelBuilder<'a> {
LabelBuilder {
text: "A label",
size: (130, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
font: None,
parent: None,
h_align: HTextAlign::Left,
v_align: VTextAlign::Center,
background_color: None
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the label in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the label in the parent window
pub fn set_size(&self, x: u32, y: u32) |
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the label text
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the label text
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"STATIC"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT};
WS_VISIBLE | SS_NOPREFIX | SS_LEFT
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOTIFY, WS_CHILD};
WS_CHILD | SS_NOTIFY
}
/// Center the text vertically.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT};
use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT};
use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let handle = self.handle.hwnd().expect(BAD_HANDLE);
let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle));
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
if bg.is_some() {
let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| {
match msg {
WM_CTLCOLORSTATIC => {
let child = l as HWND;
if child == handle {
return Some(brush as LRESULT);
}
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let mut newline_count = 1;
let buffer_size = GetWindowTextLengthW(handle) as usize;
match buffer_size == 0 {
true => {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
},
false => {
let mut buffer: Vec<u16> = vec![0; buffer_size + 1];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
}
}
}
let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc);
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler1.borrow_mut() = Some(handler1.unwrap());
}
}
}
impl PartialEq for Label {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl Drop for Label {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
let handler = self.handler1.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct LabelBuilder<'a> {
text: &'a str,
size: (i32, i32),
position: (i32, i32),
background_color: Option<[u8; 3]>,
flags: Option<LabelFlags>,
ex_flags: u32,
font: Option<&'a Font>,
h_align: HTextAlign,
v_align: VTextAlign,
parent: Option<ControlHandle>
}
impl<'a> LabelBuilder<'a> {
pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> {
self.text = text;
self
}
pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> {
self.background_color = color;
self
}
pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> {
self.h_align = align;
self
}
pub fn v_align(mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER};
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.h_align {
HTextAlign::Left => { flags |= SS_LEFT; },
HTextAlign::Right => { flags |= SS_RIGHT; },
HTextAlign::Center => { flags |= SS_CENTER; },
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Label"))
}?;
// Drop the old object
*out = Label::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
out.hook_non_client_size(self.background_color, self.v_align);
Ok(())
}
}
| {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
} | identifier_body |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!";
bitflags! {
/**
The label flags
* NONE: No flags. Equivalent to a invisible blank label.
* VISIBLE: The label is immediatly visible after creation
* DISABLED: The label cannot be interacted with by the user. It also has a grayed out look.
*/
pub struct LabelFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
/// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines.
const ELIPSIS = SS_WORDELLIPSIS;
}
}
/**
A label is a single line of static text. Use `\r\n` to split the text on multiple lines.
Label is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The label parent container.
* `text`: The label text.
* `size`: The label size.
* `position`: The label position.
* `enabled`: If the label is enabled. A disabled label won't trigger events
* `flags`: A combination of the LabelFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the label text
* `background_color`: The background color of the label
* `h_align`: The horizontal aligment of the label
**Control events:**
* `OnLabelClick`: When the user click the label
* `OnLabelDoubleClick`: When the user double click a label
* `MousePress(_)`: Generic mouse press events on the label
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
** Example **
```rust
use native_windows_gui as nwg;
fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {
nwg::Label::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(label);
}
```
*/
#[derive(Default)]
pub struct Label {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
handler1: RefCell<Option<RawEventHandler>>,
}
impl Label {
pub fn builder<'a>() -> LabelBuilder<'a> {
LabelBuilder {
text: "A label",
size: (130, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
font: None,
parent: None,
h_align: HTextAlign::Left,
v_align: VTextAlign::Center,
background_color: None
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the label in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the label in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the label text
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the label text
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"STATIC"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT};
WS_VISIBLE | SS_NOPREFIX | SS_LEFT
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOTIFY, WS_CHILD};
WS_CHILD | SS_NOTIFY
}
/// Center the text vertically.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT};
use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT};
use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let handle = self.handle.hwnd().expect(BAD_HANDLE);
let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle));
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
if bg.is_some() {
let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| {
match msg {
WM_CTLCOLORSTATIC => {
let child = l as HWND;
if child == handle {
return Some(brush as LRESULT);
}
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let mut newline_count = 1;
let buffer_size = GetWindowTextLengthW(handle) as usize;
match buffer_size == 0 {
true => {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
},
false => {
let mut buffer: Vec<u16> = vec![0; buffer_size + 1];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 | else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
}
}
}
let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc);
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler1.borrow_mut() = Some(handler1.unwrap());
}
}
}
impl PartialEq for Label {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl Drop for Label {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
let handler = self.handler1.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct LabelBuilder<'a> {
text: &'a str,
size: (i32, i32),
position: (i32, i32),
background_color: Option<[u8; 3]>,
flags: Option<LabelFlags>,
ex_flags: u32,
font: Option<&'a Font>,
h_align: HTextAlign,
v_align: VTextAlign,
parent: Option<ControlHandle>
}
impl<'a> LabelBuilder<'a> {
pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> {
self.text = text;
self
}
pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> {
self.background_color = color;
self
}
pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> {
self.h_align = align;
self
}
pub fn v_align(mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER};
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.h_align {
HTextAlign::Left => { flags |= SS_LEFT; },
HTextAlign::Right => { flags |= SS_RIGHT; },
HTextAlign::Center => { flags |= SS_CENTER; },
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Label"))
}?;
// Drop the old object
*out = Label::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
out.hook_non_client_size(self.background_color, self.v_align);
Ok(())
}
}
| {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} | conditional_block |
complex_types_macros.rs | extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rusted_cypher;
use rusted_cypher::GraphClient;
use rusted_cypher::cypher::result::Row;
const URI: &'static str = "http://neo4j:[email protected]:7474/db/data";
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Language {
name: String,
level: String,
safe: bool,
}
#[test]
fn without_params() {
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("MATCH (n:NTLY_INTG_TEST_MACROS_1) RETURN n").unwrap();
let result = graph.exec(stmt);
assert!(result.is_ok());
}
#[test]
fn save_retrive_struct() {
let rust = Language {
name: "Rust".to_owned(),
level: "low".to_owned(),
safe: true,
};
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("CREATE (n:NTLY_INTG_TEST_MACROS_2 {lang}) RETURN n", {
"lang" => &rust
}).unwrap();
let results = graph.exec(stmt).unwrap();
let rows: Vec<Row> = results.rows().take(1).collect();
let row = rows.first().unwrap();
| let lang: Language = row.get("n").unwrap();
assert_eq!(rust, lang);
graph.exec("MATCH (n:NTLY_INTG_TEST_MACROS_2) DELETE n").unwrap();
} | random_line_split |
|
complex_types_macros.rs | extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rusted_cypher;
use rusted_cypher::GraphClient;
use rusted_cypher::cypher::result::Row;
const URI: &'static str = "http://neo4j:[email protected]:7474/db/data";
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Language {
name: String,
level: String,
safe: bool,
}
#[test]
fn | () {
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("MATCH (n:NTLY_INTG_TEST_MACROS_1) RETURN n").unwrap();
let result = graph.exec(stmt);
assert!(result.is_ok());
}
#[test]
fn save_retrive_struct() {
let rust = Language {
name: "Rust".to_owned(),
level: "low".to_owned(),
safe: true,
};
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("CREATE (n:NTLY_INTG_TEST_MACROS_2 {lang}) RETURN n", {
"lang" => &rust
}).unwrap();
let results = graph.exec(stmt).unwrap();
let rows: Vec<Row> = results.rows().take(1).collect();
let row = rows.first().unwrap();
let lang: Language = row.get("n").unwrap();
assert_eq!(rust, lang);
graph.exec("MATCH (n:NTLY_INTG_TEST_MACROS_2) DELETE n").unwrap();
}
| without_params | identifier_name |
eew.rs | use chrono::{DateTime, Utc};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IssuePattern { Cancel, IntensityOnly, LowAccuracy, HighAccuracy }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Source { Tokyo, Osaka }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Kind { Normal, Drill, Cancel, DrillCancel, Reference, Trial }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Status { Normal, Correction, CancelCorrection, LastWithCorrection, Last, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum DepthAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum MagnitudeAccuracy {
NIED, PWave, PSMixed, SWave, EPOS, Level, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterCategory { Land, Sea, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum WarningStatus { Forecast, Alert, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IntensityChange { Same, Up, Down, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum ChangeReason { Nothing, Magnitude, Epicenter, Mixed, Depth, Plum, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum WaveStatus { Unreached, Reached, Plum, Unknown }
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Clone, Copy)]
pub enum IntensityClass {
Zero, One, Two, Three, Four, FiveLower, FiveUpper, SixLower, SixUpper, Seven
}
impl IntensityClass {
pub fn new(intensity: f32) -> IntensityClass
{
match intensity {
x if x < 0.5 => IntensityClass::Zero,
x if x < 1.5 => IntensityClass::One,
x if x < 2.5 => IntensityClass::Two,
x if x < 3.5 => IntensityClass::Three,
x if x < 4.5 => IntensityClass::Four,
x if x < 5.0 => IntensityClass::FiveLower,
x if x < 5.5 => IntensityClass::FiveUpper,
x if x < 6.0 => IntensityClass::SixLower,
x if x < 6.5 => IntensityClass::SixUpper,
_ => IntensityClass::Seven,
}
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct AreaEEW {
pub area_name: String,
pub minimum_intensity: IntensityClass,
pub maximum_intensity: Option<IntensityClass>,
pub reach_at: Option<DateTime<Utc>>,
pub warning_status: WarningStatus,
pub wave_status: WaveStatus,
}
#[derive(PartialEq, Debug, Clone)]
pub struct | {
pub issue_pattern: IssuePattern,
pub source: Source,
pub kind: Kind,
pub issued_at: DateTime<Utc>,
pub occurred_at: DateTime<Utc>,
pub id: String,
pub status: Status,
pub number: u32, // we don't accept an EEW which has no telegram number
pub detail: Option<EEWDetail>,
}
#[derive(PartialEq, Debug, Clone)]
pub struct EEWDetail {
pub epicenter_name: String,
pub epicenter: (f32, f32),
pub depth: Option<f32>,
pub magnitude: Option<f32>,
pub maximum_intensity: Option<IntensityClass>,
pub epicenter_accuracy: EpicenterAccuracy,
pub depth_accuracy: DepthAccuracy,
pub magnitude_accuracy: MagnitudeAccuracy,
pub epicenter_category: EpicenterCategory,
pub warning_status: WarningStatus,
pub intensity_change: IntensityChange,
pub change_reason: ChangeReason,
pub plum: bool,
pub area_info: Vec<AreaEEW>,
}
| EEW | identifier_name |
eew.rs | use chrono::{DateTime, Utc};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IssuePattern { Cancel, IntensityOnly, LowAccuracy, HighAccuracy }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Source { Tokyo, Osaka }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Kind { Normal, Drill, Cancel, DrillCancel, Reference, Trial }
| #[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Status { Normal, Correction, CancelCorrection, LastWithCorrection, Last, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum DepthAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum MagnitudeAccuracy {
NIED, PWave, PSMixed, SWave, EPOS, Level, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterCategory { Land, Sea, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum WarningStatus { Forecast, Alert, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IntensityChange { Same, Up, Down, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum ChangeReason { Nothing, Magnitude, Epicenter, Mixed, Depth, Plum, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum WaveStatus { Unreached, Reached, Plum, Unknown }
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Clone, Copy)]
pub enum IntensityClass {
Zero, One, Two, Three, Four, FiveLower, FiveUpper, SixLower, SixUpper, Seven
}
impl IntensityClass {
pub fn new(intensity: f32) -> IntensityClass
{
match intensity {
x if x < 0.5 => IntensityClass::Zero,
x if x < 1.5 => IntensityClass::One,
x if x < 2.5 => IntensityClass::Two,
x if x < 3.5 => IntensityClass::Three,
x if x < 4.5 => IntensityClass::Four,
x if x < 5.0 => IntensityClass::FiveLower,
x if x < 5.5 => IntensityClass::FiveUpper,
x if x < 6.0 => IntensityClass::SixLower,
x if x < 6.5 => IntensityClass::SixUpper,
_ => IntensityClass::Seven,
}
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct AreaEEW {
pub area_name: String,
pub minimum_intensity: IntensityClass,
pub maximum_intensity: Option<IntensityClass>,
pub reach_at: Option<DateTime<Utc>>,
pub warning_status: WarningStatus,
pub wave_status: WaveStatus,
}
#[derive(PartialEq, Debug, Clone)]
pub struct EEW {
pub issue_pattern: IssuePattern,
pub source: Source,
pub kind: Kind,
pub issued_at: DateTime<Utc>,
pub occurred_at: DateTime<Utc>,
pub id: String,
pub status: Status,
pub number: u32, // we don't accept an EEW which has no telegram number
pub detail: Option<EEWDetail>,
}
#[derive(PartialEq, Debug, Clone)]
pub struct EEWDetail {
pub epicenter_name: String,
pub epicenter: (f32, f32),
pub depth: Option<f32>,
pub magnitude: Option<f32>,
pub maximum_intensity: Option<IntensityClass>,
pub epicenter_accuracy: EpicenterAccuracy,
pub depth_accuracy: DepthAccuracy,
pub magnitude_accuracy: MagnitudeAccuracy,
pub epicenter_category: EpicenterCategory,
pub warning_status: WarningStatus,
pub intensity_change: IntensityChange,
pub change_reason: ChangeReason,
pub plum: bool,
pub area_info: Vec<AreaEEW>,
} | random_line_split |
|
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize {
self.n
}
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait EvenNature {
#[must_use = "no side effects"]
fn is_even(&self) -> bool;
}
impl EvenNature for MyStruct {
fn is_even(&self) -> bool {
self.n % 2 == 0
}
}
trait Replaceable {
fn replace(&mut self, substitute: usize) -> usize;
}
impl Replaceable for MyStruct {
// ↓ N.b.: `#[must_use]` attribute on a particular trait implementation
// method won't work; the attribute should be on the method signature in
// the trait's definition.
#[must_use]
fn replace(&mut self, substitute: usize) -> usize {
let previously = self.n;
self.n = substitute;
previously
}
}
#[must_use = "it's important"]
fn need_to_use_this_value() -> bool {
false
}
fn main() {
| m == n; //~ WARN unused comparison
}
| need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_to_use_this_associated_function_value();
//~^ WARN unused return value
m.replace(3); // won't warn (annotation needs to be in trait definition)
// comparison methods are `must_use`
2.eq(&3); //~ WARN unused return value
m.eq(&n); //~ WARN unused return value
// lint includes comparison operators
2 == 3; //~ WARN unused comparison | identifier_body |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize { | }
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait EvenNature {
#[must_use = "no side effects"]
fn is_even(&self) -> bool;
}
impl EvenNature for MyStruct {
fn is_even(&self) -> bool {
self.n % 2 == 0
}
}
trait Replaceable {
fn replace(&mut self, substitute: usize) -> usize;
}
impl Replaceable for MyStruct {
// ↓ N.b.: `#[must_use]` attribute on a particular trait implementation
// method won't work; the attribute should be on the method signature in
// the trait's definition.
#[must_use]
fn replace(&mut self, substitute: usize) -> usize {
let previously = self.n;
self.n = substitute;
previously
}
}
#[must_use = "it's important"]
fn need_to_use_this_value() -> bool {
false
}
fn main() {
need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_to_use_this_associated_function_value();
//~^ WARN unused return value
m.replace(3); // won't warn (annotation needs to be in trait definition)
// comparison methods are `must_use`
2.eq(&3); //~ WARN unused return value
m.eq(&n); //~ WARN unused return value
// lint includes comparison operators
2 == 3; //~ WARN unused comparison
m == n; //~ WARN unused comparison
} | self.n | random_line_split |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize {
self.n
}
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait EvenNature {
#[must_use = "no side effects"]
fn is_even(&self) -> bool;
}
impl EvenNature for MyStruct {
fn is_even(&self) -> bool {
self.n % 2 == 0
}
}
trait Replaceable {
fn replace(&mut self, substitute: usize) -> usize;
}
impl Replaceable for MyStruct {
// ↓ N.b.: `#[must_use]` attribute on a particular trait implementation
// method won't work; the attribute should be on the method signature in
// the trait's definition.
#[must_use]
fn replace(&mut self, substitute: usize) -> usize {
let previously = self.n;
self.n = substitute;
previously
}
}
#[must_use = "it's important"]
fn ne | -> bool {
false
}
fn main() {
need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_to_use_this_associated_function_value();
//~^ WARN unused return value
m.replace(3); // won't warn (annotation needs to be in trait definition)
// comparison methods are `must_use`
2.eq(&3); //~ WARN unused return value
m.eq(&n); //~ WARN unused return value
// lint includes comparison operators
2 == 3; //~ WARN unused comparison
m == n; //~ WARN unused comparison
}
| ed_to_use_this_value() | identifier_name |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
| fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
} | fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
| random_line_split |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool |
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
| {
self.width > other.width && self.height > other.height
} | identifier_body |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn | (&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
| can_hold | identifier_name |
lib.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#![warn(missing_docs)]
// Clippy lints, some should be disabled incrementally
#![allow(
clippy::assertions_on_constants,
clippy::bind_instead_of_map,
clippy::blocks_in_if_conditions,
clippy::clone_on_copy,
clippy::collapsible_if,
clippy::explicit_counter_loop,
clippy::field_reassign_with_default,
clippy::float_cmp,
clippy::into_iter_on_ref,
clippy::len_zero,
clippy::let_and_return,
clippy::map_clone,
clippy::map_collect_result_unit,
clippy::match_like_matches_macro,
clippy::match_ref_pats,
clippy::module_inception,
clippy::needless_lifetimes,
clippy::needless_range_loop,
clippy::needless_return,
clippy::new_without_default,
clippy::or_fun_call,
clippy::ptr_arg,
clippy::redundant_clone,
clippy::redundant_field_names,
clippy::redundant_static_lifetimes,
clippy::redundant_pattern_matching,
clippy::redundant_closure,
clippy::single_match,
clippy::stable_sort_primitive,
clippy::type_complexity,
clippy::unit_arg,
clippy::unnecessary_unwrap,
clippy::useless_format,
clippy::zero_prefixed_literal
)]
//! DataFusion is an extensible query execution framework that uses
//! [Apache Arrow](https://arrow.apache.org) as its in-memory format.
//!
//! DataFusion supports both an SQL and a DataFrame API for building logical query plans
//! as well as a query optimizer and execution engine capable of parallel execution
//! against partitioned data sources (CSV and Parquet) using threads.
//!
//! Below is an example of how to execute a query against a CSV using [`DataFrames`](dataframe::DataFrame):
//!
//! ```rust
//! # use datafusion::prelude::*;
//! # use datafusion::error::Result;
//! # use arrow::record_batch::RecordBatch;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let mut ctx = ExecutionContext::new();
//!
//! // create the dataframe
//! let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;
//!
//! // create a plan
//! let df = df.filter(col("a").lt_eq(col("b")))?
//! .aggregate(vec![col("a")], vec![min(col("b"))])?
//! .limit(100)?;
//!
//! // execute the plan
//! let results: Vec<RecordBatch> = df.collect().await?;
//! # Ok(())
//! # }
//! ```
//! | //! ```
//! # use datafusion::prelude::*;
//! # use datafusion::error::Result;
//! # use arrow::record_batch::RecordBatch;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let mut ctx = ExecutionContext::new();
//!
//! ctx.register_csv("example", "tests/example.csv", CsvReadOptions::new())?;
//!
//! // create a plan
//! let df = ctx.sql("SELECT a, MIN(b) FROM example GROUP BY a LIMIT 100")?;
//!
//! // execute the plan
//! let results: Vec<RecordBatch> = df.collect().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Parse, Plan, Optimize, Execute
//!
//! DataFusion is a fully fledged query engine capable of performing complex operations.
//! Specifically, when DataFusion receives an SQL query, there are different steps
//! that it passes through until a result is obtained. Broadly, they are:
//!
//! 1. The string is parsed to an Abstract syntax tree (AST) using [sqlparser](https://docs.rs/sqlparser/0.6.1/sqlparser/).
//! 2. The planner [`SqlToRel`](sql::planner::SqlToRel) converts logical expressions on the AST to logical expressions [`Expr`s](logical_plan::Expr).
//! 3. The planner [`SqlToRel`](sql::planner::SqlToRel) converts logical nodes on the AST to a [`LogicalPlan`](logical_plan::LogicalPlan).
//! 4. [`OptimizerRules`](optimizer::optimizer::OptimizerRule) are applied to the [`LogicalPlan`](logical_plan::LogicalPlan) to optimize it.
//! 5. The [`LogicalPlan`](logical_plan::LogicalPlan) is converted to an [`ExecutionPlan`](physical_plan::ExecutionPlan) by a [`PhysicalPlanner`](physical_plan::PhysicalPlanner)
//! 6. The [`ExecutionPlan`](physical_plan::ExecutionPlan) is executed against data through the [`ExecutionContext`](execution::context::ExecutionContext)
//!
//! With a [`DataFrame`](dataframe::DataFrame) API, steps 1-3 are not used as the DataFrame builds the [`LogicalPlan`](logical_plan::LogicalPlan) directly.
//!
//! Phases 1-5 are typically cheap when compared to phase 6, and thus DataFusion puts a
//! lot of effort to ensure that phase 6 runs efficiently and without errors.
//!
//! DataFusion's planning is divided in two main parts: logical planning and physical planning.
//!
//! ### Logical plan
//!
//! Logical planning yields [`logical plans`](logical_plan::LogicalPlan) and [`logical expressions`](logical_plan::Expr).
//! These are [`Schema`](arrow::datatypes::Schema)-aware traits that represent statements whose result is independent of how it should physically be executed.
//!
//! A [`LogicalPlan`](logical_plan::LogicalPlan) is a Direct Asyclic graph of other [`LogicalPlan`s](logical_plan::LogicalPlan) and each node contains logical expressions ([`Expr`s](logical_plan::Expr)).
//! All of these are located in [`logical_plan`](logical_plan).
//!
//! ### Physical plan
//!
//! A Physical plan ([`ExecutionPlan`](physical_plan::ExecutionPlan)) is a plan that can be executed against data.
//! Contrarily to a logical plan, the physical plan has concrete information about how the calculation
//! should be performed (e.g. what Rust functions are used) and how data should be loaded into memory.
//!
//! [`ExecutionPlan`](physical_plan::ExecutionPlan) uses the Arrow format as its in-memory representation of data, through the [arrow] crate.
//! We recommend going through [its documentation](arrow) for details on how the data is physically represented.
//!
//! A [`ExecutionPlan`](physical_plan::ExecutionPlan) is composed by nodes (implement the trait [`ExecutionPlan`](physical_plan::ExecutionPlan)),
//! and each node is composed by physical expressions ([`PhysicalExpr`](physical_plan::PhysicalExpr))
//! or aggreagate expressions ([`AggregateExpr`](physical_plan::AggregateExpr)).
//! All of these are located in the module [`physical_plan`](physical_plan).
//!
//! Broadly speaking,
//!
//! * an [`ExecutionPlan`](physical_plan::ExecutionPlan) receives a partition number and asyncronosly returns
//! an iterator over [`RecordBatch`](arrow::record_batch::RecordBatch)
//! (a node-specific struct that implements [`RecordBatchReader`](arrow::record_batch::RecordBatchReader))
//! * a [`PhysicalExpr`](physical_plan::PhysicalExpr) receives a [`RecordBatch`](arrow::record_batch::RecordBatch)
//! and returns an [`Array`](arrow::array::Array)
//! * an [`AggregateExpr`](physical_plan::AggregateExpr) receives [`RecordBatch`es](arrow::record_batch::RecordBatch)
//! and returns a [`RecordBatch`](arrow::record_batch::RecordBatch) of a single row(*)
//!
//! (*) Technically, it aggregates the results on each partition and then merges the results into a single partition.
//!
//! The following physical nodes are currently implemented:
//!
//! * Projection: [`ProjectionExec`](physical_plan::projection::ProjectionExec)
//! * Filter: [`FilterExec`](physical_plan::filter::FilterExec)
//! * Hash and Grouped aggregations: [`HashAggregateExec`](physical_plan::hash_aggregate::HashAggregateExec)
//! * Sort: [`SortExec`](physical_plan::sort::SortExec)
//! * Merge (partitions): [`MergeExec`](physical_plan::merge::MergeExec)
//! * Limit: [`LocalLimitExec`](physical_plan::limit::LocalLimitExec) and [`GlobalLimitExec`](physical_plan::limit::GlobalLimitExec)
//! * Scan a CSV: [`CsvExec`](physical_plan::csv::CsvExec)
//! * Scan a Parquet: [`ParquetExec`](physical_plan::parquet::ParquetExec)
//! * Scan from memory: [`MemoryExec`](physical_plan::memory::MemoryExec)
//! * Explain the plan: [`ExplainExec`](physical_plan::explain::ExplainExec)
//!
//! ## Customize
//!
//! DataFusion allows users to
//! * extend the planner to use user-defined logical and physical nodes ([`QueryPlanner`](execution::context::QueryPlanner))
//! * declare and use user-defined scalar functions ([`ScalarUDF`](physical_plan::udf::ScalarUDF))
//! * declare and use user-defined aggregate functions ([`AggregateUDF`](physical_plan::udaf::AggregateUDF))
//!
//! you can find examples of each of them in examples section.
extern crate arrow;
extern crate sqlparser;
pub mod dataframe;
pub mod datasource;
pub mod error;
pub mod execution;
pub mod logical_plan;
pub mod optimizer;
pub mod physical_plan;
pub mod prelude;
pub mod scalar;
pub mod sql;
pub mod variable;
#[cfg(test)]
pub mod test; | //! and how to execute a query against a CSV using SQL:
//! | random_line_split |
media_queries.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/. */
//! Servo's media-query device and expression representation.
use app_units::Au;
use context::QuirksMode;
use cssparser::{Parser, RGBA};
use euclid::{TypedScale, Size2D, TypedSize2D};
use media_queries::MediaType;
use parser::ParserContext;
use properties::ComputedValues;
use selectors::parser::SelectorParseErrorKind;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use style_traits::{CSSPixel, DevicePixel, ToCss, ParseError};
use style_traits::viewport::ViewportConstraints;
use values::computed::{self, ToComputedValue};
use values::computed::font::FontSize;
use values::specified;
/// A device is a structure that represents the current media a given document
/// is displayed in.
///
/// This is the struct against which media queries are evaluated.
#[derive(MallocSizeOf)]
pub struct Device {
/// The current media type used by de device.
media_type: MediaType,
/// The current viewport size, in CSS pixels.
viewport_size: TypedSize2D<f32, CSSPixel>,
/// The current device pixel ratio, from CSS pixels to device pixels.
device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>,
/// The font size of the root element
/// This is set when computing the style of the root
/// element, and used for rem units in other elements
///
/// When computing the style of the root element, there can't be any
/// other style being computed at the same time, given we need the style of
/// the parent to compute everything else. So it is correct to just use
/// a relaxed atomic here.
#[ignore_malloc_size_of = "Pure stack type"]
root_font_size: AtomicIsize,
/// Whether any styles computed in the document relied on the root font-size
/// by using rem units.
#[ignore_malloc_size_of = "Pure stack type"]
used_root_font_size: AtomicBool,
/// Whether any styles computed in the document relied on the viewport size.
#[ignore_malloc_size_of = "Pure stack type"]
used_viewport_units: AtomicBool,
}
impl Device {
/// Trivially construct a new `Device`.
pub fn new(
media_type: MediaType,
viewport_size: TypedSize2D<f32, CSSPixel>,
device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>
) -> Device {
Device {
media_type,
viewport_size,
device_pixel_ratio,
// FIXME(bz): Seems dubious?
root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize),
used_root_font_size: AtomicBool::new(false),
used_viewport_units: AtomicBool::new(false),
}
}
/// Return the default computed values for this device.
pub fn default_computed_values(&self) -> &ComputedValues {
// FIXME(bz): This isn't really right, but it's no more wrong
// than what we used to do. See
// https://github.com/servo/servo/issues/14773 for fixing it properly.
ComputedValues::initial_values()
}
/// Get the font size of the root element (for rem)
pub fn root_font_size(&self) -> Au {
self.used_root_font_size.store(true, Ordering::Relaxed);
Au::new(self.root_font_size.load(Ordering::Relaxed) as i32)
}
/// Set the font size of the root element (for rem)
pub fn set_root_font_size(&self, size: Au) {
self.root_font_size.store(size.0 as isize, Ordering::Relaxed)
}
/// Sets the body text color for the "inherit color from body" quirk.
///
/// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk>
pub fn set_body_text_color(&self, _color: RGBA) {
// Servo doesn't implement this quirk (yet)
}
/// Returns whether we ever looked up the root font size of the Device.
pub fn used_root_font_size(&self) -> bool {
self.used_root_font_size.load(Ordering::Relaxed)
}
/// Returns the viewport size of the current device in app units, needed,
/// among other things, to resolve viewport units.
#[inline]
pub fn au_viewport_size(&self) -> Size2D<Au> {
Size2D::new(Au::from_f32_px(self.viewport_size.width),
Au::from_f32_px(self.viewport_size.height))
}
/// Like the above, but records that we've used viewport units.
pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> {
self.used_viewport_units.store(true, Ordering::Relaxed);
self.au_viewport_size()
}
/// Whether viewport units were used since the last device change.
pub fn used_viewport_units(&self) -> bool {
self.used_viewport_units.load(Ordering::Relaxed)
}
/// Returns the device pixel ratio.
pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> {
self.device_pixel_ratio
}
/// Take into account a viewport rule taken from the stylesheets.
pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) {
self.viewport_size = constraints.size;
}
/// Return the media type of the current device.
pub fn media_type(&self) -> MediaType {
self.media_type.clone()
}
/// Returns whether document colors are enabled.
pub fn use_document_colors(&self) -> bool {
true
}
/// Returns the default background color.
pub fn default_background_color(&self) -> RGBA {
RGBA::new(255, 255, 255, 255)
}
}
/// A expression kind servo understands and parses.
///
/// Only `pub` for unit testing, please don't use it directly!
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub enum ExpressionKind {
/// <http://dev.w3.org/csswg/mediaqueries-3/#width>
Width(Range<specified::Length>),
}
/// A single expression a per:
///
/// <http://dev.w3.org/csswg/mediaqueries-3/#media1>
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct Expression(pub ExpressionKind);
impl Expression { | /// The kind of expression we're, just for unit testing.
///
/// Eventually this will become servo-only.
pub fn kind_for_testing(&self) -> &ExpressionKind {
&self.0
}
/// Parse a media expression of the form:
///
/// ```
/// (media-feature: media-value)
/// ```
///
/// Only supports width and width ranges for now.
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
input.expect_parenthesis_block()?;
input.parse_nested_block(|input| {
let name = input.expect_ident_cloned()?;
input.expect_colon()?;
// TODO: Handle other media features
Ok(Expression(match_ignore_ascii_case! { &name,
"min-width" => {
ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?))
},
"max-width" => {
ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?))
},
"width" => {
ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?))
},
_ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone())))
}))
})
}
/// Evaluate this expression and return whether it matches the current
/// device.
pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool {
let viewport_size = device.au_viewport_size();
let value = viewport_size.width;
match self.0 {
ExpressionKind::Width(ref range) => {
match range.to_computed_range(device, quirks_mode) {
Range::Min(ref width) => { value >= *width },
Range::Max(ref width) => { value <= *width },
Range::Eq(ref width) => { value == *width },
}
}
}
}
}
impl ToCss for Expression {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
let (s, l) = match self.0 {
ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l),
ExpressionKind::Width(Range::Max(ref l)) => ("(max-width: ", l),
ExpressionKind::Width(Range::Eq(ref l)) => ("(width: ", l),
};
dest.write_str(s)?;
l.to_css(dest)?;
dest.write_char(')')
}
}
/// An enumeration that represents a ranged value.
///
/// Only public for testing, implementation details of `Expression` may change
/// for Stylo.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub enum Range<T> {
/// At least the inner value.
Min(T),
/// At most the inner value.
Max(T),
/// Exactly the inner value.
Eq(T),
}
impl Range<specified::Length> {
fn to_computed_range(&self, device: &Device, quirks_mode: QuirksMode) -> Range<Au> {
computed::Context::for_media_query_evaluation(device, quirks_mode, |context| {
match *self {
Range::Min(ref width) => Range::Min(Au::from(width.to_computed_value(&context))),
Range::Max(ref width) => Range::Max(Au::from(width.to_computed_value(&context))),
Range::Eq(ref width) => Range::Eq(Au::from(width.to_computed_value(&context)))
}
})
}
} | random_line_split |
|
media_queries.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/. */
//! Servo's media-query device and expression representation.
use app_units::Au;
use context::QuirksMode;
use cssparser::{Parser, RGBA};
use euclid::{TypedScale, Size2D, TypedSize2D};
use media_queries::MediaType;
use parser::ParserContext;
use properties::ComputedValues;
use selectors::parser::SelectorParseErrorKind;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use style_traits::{CSSPixel, DevicePixel, ToCss, ParseError};
use style_traits::viewport::ViewportConstraints;
use values::computed::{self, ToComputedValue};
use values::computed::font::FontSize;
use values::specified;
/// A device is a structure that represents the current media a given document
/// is displayed in.
///
/// This is the struct against which media queries are evaluated.
#[derive(MallocSizeOf)]
pub struct Device {
/// The current media type used by de device.
media_type: MediaType,
/// The current viewport size, in CSS pixels.
viewport_size: TypedSize2D<f32, CSSPixel>,
/// The current device pixel ratio, from CSS pixels to device pixels.
device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>,
/// The font size of the root element
/// This is set when computing the style of the root
/// element, and used for rem units in other elements
///
/// When computing the style of the root element, there can't be any
/// other style being computed at the same time, given we need the style of
/// the parent to compute everything else. So it is correct to just use
/// a relaxed atomic here.
#[ignore_malloc_size_of = "Pure stack type"]
root_font_size: AtomicIsize,
/// Whether any styles computed in the document relied on the root font-size
/// by using rem units.
#[ignore_malloc_size_of = "Pure stack type"]
used_root_font_size: AtomicBool,
/// Whether any styles computed in the document relied on the viewport size.
#[ignore_malloc_size_of = "Pure stack type"]
used_viewport_units: AtomicBool,
}
impl Device {
/// Trivially construct a new `Device`.
pub fn new(
media_type: MediaType,
viewport_size: TypedSize2D<f32, CSSPixel>,
device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>
) -> Device {
Device {
media_type,
viewport_size,
device_pixel_ratio,
// FIXME(bz): Seems dubious?
root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize),
used_root_font_size: AtomicBool::new(false),
used_viewport_units: AtomicBool::new(false),
}
}
/// Return the default computed values for this device.
pub fn default_computed_values(&self) -> &ComputedValues {
// FIXME(bz): This isn't really right, but it's no more wrong
// than what we used to do. See
// https://github.com/servo/servo/issues/14773 for fixing it properly.
ComputedValues::initial_values()
}
/// Get the font size of the root element (for rem)
pub fn root_font_size(&self) -> Au {
self.used_root_font_size.store(true, Ordering::Relaxed);
Au::new(self.root_font_size.load(Ordering::Relaxed) as i32)
}
/// Set the font size of the root element (for rem)
pub fn set_root_font_size(&self, size: Au) {
self.root_font_size.store(size.0 as isize, Ordering::Relaxed)
}
/// Sets the body text color for the "inherit color from body" quirk.
///
/// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk>
pub fn set_body_text_color(&self, _color: RGBA) {
// Servo doesn't implement this quirk (yet)
}
/// Returns whether we ever looked up the root font size of the Device.
pub fn used_root_font_size(&self) -> bool {
self.used_root_font_size.load(Ordering::Relaxed)
}
/// Returns the viewport size of the current device in app units, needed,
/// among other things, to resolve viewport units.
#[inline]
pub fn au_viewport_size(&self) -> Size2D<Au> {
Size2D::new(Au::from_f32_px(self.viewport_size.width),
Au::from_f32_px(self.viewport_size.height))
}
/// Like the above, but records that we've used viewport units.
pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> {
self.used_viewport_units.store(true, Ordering::Relaxed);
self.au_viewport_size()
}
/// Whether viewport units were used since the last device change.
pub fn used_viewport_units(&self) -> bool {
self.used_viewport_units.load(Ordering::Relaxed)
}
/// Returns the device pixel ratio.
pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> {
self.device_pixel_ratio
}
/// Take into account a viewport rule taken from the stylesheets.
pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) {
self.viewport_size = constraints.size;
}
/// Return the media type of the current device.
pub fn media_type(&self) -> MediaType {
self.media_type.clone()
}
/// Returns whether document colors are enabled.
pub fn use_document_colors(&self) -> bool {
true
}
/// Returns the default background color.
pub fn default_background_color(&self) -> RGBA {
RGBA::new(255, 255, 255, 255)
}
}
/// A expression kind servo understands and parses.
///
/// Only `pub` for unit testing, please don't use it directly!
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub enum | {
/// <http://dev.w3.org/csswg/mediaqueries-3/#width>
Width(Range<specified::Length>),
}
/// A single expression a per:
///
/// <http://dev.w3.org/csswg/mediaqueries-3/#media1>
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct Expression(pub ExpressionKind);
impl Expression {
/// The kind of expression we're, just for unit testing.
///
/// Eventually this will become servo-only.
pub fn kind_for_testing(&self) -> &ExpressionKind {
&self.0
}
/// Parse a media expression of the form:
///
/// ```
/// (media-feature: media-value)
/// ```
///
/// Only supports width and width ranges for now.
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
input.expect_parenthesis_block()?;
input.parse_nested_block(|input| {
let name = input.expect_ident_cloned()?;
input.expect_colon()?;
// TODO: Handle other media features
Ok(Expression(match_ignore_ascii_case! { &name,
"min-width" => {
ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?))
},
"max-width" => {
ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?))
},
"width" => {
ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?))
},
_ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone())))
}))
})
}
/// Evaluate this expression and return whether it matches the current
/// device.
pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool {
let viewport_size = device.au_viewport_size();
let value = viewport_size.width;
match self.0 {
ExpressionKind::Width(ref range) => {
match range.to_computed_range(device, quirks_mode) {
Range::Min(ref width) => { value >= *width },
Range::Max(ref width) => { value <= *width },
Range::Eq(ref width) => { value == *width },
}
}
}
}
}
impl ToCss for Expression {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
let (s, l) = match self.0 {
ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l),
ExpressionKind::Width(Range::Max(ref l)) => ("(max-width: ", l),
ExpressionKind::Width(Range::Eq(ref l)) => ("(width: ", l),
};
dest.write_str(s)?;
l.to_css(dest)?;
dest.write_char(')')
}
}
/// An enumeration that represents a ranged value.
///
/// Only public for testing, implementation details of `Expression` may change
/// for Stylo.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub enum Range<T> {
/// At least the inner value.
Min(T),
/// At most the inner value.
Max(T),
/// Exactly the inner value.
Eq(T),
}
impl Range<specified::Length> {
fn to_computed_range(&self, device: &Device, quirks_mode: QuirksMode) -> Range<Au> {
computed::Context::for_media_query_evaluation(device, quirks_mode, |context| {
match *self {
Range::Min(ref width) => Range::Min(Au::from(width.to_computed_value(&context))),
Range::Max(ref width) => Range::Max(Au::from(width.to_computed_value(&context))),
Range::Eq(ref width) => Range::Eq(Au::from(width.to_computed_value(&context)))
}
})
}
}
| ExpressionKind | identifier_name |
test.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Various utility functions useful for writing I/O tests
use prelude::v1::*;
use env;
use libc;
use std::old_io::net::ip::*;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
// iOS has a pretty long tmpdir path which causes pipe creation
// to like: invalid argument: path must be smaller than SUN_LEN
fn next_test_unix_socket() -> String {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
// base port and pid are an attempt to be unique between multiple
// test-runners of different configurations running on one
// buildbot, the count is to be unique within this executable.
format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
COUNT.fetch_add(1, Ordering::Relaxed))
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(not(target_os = "ios"))]
pub fn next_test_unix() -> Path {
let string = next_test_unix_socket();
if cfg!(unix) {
env::temp_dir().join(string)
} else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting at 9600
pub fn next_test_ip4() -> SocketAddr |
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn next_test_ip6() -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.
*/
fn base_port() -> u16 {
let base = 9600u16;
let range = 1000u16;
let bases = [
("32-opt", base + range * 1),
("32-nopt", base + range * 2),
("64-opt", base + range * 3),
("64-nopt", base + range * 4),
("64-opt-vg", base + range * 5),
("all-opt", base + range * 6),
("snap3", base + range * 7),
("dist", base + range * 8)
];
// FIXME (#9639): This needs to handle non-utf8 paths
let path = env::current_dir().unwrap();
let path_s = path.as_str().unwrap();
let mut final_base = base;
for &(dir, base) in &bases {
if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an issue where launchctl on Mac OS X defaults the rlimit
/// maxfiles to 256/unlimited. The default soft limit of 256 ends up being far too low for our
/// multithreaded scheduler testing, depending on the number of cores available.
///
/// This fixes issue #7772.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[allow(non_camel_case_types)]
mod darwin_fd_limit {
use libc;
type rlim_t = libc::uint64_t;
#[repr(C)]
struct rlimit {
rlim_cur: rlim_t,
rlim_max: rlim_t
}
extern {
// name probably doesn't need to be mut, but the C function doesn't specify const
fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint,
oldp: *mut libc::c_void, oldlenp: *mut libc::size_t,
newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int;
fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int;
fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int;
}
static CTL_KERN: libc::c_int = 1;
static KERN_MAXFILESPERPROC: libc::c_int = 29;
static RLIMIT_NOFILE: libc::c_int = 8;
pub unsafe fn raise_fd_limit() {
// The strategy here is to fetch the current resource limits, read the kern.maxfilesperproc
// sysctl value, and bump the soft resource limit for maxfiles up to the sysctl value.
use ptr::null_mut;
use mem::size_of_val;
use os::last_os_error;
// Fetch the kern.maxfilesperproc value
let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
let mut maxfiles: libc::c_int = 0;
let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
rlim.rlim_cur = ::cmp::min(maxfiles as rlim_t, rlim.rlim_max);
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod darwin_fd_limit {
pub unsafe fn raise_fd_limit() {}
}
| {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
} | identifier_body |
test.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Various utility functions useful for writing I/O tests
use prelude::v1::*;
use env;
use libc;
use std::old_io::net::ip::*;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
// iOS has a pretty long tmpdir path which causes pipe creation
// to like: invalid argument: path must be smaller than SUN_LEN
fn next_test_unix_socket() -> String {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
// base port and pid are an attempt to be unique between multiple
// test-runners of different configurations running on one
// buildbot, the count is to be unique within this executable.
format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
COUNT.fetch_add(1, Ordering::Relaxed))
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(not(target_os = "ios"))]
pub fn next_test_unix() -> Path {
let string = next_test_unix_socket();
if cfg!(unix) {
env::temp_dir().join(string)
} else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting at 9600
pub fn next_test_ip4() -> SocketAddr {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
}
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn | () -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.
*/
fn base_port() -> u16 {
let base = 9600u16;
let range = 1000u16;
let bases = [
("32-opt", base + range * 1),
("32-nopt", base + range * 2),
("64-opt", base + range * 3),
("64-nopt", base + range * 4),
("64-opt-vg", base + range * 5),
("all-opt", base + range * 6),
("snap3", base + range * 7),
("dist", base + range * 8)
];
// FIXME (#9639): This needs to handle non-utf8 paths
let path = env::current_dir().unwrap();
let path_s = path.as_str().unwrap();
let mut final_base = base;
for &(dir, base) in &bases {
if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an issue where launchctl on Mac OS X defaults the rlimit
/// maxfiles to 256/unlimited. The default soft limit of 256 ends up being far too low for our
/// multithreaded scheduler testing, depending on the number of cores available.
///
/// This fixes issue #7772.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[allow(non_camel_case_types)]
mod darwin_fd_limit {
use libc;
type rlim_t = libc::uint64_t;
#[repr(C)]
struct rlimit {
rlim_cur: rlim_t,
rlim_max: rlim_t
}
extern {
// name probably doesn't need to be mut, but the C function doesn't specify const
fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint,
oldp: *mut libc::c_void, oldlenp: *mut libc::size_t,
newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int;
fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int;
fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int;
}
static CTL_KERN: libc::c_int = 1;
static KERN_MAXFILESPERPROC: libc::c_int = 29;
static RLIMIT_NOFILE: libc::c_int = 8;
pub unsafe fn raise_fd_limit() {
// The strategy here is to fetch the current resource limits, read the kern.maxfilesperproc
// sysctl value, and bump the soft resource limit for maxfiles up to the sysctl value.
use ptr::null_mut;
use mem::size_of_val;
use os::last_os_error;
// Fetch the kern.maxfilesperproc value
let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
let mut maxfiles: libc::c_int = 0;
let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
rlim.rlim_cur = ::cmp::min(maxfiles as rlim_t, rlim.rlim_max);
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod darwin_fd_limit {
pub unsafe fn raise_fd_limit() {}
}
| next_test_ip6 | identifier_name |
test.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Various utility functions useful for writing I/O tests
use prelude::v1::*;
use env;
use libc;
use std::old_io::net::ip::*;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
// iOS has a pretty long tmpdir path which causes pipe creation
// to like: invalid argument: path must be smaller than SUN_LEN
fn next_test_unix_socket() -> String {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
// base port and pid are an attempt to be unique between multiple
// test-runners of different configurations running on one
// buildbot, the count is to be unique within this executable.
format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
COUNT.fetch_add(1, Ordering::Relaxed))
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(not(target_os = "ios"))]
pub fn next_test_unix() -> Path {
let string = next_test_unix_socket();
if cfg!(unix) | else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting at 9600
pub fn next_test_ip4() -> SocketAddr {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
}
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn next_test_ip6() -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.
*/
fn base_port() -> u16 {
let base = 9600u16;
let range = 1000u16;
let bases = [
("32-opt", base + range * 1),
("32-nopt", base + range * 2),
("64-opt", base + range * 3),
("64-nopt", base + range * 4),
("64-opt-vg", base + range * 5),
("all-opt", base + range * 6),
("snap3", base + range * 7),
("dist", base + range * 8)
];
// FIXME (#9639): This needs to handle non-utf8 paths
let path = env::current_dir().unwrap();
let path_s = path.as_str().unwrap();
let mut final_base = base;
for &(dir, base) in &bases {
if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an issue where launchctl on Mac OS X defaults the rlimit
/// maxfiles to 256/unlimited. The default soft limit of 256 ends up being far too low for our
/// multithreaded scheduler testing, depending on the number of cores available.
///
/// This fixes issue #7772.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[allow(non_camel_case_types)]
mod darwin_fd_limit {
use libc;
type rlim_t = libc::uint64_t;
#[repr(C)]
struct rlimit {
rlim_cur: rlim_t,
rlim_max: rlim_t
}
extern {
// name probably doesn't need to be mut, but the C function doesn't specify const
fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint,
oldp: *mut libc::c_void, oldlenp: *mut libc::size_t,
newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int;
fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int;
fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int;
}
static CTL_KERN: libc::c_int = 1;
static KERN_MAXFILESPERPROC: libc::c_int = 29;
static RLIMIT_NOFILE: libc::c_int = 8;
pub unsafe fn raise_fd_limit() {
// The strategy here is to fetch the current resource limits, read the kern.maxfilesperproc
// sysctl value, and bump the soft resource limit for maxfiles up to the sysctl value.
use ptr::null_mut;
use mem::size_of_val;
use os::last_os_error;
// Fetch the kern.maxfilesperproc value
let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
let mut maxfiles: libc::c_int = 0;
let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
rlim.rlim_cur = ::cmp::min(maxfiles as rlim_t, rlim.rlim_max);
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod darwin_fd_limit {
pub unsafe fn raise_fd_limit() {}
}
| {
env::temp_dir().join(string)
} | conditional_block |
test.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Various utility functions useful for writing I/O tests
use prelude::v1::*;
use env;
use libc;
use std::old_io::net::ip::*;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
// iOS has a pretty long tmpdir path which causes pipe creation
// to like: invalid argument: path must be smaller than SUN_LEN
fn next_test_unix_socket() -> String {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
// base port and pid are an attempt to be unique between multiple
// test-runners of different configurations running on one
// buildbot, the count is to be unique within this executable.
format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
COUNT.fetch_add(1, Ordering::Relaxed))
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(not(target_os = "ios"))]
pub fn next_test_unix() -> Path {
let string = next_test_unix_socket();
if cfg!(unix) {
env::temp_dir().join(string)
} else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting at 9600
pub fn next_test_ip4() -> SocketAddr {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
}
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn next_test_ip6() -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.
*/
fn base_port() -> u16 {
let base = 9600u16;
let range = 1000u16;
let bases = [
("32-opt", base + range * 1),
("32-nopt", base + range * 2),
("64-opt", base + range * 3),
("64-nopt", base + range * 4),
("64-opt-vg", base + range * 5),
("all-opt", base + range * 6),
("snap3", base + range * 7),
("dist", base + range * 8)
];
// FIXME (#9639): This needs to handle non-utf8 paths
let path = env::current_dir().unwrap();
let path_s = path.as_str().unwrap();
let mut final_base = base;
for &(dir, base) in &bases { | if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an issue where launchctl on Mac OS X defaults the rlimit
/// maxfiles to 256/unlimited. The default soft limit of 256 ends up being far too low for our
/// multithreaded scheduler testing, depending on the number of cores available.
///
/// This fixes issue #7772.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[allow(non_camel_case_types)]
mod darwin_fd_limit {
use libc;
type rlim_t = libc::uint64_t;
#[repr(C)]
struct rlimit {
rlim_cur: rlim_t,
rlim_max: rlim_t
}
extern {
// name probably doesn't need to be mut, but the C function doesn't specify const
fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint,
oldp: *mut libc::c_void, oldlenp: *mut libc::size_t,
newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int;
fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int;
fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int;
}
static CTL_KERN: libc::c_int = 1;
static KERN_MAXFILESPERPROC: libc::c_int = 29;
static RLIMIT_NOFILE: libc::c_int = 8;
pub unsafe fn raise_fd_limit() {
// The strategy here is to fetch the current resource limits, read the kern.maxfilesperproc
// sysctl value, and bump the soft resource limit for maxfiles up to the sysctl value.
use ptr::null_mut;
use mem::size_of_val;
use os::last_os_error;
// Fetch the kern.maxfilesperproc value
let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
let mut maxfiles: libc::c_int = 0;
let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
rlim.rlim_cur = ::cmp::min(maxfiles as rlim_t, rlim.rlim_max);
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim)!= 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod darwin_fd_limit {
pub unsafe fn raise_fd_limit() {}
} | random_line_split |
|
deriving-span-Zero-tuple-struct.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This file was auto-generated using'src/etc/generate-deriving-span-tests.py'
#![feature(struct_variant)]
extern crate rand;
struct Error;
#[deriving(Zero)] //~ ERROR failed to find an implementation
struct Struct(
Error //~ ERROR
//~^ ERROR failed to find an implementation
//~^^ ERROR type `Error` does not implement any method in scope
);
fn | () {}
| main | identifier_name |
or_stack.rs | use l3::ast::*;
use std::ops::{Index, IndexMut};
use std::vec::Vec;
pub struct Frame {
pub global_index: usize,
pub e: usize,
pub cp: CodePtr,
pub b: usize,
pub bp: CodePtr,
pub tr: usize,
pub h: usize,
args: Vec<Addr>
}
impl Frame {
fn new(global_index: usize,
e: usize,
cp: CodePtr,
b: usize,
bp: CodePtr,
tr: usize,
h: usize,
n: usize)
-> Self
{
Frame {
global_index: global_index,
e: e,
cp: cp,
b: b,
bp: bp,
tr: tr,
h: h,
args: vec![Addr::HeapCell(0); n]
}
}
pub fn num_args(&self) -> usize {
self.args.len()
}
}
pub struct OrStack(Vec<Frame>);
impl OrStack {
pub fn new() -> Self {
OrStack(Vec::new())
}
pub fn push(&mut self,
global_index: usize,
e: usize,
cp: CodePtr,
b: usize,
bp: CodePtr,
tr: usize,
h: usize,
n: usize)
{
self.0.push(Frame::new(global_index, e, cp, b, bp, tr, h, n));
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn clear(&mut self) {
self.0.clear()
}
pub fn top(&self) -> Option<&Frame> {
self.0.last()
}
pub fn pop(&mut self) {
self.0.pop();
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl Index<usize> for OrStack {
type Output = Frame;
fn index(&self, index: usize) -> &Self::Output {
self.0.index(index)
}
}
impl IndexMut<usize> for OrStack {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.0.index_mut(index)
}
}
impl Index<usize> for Frame {
type Output = Addr;
fn | (&self, index: usize) -> &Self::Output {
self.args.index(index - 1)
}
}
impl IndexMut<usize> for Frame {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.args.index_mut(index - 1)
}
}
| index | identifier_name |
or_stack.rs | use l3::ast::*;
use std::ops::{Index, IndexMut};
use std::vec::Vec;
pub struct Frame {
pub global_index: usize,
pub e: usize,
pub cp: CodePtr,
pub b: usize,
pub bp: CodePtr,
pub tr: usize,
pub h: usize,
args: Vec<Addr>
}
impl Frame {
fn new(global_index: usize,
e: usize,
cp: CodePtr,
b: usize,
bp: CodePtr,
tr: usize,
h: usize,
n: usize)
-> Self
{
Frame {
global_index: global_index,
e: e,
cp: cp,
b: b,
bp: bp,
tr: tr,
h: h,
args: vec![Addr::HeapCell(0); n]
}
}
pub fn num_args(&self) -> usize {
self.args.len()
}
}
pub struct OrStack(Vec<Frame>);
impl OrStack {
pub fn new() -> Self {
OrStack(Vec::new())
}
pub fn push(&mut self,
global_index: usize,
e: usize,
cp: CodePtr,
b: usize,
bp: CodePtr,
tr: usize,
h: usize,
n: usize)
{
self.0.push(Frame::new(global_index, e, cp, b, bp, tr, h, n));
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn clear(&mut self) {
self.0.clear()
}
pub fn top(&self) -> Option<&Frame> {
self.0.last()
}
pub fn pop(&mut self) {
self.0.pop();
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl Index<usize> for OrStack {
type Output = Frame;
fn index(&self, index: usize) -> &Self::Output {
self.0.index(index)
} | fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.0.index_mut(index)
}
}
impl Index<usize> for Frame {
type Output = Addr;
fn index(&self, index: usize) -> &Self::Output {
self.args.index(index - 1)
}
}
impl IndexMut<usize> for Frame {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.args.index_mut(index - 1)
}
} | }
impl IndexMut<usize> for OrStack { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_name = "skia"]
#![crate_type = "rlib"]
#![feature(libc)]
extern crate libc;
| SkiaGrContextRef,
SkiaGrGLSharedSurfaceRef,
SkiaGrGLNativeContextRef,
SkiaSkNativeSharedGLContextCreate,
SkiaSkNativeSharedGLContextRetain,
SkiaSkNativeSharedGLContextRelease,
SkiaSkNativeSharedGLContextGetFBOID,
SkiaSkNativeSharedGLContextStealSurface,
SkiaSkNativeSharedGLContextGetGrContext,
SkiaSkNativeSharedGLContextMakeCurrent,
SkiaSkNativeSharedGLContextFlush,
};
pub mod skia; | pub use skia::{
SkiaSkNativeSharedGLContextRef, | random_line_split |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::TransportWrapper;
use opentitanlib::io::i2c::{I2cParams, Transfer};
use opentitanlib::transport::Capability;
/// Read plain data bytes from a I2C device.
#[derive(Debug, StructOpt)]
pub struct I2cRawRead {
#[structopt(short = "n", long, help = "Number of bytes to read.")]
length: usize,
}
#[derive(Debug, serde::Serialize)]
pub struct I2cRawReadResponse {
hexdata: String,
}
impl CommandDispatch for I2cRawRead {
fn run(
&self,
context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
let mut v = vec![0u8; self.length];
i2c_bus.run_transaction(context.addr, &mut [Transfer::Read(&mut v)])?;
Ok(Some(Box::new(I2cRawReadResponse {
hexdata: hex::encode(v),
})))
}
}
/// Write plain data bytes to a I2C device.
#[derive(Debug, StructOpt)]
pub struct I2cRawWrite {
#[structopt(short, long, help = "Hex data bytes to write.")]
hexdata: String,
}
impl CommandDispatch for I2cRawWrite {
fn run(
&self,
context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
i2c_bus.run_transaction(
context.addr,
&mut [Transfer::Write(&hex::decode(&self.hexdata)?)],
)?;
Ok(None)
}
}
/// Commands for interacting with a generic I2C bus.
#[derive(Debug, StructOpt, CommandDispatch)]
pub enum InternalI2cCommand {
RawRead(I2cRawRead),
RawWrite(I2cRawWrite),
}
#[derive(Debug, StructOpt)]
pub struct | {
#[structopt(flatten)]
params: I2cParams,
#[structopt(short, long, help = "7-bit address of I2C device (0..0x7F).")]
addr: u8,
#[structopt(subcommand)]
command: InternalI2cCommand,
}
impl CommandDispatch for I2cCommand {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
// None of the I2C commands care about the prior context, but they do
// care about the `bus` parameter in the current node.
self.command.run(self, transport)
}
}
| I2cCommand | identifier_name |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::TransportWrapper;
use opentitanlib::io::i2c::{I2cParams, Transfer};
use opentitanlib::transport::Capability;
/// Read plain data bytes from a I2C device.
#[derive(Debug, StructOpt)]
pub struct I2cRawRead {
#[structopt(short = "n", long, help = "Number of bytes to read.")]
length: usize,
}
#[derive(Debug, serde::Serialize)]
pub struct I2cRawReadResponse {
hexdata: String,
}
impl CommandDispatch for I2cRawRead {
fn run(
&self,
context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
let mut v = vec![0u8; self.length];
i2c_bus.run_transaction(context.addr, &mut [Transfer::Read(&mut v)])?;
Ok(Some(Box::new(I2cRawReadResponse {
hexdata: hex::encode(v),
})))
}
}
/// Write plain data bytes to a I2C device.
#[derive(Debug, StructOpt)]
pub struct I2cRawWrite {
#[structopt(short, long, help = "Hex data bytes to write.")]
hexdata: String,
}
impl CommandDispatch for I2cRawWrite {
fn run(
&self, | transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
i2c_bus.run_transaction(
context.addr,
&mut [Transfer::Write(&hex::decode(&self.hexdata)?)],
)?;
Ok(None)
}
}
/// Commands for interacting with a generic I2C bus.
#[derive(Debug, StructOpt, CommandDispatch)]
pub enum InternalI2cCommand {
RawRead(I2cRawRead),
RawWrite(I2cRawWrite),
}
#[derive(Debug, StructOpt)]
pub struct I2cCommand {
#[structopt(flatten)]
params: I2cParams,
#[structopt(short, long, help = "7-bit address of I2C device (0..0x7F).")]
addr: u8,
#[structopt(subcommand)]
command: InternalI2cCommand,
}
impl CommandDispatch for I2cCommand {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
// None of the I2C commands care about the prior context, but they do
// care about the `bus` parameter in the current node.
self.command.run(self, transport)
}
} | context: &dyn Any, | random_line_split |
i2c.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use erased_serde::Serialize;
use std::any::Any;
use structopt::StructOpt;
use opentitanlib::app::command::CommandDispatch;
use opentitanlib::app::TransportWrapper;
use opentitanlib::io::i2c::{I2cParams, Transfer};
use opentitanlib::transport::Capability;
/// Read plain data bytes from a I2C device.
#[derive(Debug, StructOpt)]
pub struct I2cRawRead {
#[structopt(short = "n", long, help = "Number of bytes to read.")]
length: usize,
}
#[derive(Debug, serde::Serialize)]
pub struct I2cRawReadResponse {
hexdata: String,
}
impl CommandDispatch for I2cRawRead {
fn run(
&self,
context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> |
}
/// Write plain data bytes to a I2C device.
#[derive(Debug, StructOpt)]
pub struct I2cRawWrite {
#[structopt(short, long, help = "Hex data bytes to write.")]
hexdata: String,
}
impl CommandDispatch for I2cRawWrite {
fn run(
&self,
context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
i2c_bus.run_transaction(
context.addr,
&mut [Transfer::Write(&hex::decode(&self.hexdata)?)],
)?;
Ok(None)
}
}
/// Commands for interacting with a generic I2C bus.
#[derive(Debug, StructOpt, CommandDispatch)]
pub enum InternalI2cCommand {
RawRead(I2cRawRead),
RawWrite(I2cRawWrite),
}
#[derive(Debug, StructOpt)]
pub struct I2cCommand {
#[structopt(flatten)]
params: I2cParams,
#[structopt(short, long, help = "7-bit address of I2C device (0..0x7F).")]
addr: u8,
#[structopt(subcommand)]
command: InternalI2cCommand,
}
impl CommandDispatch for I2cCommand {
fn run(
&self,
_context: &dyn Any,
transport: &TransportWrapper,
) -> Result<Option<Box<dyn Serialize>>> {
// None of the I2C commands care about the prior context, but they do
// care about the `bus` parameter in the current node.
self.command.run(self, transport)
}
}
| {
transport.capabilities()?.request(Capability::I2C).ok()?;
let context = context.downcast_ref::<I2cCommand>().unwrap();
let i2c_bus = context.params.create(transport)?;
let mut v = vec![0u8; self.length];
i2c_bus.run_transaction(context.addr, &mut [Transfer::Read(&mut v)])?;
Ok(Some(Box::new(I2cRawReadResponse {
hexdata: hex::encode(v),
})))
} | identifier_body |
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_vec_gen;
use malachite_base_test_util::runner::Runner;
use std::fmt::Display;
pub(crate) fn register(runner: &mut Runner) {
register_unsigned_unsigned_demos!(runner, demo_from_other_type_slice);
register_unsigned_unsigned_benches!(runner, benchmark_from_other_type_slice);
}
fn | <T: Display + FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>(
gm: GenMode,
config: GenConfig,
limit: usize,
) {
for xs in unsigned_vec_gen::<U>().get(gm, &config).take(limit) {
println!(
"{}::from_other_type_slice({:?}) = {}",
T::NAME,
xs,
T::from_other_type_slice(&xs)
);
}
}
fn benchmark_from_other_type_slice<T: FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>(
gm: GenMode,
config: GenConfig,
limit: usize,
file_name: &str,
) {
run_benchmark(
&format!("{}.from_other_type_slice(&[{}])", T::NAME, U::NAME),
BenchmarkType::Single,
unsigned_vec_gen::<U>().get(gm, &config),
gm.name(),
limit,
file_name,
&vec_len_bucketer(),
&mut [("Malachite", &mut |xs| {
no_out!(T::from_other_type_slice(&xs))
})],
);
}
| demo_from_other_type_slice | identifier_name |
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_vec_gen;
use malachite_base_test_util::runner::Runner;
use std::fmt::Display;
pub(crate) fn register(runner: &mut Runner) {
register_unsigned_unsigned_demos!(runner, demo_from_other_type_slice);
register_unsigned_unsigned_benches!(runner, benchmark_from_other_type_slice);
}
fn demo_from_other_type_slice<T: Display + FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>(
gm: GenMode,
config: GenConfig,
limit: usize,
) {
for xs in unsigned_vec_gen::<U>().get(gm, &config).take(limit) {
println!(
"{}::from_other_type_slice({:?}) = {}",
T::NAME,
xs,
T::from_other_type_slice(&xs)
);
}
}
fn benchmark_from_other_type_slice<T: FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>(
gm: GenMode,
config: GenConfig,
limit: usize,
file_name: &str,
) {
run_benchmark(
&format!("{}.from_other_type_slice(&[{}])", T::NAME, U::NAME),
BenchmarkType::Single,
unsigned_vec_gen::<U>().get(gm, &config),
gm.name(),
limit,
file_name,
&vec_len_bucketer(),
&mut [("Malachite", &mut |xs| {
no_out!(T::from_other_type_slice(&xs))
})], | );
} | random_line_split |
|
from_other_type_slice.rs | use malachite_base::named::Named;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::conversion::traits::FromOtherTypeSlice;
use malachite_base_test_util::bench::bucketers::vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_vec_gen;
use malachite_base_test_util::runner::Runner;
use std::fmt::Display;
pub(crate) fn register(runner: &mut Runner) {
register_unsigned_unsigned_demos!(runner, demo_from_other_type_slice);
register_unsigned_unsigned_benches!(runner, benchmark_from_other_type_slice);
}
fn demo_from_other_type_slice<T: Display + FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>(
gm: GenMode,
config: GenConfig,
limit: usize,
) {
for xs in unsigned_vec_gen::<U>().get(gm, &config).take(limit) {
println!(
"{}::from_other_type_slice({:?}) = {}",
T::NAME,
xs,
T::from_other_type_slice(&xs)
);
}
}
fn benchmark_from_other_type_slice<T: FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>(
gm: GenMode,
config: GenConfig,
limit: usize,
file_name: &str,
) | {
run_benchmark(
&format!("{}.from_other_type_slice(&[{}])", T::NAME, U::NAME),
BenchmarkType::Single,
unsigned_vec_gen::<U>().get(gm, &config),
gm.name(),
limit,
file_name,
&vec_len_bucketer(),
&mut [("Malachite", &mut |xs| {
no_out!(T::from_other_type_slice(&xs))
})],
);
} | identifier_body |
|
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs | use std::io::prelude::*;
use std::os::unix;
use std::path::Path;
// A simple implementation of `% cat path`
fn cat(path: &Path) -> io::Result<String> {
let mut f = try!(File::open(path));
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
// A simple implementation of `% echo s > path`
fn echo(s: &str, path: &Path) -> io::Result<()> {
let mut f = try!(File::create(path));
f.write_all(s.as_bytes())
}
// A simple implementation of `% touch path` (ignores existing files)
fn touch(path: &Path) -> io::Result<()> {
match OpenOptions::new().create(true).write(true).open(path) {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
fn main() {
println!("`mkdir a`");
// Create a directory, returns `io::Result<()>`
match fs::create_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(_) => {},
}
println!("`echo hello > a/b.txt`");
// The previous match can be simplified using the `unwrap_or_else` method
echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`mkdir -p a/c/d`");
// Recursively create a directory, returns `io::Result<()>`
fs::create_dir_all("a/c/d").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`touch a/c/e.txt`");
touch(&Path::new("a/c/e.txt")).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`ln -s../b.txt a/c/b.txt`");
// Create a symbolinc link, returns `io::Result<()>`
if cfg!(target_family = "unix") {
unix::fs::symlink("../b.txt", "a/c/b.txt").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
}
println!("`cat a/c/b.txt`");
match cat(&Path::new("a/c/b.txt")) {
Err(why) => println!("! {:?}", why.kind()),
Ok(s) => println!("> {}", s),
}
println!("`ls a`");
// Read the constants of a directory, return `io::Result<Vec<Path>>`
match fs::read_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(paths) => for path in paths {
println!("> {:?}", path.unwrap().path());
},
}
println!("`rm a/c/e.txt`");
// Remove a file, returns `io::Result<()>`
fs::remove_file("a/c/e.txt").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`rmdir a/c/d`");
// Remove an empty directory, returns `io::Result<()>`
fs::remove_dir("a/c/d").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
} |
use std::fs;
use std::fs::{File, OpenOptions};
use std::io; | random_line_split |
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs
use std::fs;
use std::fs::{File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::os::unix;
use std::path::Path;
// A simple implementation of `% cat path`
fn cat(path: &Path) -> io::Result<String> {
let mut f = try!(File::open(path));
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
// A simple implementation of `% echo s > path`
fn echo(s: &str, path: &Path) -> io::Result<()> {
let mut f = try!(File::create(path));
f.write_all(s.as_bytes())
}
// A simple implementation of `% touch path` (ignores existing files)
fn touch(path: &Path) -> io::Result<()> {
match OpenOptions::new().create(true).write(true).open(path) {
Ok(_) => Ok(()),
| atch fs::create_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(_) => {},
}
println!("`echo hello > a/b.txt`");
// The previous match can be simplified using the `unwrap_or_else` method
echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`mkdir -p a/c/d`");
// Recursively create a directory, returns `io::Result<()>`
fs::create_dir_all("a/c/d").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`touch a/c/e.txt`");
touch(&Path::new("a/c/e.txt")).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`ln -s../b.txt a/c/b.txt`");
// Create a symbolinc link, returns `io::Result<()>`
if cfg!(target_family = "unix") {
unix::fs::symlink("../b.txt", "a/c/b.txt").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
}
println!("`cat a/c/b.txt`");
match cat(&Path::new("a/c/b.txt")) {
Err(why) => println!("! {:?}", why.kind()),
Ok(s) => println!("> {}", s),
}
println!("`ls a`");
// Read the constants of a directory, return `io::Result<Vec<Path>>`
match fs::read_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(paths) => for path in paths {
println!("> {:?}", path.unwrap().path());
},
}
println!("`rm a/c/e.txt`");
// Remove a file, returns `io::Result<()>`
fs::remove_file("a/c/e.txt").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`rmdir a/c/d`");
// Remove an empty directory, returns `io::Result<()>`
fs::remove_dir("a/c/d").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
}
| Err(e) => Err(e),
}
}
fn main() {
println!("`mkdir a`");
// Create a directory, returns `io::Result<()>`
m | identifier_body |
fs.rs | /*
Rust - Std Misc Filesystem Operation
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
// fs.rs
use std::fs;
use std::fs::{File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::os::unix;
use std::path::Path;
// A simple implementation of `% cat path`
fn cat(path: &Path) -> io::Result<String> {
let mut f = try!(File::open(path));
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
// A simple implementation of `% echo s > path`
fn echo(s: &str, path: &Path) -> io::Result<()> {
let mut f = try!(File::create(path));
f.write_all(s.as_bytes())
}
// A simple implementation of `% touch path` (ignores existing files)
fn touch(path: &Path) -> io::Result<()> {
match OpenOptions::new().create(true).write(true).open( | {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
fn main() {
println!("`mkdir a`");
// Create a directory, returns `io::Result<()>`
match fs::create_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(_) => {},
}
println!("`echo hello > a/b.txt`");
// The previous match can be simplified using the `unwrap_or_else` method
echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`mkdir -p a/c/d`");
// Recursively create a directory, returns `io::Result<()>`
fs::create_dir_all("a/c/d").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`touch a/c/e.txt`");
touch(&Path::new("a/c/e.txt")).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`ln -s../b.txt a/c/b.txt`");
// Create a symbolinc link, returns `io::Result<()>`
if cfg!(target_family = "unix") {
unix::fs::symlink("../b.txt", "a/c/b.txt").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
}
println!("`cat a/c/b.txt`");
match cat(&Path::new("a/c/b.txt")) {
Err(why) => println!("! {:?}", why.kind()),
Ok(s) => println!("> {}", s),
}
println!("`ls a`");
// Read the constants of a directory, return `io::Result<Vec<Path>>`
match fs::read_dir("a") {
Err(why) => println!("! {:?}", why.kind()),
Ok(paths) => for path in paths {
println!("> {:?}", path.unwrap().path());
},
}
println!("`rm a/c/e.txt`");
// Remove a file, returns `io::Result<()>`
fs::remove_file("a/c/e.txt").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
println!("`rmdir a/c/d`");
// Remove an empty directory, returns `io::Result<()>`
fs::remove_dir("a/c/d").unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
}
| path) | identifier_name |
loops.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use self::Context::*;
use rustc::session::Session;
use rustc::hir::map::Map;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::{self, Node, Destination};
use syntax::ast;
use syntax_pos::Span;
use errors::Applicability;
#[derive(Clone, Copy, Debug, PartialEq)]
enum LoopKind {
Loop(hir::LoopSource),
WhileLoop,
}
impl LoopKind {
fn name(self) -> &'static str {
match self {
LoopKind::Loop(hir::LoopSource::Loop) => "loop",
LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
LoopKind::WhileLoop => "while",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Context {
Normal,
Loop(LoopKind),
Closure,
LabeledBlock,
AnonConst,
}
#[derive(Copy, Clone)]
struct CheckLoopVisitor<'a, 'hir: 'a> {
sess: &'a Session,
hir_map: &'a Map<'hir>,
cx: Context,
}
pub fn check_crate(sess: &Session, map: &Map) {
let krate = map.krate();
krate.visit_all_item_likes(&mut CheckLoopVisitor {
sess,
hir_map: map,
cx: Normal,
}.as_deep_visitor());
}
impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
fn | <'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
}
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, i));
}
fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
self.with_context(Normal, |v| intravisit::walk_impl_item(v, i));
}
fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) {
self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c));
}
fn visit_expr(&mut self, e: &'hir hir::Expr) {
match e.node {
hir::ExprKind::While(ref e, ref b, _) => {
self.with_context(Loop(LoopKind::WhileLoop), |v| {
v.visit_expr(&e);
v.visit_block(&b);
});
}
hir::ExprKind::Loop(ref b, _, source) => {
self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
}
hir::ExprKind::Closure(_, ref function_decl, b, _, _) => {
self.visit_fn_decl(&function_decl);
self.with_context(Closure, |v| v.visit_nested_body(b));
}
hir::ExprKind::Block(ref b, Some(_label)) => {
self.with_context(LabeledBlock, |v| v.visit_block(&b));
}
hir::ExprKind::Break(label, ref opt_expr) => {
opt_expr.as_ref().map(|e| self.visit_expr(e));
if self.require_label_in_labeled_block(e.span, &label, "break") {
// If we emitted an error about an unlabeled break in a labeled
// block, we don't need any further checking for this break any more
return;
}
let loop_id = match label.target_id.into() {
Ok(loop_id) => loop_id,
Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "break");
ast::DUMMY_NODE_ID
},
Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
};
if loop_id!= ast::DUMMY_NODE_ID {
if let Node::Block(_) = self.hir_map.find(loop_id).unwrap() {
return
}
}
if opt_expr.is_some() {
let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
None
} else {
Some(match self.hir_map.expect_expr(loop_id).node {
hir::ExprKind::While(..) => LoopKind::WhileLoop,
hir::ExprKind::Loop(_, _, source) => LoopKind::Loop(source),
ref r => span_bug!(e.span,
"break label resolved to a non-loop: {:?}", r),
})
};
match loop_kind {
None |
Some(LoopKind::Loop(hir::LoopSource::Loop)) => (),
Some(kind) => {
struct_span_err!(self.sess, e.span, E0571,
"`break` with value from a `{}` loop",
kind.name())
.span_label(e.span,
"can only break with a value inside \
`loop` or breakable block")
.span_suggestion_with_applicability(
e.span,
&format!(
"instead, use `break` on its own \
without a value inside this `{}` loop",
kind.name()
),
"break".to_string(),
Applicability::MaybeIncorrect,
)
.emit();
}
}
}
self.require_break_cx("break", e.span);
}
hir::ExprKind::Continue(destination) => {
self.require_label_in_labeled_block(e.span, &destination, "continue");
match destination.target_id {
Ok(loop_id) => {
if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() {
struct_span_err!(self.sess, e.span, E0696,
"`continue` pointing to a labeled block")
.span_label(e.span,
"labeled blocks cannot be `continue`'d")
.span_note(block.span,
"labeled block the continue points to")
.emit();
}
}
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "continue");
}
Err(_) => {}
}
self.require_break_cx("continue", e.span)
},
_ => intravisit::walk_expr(self, e),
}
}
}
impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
fn with_context<F>(&mut self, cx: Context, f: F)
where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
{
let old_cx = self.cx;
self.cx = cx;
f(self);
self.cx = old_cx;
}
fn require_break_cx(&self, name: &str, span: Span) {
match self.cx {
LabeledBlock | Loop(_) => {}
Closure => {
struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
.span_label(span, "cannot break inside of a closure")
.emit();
}
Normal | AnonConst => {
struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
.span_label(span, "cannot break outside of a loop")
.emit();
}
}
}
fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str)
-> bool
{
if self.cx == LabeledBlock {
if label.label.is_none() {
struct_span_err!(self.sess, span, E0695,
"unlabeled `{}` inside of a labeled block", cf_type)
.span_label(span,
format!("`{}` statements that would diverge to or through \
a labeled block need to bear a label", cf_type))
.emit();
return true;
}
}
return false;
}
fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
struct_span_err!(self.sess, span, E0590,
"`break` or `continue` with no label in the condition of a `while` loop")
.span_label(span,
format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
.emit();
}
}
| nested_visit_map | identifier_name |
loops.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use self::Context::*;
use rustc::session::Session;
use rustc::hir::map::Map;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::{self, Node, Destination};
use syntax::ast;
use syntax_pos::Span;
use errors::Applicability;
#[derive(Clone, Copy, Debug, PartialEq)]
enum LoopKind {
Loop(hir::LoopSource),
WhileLoop,
}
impl LoopKind {
fn name(self) -> &'static str {
match self {
LoopKind::Loop(hir::LoopSource::Loop) => "loop",
LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
LoopKind::WhileLoop => "while",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Context {
Normal,
Loop(LoopKind),
Closure,
LabeledBlock,
AnonConst,
}
#[derive(Copy, Clone)]
struct CheckLoopVisitor<'a, 'hir: 'a> {
sess: &'a Session,
hir_map: &'a Map<'hir>,
cx: Context,
}
pub fn check_crate(sess: &Session, map: &Map) {
let krate = map.krate();
krate.visit_all_item_likes(&mut CheckLoopVisitor {
sess,
hir_map: map,
cx: Normal,
}.as_deep_visitor());
}
impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
}
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, i));
}
fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
self.with_context(Normal, |v| intravisit::walk_impl_item(v, i));
}
fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) {
self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c));
}
fn visit_expr(&mut self, e: &'hir hir::Expr) {
match e.node {
hir::ExprKind::While(ref e, ref b, _) => {
self.with_context(Loop(LoopKind::WhileLoop), |v| {
v.visit_expr(&e);
v.visit_block(&b);
});
}
hir::ExprKind::Loop(ref b, _, source) => {
self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
}
hir::ExprKind::Closure(_, ref function_decl, b, _, _) => {
self.visit_fn_decl(&function_decl);
self.with_context(Closure, |v| v.visit_nested_body(b));
}
hir::ExprKind::Block(ref b, Some(_label)) => {
self.with_context(LabeledBlock, |v| v.visit_block(&b));
}
hir::ExprKind::Break(label, ref opt_expr) => {
opt_expr.as_ref().map(|e| self.visit_expr(e));
if self.require_label_in_labeled_block(e.span, &label, "break") {
// If we emitted an error about an unlabeled break in a labeled
// block, we don't need any further checking for this break any more
return;
}
let loop_id = match label.target_id.into() {
Ok(loop_id) => loop_id,
Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "break");
ast::DUMMY_NODE_ID
},
Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
};
if loop_id!= ast::DUMMY_NODE_ID {
if let Node::Block(_) = self.hir_map.find(loop_id).unwrap() {
return
}
}
if opt_expr.is_some() {
let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
None
} else {
Some(match self.hir_map.expect_expr(loop_id).node {
hir::ExprKind::While(..) => LoopKind::WhileLoop,
hir::ExprKind::Loop(_, _, source) => LoopKind::Loop(source),
ref r => span_bug!(e.span,
"break label resolved to a non-loop: {:?}", r),
})
};
match loop_kind {
None |
Some(LoopKind::Loop(hir::LoopSource::Loop)) => (),
Some(kind) => {
struct_span_err!(self.sess, e.span, E0571,
"`break` with value from a `{}` loop",
kind.name())
.span_label(e.span,
"can only break with a value inside \
`loop` or breakable block")
.span_suggestion_with_applicability(
e.span,
&format!(
"instead, use `break` on its own \
without a value inside this `{}` loop",
kind.name()
),
"break".to_string(),
Applicability::MaybeIncorrect,
)
.emit();
}
}
}
self.require_break_cx("break", e.span);
}
hir::ExprKind::Continue(destination) => {
self.require_label_in_labeled_block(e.span, &destination, "continue");
match destination.target_id {
Ok(loop_id) => {
if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() {
struct_span_err!(self.sess, e.span, E0696,
"`continue` pointing to a labeled block")
.span_label(e.span,
"labeled blocks cannot be `continue`'d")
.span_note(block.span,
"labeled block the continue points to")
.emit();
}
}
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "continue");
}
Err(_) => {}
}
self.require_break_cx("continue", e.span)
},
_ => intravisit::walk_expr(self, e),
}
}
}
impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
fn with_context<F>(&mut self, cx: Context, f: F)
where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
{
let old_cx = self.cx;
self.cx = cx;
f(self);
self.cx = old_cx;
}
fn require_break_cx(&self, name: &str, span: Span) {
match self.cx {
LabeledBlock | Loop(_) => {} | Normal | AnonConst => {
struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
.span_label(span, "cannot break outside of a loop")
.emit();
}
}
}
fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str)
-> bool
{
if self.cx == LabeledBlock {
if label.label.is_none() {
struct_span_err!(self.sess, span, E0695,
"unlabeled `{}` inside of a labeled block", cf_type)
.span_label(span,
format!("`{}` statements that would diverge to or through \
a labeled block need to bear a label", cf_type))
.emit();
return true;
}
}
return false;
}
fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
struct_span_err!(self.sess, span, E0590,
"`break` or `continue` with no label in the condition of a `while` loop")
.span_label(span,
format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
.emit();
}
} | Closure => {
struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
.span_label(span, "cannot break inside of a closure")
.emit();
} | random_line_split |
loops.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use self::Context::*;
use rustc::session::Session;
use rustc::hir::map::Map;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::{self, Node, Destination};
use syntax::ast;
use syntax_pos::Span;
use errors::Applicability;
#[derive(Clone, Copy, Debug, PartialEq)]
enum LoopKind {
Loop(hir::LoopSource),
WhileLoop,
}
impl LoopKind {
fn name(self) -> &'static str {
match self {
LoopKind::Loop(hir::LoopSource::Loop) => "loop",
LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
LoopKind::WhileLoop => "while",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Context {
Normal,
Loop(LoopKind),
Closure,
LabeledBlock,
AnonConst,
}
#[derive(Copy, Clone)]
struct CheckLoopVisitor<'a, 'hir: 'a> {
sess: &'a Session,
hir_map: &'a Map<'hir>,
cx: Context,
}
pub fn check_crate(sess: &Session, map: &Map) |
impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
}
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, i));
}
fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
self.with_context(Normal, |v| intravisit::walk_impl_item(v, i));
}
fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) {
self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c));
}
fn visit_expr(&mut self, e: &'hir hir::Expr) {
match e.node {
hir::ExprKind::While(ref e, ref b, _) => {
self.with_context(Loop(LoopKind::WhileLoop), |v| {
v.visit_expr(&e);
v.visit_block(&b);
});
}
hir::ExprKind::Loop(ref b, _, source) => {
self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
}
hir::ExprKind::Closure(_, ref function_decl, b, _, _) => {
self.visit_fn_decl(&function_decl);
self.with_context(Closure, |v| v.visit_nested_body(b));
}
hir::ExprKind::Block(ref b, Some(_label)) => {
self.with_context(LabeledBlock, |v| v.visit_block(&b));
}
hir::ExprKind::Break(label, ref opt_expr) => {
opt_expr.as_ref().map(|e| self.visit_expr(e));
if self.require_label_in_labeled_block(e.span, &label, "break") {
// If we emitted an error about an unlabeled break in a labeled
// block, we don't need any further checking for this break any more
return;
}
let loop_id = match label.target_id.into() {
Ok(loop_id) => loop_id,
Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "break");
ast::DUMMY_NODE_ID
},
Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
};
if loop_id!= ast::DUMMY_NODE_ID {
if let Node::Block(_) = self.hir_map.find(loop_id).unwrap() {
return
}
}
if opt_expr.is_some() {
let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
None
} else {
Some(match self.hir_map.expect_expr(loop_id).node {
hir::ExprKind::While(..) => LoopKind::WhileLoop,
hir::ExprKind::Loop(_, _, source) => LoopKind::Loop(source),
ref r => span_bug!(e.span,
"break label resolved to a non-loop: {:?}", r),
})
};
match loop_kind {
None |
Some(LoopKind::Loop(hir::LoopSource::Loop)) => (),
Some(kind) => {
struct_span_err!(self.sess, e.span, E0571,
"`break` with value from a `{}` loop",
kind.name())
.span_label(e.span,
"can only break with a value inside \
`loop` or breakable block")
.span_suggestion_with_applicability(
e.span,
&format!(
"instead, use `break` on its own \
without a value inside this `{}` loop",
kind.name()
),
"break".to_string(),
Applicability::MaybeIncorrect,
)
.emit();
}
}
}
self.require_break_cx("break", e.span);
}
hir::ExprKind::Continue(destination) => {
self.require_label_in_labeled_block(e.span, &destination, "continue");
match destination.target_id {
Ok(loop_id) => {
if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() {
struct_span_err!(self.sess, e.span, E0696,
"`continue` pointing to a labeled block")
.span_label(e.span,
"labeled blocks cannot be `continue`'d")
.span_note(block.span,
"labeled block the continue points to")
.emit();
}
}
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "continue");
}
Err(_) => {}
}
self.require_break_cx("continue", e.span)
},
_ => intravisit::walk_expr(self, e),
}
}
}
impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
fn with_context<F>(&mut self, cx: Context, f: F)
where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
{
let old_cx = self.cx;
self.cx = cx;
f(self);
self.cx = old_cx;
}
fn require_break_cx(&self, name: &str, span: Span) {
match self.cx {
LabeledBlock | Loop(_) => {}
Closure => {
struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
.span_label(span, "cannot break inside of a closure")
.emit();
}
Normal | AnonConst => {
struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
.span_label(span, "cannot break outside of a loop")
.emit();
}
}
}
fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str)
-> bool
{
if self.cx == LabeledBlock {
if label.label.is_none() {
struct_span_err!(self.sess, span, E0695,
"unlabeled `{}` inside of a labeled block", cf_type)
.span_label(span,
format!("`{}` statements that would diverge to or through \
a labeled block need to bear a label", cf_type))
.emit();
return true;
}
}
return false;
}
fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
struct_span_err!(self.sess, span, E0590,
"`break` or `continue` with no label in the condition of a `while` loop")
.span_label(span,
format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
.emit();
}
}
| {
let krate = map.krate();
krate.visit_all_item_likes(&mut CheckLoopVisitor {
sess,
hir_map: map,
cx: Normal,
}.as_deep_visitor());
} | identifier_body |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::DerivationContext;
use futures::{future, TryFutureExt, TryStreamExt};
use manifest::ManifestOps;
use mononoke_types::{BonsaiChangeset, ChangesetId, FileUnodeId, MPath};
use std::collections::HashMap;
use thiserror::Error;
mod derive;
mod mapping;
pub use mapping::RootUnodeManifestId;
#[derive(Debug, Error)]
pub enum ErrorKind {
#[error("Invalid bonsai changeset: {0}")]
InvalidBonsai(String),
}
/// A rename source for a file that is renamed.
#[derive(Debug, Clone)]
pub struct UnodeRenameSource {
/// Index of the parent changeset in the list of parents in the bonsai
/// changeset.
pub parent_index: usize,
/// Path of the file in the parent changeset (i.e., the path it was
/// renamed from).
pub from_path: MPath,
/// Unode ID of the file in the parent changeset.
pub unode_id: FileUnodeId,
}
/// Given a bonsai changeset, find sources for all of the renames that
/// happened in this changeset.
///
/// Returns a mapping from paths in the current changeset to the source of the
/// rename in the parent changesets.
pub async fn find_unode_rename_sources(
ctx: &CoreContext,
derivation_ctx: &DerivationContext,
bonsai: &BonsaiChangeset,
) -> Result<HashMap<MPath, UnodeRenameSource>, Error> {
// Collect together a map of (source_path -> [dest_paths]) for each parent
// changeset.
let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
references
.entry(*csid)
.or_insert_with(HashMap::new)
.entry(from_path)
.or_insert_with(Vec::new)
.push(to_path);
}
}
let blobstore = derivation_ctx.blobstore();
let sources_futs = references.into_iter().map(|(csid, mut paths)| {
cloned!(blobstore);
async move {
let parent_index = bonsai.parents().position(|p| p == csid).ok_or_else(|| {
anyhow!(
"bonsai changeset {} contains invalid copy from parent: {}",
bonsai.get_changeset_id(),
csid
)
})?;
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid)
.await?;
let from_paths: Vec<_> = paths.keys().cloned().cloned().collect();
let unodes = mf_root
.manifest_unode_id()
.find_entries(ctx.clone(), blobstore, from_paths)
.try_collect::<Vec<_>>()
.await?;
let mut sources = Vec::new();
for (from_path, entry) in unodes {
if let (Some(from_path), Some(unode_id)) = (from_path, entry.into_leaf()) {
if let Some(to_paths) = paths.remove(&from_path) |
}
}
Ok(sources)
}
});
future::try_join_all(sources_futs)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
/// Given bonsai changeset find unodes for all renames that happened in this changesest.
///
/// Returns mapping from paths in current changeset to file unodes in parents changesets
/// that were coppied to a given path.
///
/// This version of the function is incorrect: it fails to take into account
/// files that are copied multiple times. The function is retained for
/// blame_v1 compatibility.
pub async fn find_unode_renames_incorrect_for_blame_v1(
ctx: &CoreContext,
derivation_ctx: &DerivationContext,
bonsai: &BonsaiChangeset,
) -> Result<HashMap<MPath, FileUnodeId>, Error> {
let mut references: HashMap<ChangesetId, HashMap<MPath, MPath>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
references
.entry(*csid)
.or_default()
.insert(from_path.clone(), to_path.clone());
}
}
let unodes = references.into_iter().map(|(csid, mut paths)| async move {
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid)
.await?;
let from_paths: Vec<_> = paths.keys().cloned().collect();
let blobstore = derivation_ctx.blobstore();
mf_root
.manifest_unode_id()
.clone()
.find_entries(ctx.clone(), blobstore.clone(), from_paths)
.map_ok(|(from_path, entry)| Some((from_path?, entry.into_leaf()?)))
.try_filter_map(future::ok)
.try_collect::<Vec<_>>()
.map_ok(move |unodes| {
unodes
.into_iter()
.filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id)))
.collect::<HashMap<_, _>>()
})
.await
});
future::try_join_all(unodes)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use blobrepo::BlobRepo;
use blobstore::Loadable;
use borrowed::borrowed;
use context::CoreContext;
use fbinit::FacebookInit;
use mononoke_types::MPath;
use repo_derived_data::RepoDerivedDataRef;
use tests_utils::CreateCommitContext;
#[fbinit::test]
async fn test_find_unode_rename_sources(fb: FacebookInit) -> Result<()> {
let ctx = CoreContext::test_mock(fb);
let repo: BlobRepo = test_repo_factory::build_empty()?;
borrowed!(ctx, repo);
let c1 = CreateCommitContext::new_root(ctx, repo)
.add_file("file1", "content")
.commit()
.await?;
let c2 = CreateCommitContext::new(ctx, repo, vec![c1])
.add_file("file2", "content")
.commit()
.await?;
let c3 = CreateCommitContext::new(ctx, repo, vec![c1])
.add_file("file3", "content")
.commit()
.await?;
let c4 = CreateCommitContext::new(ctx, repo, vec![c2, c3])
.add_file_with_copy_info("file1a", "content a", (c2, "file1"))
.delete_file("file1")
.add_file_with_copy_info("file2a", "content a", (c2, "file2"))
.add_file_with_copy_info("file2b", "content b", (c2, "file2"))
.add_file_with_copy_info("file3a", "content a", (c3, "file3"))
.add_file_with_copy_info("file3b", "content b", (c3, "file3"))
.commit()
.await?;
let bonsai = c4.load(ctx, repo.blobstore()).await?;
let derivation_ctx = repo.repo_derived_data().manager().derivation_context(None);
let renames = crate::find_unode_rename_sources(ctx, &derivation_ctx, &bonsai).await?;
let check = |path: &str, parent_index: usize, from_path: &str| {
let source = renames
.get(&MPath::new(path).unwrap())
.expect("path should exist");
assert_eq!(source.parent_index, parent_index);
assert_eq!(source.from_path, MPath::new(from_path).unwrap());
};
check("file1a", 0, "file1");
check("file2a", 0, "file2");
check("file2b", 0, "file2");
check("file3a", 1, "file3");
check("file3b", 1, "file3");
assert_eq!(renames.len(), 5);
Ok(())
}
}
| {
for to_path in to_paths {
sources.push((
to_path.clone(),
UnodeRenameSource {
parent_index,
from_path: from_path.clone(),
unode_id,
},
));
}
} | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::DerivationContext;
use futures::{future, TryFutureExt, TryStreamExt};
use manifest::ManifestOps;
use mononoke_types::{BonsaiChangeset, ChangesetId, FileUnodeId, MPath};
use std::collections::HashMap;
use thiserror::Error;
mod derive;
mod mapping;
pub use mapping::RootUnodeManifestId;
#[derive(Debug, Error)]
pub enum ErrorKind {
#[error("Invalid bonsai changeset: {0}")]
InvalidBonsai(String),
}
/// A rename source for a file that is renamed.
#[derive(Debug, Clone)]
pub struct UnodeRenameSource {
/// Index of the parent changeset in the list of parents in the bonsai
/// changeset.
pub parent_index: usize,
/// Path of the file in the parent changeset (i.e., the path it was
/// renamed from).
pub from_path: MPath,
/// Unode ID of the file in the parent changeset.
pub unode_id: FileUnodeId,
}
/// Given a bonsai changeset, find sources for all of the renames that
/// happened in this changeset.
///
/// Returns a mapping from paths in the current changeset to the source of the
/// rename in the parent changesets.
pub async fn find_unode_rename_sources(
ctx: &CoreContext,
derivation_ctx: &DerivationContext,
bonsai: &BonsaiChangeset,
) -> Result<HashMap<MPath, UnodeRenameSource>, Error> {
// Collect together a map of (source_path -> [dest_paths]) for each parent
// changeset.
let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
references
.entry(*csid)
.or_insert_with(HashMap::new)
.entry(from_path)
.or_insert_with(Vec::new)
.push(to_path);
}
}
let blobstore = derivation_ctx.blobstore();
let sources_futs = references.into_iter().map(|(csid, mut paths)| {
cloned!(blobstore);
async move {
let parent_index = bonsai.parents().position(|p| p == csid).ok_or_else(|| {
anyhow!(
"bonsai changeset {} contains invalid copy from parent: {}",
bonsai.get_changeset_id(),
csid
)
})?;
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid)
.await?;
let from_paths: Vec<_> = paths.keys().cloned().cloned().collect();
let unodes = mf_root
.manifest_unode_id()
.find_entries(ctx.clone(), blobstore, from_paths)
.try_collect::<Vec<_>>()
.await?;
let mut sources = Vec::new();
for (from_path, entry) in unodes {
if let (Some(from_path), Some(unode_id)) = (from_path, entry.into_leaf()) {
if let Some(to_paths) = paths.remove(&from_path) {
for to_path in to_paths {
sources.push((
to_path.clone(),
UnodeRenameSource {
parent_index,
from_path: from_path.clone(),
unode_id,
},
));
}
}
}
}
Ok(sources)
}
});
future::try_join_all(sources_futs)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
/// Given bonsai changeset find unodes for all renames that happened in this changesest.
///
/// Returns mapping from paths in current changeset to file unodes in parents changesets
/// that were coppied to a given path.
///
/// This version of the function is incorrect: it fails to take into account
/// files that are copied multiple times. The function is retained for
/// blame_v1 compatibility.
pub async fn find_unode_renames_incorrect_for_blame_v1(
ctx: &CoreContext,
derivation_ctx: &DerivationContext,
bonsai: &BonsaiChangeset,
) -> Result<HashMap<MPath, FileUnodeId>, Error> {
let mut references: HashMap<ChangesetId, HashMap<MPath, MPath>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
references
.entry(*csid)
.or_default()
.insert(from_path.clone(), to_path.clone());
}
}
let unodes = references.into_iter().map(|(csid, mut paths)| async move {
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid)
.await?;
let from_paths: Vec<_> = paths.keys().cloned().collect();
let blobstore = derivation_ctx.blobstore();
mf_root
.manifest_unode_id()
.clone()
.find_entries(ctx.clone(), blobstore.clone(), from_paths)
.map_ok(|(from_path, entry)| Some((from_path?, entry.into_leaf()?)))
.try_filter_map(future::ok)
.try_collect::<Vec<_>>()
.map_ok(move |unodes| {
unodes
.into_iter() | .collect::<HashMap<_, _>>()
})
.await
});
future::try_join_all(unodes)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use blobrepo::BlobRepo;
use blobstore::Loadable;
use borrowed::borrowed;
use context::CoreContext;
use fbinit::FacebookInit;
use mononoke_types::MPath;
use repo_derived_data::RepoDerivedDataRef;
use tests_utils::CreateCommitContext;
#[fbinit::test]
async fn test_find_unode_rename_sources(fb: FacebookInit) -> Result<()> {
let ctx = CoreContext::test_mock(fb);
let repo: BlobRepo = test_repo_factory::build_empty()?;
borrowed!(ctx, repo);
let c1 = CreateCommitContext::new_root(ctx, repo)
.add_file("file1", "content")
.commit()
.await?;
let c2 = CreateCommitContext::new(ctx, repo, vec![c1])
.add_file("file2", "content")
.commit()
.await?;
let c3 = CreateCommitContext::new(ctx, repo, vec![c1])
.add_file("file3", "content")
.commit()
.await?;
let c4 = CreateCommitContext::new(ctx, repo, vec![c2, c3])
.add_file_with_copy_info("file1a", "content a", (c2, "file1"))
.delete_file("file1")
.add_file_with_copy_info("file2a", "content a", (c2, "file2"))
.add_file_with_copy_info("file2b", "content b", (c2, "file2"))
.add_file_with_copy_info("file3a", "content a", (c3, "file3"))
.add_file_with_copy_info("file3b", "content b", (c3, "file3"))
.commit()
.await?;
let bonsai = c4.load(ctx, repo.blobstore()).await?;
let derivation_ctx = repo.repo_derived_data().manager().derivation_context(None);
let renames = crate::find_unode_rename_sources(ctx, &derivation_ctx, &bonsai).await?;
let check = |path: &str, parent_index: usize, from_path: &str| {
let source = renames
.get(&MPath::new(path).unwrap())
.expect("path should exist");
assert_eq!(source.parent_index, parent_index);
assert_eq!(source.from_path, MPath::new(from_path).unwrap());
};
check("file1a", 0, "file1");
check("file2a", 0, "file2");
check("file2b", 0, "file2");
check("file3a", 1, "file3");
check("file3b", 1, "file3");
assert_eq!(renames.len(), 5);
Ok(())
}
} | .filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id))) | random_line_split |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::DerivationContext;
use futures::{future, TryFutureExt, TryStreamExt};
use manifest::ManifestOps;
use mononoke_types::{BonsaiChangeset, ChangesetId, FileUnodeId, MPath};
use std::collections::HashMap;
use thiserror::Error;
mod derive;
mod mapping;
pub use mapping::RootUnodeManifestId;
#[derive(Debug, Error)]
pub enum ErrorKind {
#[error("Invalid bonsai changeset: {0}")]
InvalidBonsai(String),
}
/// A rename source for a file that is renamed.
#[derive(Debug, Clone)]
pub struct | {
/// Index of the parent changeset in the list of parents in the bonsai
/// changeset.
pub parent_index: usize,
/// Path of the file in the parent changeset (i.e., the path it was
/// renamed from).
pub from_path: MPath,
/// Unode ID of the file in the parent changeset.
pub unode_id: FileUnodeId,
}
/// Given a bonsai changeset, find sources for all of the renames that
/// happened in this changeset.
///
/// Returns a mapping from paths in the current changeset to the source of the
/// rename in the parent changesets.
pub async fn find_unode_rename_sources(
ctx: &CoreContext,
derivation_ctx: &DerivationContext,
bonsai: &BonsaiChangeset,
) -> Result<HashMap<MPath, UnodeRenameSource>, Error> {
// Collect together a map of (source_path -> [dest_paths]) for each parent
// changeset.
let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
references
.entry(*csid)
.or_insert_with(HashMap::new)
.entry(from_path)
.or_insert_with(Vec::new)
.push(to_path);
}
}
let blobstore = derivation_ctx.blobstore();
let sources_futs = references.into_iter().map(|(csid, mut paths)| {
cloned!(blobstore);
async move {
let parent_index = bonsai.parents().position(|p| p == csid).ok_or_else(|| {
anyhow!(
"bonsai changeset {} contains invalid copy from parent: {}",
bonsai.get_changeset_id(),
csid
)
})?;
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid)
.await?;
let from_paths: Vec<_> = paths.keys().cloned().cloned().collect();
let unodes = mf_root
.manifest_unode_id()
.find_entries(ctx.clone(), blobstore, from_paths)
.try_collect::<Vec<_>>()
.await?;
let mut sources = Vec::new();
for (from_path, entry) in unodes {
if let (Some(from_path), Some(unode_id)) = (from_path, entry.into_leaf()) {
if let Some(to_paths) = paths.remove(&from_path) {
for to_path in to_paths {
sources.push((
to_path.clone(),
UnodeRenameSource {
parent_index,
from_path: from_path.clone(),
unode_id,
},
));
}
}
}
}
Ok(sources)
}
});
future::try_join_all(sources_futs)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
/// Given bonsai changeset find unodes for all renames that happened in this changesest.
///
/// Returns mapping from paths in current changeset to file unodes in parents changesets
/// that were coppied to a given path.
///
/// This version of the function is incorrect: it fails to take into account
/// files that are copied multiple times. The function is retained for
/// blame_v1 compatibility.
pub async fn find_unode_renames_incorrect_for_blame_v1(
ctx: &CoreContext,
derivation_ctx: &DerivationContext,
bonsai: &BonsaiChangeset,
) -> Result<HashMap<MPath, FileUnodeId>, Error> {
let mut references: HashMap<ChangesetId, HashMap<MPath, MPath>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
references
.entry(*csid)
.or_default()
.insert(from_path.clone(), to_path.clone());
}
}
let unodes = references.into_iter().map(|(csid, mut paths)| async move {
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid)
.await?;
let from_paths: Vec<_> = paths.keys().cloned().collect();
let blobstore = derivation_ctx.blobstore();
mf_root
.manifest_unode_id()
.clone()
.find_entries(ctx.clone(), blobstore.clone(), from_paths)
.map_ok(|(from_path, entry)| Some((from_path?, entry.into_leaf()?)))
.try_filter_map(future::ok)
.try_collect::<Vec<_>>()
.map_ok(move |unodes| {
unodes
.into_iter()
.filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id)))
.collect::<HashMap<_, _>>()
})
.await
});
future::try_join_all(unodes)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use blobrepo::BlobRepo;
use blobstore::Loadable;
use borrowed::borrowed;
use context::CoreContext;
use fbinit::FacebookInit;
use mononoke_types::MPath;
use repo_derived_data::RepoDerivedDataRef;
use tests_utils::CreateCommitContext;
#[fbinit::test]
async fn test_find_unode_rename_sources(fb: FacebookInit) -> Result<()> {
let ctx = CoreContext::test_mock(fb);
let repo: BlobRepo = test_repo_factory::build_empty()?;
borrowed!(ctx, repo);
let c1 = CreateCommitContext::new_root(ctx, repo)
.add_file("file1", "content")
.commit()
.await?;
let c2 = CreateCommitContext::new(ctx, repo, vec![c1])
.add_file("file2", "content")
.commit()
.await?;
let c3 = CreateCommitContext::new(ctx, repo, vec![c1])
.add_file("file3", "content")
.commit()
.await?;
let c4 = CreateCommitContext::new(ctx, repo, vec![c2, c3])
.add_file_with_copy_info("file1a", "content a", (c2, "file1"))
.delete_file("file1")
.add_file_with_copy_info("file2a", "content a", (c2, "file2"))
.add_file_with_copy_info("file2b", "content b", (c2, "file2"))
.add_file_with_copy_info("file3a", "content a", (c3, "file3"))
.add_file_with_copy_info("file3b", "content b", (c3, "file3"))
.commit()
.await?;
let bonsai = c4.load(ctx, repo.blobstore()).await?;
let derivation_ctx = repo.repo_derived_data().manager().derivation_context(None);
let renames = crate::find_unode_rename_sources(ctx, &derivation_ctx, &bonsai).await?;
let check = |path: &str, parent_index: usize, from_path: &str| {
let source = renames
.get(&MPath::new(path).unwrap())
.expect("path should exist");
assert_eq!(source.parent_index, parent_index);
assert_eq!(source.from_path, MPath::new(from_path).unwrap());
};
check("file1a", 0, "file1");
check("file2a", 0, "file2");
check("file2b", 0, "file2");
check("file3a", 1, "file3");
check("file3b", 1, "file3");
assert_eq!(renames.len(), 5);
Ok(())
}
}
| UnodeRenameSource | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use anyhow::{anyhow, Error, Result};
use cloned::cloned;
use context::CoreContext;
use derived_data_manager::DerivationContext;
use futures::{future, TryFutureExt, TryStreamExt};
use manifest::ManifestOps;
use mononoke_types::{BonsaiChangeset, ChangesetId, FileUnodeId, MPath};
use std::collections::HashMap;
use thiserror::Error;
mod derive;
mod mapping;
pub use mapping::RootUnodeManifestId;
#[derive(Debug, Error)]
pub enum ErrorKind {
#[error("Invalid bonsai changeset: {0}")]
InvalidBonsai(String),
}
/// A rename source for a file that is renamed.
#[derive(Debug, Clone)]
pub struct UnodeRenameSource {
/// Index of the parent changeset in the list of parents in the bonsai
/// changeset.
pub parent_index: usize,
/// Path of the file in the parent changeset (i.e., the path it was
/// renamed from).
pub from_path: MPath,
/// Unode ID of the file in the parent changeset.
pub unode_id: FileUnodeId,
}
/// Given a bonsai changeset, find sources for all of the renames that
/// happened in this changeset.
///
/// Returns a mapping from paths in the current changeset to the source of the
/// rename in the parent changesets.
pub async fn find_unode_rename_sources(
ctx: &CoreContext,
derivation_ctx: &DerivationContext,
bonsai: &BonsaiChangeset,
) -> Result<HashMap<MPath, UnodeRenameSource>, Error> | anyhow!(
"bonsai changeset {} contains invalid copy from parent: {}",
bonsai.get_changeset_id(),
csid
)
})?;
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid)
.await?;
let from_paths: Vec<_> = paths.keys().cloned().cloned().collect();
let unodes = mf_root
.manifest_unode_id()
.find_entries(ctx.clone(), blobstore, from_paths)
.try_collect::<Vec<_>>()
.await?;
let mut sources = Vec::new();
for (from_path, entry) in unodes {
if let (Some(from_path), Some(unode_id)) = (from_path, entry.into_leaf()) {
if let Some(to_paths) = paths.remove(&from_path) {
for to_path in to_paths {
sources.push((
to_path.clone(),
UnodeRenameSource {
parent_index,
from_path: from_path.clone(),
unode_id,
},
));
}
}
}
}
Ok(sources)
}
});
future::try_join_all(sources_futs)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
/// Given bonsai changeset find unodes for all renames that happened in this changesest.
///
/// Returns mapping from paths in current changeset to file unodes in parents changesets
/// that were coppied to a given path.
///
/// This version of the function is incorrect: it fails to take into account
/// files that are copied multiple times. The function is retained for
/// blame_v1 compatibility.
pub async fn find_unode_renames_incorrect_for_blame_v1(
ctx: &CoreContext,
derivation_ctx: &DerivationContext,
bonsai: &BonsaiChangeset,
) -> Result<HashMap<MPath, FileUnodeId>, Error> {
let mut references: HashMap<ChangesetId, HashMap<MPath, MPath>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
references
.entry(*csid)
.or_default()
.insert(from_path.clone(), to_path.clone());
}
}
let unodes = references.into_iter().map(|(csid, mut paths)| async move {
let mf_root = derivation_ctx
.derive_dependency::<RootUnodeManifestId>(ctx, csid)
.await?;
let from_paths: Vec<_> = paths.keys().cloned().collect();
let blobstore = derivation_ctx.blobstore();
mf_root
.manifest_unode_id()
.clone()
.find_entries(ctx.clone(), blobstore.clone(), from_paths)
.map_ok(|(from_path, entry)| Some((from_path?, entry.into_leaf()?)))
.try_filter_map(future::ok)
.try_collect::<Vec<_>>()
.map_ok(move |unodes| {
unodes
.into_iter()
.filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id)))
.collect::<HashMap<_, _>>()
})
.await
});
future::try_join_all(unodes)
.map_ok(|unodes| unodes.into_iter().flatten().collect())
.await
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use blobrepo::BlobRepo;
use blobstore::Loadable;
use borrowed::borrowed;
use context::CoreContext;
use fbinit::FacebookInit;
use mononoke_types::MPath;
use repo_derived_data::RepoDerivedDataRef;
use tests_utils::CreateCommitContext;
#[fbinit::test]
async fn test_find_unode_rename_sources(fb: FacebookInit) -> Result<()> {
let ctx = CoreContext::test_mock(fb);
let repo: BlobRepo = test_repo_factory::build_empty()?;
borrowed!(ctx, repo);
let c1 = CreateCommitContext::new_root(ctx, repo)
.add_file("file1", "content")
.commit()
.await?;
let c2 = CreateCommitContext::new(ctx, repo, vec![c1])
.add_file("file2", "content")
.commit()
.await?;
let c3 = CreateCommitContext::new(ctx, repo, vec![c1])
.add_file("file3", "content")
.commit()
.await?;
let c4 = CreateCommitContext::new(ctx, repo, vec![c2, c3])
.add_file_with_copy_info("file1a", "content a", (c2, "file1"))
.delete_file("file1")
.add_file_with_copy_info("file2a", "content a", (c2, "file2"))
.add_file_with_copy_info("file2b", "content b", (c2, "file2"))
.add_file_with_copy_info("file3a", "content a", (c3, "file3"))
.add_file_with_copy_info("file3b", "content b", (c3, "file3"))
.commit()
.await?;
let bonsai = c4.load(ctx, repo.blobstore()).await?;
let derivation_ctx = repo.repo_derived_data().manager().derivation_context(None);
let renames = crate::find_unode_rename_sources(ctx, &derivation_ctx, &bonsai).await?;
let check = |path: &str, parent_index: usize, from_path: &str| {
let source = renames
.get(&MPath::new(path).unwrap())
.expect("path should exist");
assert_eq!(source.parent_index, parent_index);
assert_eq!(source.from_path, MPath::new(from_path).unwrap());
};
check("file1a", 0, "file1");
check("file2a", 0, "file2");
check("file2b", 0, "file2");
check("file3a", 1, "file3");
check("file3b", 1, "file3");
assert_eq!(renames.len(), 5);
Ok(())
}
}
| {
// Collect together a map of (source_path -> [dest_paths]) for each parent
// changeset.
let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new();
for (to_path, file_change) in bonsai.file_changes() {
if let Some((from_path, csid)) = file_change.copy_from() {
references
.entry(*csid)
.or_insert_with(HashMap::new)
.entry(from_path)
.or_insert_with(Vec::new)
.push(to_path);
}
}
let blobstore = derivation_ctx.blobstore();
let sources_futs = references.into_iter().map(|(csid, mut paths)| {
cloned!(blobstore);
async move {
let parent_index = bonsai.parents().position(|p| p == csid).ok_or_else(|| { | identifier_body |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str {
match num {
0...9 => singler(num),
10 => "ten",
11 => "eleven",
12 => "twelve",
13 => "thirteen",
14 => "fourteen",
15 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen",
_ => "",
}
}
fn hunnert<'a>(num: u32) -> String {
match num {
0...19 => twentor(num).to_string(),
20 => "twenty".to_string(),
21...29 => format!("twenty-{}", singler(num % 20)),
30 => "thirty".to_string(),
31...39 => format!("thirty-{}", singler(num % 30)),
40 => "forty".to_string(),
41...49 => format!("forty-{}", singler(num % 40)),
50 => "fifty".to_string(),
51...59 => format!("fifty-{}", singler(num % 50)),
60 => "sixty".to_string(),
61...69 => format!("sixty-{}", singler(num % 60)),
70 => "seventy".to_string(),
71...79 => format!("seventy-{}", singler(num % 70)),
80 => "eighty".to_string(), | }
fn thouse(num: u32) -> String {
match num {
0...99 => hunnert(num).to_string(),
100 => "one hundred".to_string(),
101...199 => format!("one hundred and {}", hunnert(num % 100)),
200 => "two hundred".to_string(),
201...299 => format!("two hundred and {}", hunnert(num % 100)),
300 => "three hundred".to_string(),
301...399 => format!("three hundred and {}", hunnert(num % 100)),
400 => "four hundred".to_string(),
401...499 => format!("four hundred and {}", hunnert(num % 100)),
500 => "five hundred".to_string(),
501...599 => format!("five hundred and {}", hunnert(num % 100)),
600 => "six hundred".to_string(),
601...699 => format!("six hundred and {}", hunnert(num % 100)),
700 => "seven hundred".to_string(),
701...799 => format!("seven hundred and {}", hunnert(num % 100)),
800 => "eight hundred".to_string(),
801...899 => format!("eight hundred and {}", hunnert(num % 100)),
900 => "nine hundred".to_string(),
901...999 => format!("nine hundred and {}", hunnert(num % 100)),
1000 => "one thousand".to_string(),
_ => "".to_string(),
}
}
fn count(s: String) -> u32 {
s.chars().fold(0, |memo, ch| {
memo + match ch {
'a'...'z' => 1,
_ => 0,
}
})
}
pub fn run() {
let sum: u32 = (1..1001).map(|i| count(thouse(i))).sum();
println!("Sum of number words: {}", sum);
} | 81...89 => format!("eighty-{}", singler(num % 80)),
90 => "ninety".to_string(),
91...99 => format!("ninety-{}", singler(num % 90)),
_ => "".to_string(),
} | random_line_split |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str |
fn hunnert<'a>(num: u32) -> String {
match num {
0...19 => twentor(num).to_string(),
20 => "twenty".to_string(),
21...29 => format!("twenty-{}", singler(num % 20)),
30 => "thirty".to_string(),
31...39 => format!("thirty-{}", singler(num % 30)),
40 => "forty".to_string(),
41...49 => format!("forty-{}", singler(num % 40)),
50 => "fifty".to_string(),
51...59 => format!("fifty-{}", singler(num % 50)),
60 => "sixty".to_string(),
61...69 => format!("sixty-{}", singler(num % 60)),
70 => "seventy".to_string(),
71...79 => format!("seventy-{}", singler(num % 70)),
80 => "eighty".to_string(),
81...89 => format!("eighty-{}", singler(num % 80)),
90 => "ninety".to_string(),
91...99 => format!("ninety-{}", singler(num % 90)),
_ => "".to_string(),
}
}
fn thouse(num: u32) -> String {
match num {
0...99 => hunnert(num).to_string(),
100 => "one hundred".to_string(),
101...199 => format!("one hundred and {}", hunnert(num % 100)),
200 => "two hundred".to_string(),
201...299 => format!("two hundred and {}", hunnert(num % 100)),
300 => "three hundred".to_string(),
301...399 => format!("three hundred and {}", hunnert(num % 100)),
400 => "four hundred".to_string(),
401...499 => format!("four hundred and {}", hunnert(num % 100)),
500 => "five hundred".to_string(),
501...599 => format!("five hundred and {}", hunnert(num % 100)),
600 => "six hundred".to_string(),
601...699 => format!("six hundred and {}", hunnert(num % 100)),
700 => "seven hundred".to_string(),
701...799 => format!("seven hundred and {}", hunnert(num % 100)),
800 => "eight hundred".to_string(),
801...899 => format!("eight hundred and {}", hunnert(num % 100)),
900 => "nine hundred".to_string(),
901...999 => format!("nine hundred and {}", hunnert(num % 100)),
1000 => "one thousand".to_string(),
_ => "".to_string(),
}
}
fn count(s: String) -> u32 {
s.chars().fold(0, |memo, ch| {
memo + match ch {
'a'...'z' => 1,
_ => 0,
}
})
}
pub fn run() {
let sum: u32 = (1..1001).map(|i| count(thouse(i))).sum();
println!("Sum of number words: {}", sum);
} | {
match num {
0...9 => singler(num),
10 => "ten",
11 => "eleven",
12 => "twelve",
13 => "thirteen",
14 => "fourteen",
15 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen",
_ => "",
}
} | identifier_body |
seventeen.rs | use std::string::ToString;
fn singler<'a>(digit: u32) -> &'a str {
match digit {
0 => "zero",
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
_ => "",
}
}
fn twentor<'a>(num: u32) -> &'a str {
match num {
0...9 => singler(num),
10 => "ten",
11 => "eleven",
12 => "twelve",
13 => "thirteen",
14 => "fourteen",
15 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen",
_ => "",
}
}
fn hunnert<'a>(num: u32) -> String {
match num {
0...19 => twentor(num).to_string(),
20 => "twenty".to_string(),
21...29 => format!("twenty-{}", singler(num % 20)),
30 => "thirty".to_string(),
31...39 => format!("thirty-{}", singler(num % 30)),
40 => "forty".to_string(),
41...49 => format!("forty-{}", singler(num % 40)),
50 => "fifty".to_string(),
51...59 => format!("fifty-{}", singler(num % 50)),
60 => "sixty".to_string(),
61...69 => format!("sixty-{}", singler(num % 60)),
70 => "seventy".to_string(),
71...79 => format!("seventy-{}", singler(num % 70)),
80 => "eighty".to_string(),
81...89 => format!("eighty-{}", singler(num % 80)),
90 => "ninety".to_string(),
91...99 => format!("ninety-{}", singler(num % 90)),
_ => "".to_string(),
}
}
fn thouse(num: u32) -> String {
match num {
0...99 => hunnert(num).to_string(),
100 => "one hundred".to_string(),
101...199 => format!("one hundred and {}", hunnert(num % 100)),
200 => "two hundred".to_string(),
201...299 => format!("two hundred and {}", hunnert(num % 100)),
300 => "three hundred".to_string(),
301...399 => format!("three hundred and {}", hunnert(num % 100)),
400 => "four hundred".to_string(),
401...499 => format!("four hundred and {}", hunnert(num % 100)),
500 => "five hundred".to_string(),
501...599 => format!("five hundred and {}", hunnert(num % 100)),
600 => "six hundred".to_string(),
601...699 => format!("six hundred and {}", hunnert(num % 100)),
700 => "seven hundred".to_string(),
701...799 => format!("seven hundred and {}", hunnert(num % 100)),
800 => "eight hundred".to_string(),
801...899 => format!("eight hundred and {}", hunnert(num % 100)),
900 => "nine hundred".to_string(),
901...999 => format!("nine hundred and {}", hunnert(num % 100)),
1000 => "one thousand".to_string(),
_ => "".to_string(),
}
}
fn | (s: String) -> u32 {
s.chars().fold(0, |memo, ch| {
memo + match ch {
'a'...'z' => 1,
_ => 0,
}
})
}
pub fn run() {
let sum: u32 = (1..1001).map(|i| count(thouse(i))).sum();
println!("Sum of number words: {}", sum);
} | count | identifier_name |
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate gl_generator;
use gl_generator::{Registry, Api, Profile, Fallbacks, GlobalGenerator}; | use std::fs::File;
use std::path::Path;
fn main() {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bindings(GlobalGenerator, &mut file)
.unwrap();
} | use std::env; | random_line_split |
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate gl_generator;
use gl_generator::{Registry, Api, Profile, Fallbacks, GlobalGenerator};
use std::env;
use std::fs::File;
use std::path::Path;
fn main() | {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bindings(GlobalGenerator, &mut file)
.unwrap();
} | identifier_body |
|
build.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate gl_generator;
use gl_generator::{Registry, Api, Profile, Fallbacks, GlobalGenerator};
use std::env;
use std::fs::File;
use std::path::Path;
fn | () {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [
"GL_ARB_blend_func_extended"
])
.write_bindings(GlobalGenerator, &mut file)
.unwrap();
}
| main | identifier_name |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>), | Box<Fn(IndyResult<i32 /* handle */>) + Send>),
}
pub struct BlobStorageCommandExecutor {
blob_storage_service: Rc<BlobStorageService>
}
impl BlobStorageCommandExecutor {
pub fn new(blob_storage_service: Rc<BlobStorageService>) -> BlobStorageCommandExecutor {
BlobStorageCommandExecutor {
blob_storage_service
}
}
pub fn execute(&self, command: BlobStorageCommand) {
match command {
BlobStorageCommand::OpenReader(type_, config, cb) => {
info!("OpenReader command received");
cb(self.open_reader(&type_, &config));
}
BlobStorageCommand::OpenWriter(writer_type, writer_config, cb) => {
info!("OpenWriter command received");
cb(self.open_writer(&writer_type, &writer_config));
}
}
}
fn open_reader(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_reader >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_reader(type_, config).map_err(IndyError::from);
debug!("open_reader << res: {:?}", res);
res
}
fn open_writer(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_writer >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_writer(type_, config).map_err(IndyError::from);
debug!("open_writer << res: {:?}", res);
res
}
} | OpenWriter(
String, // writer type
String, // writer config JSON | random_line_split |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
OpenWriter(
String, // writer type
String, // writer config JSON
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
}
pub struct BlobStorageCommandExecutor {
blob_storage_service: Rc<BlobStorageService>
}
impl BlobStorageCommandExecutor {
pub fn new(blob_storage_service: Rc<BlobStorageService>) -> BlobStorageCommandExecutor {
BlobStorageCommandExecutor {
blob_storage_service
}
}
pub fn | (&self, command: BlobStorageCommand) {
match command {
BlobStorageCommand::OpenReader(type_, config, cb) => {
info!("OpenReader command received");
cb(self.open_reader(&type_, &config));
}
BlobStorageCommand::OpenWriter(writer_type, writer_config, cb) => {
info!("OpenWriter command received");
cb(self.open_writer(&writer_type, &writer_config));
}
}
}
fn open_reader(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_reader >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_reader(type_, config).map_err(IndyError::from);
debug!("open_reader << res: {:?}", res);
res
}
fn open_writer(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_writer >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_writer(type_, config).map_err(IndyError::from);
debug!("open_writer << res: {:?}", res);
res
}
}
| execute | identifier_name |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
OpenWriter(
String, // writer type
String, // writer config JSON
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
}
pub struct BlobStorageCommandExecutor {
blob_storage_service: Rc<BlobStorageService>
}
impl BlobStorageCommandExecutor {
pub fn new(blob_storage_service: Rc<BlobStorageService>) -> BlobStorageCommandExecutor {
BlobStorageCommandExecutor {
blob_storage_service
}
}
pub fn execute(&self, command: BlobStorageCommand) {
match command {
BlobStorageCommand::OpenReader(type_, config, cb) => {
info!("OpenReader command received");
cb(self.open_reader(&type_, &config));
}
BlobStorageCommand::OpenWriter(writer_type, writer_config, cb) => {
info!("OpenWriter command received");
cb(self.open_writer(&writer_type, &writer_config));
}
}
}
fn open_reader(&self, type_: &str, config: &str) -> IndyResult<i32> |
fn open_writer(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_writer >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_writer(type_, config).map_err(IndyError::from);
debug!("open_writer << res: {:?}", res);
res
}
}
| {
debug!("open_reader >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_reader(type_, config).map_err(IndyError::from);
debug!("open_reader << res: {:?}", res);
res
} | identifier_body |
lib.rs | #![crate_type="dylib"]
#![feature(plugin_registrar)]
#![deny(warnings)]
#![allow(unstable)]
extern crate syntax;
extern crate sodiumoxide;
#[macro_use] extern crate rustc;
use std::borrow::ToOwned;
use std::io::File;
use syntax::ast;
use syntax::visit;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use rustc::lint::{Context, LintPass, LintPassObject, LintArray};
use rustc::plugin::Registry;
use rustc::session::Session;
use sodiumoxide::crypto::sign;
use sodiumoxide::crypto::sign::{PublicKey, SecretKey};
use validator::Validator;
mod validator;
fn read_key(sess: &Session, buf: &mut [u8], filename: &str) {
let mut file = match File::open(&Path::new(filename)) {
Err(e) => {
sess.err(format!("could not open key file {}: {:?}", filename, e).as_slice());
return;
}
Ok(f) => f,
};
match file.read(buf) {
Ok(n) if n == buf.len() => (),
r => sess.err(format!("could not read full key from key file {}: got {:?}",
filename, r).as_slice()),
}
}
fn write_key(buf: &[u8], path: &Path) {
let mut file = File::create(path).unwrap();
file.write(buf).unwrap();
}
/// Generate a key pair and write it out as two files.
pub fn gen_keypair(pubkey: &Path, seckey: &Path) {
let (pk, sk) = sign::gen_keypair();
write_key(pk.0.as_slice(), pubkey);
write_key(sk.0.as_slice(), seckey);
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
sodiumoxide::init();
let mut pubkey = None;
let mut seckey = None;
{
let args = match reg.args().meta_item_list() {
Some(args) => args,
None => {
reg.sess.span_err(reg.args().span,
r#"usage: #[plugin(public_key="filename",...)]"#);
return;
}
};
macro_rules! read_key {
($attr:expr, $size:expr) => ({
let mut k = [0u8; $size];
if let Some(filename) = $attr.value_str() {
read_key(reg.sess, k.as_mut_slice(), filename.get());
Some(k)
} else {
None
}
});
}
for attr in args.iter() {
if attr.check_name("public_key") {
pubkey = read_key!(attr, sign::PUBLICKEYBYTES);
} else if attr.check_name("secret_key") {
seckey = read_key!(attr, sign::SECRETKEYBYTES);
} else {
reg.sess.span_err(attr.span, "unknown argument");
}
}
}
let pubkey = match pubkey {
None => {
reg.sess.span_err(reg.args().span, "public key must be specified");
return;
}
Some(k) => k,
};
let pass = Pass {
authenticated_parent: None,
pubkey: PublicKey(pubkey),
seckey: seckey.map(|k| SecretKey(k)),
};
reg.register_lint_pass(Box::new(pass) as LintPassObject);
}
// Is `child` a child of `parent` in the AST?
fn child_of(cx: &Context, child: ast::NodeId, parent: ast::NodeId) -> bool {
let mut id = child;
loop {
if id == parent { return true; }
match cx.tcx.map.get_parent(id) {
i if i == id => return false, // no parent
i => id = i,
}
}
}
// Grab a span of bytes from the original source file.
fn snip(cx: &Context, span: Span) -> Vec<u8> {
match cx.sess().codemap().span_to_snippet(span) {
None => {
cx.sess().span_err(span, "can't get snippet");
vec![]
}
Some(s) => s.into_bytes(),
}
}
declare_lint!(UNAUTHORIZED_UNSAFE, Warn, "unauthorized unsafe blocks");
declare_lint!(WRONG_LAUNCH_CODE, Warn, "incorrect #[launch_code] attributes");
struct Pass {
authenticated_parent: Option<ast::NodeId>,
pubkey: PublicKey,
seckey: Option<SecretKey>,
}
impl Pass {
// Warn if this AST node does not have an authenticated ancestor.
fn | (&self, cx: &Context, span: Span, id: ast::NodeId) {
if match self.authenticated_parent {
None => true,
Some(p) =>!child_of(cx, id, p),
} {
cx.span_lint(UNAUTHORIZED_UNSAFE, span, "unauthorized unsafe block");
}
}
// Check a function's #[launch_code] attribute, if any.
fn authenticate(&mut self,
cx: &Context,
attrs: &[ast::Attribute],
span: Span,
id: ast::NodeId) {
let mut launch_code = None;
let mut val = Validator::new();
for attr in attrs.iter() {
if attr.check_name("launch_code") {
let value = attr.value_str()
.map(|s| s.get().to_owned())
.unwrap_or_else(|| "".to_owned());
launch_code = Some((attr.span, value));
} else {
// Authenticate all attributes other than #[launch_code] itself.
// This includes doc comments and attribute order.
val.write(snip(cx, attr.span).as_slice());
}
}
let launch_code = match launch_code {
Some(c) => c,
None => return,
};
// Authenticate the function arguments and body.
val.write(snip(cx, span).as_slice());
if val.verify(launch_code.1.as_slice(), &self.pubkey) {
self.authenticated_parent = Some(id);
} else {
let msg = match self.seckey.as_ref() {
None => "incorrect launch code".to_owned(),
Some(sk) => format!("correct launch code is {}", val.compute(sk)),
};
cx.span_lint(WRONG_LAUNCH_CODE, launch_code.0, msg.as_slice());
}
}
}
impl LintPass for Pass {
fn get_lints(&self) -> LintArray {
lint_array!(UNAUTHORIZED_UNSAFE, WRONG_LAUNCH_CODE)
}
fn check_block(&mut self,
cx: &Context,
block: &ast::Block) {
match block.rules {
ast::DefaultBlock => (),
ast::UnsafeBlock(..) => self.authorize(cx, block.span, block.id),
}
}
fn check_fn(&mut self,
cx: &Context,
fk: visit::FnKind,
_: &ast::FnDecl,
_: &ast::Block,
span: Span,
id: ast::NodeId) {
if match fk {
visit::FkItemFn(_, _, ast::Unsafety::Unsafe, _) => true,
visit::FkItemFn(..) => false,
visit::FkMethod(_, _, m) => match m.node {
ast::MethDecl(_, _, _, _, ast::Unsafety::Unsafe, _, _, _) => true,
ast::MethDecl(..) => false,
ast::MethMac(..) => cx.sess().bug("method macro remains during lint pass"),
},
// closures inherit unsafety from the context
visit::FkFnBlock => false,
} {
self.authorize(cx, span, id);
}
}
fn check_ty_method(&mut self, cx: &Context, m: &ast::TypeMethod) {
self.authenticate(cx, &m.attrs[], m.span, m.id);
}
fn check_trait_method(&mut self, cx: &Context, it: &ast::TraitItem) {
match *it {
ast::RequiredMethod(ref m) => self.authenticate(cx, &m.attrs[], m.span, m.id),
ast::ProvidedMethod(ref m) => self.authenticate(cx, &m.attrs[], m.span, m.id),
ast::TypeTraitItem(..) => (),
}
}
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
self.authenticate(cx, &it.attrs[], it.span, it.id);
}
}
| authorize | identifier_name |
lib.rs | #![crate_type="dylib"]
#![feature(plugin_registrar)]
#![deny(warnings)]
#![allow(unstable)]
extern crate syntax;
extern crate sodiumoxide;
#[macro_use] extern crate rustc;
use std::borrow::ToOwned;
use std::io::File;
use syntax::ast;
use syntax::visit;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use rustc::lint::{Context, LintPass, LintPassObject, LintArray};
use rustc::plugin::Registry;
use rustc::session::Session;
use sodiumoxide::crypto::sign;
use sodiumoxide::crypto::sign::{PublicKey, SecretKey};
use validator::Validator;
mod validator;
fn read_key(sess: &Session, buf: &mut [u8], filename: &str) {
let mut file = match File::open(&Path::new(filename)) {
Err(e) => {
sess.err(format!("could not open key file {}: {:?}", filename, e).as_slice());
return;
}
Ok(f) => f,
};
match file.read(buf) {
Ok(n) if n == buf.len() => (),
r => sess.err(format!("could not read full key from key file {}: got {:?}",
filename, r).as_slice()),
}
}
fn write_key(buf: &[u8], path: &Path) {
let mut file = File::create(path).unwrap();
file.write(buf).unwrap();
}
/// Generate a key pair and write it out as two files.
pub fn gen_keypair(pubkey: &Path, seckey: &Path) {
let (pk, sk) = sign::gen_keypair();
write_key(pk.0.as_slice(), pubkey);
write_key(sk.0.as_slice(), seckey);
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
sodiumoxide::init();
let mut pubkey = None;
let mut seckey = None;
{
let args = match reg.args().meta_item_list() {
Some(args) => args,
None => {
reg.sess.span_err(reg.args().span,
r#"usage: #[plugin(public_key="filename",...)]"#);
return;
}
};
macro_rules! read_key {
($attr:expr, $size:expr) => ({
let mut k = [0u8; $size];
if let Some(filename) = $attr.value_str() {
read_key(reg.sess, k.as_mut_slice(), filename.get());
Some(k)
} else {
None
}
});
}
for attr in args.iter() {
if attr.check_name("public_key") {
pubkey = read_key!(attr, sign::PUBLICKEYBYTES);
} else if attr.check_name("secret_key") {
seckey = read_key!(attr, sign::SECRETKEYBYTES);
} else {
reg.sess.span_err(attr.span, "unknown argument");
}
}
}
let pubkey = match pubkey {
None => {
reg.sess.span_err(reg.args().span, "public key must be specified");
return;
}
Some(k) => k,
};
let pass = Pass {
authenticated_parent: None,
pubkey: PublicKey(pubkey),
seckey: seckey.map(|k| SecretKey(k)),
};
reg.register_lint_pass(Box::new(pass) as LintPassObject);
}
// Is `child` a child of `parent` in the AST?
fn child_of(cx: &Context, child: ast::NodeId, parent: ast::NodeId) -> bool {
let mut id = child;
loop {
if id == parent { return true; }
match cx.tcx.map.get_parent(id) {
i if i == id => return false, // no parent
i => id = i,
}
}
}
// Grab a span of bytes from the original source file.
fn snip(cx: &Context, span: Span) -> Vec<u8> {
match cx.sess().codemap().span_to_snippet(span) {
None => {
cx.sess().span_err(span, "can't get snippet");
vec![]
}
Some(s) => s.into_bytes(),
}
}
declare_lint!(UNAUTHORIZED_UNSAFE, Warn, "unauthorized unsafe blocks");
declare_lint!(WRONG_LAUNCH_CODE, Warn, "incorrect #[launch_code] attributes");
struct Pass {
authenticated_parent: Option<ast::NodeId>,
pubkey: PublicKey,
seckey: Option<SecretKey>,
}
impl Pass {
// Warn if this AST node does not have an authenticated ancestor.
fn authorize(&self, cx: &Context, span: Span, id: ast::NodeId) {
if match self.authenticated_parent {
None => true,
Some(p) =>!child_of(cx, id, p),
} {
cx.span_lint(UNAUTHORIZED_UNSAFE, span, "unauthorized unsafe block");
}
}
// Check a function's #[launch_code] attribute, if any.
fn authenticate(&mut self,
cx: &Context,
attrs: &[ast::Attribute],
span: Span,
id: ast::NodeId) {
let mut launch_code = None;
let mut val = Validator::new();
for attr in attrs.iter() {
if attr.check_name("launch_code") {
let value = attr.value_str()
.map(|s| s.get().to_owned())
.unwrap_or_else(|| "".to_owned());
launch_code = Some((attr.span, value));
} else {
// Authenticate all attributes other than #[launch_code] itself.
// This includes doc comments and attribute order.
val.write(snip(cx, attr.span).as_slice()); |
let launch_code = match launch_code {
Some(c) => c,
None => return,
};
// Authenticate the function arguments and body.
val.write(snip(cx, span).as_slice());
if val.verify(launch_code.1.as_slice(), &self.pubkey) {
self.authenticated_parent = Some(id);
} else {
let msg = match self.seckey.as_ref() {
None => "incorrect launch code".to_owned(),
Some(sk) => format!("correct launch code is {}", val.compute(sk)),
};
cx.span_lint(WRONG_LAUNCH_CODE, launch_code.0, msg.as_slice());
}
}
}
impl LintPass for Pass {
fn get_lints(&self) -> LintArray {
lint_array!(UNAUTHORIZED_UNSAFE, WRONG_LAUNCH_CODE)
}
fn check_block(&mut self,
cx: &Context,
block: &ast::Block) {
match block.rules {
ast::DefaultBlock => (),
ast::UnsafeBlock(..) => self.authorize(cx, block.span, block.id),
}
}
fn check_fn(&mut self,
cx: &Context,
fk: visit::FnKind,
_: &ast::FnDecl,
_: &ast::Block,
span: Span,
id: ast::NodeId) {
if match fk {
visit::FkItemFn(_, _, ast::Unsafety::Unsafe, _) => true,
visit::FkItemFn(..) => false,
visit::FkMethod(_, _, m) => match m.node {
ast::MethDecl(_, _, _, _, ast::Unsafety::Unsafe, _, _, _) => true,
ast::MethDecl(..) => false,
ast::MethMac(..) => cx.sess().bug("method macro remains during lint pass"),
},
// closures inherit unsafety from the context
visit::FkFnBlock => false,
} {
self.authorize(cx, span, id);
}
}
fn check_ty_method(&mut self, cx: &Context, m: &ast::TypeMethod) {
self.authenticate(cx, &m.attrs[], m.span, m.id);
}
fn check_trait_method(&mut self, cx: &Context, it: &ast::TraitItem) {
match *it {
ast::RequiredMethod(ref m) => self.authenticate(cx, &m.attrs[], m.span, m.id),
ast::ProvidedMethod(ref m) => self.authenticate(cx, &m.attrs[], m.span, m.id),
ast::TypeTraitItem(..) => (),
}
}
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
self.authenticate(cx, &it.attrs[], it.span, it.id);
}
} | }
} | random_line_split |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf}; | search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname!= unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test;
}
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool +'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
} |
pub(super) fn find_library(
name: Symbol,
verbatim: bool, | random_line_split |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else | ;
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname!= unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test;
}
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool +'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
}
| {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
} | conditional_block |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn | (
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname!= unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test;
}
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool +'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
}
| find_library | identifier_name |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf | }
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool +'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
}
| {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname != unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test; | identifier_body |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib::network::protocol::socket_cleanup;
use pueue_lib::network::secret::init_shared_secret;
use pueue_lib::settings::Settings;
use pueue_lib::state::State;
use self::state_helper::{restore_state, save_state};
use crate::network::socket::accept_incoming;
use crate::task_handler::TaskHandler;
pub mod cli;
mod network;
mod pid;
mod platform;
/// Contains re-usable helper functions, that operate on the pueue-lib state.
pub mod state_helper;
mod task_handler;
/// The main entry point for the daemon logic.
/// It's basically the `main`, but publicly exported as a library.
/// That way we can properly do integration testing for the daemon.
///
/// For the purpose of testing, some things shouldn't be run during tests.
/// There are some global operations that crash during tests, such as the ctlc handler.
/// This is due to the fact, that tests in the same file are executed in multiple threads.
/// Since the threads own the same global space, this would crash.
pub async fn run(config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the first time and we have to create a
// default config file once.
if!config_found {
if let Err(error) = settings.save(&config_path) {
bail!("Failed saving config file: {error:?}.");
}
};
// Load any requested profile.
if let Some(profile) = &profile {
settings.load_profile(profile)?;
}
#[allow(deprecated)]
if settings.daemon.groups.is_some() {
error!(
"Please delete the 'daemon.groups' section from your config file. \n\
It is no longer used and groups can now only be edited via the commandline interface. \n\n\
Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!"
)
}
init_directories(&settings.shared.pueue_directory());
if!settings.shared.daemon_key().exists() &&!settings.shared.daemon_cert().exists() {
create_certificates(&settings.shared)?;
}
init_shared_secret(&settings.shared.shared_secret_path())?;
pid::create_pid_file(&settings.shared.pueue_directory())?;
// Restore the previous state and save any changes that might have happened during this
// process. If no previous state exists, just create a new one.
// Create a new empty state if any errors occur, but print the error message.
let mut state = match restore_state(&settings.shared.pueue_directory()) {
Ok(Some(state)) => state,
Ok(None) => State::new(&settings, config_path.clone()),
Err(error) => {
warn!("Failed to restore previous state:\n {error:?}");
warn!("Using clean state instead.");
State::new(&settings, config_path.clone())
}
};
state.settings = settings.clone();
save_state(&state)?;
let state = Arc::new(Mutex::new(state));
let (sender, receiver) = unbounded();
let mut task_handler = TaskHandler::new(state.clone(), receiver);
// Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if!test |
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if!pueue_dir.exists() {
if let Err(error) = create_dir_all(&pueue_dir) {
panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}");
}
}
// Task log dir
let log_dir = pueue_dir.join("log");
if!log_dir.exists() {
if let Err(error) = create_dir_all(&log_dir) {
panic!("Failed to create log directory at {log_dir:?} error: {error:?}",);
}
}
// Task certs dir
let certs_dir = pueue_dir.join("certs");
if!certs_dir.exists() {
if let Err(error) = create_dir_all(&certs_dir) {
panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}");
}
}
// Task log dir
let logs_dir = pueue_dir.join("task_logs");
if!logs_dir.exists() {
if let Err(error) = create_dir_all(&logs_dir) {
panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}");
}
}
}
/// Setup signal handling and panic handling.
///
/// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the
/// TaskHandler. This is to prevent dangling processes and other weird edge-cases.
///
/// On panic, we want to cleanup existing unix sockets and the PID file.
fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sender_clone
.send(Message::DaemonShutdown(Shutdown::Emergency))
.expect("Failed to send Message to TaskHandler on Shutdown");
})?;
// Try to do some final cleanup, even if we panic.
let settings_clone = settings.clone();
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
// Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_clone.shared) {
println!("Failed to cleanup socket after panic.");
println!("{error}");
}
std::process::exit(1);
}));
Ok(())
}
| {
setup_signal_panic_handling(&settings, &sender)?;
} | conditional_block |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib::network::protocol::socket_cleanup;
use pueue_lib::network::secret::init_shared_secret;
use pueue_lib::settings::Settings;
use pueue_lib::state::State;
use self::state_helper::{restore_state, save_state};
use crate::network::socket::accept_incoming;
use crate::task_handler::TaskHandler;
pub mod cli;
mod network;
mod pid;
mod platform;
/// Contains re-usable helper functions, that operate on the pueue-lib state.
pub mod state_helper;
mod task_handler;
/// The main entry point for the daemon logic.
/// It's basically the `main`, but publicly exported as a library.
/// That way we can properly do integration testing for the daemon.
///
/// For the purpose of testing, some things shouldn't be run during tests.
/// There are some global operations that crash during tests, such as the ctlc handler.
/// This is due to the fact, that tests in the same file are executed in multiple threads.
/// Since the threads own the same global space, this would crash.
pub async fn run(config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the first time and we have to create a
// default config file once.
if!config_found {
if let Err(error) = settings.save(&config_path) {
bail!("Failed saving config file: {error:?}.");
}
};
// Load any requested profile.
if let Some(profile) = &profile {
settings.load_profile(profile)?;
}
#[allow(deprecated)]
if settings.daemon.groups.is_some() {
error!(
"Please delete the 'daemon.groups' section from your config file. \n\
It is no longer used and groups can now only be edited via the commandline interface. \n\n\
Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!"
)
}
init_directories(&settings.shared.pueue_directory());
if!settings.shared.daemon_key().exists() &&!settings.shared.daemon_cert().exists() {
create_certificates(&settings.shared)?;
}
init_shared_secret(&settings.shared.shared_secret_path())?;
pid::create_pid_file(&settings.shared.pueue_directory())?;
// Restore the previous state and save any changes that might have happened during this
// process. If no previous state exists, just create a new one.
// Create a new empty state if any errors occur, but print the error message.
let mut state = match restore_state(&settings.shared.pueue_directory()) {
Ok(Some(state)) => state,
Ok(None) => State::new(&settings, config_path.clone()),
Err(error) => {
warn!("Failed to restore previous state:\n {error:?}");
warn!("Using clean state instead.");
State::new(&settings, config_path.clone())
}
};
state.settings = settings.clone();
save_state(&state)?;
let state = Arc::new(Mutex::new(state));
let (sender, receiver) = unbounded();
let mut task_handler = TaskHandler::new(state.clone(), receiver);
| }
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if!pueue_dir.exists() {
if let Err(error) = create_dir_all(&pueue_dir) {
panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}");
}
}
// Task log dir
let log_dir = pueue_dir.join("log");
if!log_dir.exists() {
if let Err(error) = create_dir_all(&log_dir) {
panic!("Failed to create log directory at {log_dir:?} error: {error:?}",);
}
}
// Task certs dir
let certs_dir = pueue_dir.join("certs");
if!certs_dir.exists() {
if let Err(error) = create_dir_all(&certs_dir) {
panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}");
}
}
// Task log dir
let logs_dir = pueue_dir.join("task_logs");
if!logs_dir.exists() {
if let Err(error) = create_dir_all(&logs_dir) {
panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}");
}
}
}
/// Setup signal handling and panic handling.
///
/// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the
/// TaskHandler. This is to prevent dangling processes and other weird edge-cases.
///
/// On panic, we want to cleanup existing unix sockets and the PID file.
fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sender_clone
.send(Message::DaemonShutdown(Shutdown::Emergency))
.expect("Failed to send Message to TaskHandler on Shutdown");
})?;
// Try to do some final cleanup, even if we panic.
let settings_clone = settings.clone();
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
// Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_clone.shared) {
println!("Failed to cleanup socket after panic.");
println!("{error}");
}
std::process::exit(1);
}));
Ok(())
} | // Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if !test {
setup_signal_panic_handling(&settings, &sender)?; | random_line_split |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib::network::protocol::socket_cleanup;
use pueue_lib::network::secret::init_shared_secret;
use pueue_lib::settings::Settings;
use pueue_lib::state::State;
use self::state_helper::{restore_state, save_state};
use crate::network::socket::accept_incoming;
use crate::task_handler::TaskHandler;
pub mod cli;
mod network;
mod pid;
mod platform;
/// Contains re-usable helper functions, that operate on the pueue-lib state.
pub mod state_helper;
mod task_handler;
/// The main entry point for the daemon logic.
/// It's basically the `main`, but publicly exported as a library.
/// That way we can properly do integration testing for the daemon.
///
/// For the purpose of testing, some things shouldn't be run during tests.
/// There are some global operations that crash during tests, such as the ctlc handler.
/// This is due to the fact, that tests in the same file are executed in multiple threads.
/// Since the threads own the same global space, this would crash.
pub async fn | (config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the first time and we have to create a
// default config file once.
if!config_found {
if let Err(error) = settings.save(&config_path) {
bail!("Failed saving config file: {error:?}.");
}
};
// Load any requested profile.
if let Some(profile) = &profile {
settings.load_profile(profile)?;
}
#[allow(deprecated)]
if settings.daemon.groups.is_some() {
error!(
"Please delete the 'daemon.groups' section from your config file. \n\
It is no longer used and groups can now only be edited via the commandline interface. \n\n\
Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!"
)
}
init_directories(&settings.shared.pueue_directory());
if!settings.shared.daemon_key().exists() &&!settings.shared.daemon_cert().exists() {
create_certificates(&settings.shared)?;
}
init_shared_secret(&settings.shared.shared_secret_path())?;
pid::create_pid_file(&settings.shared.pueue_directory())?;
// Restore the previous state and save any changes that might have happened during this
// process. If no previous state exists, just create a new one.
// Create a new empty state if any errors occur, but print the error message.
let mut state = match restore_state(&settings.shared.pueue_directory()) {
Ok(Some(state)) => state,
Ok(None) => State::new(&settings, config_path.clone()),
Err(error) => {
warn!("Failed to restore previous state:\n {error:?}");
warn!("Using clean state instead.");
State::new(&settings, config_path.clone())
}
};
state.settings = settings.clone();
save_state(&state)?;
let state = Arc::new(Mutex::new(state));
let (sender, receiver) = unbounded();
let mut task_handler = TaskHandler::new(state.clone(), receiver);
// Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if!test {
setup_signal_panic_handling(&settings, &sender)?;
}
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if!pueue_dir.exists() {
if let Err(error) = create_dir_all(&pueue_dir) {
panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}");
}
}
// Task log dir
let log_dir = pueue_dir.join("log");
if!log_dir.exists() {
if let Err(error) = create_dir_all(&log_dir) {
panic!("Failed to create log directory at {log_dir:?} error: {error:?}",);
}
}
// Task certs dir
let certs_dir = pueue_dir.join("certs");
if!certs_dir.exists() {
if let Err(error) = create_dir_all(&certs_dir) {
panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}");
}
}
// Task log dir
let logs_dir = pueue_dir.join("task_logs");
if!logs_dir.exists() {
if let Err(error) = create_dir_all(&logs_dir) {
panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}");
}
}
}
/// Setup signal handling and panic handling.
///
/// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the
/// TaskHandler. This is to prevent dangling processes and other weird edge-cases.
///
/// On panic, we want to cleanup existing unix sockets and the PID file.
fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sender_clone
.send(Message::DaemonShutdown(Shutdown::Emergency))
.expect("Failed to send Message to TaskHandler on Shutdown");
})?;
// Try to do some final cleanup, even if we panic.
let settings_clone = settings.clone();
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
// Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_clone.shared) {
println!("Failed to cleanup socket after panic.");
println!("{error}");
}
std::process::exit(1);
}));
Ok(())
}
| run | identifier_name |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib::network::protocol::socket_cleanup;
use pueue_lib::network::secret::init_shared_secret;
use pueue_lib::settings::Settings;
use pueue_lib::state::State;
use self::state_helper::{restore_state, save_state};
use crate::network::socket::accept_incoming;
use crate::task_handler::TaskHandler;
pub mod cli;
mod network;
mod pid;
mod platform;
/// Contains re-usable helper functions, that operate on the pueue-lib state.
pub mod state_helper;
mod task_handler;
/// The main entry point for the daemon logic.
/// It's basically the `main`, but publicly exported as a library.
/// That way we can properly do integration testing for the daemon.
///
/// For the purpose of testing, some things shouldn't be run during tests.
/// There are some global operations that crash during tests, such as the ctlc handler.
/// This is due to the fact, that tests in the same file are executed in multiple threads.
/// Since the threads own the same global space, this would crash.
pub async fn run(config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the first time and we have to create a
// default config file once.
if!config_found {
if let Err(error) = settings.save(&config_path) {
bail!("Failed saving config file: {error:?}.");
}
};
// Load any requested profile.
if let Some(profile) = &profile {
settings.load_profile(profile)?;
}
#[allow(deprecated)]
if settings.daemon.groups.is_some() {
error!(
"Please delete the 'daemon.groups' section from your config file. \n\
It is no longer used and groups can now only be edited via the commandline interface. \n\n\
Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!"
)
}
init_directories(&settings.shared.pueue_directory());
if!settings.shared.daemon_key().exists() &&!settings.shared.daemon_cert().exists() {
create_certificates(&settings.shared)?;
}
init_shared_secret(&settings.shared.shared_secret_path())?;
pid::create_pid_file(&settings.shared.pueue_directory())?;
// Restore the previous state and save any changes that might have happened during this
// process. If no previous state exists, just create a new one.
// Create a new empty state if any errors occur, but print the error message.
let mut state = match restore_state(&settings.shared.pueue_directory()) {
Ok(Some(state)) => state,
Ok(None) => State::new(&settings, config_path.clone()),
Err(error) => {
warn!("Failed to restore previous state:\n {error:?}");
warn!("Using clean state instead.");
State::new(&settings, config_path.clone())
}
};
state.settings = settings.clone();
save_state(&state)?;
let state = Arc::new(Mutex::new(state));
let (sender, receiver) = unbounded();
let mut task_handler = TaskHandler::new(state.clone(), receiver);
// Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if!test {
setup_signal_panic_handling(&settings, &sender)?;
}
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if!pueue_dir.exists() {
if let Err(error) = create_dir_all(&pueue_dir) {
panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}");
}
}
// Task log dir
let log_dir = pueue_dir.join("log");
if!log_dir.exists() {
if let Err(error) = create_dir_all(&log_dir) {
panic!("Failed to create log directory at {log_dir:?} error: {error:?}",);
}
}
// Task certs dir
let certs_dir = pueue_dir.join("certs");
if!certs_dir.exists() {
if let Err(error) = create_dir_all(&certs_dir) {
panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}");
}
}
// Task log dir
let logs_dir = pueue_dir.join("task_logs");
if!logs_dir.exists() {
if let Err(error) = create_dir_all(&logs_dir) {
panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}");
}
}
}
/// Setup signal handling and panic handling.
///
/// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the
/// TaskHandler. This is to prevent dangling processes and other weird edge-cases.
///
/// On panic, we want to cleanup existing unix sockets and the PID file.
fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> | // Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_clone.shared) {
println!("Failed to cleanup socket after panic.");
println!("{error}");
}
std::process::exit(1);
}));
Ok(())
}
| {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sender_clone
.send(Message::DaemonShutdown(Shutdown::Emergency))
.expect("Failed to send Message to TaskHandler on Shutdown");
})?;
// Try to do some final cleanup, even if we panic.
let settings_clone = settings.clone();
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
| identifier_body |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads. Thus, one test
//! may modify an environment variable for itself while simultaneously
//! clobbering any similar changes being made concurrently by another
//! test.
//!
//! We can run all tests using only a single thread, but this
//! needlessly slows down the entire test suite for what may be as few
//! as two test cases.
//!
//! This module provides types and macros to use in tests to create a
//! global lock on individual environment variables. For tests that
//! depend on a given environment variable, you should declare a locked
//! variable using the `locked_env_var!` macro _outside_ of any
//! individual test case. Then, in each test case, you can obtain the
//! lock to the variable using the lock function created by the
//! macro. This will provide a reference to the locked environment
//! variable, ensuring that the current test is the only one with
//! access to it. Changes may be made using the `set` method of the
//! lock; any value that the variable had prior to the test is
//! remembered and set back when the lock is dropped.
//!
//! This does, of course, depend on the test author taking care to set
//! up the locking infrastructure, and you're on the honor system to
//! not try and modify the variable outside of the bounds of this
//! locking paradigm. Once the locks are in place, however, only the
//! tests that need access to the locked variable will be serialized,
//! leaving the rest of the tests to proceed in parallel.
use std::{env,
ffi::{OsStr,
OsString},
sync::MutexGuard};
/// Models an exclusive "honor system" lock on a single environment variable.
pub struct LockedEnvVar {
/// The checked-out lock for the variable.
lock: MutexGuard<'static, String>,
/// The original value of the environment variable, prior to any
/// modifications through this lock.
///
/// `Some` means a value was set when this struct was created,
/// while `None` means that the variable was not present.
original_value: Option<OsString>,
}
impl LockedEnvVar {
/// Create a new lock. Users should not call this directly, but
/// use locking function generated by the `locked_env_var!` macro.
///
/// The current value of the variable is recorded at the time of
/// creation; it will be reset when the lock is dropped.
pub fn new(lock: MutexGuard<'static, String>) -> Self {
let original = match env::var(&*lock) {
Ok(val) => Some(OsString::from(val)),
Err(env::VarError::NotPresent) => None,
Err(env::VarError::NotUnicode(os_string)) => Some(os_string),
};
LockedEnvVar { lock,
original_value: original }
}
/// Set the locked environment variable to `value`.
pub fn set<V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) |
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
Some(ref val) => {
env::set_var(&*self.lock, val);
}
None => {
env::remove_var(&*self.lock);
}
}
}
}
/// Create a static thread-safe mutex for accessing a named
/// environment variable.
///
/// `lock_fn` is the name of the function to create to actually check
/// out this lock. You have to provide it explicitly because Rust's
/// macros are not able to generate identifiers at this time.
#[macro_export]
macro_rules! locked_env_var {
($env_var_name:ident, $lock_fn:ident) => {
lazy_static::lazy_static! {
static ref $env_var_name: ::std::sync::Arc<::std::sync::Mutex<String>> =
::std::sync::Arc::new(::std::sync::Mutex::new(String::from(stringify!(
$env_var_name
))));
}
fn $lock_fn() -> $crate::locked_env_var::LockedEnvVar {
// Yup, we're ignoring poisoned mutexes. We're not
// actually changing the contents of the mutex, just using
// it to serialize access.
//
// Furthermore, if a test using the lock fails, that's a
// panic! That would end up failing any tests that were
// run afterwards.
let lock = match $env_var_name.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
$crate::locked_env_var::LockedEnvVar::new(lock)
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env::VarError,
thread};
#[test]
fn initially_unset_value_is_unset_after_drop() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET, lock_var);
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Ok(String::from("foo")));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
}
#[test]
fn original_value_is_retained_across_multiple_modifications() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR, lock_var);
env::set_var("HAB_TESTING_LOCKED_ENV_VAR", "original_value");
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foo")));
lock.set("bar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("bar")));
lock.set("foobar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foobar")));
lock.unset();
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Err(VarError::NotPresent));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("original_value")));
}
#[test]
fn can_recover_from_poisoned_mutex() {
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_POISONED, lock_var);
// Poison the lock
let _ = thread::Builder::new().name("testing-locked-env-var-panic".into())
.spawn(move || {
let _lock = lock_var();
panic!("This is an intentional panic; it's OK");
})
.expect("Couldn't spawn thread!")
.join();
// We should still be able to do something with it; otherwise
// any test that used this variable and failed would fail any
// other test that ran after it.
let lock = lock_var();
lock.set("poisoned foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_POISONED"),
Ok(String::from("poisoned foo")));
}
}
| { env::remove_var(&*self.lock); } | identifier_body |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads. Thus, one test
//! may modify an environment variable for itself while simultaneously
//! clobbering any similar changes being made concurrently by another
//! test.
//!
//! We can run all tests using only a single thread, but this
//! needlessly slows down the entire test suite for what may be as few
//! as two test cases.
//!
//! This module provides types and macros to use in tests to create a
//! global lock on individual environment variables. For tests that
//! depend on a given environment variable, you should declare a locked
//! variable using the `locked_env_var!` macro _outside_ of any
//! individual test case. Then, in each test case, you can obtain the
//! lock to the variable using the lock function created by the
//! macro. This will provide a reference to the locked environment
//! variable, ensuring that the current test is the only one with
//! access to it. Changes may be made using the `set` method of the
//! lock; any value that the variable had prior to the test is
//! remembered and set back when the lock is dropped.
//!
//! This does, of course, depend on the test author taking care to set
//! up the locking infrastructure, and you're on the honor system to
//! not try and modify the variable outside of the bounds of this
//! locking paradigm. Once the locks are in place, however, only the
//! tests that need access to the locked variable will be serialized,
//! leaving the rest of the tests to proceed in parallel.
use std::{env,
ffi::{OsStr,
OsString},
sync::MutexGuard};
/// Models an exclusive "honor system" lock on a single environment variable.
pub struct LockedEnvVar {
/// The checked-out lock for the variable.
lock: MutexGuard<'static, String>,
/// The original value of the environment variable, prior to any
/// modifications through this lock.
///
/// `Some` means a value was set when this struct was created,
/// while `None` means that the variable was not present.
original_value: Option<OsString>,
}
impl LockedEnvVar {
/// Create a new lock. Users should not call this directly, but
/// use locking function generated by the `locked_env_var!` macro.
///
/// The current value of the variable is recorded at the time of
/// creation; it will be reset when the lock is dropped.
pub fn new(lock: MutexGuard<'static, String>) -> Self {
let original = match env::var(&*lock) {
Ok(val) => Some(OsString::from(val)),
Err(env::VarError::NotPresent) => None,
Err(env::VarError::NotUnicode(os_string)) => Some(os_string),
};
LockedEnvVar { lock,
original_value: original }
}
/// Set the locked environment variable to `value`.
pub fn set<V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) { env::remove_var(&*self.lock); }
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
Some(ref val) => {
env::set_var(&*self.lock, val);
}
None => {
env::remove_var(&*self.lock);
}
}
}
}
/// Create a static thread-safe mutex for accessing a named
/// environment variable.
///
/// `lock_fn` is the name of the function to create to actually check
/// out this lock. You have to provide it explicitly because Rust's
/// macros are not able to generate identifiers at this time.
#[macro_export]
macro_rules! locked_env_var {
($env_var_name:ident, $lock_fn:ident) => {
lazy_static::lazy_static! {
static ref $env_var_name: ::std::sync::Arc<::std::sync::Mutex<String>> =
::std::sync::Arc::new(::std::sync::Mutex::new(String::from(stringify!(
$env_var_name
))));
}
fn $lock_fn() -> $crate::locked_env_var::LockedEnvVar {
// Yup, we're ignoring poisoned mutexes. We're not
// actually changing the contents of the mutex, just using
// it to serialize access.
//
// Furthermore, if a test using the lock fails, that's a
// panic! That would end up failing any tests that were
// run afterwards.
let lock = match $env_var_name.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
$crate::locked_env_var::LockedEnvVar::new(lock)
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env::VarError,
thread};
#[test]
fn initially_unset_value_is_unset_after_drop() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET, lock_var);
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Ok(String::from("foo")));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
}
#[test]
fn original_value_is_retained_across_multiple_modifications() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR, lock_var);
env::set_var("HAB_TESTING_LOCKED_ENV_VAR", "original_value"); | assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foo")));
lock.set("bar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("bar")));
lock.set("foobar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foobar")));
lock.unset();
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Err(VarError::NotPresent));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("original_value")));
}
#[test]
fn can_recover_from_poisoned_mutex() {
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_POISONED, lock_var);
// Poison the lock
let _ = thread::Builder::new().name("testing-locked-env-var-panic".into())
.spawn(move || {
let _lock = lock_var();
panic!("This is an intentional panic; it's OK");
})
.expect("Couldn't spawn thread!")
.join();
// We should still be able to do something with it; otherwise
// any test that used this variable and failed would fail any
// other test that ran after it.
let lock = lock_var();
lock.set("poisoned foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_POISONED"),
Ok(String::from("poisoned foo")));
}
} |
{
let lock = lock_var();
lock.set("foo"); | random_line_split |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads. Thus, one test
//! may modify an environment variable for itself while simultaneously
//! clobbering any similar changes being made concurrently by another
//! test.
//!
//! We can run all tests using only a single thread, but this
//! needlessly slows down the entire test suite for what may be as few
//! as two test cases.
//!
//! This module provides types and macros to use in tests to create a
//! global lock on individual environment variables. For tests that
//! depend on a given environment variable, you should declare a locked
//! variable using the `locked_env_var!` macro _outside_ of any
//! individual test case. Then, in each test case, you can obtain the
//! lock to the variable using the lock function created by the
//! macro. This will provide a reference to the locked environment
//! variable, ensuring that the current test is the only one with
//! access to it. Changes may be made using the `set` method of the
//! lock; any value that the variable had prior to the test is
//! remembered and set back when the lock is dropped.
//!
//! This does, of course, depend on the test author taking care to set
//! up the locking infrastructure, and you're on the honor system to
//! not try and modify the variable outside of the bounds of this
//! locking paradigm. Once the locks are in place, however, only the
//! tests that need access to the locked variable will be serialized,
//! leaving the rest of the tests to proceed in parallel.
use std::{env,
ffi::{OsStr,
OsString},
sync::MutexGuard};
/// Models an exclusive "honor system" lock on a single environment variable.
pub struct LockedEnvVar {
/// The checked-out lock for the variable.
lock: MutexGuard<'static, String>,
/// The original value of the environment variable, prior to any
/// modifications through this lock.
///
/// `Some` means a value was set when this struct was created,
/// while `None` means that the variable was not present.
original_value: Option<OsString>,
}
impl LockedEnvVar {
/// Create a new lock. Users should not call this directly, but
/// use locking function generated by the `locked_env_var!` macro.
///
/// The current value of the variable is recorded at the time of
/// creation; it will be reset when the lock is dropped.
pub fn new(lock: MutexGuard<'static, String>) -> Self {
let original = match env::var(&*lock) {
Ok(val) => Some(OsString::from(val)),
Err(env::VarError::NotPresent) => None,
Err(env::VarError::NotUnicode(os_string)) => Some(os_string),
};
LockedEnvVar { lock,
original_value: original }
}
/// Set the locked environment variable to `value`.
pub fn | <V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) { env::remove_var(&*self.lock); }
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
Some(ref val) => {
env::set_var(&*self.lock, val);
}
None => {
env::remove_var(&*self.lock);
}
}
}
}
/// Create a static thread-safe mutex for accessing a named
/// environment variable.
///
/// `lock_fn` is the name of the function to create to actually check
/// out this lock. You have to provide it explicitly because Rust's
/// macros are not able to generate identifiers at this time.
#[macro_export]
macro_rules! locked_env_var {
($env_var_name:ident, $lock_fn:ident) => {
lazy_static::lazy_static! {
static ref $env_var_name: ::std::sync::Arc<::std::sync::Mutex<String>> =
::std::sync::Arc::new(::std::sync::Mutex::new(String::from(stringify!(
$env_var_name
))));
}
fn $lock_fn() -> $crate::locked_env_var::LockedEnvVar {
// Yup, we're ignoring poisoned mutexes. We're not
// actually changing the contents of the mutex, just using
// it to serialize access.
//
// Furthermore, if a test using the lock fails, that's a
// panic! That would end up failing any tests that were
// run afterwards.
let lock = match $env_var_name.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
$crate::locked_env_var::LockedEnvVar::new(lock)
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env::VarError,
thread};
#[test]
fn initially_unset_value_is_unset_after_drop() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET, lock_var);
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Ok(String::from("foo")));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
}
#[test]
fn original_value_is_retained_across_multiple_modifications() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR, lock_var);
env::set_var("HAB_TESTING_LOCKED_ENV_VAR", "original_value");
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foo")));
lock.set("bar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("bar")));
lock.set("foobar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foobar")));
lock.unset();
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Err(VarError::NotPresent));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("original_value")));
}
#[test]
fn can_recover_from_poisoned_mutex() {
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_POISONED, lock_var);
// Poison the lock
let _ = thread::Builder::new().name("testing-locked-env-var-panic".into())
.spawn(move || {
let _lock = lock_var();
panic!("This is an intentional panic; it's OK");
})
.expect("Couldn't spawn thread!")
.join();
// We should still be able to do something with it; otherwise
// any test that used this variable and failed would fail any
// other test that ran after it.
let lock = lock_var();
lock.set("poisoned foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_POISONED"),
Ok(String::from("poisoned foo")));
}
}
| set | identifier_name |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn from_frac(s: bool, a: u64, b: u64) -> Jacobi {
Jacobi::Frac{pos: s, numer: a, denom: b}
}
fn print(&self) {
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
println!(" {} J( {} / {} )",
if p { '+' } else { '-' }, n, d);
} else if let &Jacobi::Value(v) = self {
println!(" {} ", v)
}
}
fn reduce(&self) -> Jacobi {
//let reductions = vec![Jacobi::modulo, Jacobi::two_numer, Jacobi::reciprocal];
let a = &Jacobi::modulo;
let b = &Jacobi::two_numer;
let c = &Jacobi::reciprocal;;
let mut reductions: Vec<&Fn(&Jacobi) -> Option<Jacobi>> = Vec::new();
reductions.push(a);
reductions.push(b);
reductions.push(c);
let mut attempts: HashSet<Jacobi> = HashSet::new();
loop {
}
Jacobi::Value(0)
}
//methods of reducing:
fn modulo(&self) -> Option<Jacobi> {
// if a≡b(mod p), L(a/p) = L(b/p)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
Some(Jacobi::from_frac(p, n.modulo(d), d)) | }
}
fn two_numer(&self) -> Option<Jacobi> {
// J((ab)/n) = J(a/n)*J(b/n)
// J(2/n) = { 1 iff n≡±1(mod 8), -1 iff n≡ٍ±3(mod 8) }
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
let z = n.trailing_zeros();
let n_ = n / 2u64.pow(z);
let rem = d.modulo(8);
let sign: i8 = {
if rem == 1 || rem == 7 { 1 }
else if rem == 3 || rem == 5 { -1 }
else { return None }
};
let mut acc_sign = sign.pow(z);
if!p { acc_sign *= -1; }
Some(Jacobi::from_frac(acc_sign == 1, n, d))
} else {
None
}
}
fn reciprocal(&self) -> Option<Jacobi> {
// J(m/n) = {-J(n/m) if m≡n≡3(mod 4)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
if n.modulo(4) == 3 && d.modulo(4) == 3 {
Some(Jacobi::from_frac(!p, d, n))
} else {
None
}
} else {
None
}
}
} | } else {
None | random_line_split |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn | (s: bool, a: u64, b: u64) -> Jacobi {
Jacobi::Frac{pos: s, numer: a, denom: b}
}
fn print(&self) {
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
println!(" {} J( {} / {} )",
if p { '+' } else { '-' }, n, d);
} else if let &Jacobi::Value(v) = self {
println!(" {} ", v)
}
}
fn reduce(&self) -> Jacobi {
//let reductions = vec![Jacobi::modulo, Jacobi::two_numer, Jacobi::reciprocal];
let a = &Jacobi::modulo;
let b = &Jacobi::two_numer;
let c = &Jacobi::reciprocal;;
let mut reductions: Vec<&Fn(&Jacobi) -> Option<Jacobi>> = Vec::new();
reductions.push(a);
reductions.push(b);
reductions.push(c);
let mut attempts: HashSet<Jacobi> = HashSet::new();
loop {
}
Jacobi::Value(0)
}
//methods of reducing:
fn modulo(&self) -> Option<Jacobi> {
// if a≡b(mod p), L(a/p) = L(b/p)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
Some(Jacobi::from_frac(p, n.modulo(d), d))
} else {
None
}
}
fn two_numer(&self) -> Option<Jacobi> {
// J((ab)/n) = J(a/n)*J(b/n)
// J(2/n) = { 1 iff n≡±1(mod 8), -1 iff n≡ٍ±3(mod 8) }
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
let z = n.trailing_zeros();
let n_ = n / 2u64.pow(z);
let rem = d.modulo(8);
let sign: i8 = {
if rem == 1 || rem == 7 { 1 }
else if rem == 3 || rem == 5 { -1 }
else { return None }
};
let mut acc_sign = sign.pow(z);
if!p { acc_sign *= -1; }
Some(Jacobi::from_frac(acc_sign == 1, n, d))
} else {
None
}
}
fn reciprocal(&self) -> Option<Jacobi> {
// J(m/n) = {-J(n/m) if m≡n≡3(mod 4)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
if n.modulo(4) == 3 && d.modulo(4) == 3 {
Some(Jacobi::from_frac(!p, d, n))
} else {
None
}
} else {
None
}
}
}
| from_frac | identifier_name |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn from_frac(s: bool, a: u64, b: u64) -> Jacobi {
Jacobi::Frac{pos: s, numer: a, denom: b}
}
fn print(&self) {
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
println!(" {} J( {} / {} )",
if p { '+' } else { '-' }, n, d);
} else if let &Jacobi::Value(v) = self {
println!(" {} ", v)
}
}
fn reduce(&self) -> Jacobi {
//let reductions = vec![Jacobi::modulo, Jacobi::two_numer, Jacobi::reciprocal];
let a = &Jacobi::modulo;
let b = &Jacobi::two_numer;
let c = &Jacobi::reciprocal;;
let mut reductions: Vec<&Fn(&Jacobi) -> Option<Jacobi>> = Vec::new();
reductions.push(a);
reductions.push(b);
reductions.push(c);
let mut attempts: HashSet<Jacobi> = HashSet::new();
loop {
}
Jacobi::Value(0)
}
//methods of reducing:
fn modulo(&self) -> Option<Jacobi> {
// if a≡b(mod p), L(a/p) = L(b/p)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
Some(Jacobi::from_frac(p, n.modulo(d), d))
} else {
None
}
}
fn two_numer(&self) -> Option<Jacobi> {
// J((ab)/n) = J(a/n)*J(b/n)
// J(2/n) = { 1 iff n≡±1(mod 8), -1 iff n≡ٍ±3(mod 8) }
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
let z = n.trailing_zeros();
let n_ = n / 2u64.pow(z);
let rem = d.modulo(8);
let sign: i8 = {
if rem == 1 || rem == 7 { 1 }
else if rem == 3 || rem == 5 { -1 }
else { return None }
};
let mut acc_sign = sign.pow(z);
if!p { acc_sign *= -1; }
Some(Jacobi::from_frac(acc_sign == 1, n, d))
} else {
None
}
}
fn reciprocal(&self) -> Option<Jacobi> {
// J(m/n) = {-J(n/m) if m≡n≡3(mod 4)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
| None
}
}
}
| if n.modulo(4) == 3 && d.modulo(4) == 3 {
Some(Jacobi::from_frac(!p, d, n))
} else {
None
}
} else {
| conditional_block |
issue-13698.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 | // except according to those terms.
// aux-build:issue-13698.rs
// ignore-cross-compile
extern crate issue_13698;
pub struct Foo;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) {}
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {} | // option. This file may not be copied, modified, or distributed | random_line_split |
issue-13698.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.
// aux-build:issue-13698.rs
// ignore-cross-compile
extern crate issue_13698;
pub struct Foo;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) |
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {}
| {} | identifier_body |
issue-13698.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.
// aux-build:issue-13698.rs
// ignore-cross-compile
extern crate issue_13698;
pub struct | ;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) {}
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {}
| Foo | identifier_name |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEvent = lv2::lv2_atom_sequence_begin(&(*seq).body);
// loop through event sequence
while!lv2::lv2_atom_sequence_is_end(&(*seq).body, (*seq).atom.size, ev) {
// check if event is midi
if (*ev).body.mytype == (*uris).midi_event {
// pointer to midi event data
let msg: *const u8 = ev.offset(1) as *const u8;
(*synth).midievent(msg);
for i in istart-1..n_samples {
*output.offset(i as isize) = (*synth).getAmp();
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
}
}
pub extern fn | (instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Synth;
// frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples
let istart = (*ev).time_in_frames as u32;
match lv2::lv2_midi_message_type(msg) {
// note on event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOn => {
(*synth).noteison = true;
let f0 = f0_from_midimsg(msg);
(*synth).f0 = f0;
(*synth).currentmidivel = *msg.offset(2);
let coef = 1.0 as f32;
(*synth).osc.reset();
(*synth).osc.set_dphase(f0,(*synth).fs);
// TODO don't set fs here
(*synth).OscBLIT.reset((*synth).fs);
(*synth).OscBLIT.set_f0fn(f0);
for i in istart-1..n_samples {
// let amp = (*synth).osc.get() as f32;
let amp = (*synth).OscBLIT.get() as f32;
*output.offset(i as isize) = amp;
}
}
// note off event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOff => {
(*synth).noteison = false;
(*synth).makesilence = true;
for i in istart-1..n_samples {
let amp = 0.0 as f32;
*output.offset(i as isize) = amp as f32;
}
}
_ => {
println!("DON'T UNDERSTAND MESSAGE")
}
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
if (*synth).noteison {
let coef = 1.0 as f32;
let f0 = (*synth).f0;
for i in 0..n_samples {
// let amp = (*synth).osc.get();
let amp = (*synth).OscBLIT.get();
*output.offset(i as isize) = (amp as f32) * coef;
}
} else if (*synth).makesilence {
(*synth).makesilence = false;
for i in 0..n_samples {
let amp = 0.0;
*output.offset(i as isize) = amp as f32;
}
}
}
}
| run | identifier_name |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEvent = lv2::lv2_atom_sequence_begin(&(*seq).body);
// loop through event sequence
while!lv2::lv2_atom_sequence_is_end(&(*seq).body, (*seq).atom.size, ev) {
// check if event is midi
if (*ev).body.mytype == (*uris).midi_event {
// pointer to midi event data
let msg: *const u8 = ev.offset(1) as *const u8;
(*synth).midievent(msg);
for i in istart-1..n_samples {
*output.offset(i as isize) = (*synth).getAmp();
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
}
}
pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) | // TODO don't set fs here
(*synth).OscBLIT.reset((*synth).fs);
(*synth).OscBLIT.set_f0fn(f0);
for i in istart-1..n_samples {
// let amp = (*synth).osc.get() as f32;
let amp = (*synth).OscBLIT.get() as f32;
*output.offset(i as isize) = amp;
}
}
// note off event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOff => {
(*synth).noteison = false;
(*synth).makesilence = true;
for i in istart-1..n_samples {
let amp = 0.0 as f32;
*output.offset(i as isize) = amp as f32;
}
}
_ => {
println!("DON'T UNDERSTAND MESSAGE")
}
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
if (*synth).noteison {
let coef = 1.0 as f32;
let f0 = (*synth).f0;
for i in 0..n_samples {
// let amp = (*synth).osc.get();
let amp = (*synth).OscBLIT.get();
*output.offset(i as isize) = (amp as f32) * coef;
}
} else if (*synth).makesilence {
(*synth).makesilence = false;
for i in 0..n_samples {
let amp = 0.0;
*output.offset(i as isize) = amp as f32;
}
}
}
}
| {
unsafe{
let synth = instance as *mut Synth;
// frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples
let istart = (*ev).time_in_frames as u32;
match lv2::lv2_midi_message_type(msg) {
// note on event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOn => {
(*synth).noteison = true;
let f0 = f0_from_midimsg(msg);
(*synth).f0 = f0;
(*synth).currentmidivel = *msg.offset(2);
let coef = 1.0 as f32;
(*synth).osc.reset();
(*synth).osc.set_dphase(f0,(*synth).fs);
| identifier_body |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEvent = lv2::lv2_atom_sequence_begin(&(*seq).body);
// loop through event sequence
while!lv2::lv2_atom_sequence_is_end(&(*seq).body, (*seq).atom.size, ev) {
// check if event is midi
if (*ev).body.mytype == (*uris).midi_event {
// pointer to midi event data
let msg: *const u8 = ev.offset(1) as *const u8;
(*synth).midievent(msg);
for i in istart-1..n_samples {
*output.offset(i as isize) = (*synth).getAmp();
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
}
}
pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Synth;
// frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples
let istart = (*ev).time_in_frames as u32;
match lv2::lv2_midi_message_type(msg) {
// note on event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOn => {
(*synth).noteison = true;
let f0 = f0_from_midimsg(msg); | (*synth).osc.set_dphase(f0,(*synth).fs);
// TODO don't set fs here
(*synth).OscBLIT.reset((*synth).fs);
(*synth).OscBLIT.set_f0fn(f0);
for i in istart-1..n_samples {
// let amp = (*synth).osc.get() as f32;
let amp = (*synth).OscBLIT.get() as f32;
*output.offset(i as isize) = amp;
}
}
// note off event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOff => {
(*synth).noteison = false;
(*synth).makesilence = true;
for i in istart-1..n_samples {
let amp = 0.0 as f32;
*output.offset(i as isize) = amp as f32;
}
}
_ => {
println!("DON'T UNDERSTAND MESSAGE")
}
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
if (*synth).noteison {
let coef = 1.0 as f32;
let f0 = (*synth).f0;
for i in 0..n_samples {
// let amp = (*synth).osc.get();
let amp = (*synth).OscBLIT.get();
*output.offset(i as isize) = (amp as f32) * coef;
}
} else if (*synth).makesilence {
(*synth).makesilence = false;
for i in 0..n_samples {
let amp = 0.0;
*output.offset(i as isize) = amp as f32;
}
}
}
} | (*synth).f0 = f0;
(*synth).currentmidivel = *msg.offset(2);
let coef = 1.0 as f32;
(*synth).osc.reset(); | random_line_split |
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_escape() {
let mut x = ffi::escape;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
#[test]
fn from_attack() {
let mut x = ffi::attack;
let p = x.next_pika2();
assert_eq!(x, ffi::defend);
assert_eq!(p, ffi::defend);
}
#[test]
fn | () {
let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
}
| from_defend | identifier_name |
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_escape() {
let mut x = ffi::escape;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
#[test]
fn from_attack() {
let mut x = ffi::attack;
let p = x.next_pika2();
assert_eq!(x, ffi::defend);
assert_eq!(p, ffi::defend);
}
#[test]
fn from_defend() { | let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
} | random_line_split |
|
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_escape() {
let mut x = ffi::escape;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
#[test]
fn from_attack() |
#[test]
fn from_defend() {
let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
}
| {
let mut x = ffi::attack;
let p = x.next_pika2();
assert_eq!(x, ffi::defend);
assert_eq!(p, ffi::defend);
} | identifier_body |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
fn | <T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T,
) -> T {
x.wrapping_sub(y.wrapping_mul(z))
}
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_rules! impl_wrapping_sub_mul {
($t:ident) => {
impl WrappingSubMul<$t> for $t {
type Output = $t;
/// Computes $x - yz$, wrapping around at the boundary of the type.
///
/// $f(x, y, z) = w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul(self, y: $t, z: $t) -> $t {
wrapping_sub_mul(self, y, z)
}
}
impl WrappingSubMulAssign<$t> for $t {
/// Replaces $x$ with $x - yz$, wrapping around at the boundary of the type.
///
/// $x \gets w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul_assign(&mut self, y: $t, z: $t) {
wrapping_sub_mul_assign(self, y, z)
}
}
};
}
apply_to_primitive_ints!(impl_wrapping_sub_mul);
| wrapping_sub_mul | identifier_name |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
| ) -> T {
x.wrapping_sub(y.wrapping_mul(z))
}
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_rules! impl_wrapping_sub_mul {
($t:ident) => {
impl WrappingSubMul<$t> for $t {
type Output = $t;
/// Computes $x - yz$, wrapping around at the boundary of the type.
///
/// $f(x, y, z) = w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul(self, y: $t, z: $t) -> $t {
wrapping_sub_mul(self, y, z)
}
}
impl WrappingSubMulAssign<$t> for $t {
/// Replaces $x$ with $x - yz$, wrapping around at the boundary of the type.
///
/// $x \gets w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul_assign(&mut self, y: $t, z: $t) {
wrapping_sub_mul_assign(self, y, z)
}
}
};
}
apply_to_primitive_ints!(impl_wrapping_sub_mul); | fn wrapping_sub_mul<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T, | random_line_split |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
fn wrapping_sub_mul<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T,
) -> T |
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_rules! impl_wrapping_sub_mul {
($t:ident) => {
impl WrappingSubMul<$t> for $t {
type Output = $t;
/// Computes $x - yz$, wrapping around at the boundary of the type.
///
/// $f(x, y, z) = w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul(self, y: $t, z: $t) -> $t {
wrapping_sub_mul(self, y, z)
}
}
impl WrappingSubMulAssign<$t> for $t {
/// Replaces $x$ with $x - yz$, wrapping around at the boundary of the type.
///
/// $x \gets w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul_assign(&mut self, y: $t, z: $t) {
wrapping_sub_mul_assign(self, y, z)
}
}
};
}
apply_to_primitive_ints!(impl_wrapping_sub_mul);
| {
x.wrapping_sub(y.wrapping_mul(z))
} | identifier_body |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Interface to the measurements in the task_basic_info struct, gathered by
//! invoking `task_info()` with the `TASK_BASIC_INFO` flavor.
use std::os::raw::c_int;
#[allow(non_camel_case_types)]
type size_t = usize;
/// Obtains task_basic_info::virtual_size.
pub fn virtual_size() -> Option<usize> {
let mut virtual_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoVirtualSize(&mut virtual_size)
};
if rv == 0 { Some(virtual_size as usize) } else { None }
} | let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
}
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_stuff() {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_size().unwrap() > 0);
assert!(resident_size().unwrap() > 0);
}
} |
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> { | random_line_split |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Interface to the measurements in the task_basic_info struct, gathered by
//! invoking `task_info()` with the `TASK_BASIC_INFO` flavor.
use std::os::raw::c_int;
#[allow(non_camel_case_types)]
type size_t = usize;
/// Obtains task_basic_info::virtual_size.
pub fn virtual_size() -> Option<usize> {
let mut virtual_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoVirtualSize(&mut virtual_size)
};
if rv == 0 { Some(virtual_size as usize) } else { None }
}
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> |
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_stuff() {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_size().unwrap() > 0);
assert!(resident_size().unwrap() > 0);
}
}
| {
let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
} | identifier_body |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Interface to the measurements in the task_basic_info struct, gathered by
//! invoking `task_info()` with the `TASK_BASIC_INFO` flavor.
use std::os::raw::c_int;
#[allow(non_camel_case_types)]
type size_t = usize;
/// Obtains task_basic_info::virtual_size.
pub fn virtual_size() -> Option<usize> {
let mut virtual_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoVirtualSize(&mut virtual_size)
};
if rv == 0 | else { None }
}
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> {
let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
}
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_stuff() {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_size().unwrap() > 0);
assert!(resident_size().unwrap() > 0);
}
}
| { Some(virtual_size as usize) } | conditional_block |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Interface to the measurements in the task_basic_info struct, gathered by
//! invoking `task_info()` with the `TASK_BASIC_INFO` flavor.
use std::os::raw::c_int;
#[allow(non_camel_case_types)]
type size_t = usize;
/// Obtains task_basic_info::virtual_size.
pub fn virtual_size() -> Option<usize> {
let mut virtual_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoVirtualSize(&mut virtual_size)
};
if rv == 0 { Some(virtual_size as usize) } else { None }
}
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> {
let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
}
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn | () {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_size().unwrap() > 0);
assert!(resident_size().unwrap() > 0);
}
}
| test_stuff | identifier_name |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
use std::cell::RefCell;
use std::ops::Deref;
/// Closures defined within the function. For example:
///
/// fn foo() {
/// bar(move|| {... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited<'a, 'tcx> {
pub(super) infcx: InferCtxt<'a, 'tcx>,
pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
// Some additional `Sized` obligations badly affect type inference. | RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference can kick in and make the
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
/// Reports whether this is in a const context.
pub(super) constness: hir::Constness,
pub(super) body_id: Option<hir::BodyId>,
}
impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
type Target = InferCtxt<'a, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx>,
def_id: LocalDefId,
}
impl Inherited<'_, 'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
InheritedBuilder {
infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
def_id,
}
}
}
impl<'tcx> InheritedBuilder<'tcx> {
pub fn enter<F, R>(&mut self, f: F) -> R
where
F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
{
let def_id = self.def_id;
self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
}
}
impl Inherited<'a, 'tcx> {
pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
}
pub(super) fn with_constness(
infcx: InferCtxt<'a, 'tcx>,
def_id: LocalDefId,
constness: hir::Constness,
) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = tcx.hir().maybe_body_owned_by(item_id);
Inherited {
typeck_results: MaybeInProgressTables {
maybe_typeck_results: infcx.in_progress_typeck_results,
},
infcx,
fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
locals: RefCell::new(Default::default()),
deferred_sized_obligations: RefCell::new(Vec::new()),
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
constness,
body_id,
}
}
pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
}
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
}
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
self.register_predicates(infer_ok.obligations);
infer_ok.value
}
pub(super) fn normalize_associated_types_in<T>(
&self,
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.normalize_associated_types_in_with_cause(
ObligationCause::misc(span, body_id),
param_env,
value,
)
}
pub(super) fn normalize_associated_types_in_with_cause<T>(
&self,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
debug!(?ok);
self.register_infer_ok_obligations(ok)
}
} | // These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations: | random_line_split |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
use std::cell::RefCell;
use std::ops::Deref;
/// Closures defined within the function. For example:
///
/// fn foo() {
/// bar(move|| {... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited<'a, 'tcx> {
pub(super) infcx: InferCtxt<'a, 'tcx>,
pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
// Some additional `Sized` obligations badly affect type inference.
// These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations:
RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference can kick in and make the
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
/// Reports whether this is in a const context.
pub(super) constness: hir::Constness,
pub(super) body_id: Option<hir::BodyId>,
}
impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
type Target = InferCtxt<'a, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx>,
def_id: LocalDefId,
}
impl Inherited<'_, 'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
InheritedBuilder {
infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
def_id,
}
}
}
impl<'tcx> InheritedBuilder<'tcx> {
pub fn enter<F, R>(&mut self, f: F) -> R
where
F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
{
let def_id = self.def_id;
self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
}
}
impl Inherited<'a, 'tcx> {
pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
}
pub(super) fn with_constness(
infcx: InferCtxt<'a, 'tcx>,
def_id: LocalDefId,
constness: hir::Constness,
) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = tcx.hir().maybe_body_owned_by(item_id);
Inherited {
typeck_results: MaybeInProgressTables {
maybe_typeck_results: infcx.in_progress_typeck_results,
},
infcx,
fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
locals: RefCell::new(Default::default()),
deferred_sized_obligations: RefCell::new(Vec::new()),
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
constness,
body_id,
}
}
pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) |
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
self.register_predicates(infer_ok.obligations);
infer_ok.value
}
pub(super) fn normalize_associated_types_in<T>(
&self,
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.normalize_associated_types_in_with_cause(
ObligationCause::misc(span, body_id),
param_env,
value,
)
}
pub(super) fn normalize_associated_types_in_with_cause<T>(
&self,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
debug!(?ok);
self.register_infer_ok_obligations(ok)
}
}
| {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
}
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
} | identifier_body |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
use std::cell::RefCell;
use std::ops::Deref;
/// Closures defined within the function. For example:
///
/// fn foo() {
/// bar(move|| {... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited<'a, 'tcx> {
pub(super) infcx: InferCtxt<'a, 'tcx>,
pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
// Some additional `Sized` obligations badly affect type inference.
// These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations:
RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference can kick in and make the
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
/// Reports whether this is in a const context.
pub(super) constness: hir::Constness,
pub(super) body_id: Option<hir::BodyId>,
}
impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
type Target = InferCtxt<'a, 'tcx>;
fn | (&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx>,
def_id: LocalDefId,
}
impl Inherited<'_, 'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
InheritedBuilder {
infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
def_id,
}
}
}
impl<'tcx> InheritedBuilder<'tcx> {
pub fn enter<F, R>(&mut self, f: F) -> R
where
F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
{
let def_id = self.def_id;
self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
}
}
impl Inherited<'a, 'tcx> {
pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
}
pub(super) fn with_constness(
infcx: InferCtxt<'a, 'tcx>,
def_id: LocalDefId,
constness: hir::Constness,
) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = tcx.hir().maybe_body_owned_by(item_id);
Inherited {
typeck_results: MaybeInProgressTables {
maybe_typeck_results: infcx.in_progress_typeck_results,
},
infcx,
fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
locals: RefCell::new(Default::default()),
deferred_sized_obligations: RefCell::new(Vec::new()),
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
constness,
body_id,
}
}
pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
}
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
}
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
self.register_predicates(infer_ok.obligations);
infer_ok.value
}
pub(super) fn normalize_associated_types_in<T>(
&self,
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.normalize_associated_types_in_with_cause(
ObligationCause::misc(span, body_id),
param_env,
value,
)
}
pub(super) fn normalize_associated_types_in_with_cause<T>(
&self,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
debug!(?ok);
self.register_infer_ok_obligations(ok)
}
}
| deref | identifier_name |
inherited.rs | use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
use std::cell::RefCell;
use std::ops::Deref;
/// Closures defined within the function. For example:
///
/// fn foo() {
/// bar(move|| {... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited<'a, 'tcx> {
pub(super) infcx: InferCtxt<'a, 'tcx>,
pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
// Some additional `Sized` obligations badly affect type inference.
// These obligations are added in a later stage of typeck.
pub(super) deferred_sized_obligations:
RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
// When we process a call like `c()` where `c` is a closure type,
// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
// `FnOnce` closure. In that case, we defer full resolution of the
// call until upvar inference can kick in and make the
// decision. We keep these deferred resolutions grouped by the
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
/// Reports whether this is in a const context.
pub(super) constness: hir::Constness,
pub(super) body_id: Option<hir::BodyId>,
}
impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
type Target = InferCtxt<'a, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.infcx
}
}
/// Helper type of a temporary returned by `Inherited::build(...)`.
/// Necessary because we can't write the following bound:
/// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
pub struct InheritedBuilder<'tcx> {
infcx: infer::InferCtxtBuilder<'tcx>,
def_id: LocalDefId,
}
impl Inherited<'_, 'tcx> {
pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
InheritedBuilder {
infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
def_id,
}
}
}
impl<'tcx> InheritedBuilder<'tcx> {
pub fn enter<F, R>(&mut self, f: F) -> R
where
F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
{
let def_id = self.def_id;
self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
}
}
impl Inherited<'a, 'tcx> {
pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
}
pub(super) fn with_constness(
infcx: InferCtxt<'a, 'tcx>,
def_id: LocalDefId,
constness: hir::Constness,
) -> Self {
let tcx = infcx.tcx;
let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
let body_id = tcx.hir().maybe_body_owned_by(item_id);
Inherited {
typeck_results: MaybeInProgressTables {
maybe_typeck_results: infcx.in_progress_typeck_results,
},
infcx,
fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
locals: RefCell::new(Default::default()),
deferred_sized_obligations: RefCell::new(Vec::new()),
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
constness,
body_id,
}
}
pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
debug!("register_predicate({:?})", obligation);
if obligation.has_escaping_bound_vars() |
self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
}
pub(super) fn register_predicates<I>(&self, obligations: I)
where
I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
{
for obligation in obligations {
self.register_predicate(obligation);
}
}
pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
self.register_predicates(infer_ok.obligations);
infer_ok.value
}
pub(super) fn normalize_associated_types_in<T>(
&self,
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
self.normalize_associated_types_in_with_cause(
ObligationCause::misc(span, body_id),
param_env,
value,
)
}
pub(super) fn normalize_associated_types_in_with_cause<T>(
&self,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: T,
) -> T
where
T: TypeFoldable<'tcx>,
{
let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
debug!(?ok);
self.register_infer_ok_obligations(ok)
}
}
| {
span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
} | conditional_block |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::conversions::native_from_reflector_jsmanaged;
use dom::bindings::js::{JS, JSRef, Root, Unrooted};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window::{self, WindowHelpers};
use devtools_traits::DevtoolsControlChan;
use script_task::{ScriptChan, ScriptPort, ScriptMsg, ScriptTask};
use msg::constellation_msg::{PipelineId, WorkerId};
use net_traits::ResourceTask;
use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use url::Url;
/// A freely-copyable reference to a rooted global object.
#[derive(Copy)]
pub enum GlobalRef<'a> {
/// A reference to a `Window` object.
Window(JSRef<'a, window::Window>),
/// A reference to a `WorkerGlobalScope` object.
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
pub enum GlobalRoot {
/// A root for a `Window` object.
Window(Root<window::Window>),
/// A root for a `WorkerGlobalScope` object.
Worker(Root<WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
/// A field for a `Window` object.
Window(JS<window::Window>),
/// A field for a `WorkerGlobalScope` object.
Worker(JS<WorkerGlobalScope>),
}
/// An unrooted reference to a global object.
#[must_root]
pub enum GlobalUnrooted {
/// An unrooted reference to a `Window` object.
Window(Unrooted<window::Window>),
/// An unrooted reference to a `WorkerGlobalScope` object.
Worker(Unrooted<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
match *self {
GlobalRef::Window(window) => window,
GlobalRef::Worker(_) => panic!("expected a Window scope"),
}
}
/// Get the `PipelineId` for this global scope.
pub fn pipeline(&self) -> PipelineId {
match *self {
GlobalRef::Window(window) => window.pipeline(),
GlobalRef::Worker(worker) => worker.pipeline(),
}
}
/// Get `DevtoolsControlChan` to send messages to Devtools
/// task when available.
pub fn devtools_chan(&self) -> Option<DevtoolsControlChan> {
match *self {
GlobalRef::Window(window) => window.devtools_chan(),
GlobalRef::Worker(worker) => worker.devtools_chan(),
}
}
/// Get the `ResourceTask` for this global scope.
pub fn resource_task(&self) -> ResourceTask {
match *self {
GlobalRef::Window(ref window) => window.resource_task().clone(),
GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
}
}
/// Get next worker id.
pub fn get_next_worker_id(&self) -> WorkerId {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
}
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
match *self {
GlobalRef::Window(ref window) => window.get_url(),
GlobalRef::Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan(&self) -> Box<ScriptChan+Send> {
match *self {
GlobalRef::Window(ref window) => window.script_chan(),
GlobalRef::Worker(ref worker) => worker.script_chan(),
}
}
/// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for implementing web APIs that require blocking semantics
/// without resorting to nested event loops.
pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) {
match *self {
GlobalRef::Window(ref window) => window.new_script_pair(),
GlobalRef::Worker(ref worker) => worker.new_script_pair(),
}
}
/// Process a single event as if it were the next event in the task queue for
/// this global.
pub fn process_event(&self, msg: ScriptMsg) {
match *self {
GlobalRef::Window(_) => ScriptTask::process_event(msg),
GlobalRef::Worker(ref worker) => worker.process_event(msg),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
GlobalRef::Window(ref window) => window.reflector(),
GlobalRef::Worker(ref worker) => worker.reflector(),
}
}
}
impl GlobalRoot {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
}
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn | (&self) -> GlobalRoot {
match *self {
GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
impl GlobalUnrooted {
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalUnrooted::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalUnrooted::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalUnrooted {
unsafe {
let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL))!= 0);
match native_from_reflector_jsmanaged(global) {
Ok(window) => return GlobalUnrooted::Window(window),
Err(_) => (),
}
match native_from_reflector_jsmanaged(global) {
Ok(worker) => return GlobalUnrooted::Worker(worker),
Err(_) => (),
}
panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
}
}
| root | identifier_name |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::conversions::native_from_reflector_jsmanaged;
use dom::bindings::js::{JS, JSRef, Root, Unrooted};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window::{self, WindowHelpers};
use devtools_traits::DevtoolsControlChan;
use script_task::{ScriptChan, ScriptPort, ScriptMsg, ScriptTask};
use msg::constellation_msg::{PipelineId, WorkerId};
use net_traits::ResourceTask;
use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use url::Url;
/// A freely-copyable reference to a rooted global object.
#[derive(Copy)]
pub enum GlobalRef<'a> {
/// A reference to a `Window` object.
Window(JSRef<'a, window::Window>),
/// A reference to a `WorkerGlobalScope` object.
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
pub enum GlobalRoot {
/// A root for a `Window` object.
Window(Root<window::Window>),
/// A root for a `WorkerGlobalScope` object.
Worker(Root<WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
/// A field for a `Window` object.
Window(JS<window::Window>),
/// A field for a `WorkerGlobalScope` object.
Worker(JS<WorkerGlobalScope>),
}
/// An unrooted reference to a global object.
#[must_root]
pub enum GlobalUnrooted {
/// An unrooted reference to a `Window` object.
Window(Unrooted<window::Window>),
/// An unrooted reference to a `WorkerGlobalScope` object.
Worker(Unrooted<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
match *self {
GlobalRef::Window(window) => window,
GlobalRef::Worker(_) => panic!("expected a Window scope"),
}
}
/// Get the `PipelineId` for this global scope.
pub fn pipeline(&self) -> PipelineId {
match *self {
GlobalRef::Window(window) => window.pipeline(),
GlobalRef::Worker(worker) => worker.pipeline(),
}
}
/// Get `DevtoolsControlChan` to send messages to Devtools
/// task when available.
pub fn devtools_chan(&self) -> Option<DevtoolsControlChan> {
match *self {
GlobalRef::Window(window) => window.devtools_chan(),
GlobalRef::Worker(worker) => worker.devtools_chan(),
}
}
/// Get the `ResourceTask` for this global scope.
pub fn resource_task(&self) -> ResourceTask {
match *self {
GlobalRef::Window(ref window) => window.resource_task().clone(),
GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
}
}
/// Get next worker id.
pub fn get_next_worker_id(&self) -> WorkerId {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
}
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
match *self {
GlobalRef::Window(ref window) => window.get_url(),
GlobalRef::Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan(&self) -> Box<ScriptChan+Send> {
match *self {
GlobalRef::Window(ref window) => window.script_chan(),
GlobalRef::Worker(ref worker) => worker.script_chan(),
}
}
| match *self {
GlobalRef::Window(ref window) => window.new_script_pair(),
GlobalRef::Worker(ref worker) => worker.new_script_pair(),
}
}
/// Process a single event as if it were the next event in the task queue for
/// this global.
pub fn process_event(&self, msg: ScriptMsg) {
match *self {
GlobalRef::Window(_) => ScriptTask::process_event(msg),
GlobalRef::Worker(ref worker) => worker.process_event(msg),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
GlobalRef::Window(ref window) => window.reflector(),
GlobalRef::Worker(ref worker) => worker.reflector(),
}
}
}
impl GlobalRoot {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
}
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
impl GlobalUnrooted {
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalUnrooted::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalUnrooted::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalUnrooted {
unsafe {
let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL))!= 0);
match native_from_reflector_jsmanaged(global) {
Ok(window) => return GlobalUnrooted::Window(window),
Err(_) => (),
}
match native_from_reflector_jsmanaged(global) {
Ok(worker) => return GlobalUnrooted::Worker(worker),
Err(_) => (),
}
panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
}
} | /// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for implementing web APIs that require blocking semantics
/// without resorting to nested event loops.
pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.