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 |
---|---|---|---|---|
checkbox.rs
|
use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Printer;
use crate::Vec2;
use crate::With;
use std::rc::Rc;
/// Checkable box.
///
/// # Examples
///
/// ```
/// use cursive_core::views::Checkbox;
/// use cursive_core::traits::Identifiable;
///
/// let checkbox = Checkbox::new().checked().with_name("check");
/// ```
pub struct Checkbox {
checked: bool,
enabled: bool,
on_change: Option<Rc<dyn Fn(&mut Cursive, bool)>>,
}
new_default!(Checkbox);
impl Checkbox {
impl_enabled!(self.enabled);
/// Creates a new, unchecked checkbox.
pub fn new() -> Self {
Checkbox {
checked: false,
enabled: true,
on_change: None,
}
}
/// Sets a callback to be used when the state changes.
pub fn set_on_change<F:'static + Fn(&mut Cursive, bool)>(
&mut self,
on_change: F,
) {
self.on_change = Some(Rc::new(on_change));
}
/// Sets a callback to be used when the state changes.
///
/// Chainable variant.
pub fn on_change<F:'static + Fn(&mut Cursive, bool)>(
self,
on_change: F,
) -> Self {
self.with(|s| s.set_on_change(on_change))
}
/// Toggles the checkbox state.
pub fn toggle(&mut self) -> EventResult {
let checked =!self.checked;
self.set_checked(checked)
}
/// Check the checkbox.
pub fn check(&mut self) -> EventResult {
self.set_checked(true)
}
/// Check the checkbox.
///
/// Chainable variant.
pub fn checked(self) -> Self {
self.with(|s| {
s.check();
})
}
/// Returns `true` if the checkbox is checked.
///
/// # Examples
///
/// ```
/// use cursive_core::views::Checkbox;
///
/// let mut checkbox = Checkbox::new().checked();
/// assert!(checkbox.is_checked());
///
/// checkbox.uncheck();
/// assert!(!checkbox.is_checked());
/// ```
pub fn is_checked(&self) -> bool {
self.checked
}
/// Uncheck the checkbox.
pub fn uncheck(&mut self) -> EventResult {
self.set_checked(false)
}
/// Uncheck the checkbox.
///
/// Chainable variant.
pub fn unchecked(self) -> Self {
self.with(|s| {
s.uncheck();
})
}
/// Sets the checkbox state.
pub fn set_checked(&mut self, checked: bool) -> EventResult {
self.checked = checked;
if let Some(ref on_change) = self.on_change {
let on_change = Rc::clone(on_change);
EventResult::with_cb(move |s| on_change(s, checked))
} else {
EventResult::Consumed(None)
}
}
|
s.set_checked(is_checked);
})
}
fn draw_internal(&self, printer: &Printer) {
printer.print((0, 0), "[ ]");
if self.checked {
printer.print((1, 0), "X");
}
}
}
impl View for Checkbox {
fn required_size(&mut self, _: Vec2) -> Vec2 {
Vec2::new(3, 1)
}
fn take_focus(&mut self, _: Direction) -> bool {
self.enabled
}
fn draw(&self, printer: &Printer) {
if self.enabled && printer.enabled {
printer.with_selection(printer.focused, |printer| {
self.draw_internal(printer)
});
} else {
printer.with_color(ColorStyle::secondary(), |printer| {
self.draw_internal(printer)
});
}
}
fn on_event(&mut self, event: Event) -> EventResult {
if!self.enabled {
return EventResult::Ignored;
}
match event {
Event::Key(Key::Enter) | Event::Char(' ') => self.toggle(),
Event::Mouse {
event: MouseEvent::Release(MouseButton::Left),
position,
offset,
} if position.fits_in_rect(offset, (3, 1)) => self.toggle(),
_ => EventResult::Ignored,
}
}
}
|
/// Set the checkbox state.
///
/// Chainable variant.
pub fn with_checked(self, is_checked: bool) -> Self {
self.with(|s| {
|
random_line_split
|
checkbox.rs
|
use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Printer;
use crate::Vec2;
use crate::With;
use std::rc::Rc;
/// Checkable box.
///
/// # Examples
///
/// ```
/// use cursive_core::views::Checkbox;
/// use cursive_core::traits::Identifiable;
///
/// let checkbox = Checkbox::new().checked().with_name("check");
/// ```
pub struct Checkbox {
checked: bool,
enabled: bool,
on_change: Option<Rc<dyn Fn(&mut Cursive, bool)>>,
}
new_default!(Checkbox);
impl Checkbox {
impl_enabled!(self.enabled);
/// Creates a new, unchecked checkbox.
pub fn new() -> Self {
Checkbox {
checked: false,
enabled: true,
on_change: None,
}
}
/// Sets a callback to be used when the state changes.
pub fn set_on_change<F:'static + Fn(&mut Cursive, bool)>(
&mut self,
on_change: F,
) {
self.on_change = Some(Rc::new(on_change));
}
/// Sets a callback to be used when the state changes.
///
/// Chainable variant.
pub fn on_change<F:'static + Fn(&mut Cursive, bool)>(
self,
on_change: F,
) -> Self {
self.with(|s| s.set_on_change(on_change))
}
/// Toggles the checkbox state.
pub fn toggle(&mut self) -> EventResult {
let checked =!self.checked;
self.set_checked(checked)
}
/// Check the checkbox.
pub fn check(&mut self) -> EventResult {
self.set_checked(true)
}
/// Check the checkbox.
///
/// Chainable variant.
pub fn checked(self) -> Self {
self.with(|s| {
s.check();
})
}
/// Returns `true` if the checkbox is checked.
///
/// # Examples
///
/// ```
/// use cursive_core::views::Checkbox;
///
/// let mut checkbox = Checkbox::new().checked();
/// assert!(checkbox.is_checked());
///
/// checkbox.uncheck();
/// assert!(!checkbox.is_checked());
/// ```
pub fn is_checked(&self) -> bool {
self.checked
}
/// Uncheck the checkbox.
pub fn uncheck(&mut self) -> EventResult {
self.set_checked(false)
}
/// Uncheck the checkbox.
///
/// Chainable variant.
pub fn unchecked(self) -> Self {
self.with(|s| {
s.uncheck();
})
}
/// Sets the checkbox state.
pub fn set_checked(&mut self, checked: bool) -> EventResult {
self.checked = checked;
if let Some(ref on_change) = self.on_change {
let on_change = Rc::clone(on_change);
EventResult::with_cb(move |s| on_change(s, checked))
} else {
EventResult::Consumed(None)
}
}
/// Set the checkbox state.
///
/// Chainable variant.
pub fn with_checked(self, is_checked: bool) -> Self {
self.with(|s| {
s.set_checked(is_checked);
})
}
fn
|
(&self, printer: &Printer) {
printer.print((0, 0), "[ ]");
if self.checked {
printer.print((1, 0), "X");
}
}
}
impl View for Checkbox {
fn required_size(&mut self, _: Vec2) -> Vec2 {
Vec2::new(3, 1)
}
fn take_focus(&mut self, _: Direction) -> bool {
self.enabled
}
fn draw(&self, printer: &Printer) {
if self.enabled && printer.enabled {
printer.with_selection(printer.focused, |printer| {
self.draw_internal(printer)
});
} else {
printer.with_color(ColorStyle::secondary(), |printer| {
self.draw_internal(printer)
});
}
}
fn on_event(&mut self, event: Event) -> EventResult {
if!self.enabled {
return EventResult::Ignored;
}
match event {
Event::Key(Key::Enter) | Event::Char(' ') => self.toggle(),
Event::Mouse {
event: MouseEvent::Release(MouseButton::Left),
position,
offset,
} if position.fits_in_rect(offset, (3, 1)) => self.toggle(),
_ => EventResult::Ignored,
}
}
}
|
draw_internal
|
identifier_name
|
checkbox.rs
|
use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Printer;
use crate::Vec2;
use crate::With;
use std::rc::Rc;
/// Checkable box.
///
/// # Examples
///
/// ```
/// use cursive_core::views::Checkbox;
/// use cursive_core::traits::Identifiable;
///
/// let checkbox = Checkbox::new().checked().with_name("check");
/// ```
pub struct Checkbox {
checked: bool,
enabled: bool,
on_change: Option<Rc<dyn Fn(&mut Cursive, bool)>>,
}
new_default!(Checkbox);
impl Checkbox {
impl_enabled!(self.enabled);
/// Creates a new, unchecked checkbox.
pub fn new() -> Self {
Checkbox {
checked: false,
enabled: true,
on_change: None,
}
}
/// Sets a callback to be used when the state changes.
pub fn set_on_change<F:'static + Fn(&mut Cursive, bool)>(
&mut self,
on_change: F,
) {
self.on_change = Some(Rc::new(on_change));
}
/// Sets a callback to be used when the state changes.
///
/// Chainable variant.
pub fn on_change<F:'static + Fn(&mut Cursive, bool)>(
self,
on_change: F,
) -> Self {
self.with(|s| s.set_on_change(on_change))
}
/// Toggles the checkbox state.
pub fn toggle(&mut self) -> EventResult {
let checked =!self.checked;
self.set_checked(checked)
}
/// Check the checkbox.
pub fn check(&mut self) -> EventResult {
self.set_checked(true)
}
/// Check the checkbox.
///
/// Chainable variant.
pub fn checked(self) -> Self {
self.with(|s| {
s.check();
})
}
/// Returns `true` if the checkbox is checked.
///
/// # Examples
///
/// ```
/// use cursive_core::views::Checkbox;
///
/// let mut checkbox = Checkbox::new().checked();
/// assert!(checkbox.is_checked());
///
/// checkbox.uncheck();
/// assert!(!checkbox.is_checked());
/// ```
pub fn is_checked(&self) -> bool {
self.checked
}
/// Uncheck the checkbox.
pub fn uncheck(&mut self) -> EventResult {
self.set_checked(false)
}
/// Uncheck the checkbox.
///
/// Chainable variant.
pub fn unchecked(self) -> Self {
self.with(|s| {
s.uncheck();
})
}
/// Sets the checkbox state.
pub fn set_checked(&mut self, checked: bool) -> EventResult {
self.checked = checked;
if let Some(ref on_change) = self.on_change {
let on_change = Rc::clone(on_change);
EventResult::with_cb(move |s| on_change(s, checked))
} else {
EventResult::Consumed(None)
}
}
/// Set the checkbox state.
///
/// Chainable variant.
pub fn with_checked(self, is_checked: bool) -> Self {
self.with(|s| {
s.set_checked(is_checked);
})
}
fn draw_internal(&self, printer: &Printer) {
printer.print((0, 0), "[ ]");
if self.checked {
printer.print((1, 0), "X");
}
}
}
impl View for Checkbox {
fn required_size(&mut self, _: Vec2) -> Vec2 {
Vec2::new(3, 1)
}
fn take_focus(&mut self, _: Direction) -> bool {
self.enabled
}
fn draw(&self, printer: &Printer) {
if self.enabled && printer.enabled {
printer.with_selection(printer.focused, |printer| {
self.draw_internal(printer)
});
} else {
printer.with_color(ColorStyle::secondary(), |printer| {
self.draw_internal(printer)
});
}
}
fn on_event(&mut self, event: Event) -> EventResult {
if!self.enabled
|
match event {
Event::Key(Key::Enter) | Event::Char(' ') => self.toggle(),
Event::Mouse {
event: MouseEvent::Release(MouseButton::Left),
position,
offset,
} if position.fits_in_rect(offset, (3, 1)) => self.toggle(),
_ => EventResult::Ignored,
}
}
}
|
{
return EventResult::Ignored;
}
|
conditional_block
|
x2apic.rs
|
//! x2APIC, the most recent APIC on x86 for large servers with more than 255 cores.
use bit_field::BitField;
use super::*;
use crate::msr::{
rdmsr, wrmsr, IA32_APIC_BASE, IA32_TSC_DEADLINE, IA32_X2APIC_APICID, IA32_X2APIC_EOI,
IA32_X2APIC_ESR, IA32_X2APIC_ICR, IA32_X2APIC_LDR, IA32_X2APIC_LVT_LINT0,
IA32_X2APIC_LVT_TIMER, IA32_X2APIC_SELF_IPI, IA32_X2APIC_SIVR, IA32_X2APIC_VERSION,
};
/// Represents an x2APIC driver instance.
#[derive(Debug)]
pub struct X2APIC {
/// Initial BASE msr register value.
base: u64,
}
impl Default for X2APIC {
fn default() -> Self {
unsafe {
X2APIC {
base: rdmsr(IA32_APIC_BASE),
}
}
}
}
impl X2APIC {
/// Create a new x2APIC driver object for the local core.
pub fn new() -> X2APIC {
Default::default()
}
/// Attach to APIC (enable x2APIC mode, initialize LINT0)
pub fn attach(&mut self) {
// Enable
unsafe {
// Enable x2APIC mode globally
self.base = rdmsr(IA32_APIC_BASE);
self.base.set_bit(10, true); // Enable x2APIC
self.base.set_bit(11, true); // Enable xAPIC
wrmsr(IA32_APIC_BASE, self.base);
// Enable this XAPIC (set bit 8, spurious IRQ vector 15)
let svr: u64 = 1 << 8 | 15;
wrmsr(IA32_X2APIC_SIVR, svr);
// TODO: Fix magic number?
let lint0 = 1 << 16 | (1 << 15) | (0b111 << 8) | 0x20;
wrmsr(IA32_X2APIC_LVT_LINT0, lint0);
let _esr = rdmsr(IA32_X2APIC_ESR);
}
}
/// Detach from APIC (disable x2APIC and xAPIC mode).
pub fn detach(&mut self) {
unsafe {
self.base = rdmsr(IA32_APIC_BASE);
self.base.set_bit(10, false); // x2APIC
self.base.set_bit(11, false); // xAPIC
wrmsr(IA32_APIC_BASE, self.base);
}
}
|
/// Send an IPI to yourself.
///
/// # Safety
/// Will interrupt core with `vector`.
pub unsafe fn send_self_ipi(&self, vector: u64) {
wrmsr(IA32_X2APIC_SELF_IPI, vector);
}
}
/// Abstracts common interface of APIC (x2APIC, xAPIC) hardware devices.
impl ApicControl for X2APIC {
/// Is a bootstrap processor?
fn bsp(&self) -> bool {
(self.base & (1 << 8)) > 0
}
/// Read local x2APIC ID.
fn id(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_APICID) as u32 }
}
/// In x2APIC mode, the 32-bit logical x2APIC ID, can be read from LDR.
fn logical_id(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_LDR) as u32 }
}
/// Read APIC version.
fn version(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_VERSION) as u32 }
}
/// Enable TSC timer
fn tsc_enable(&mut self, vector: u8) {
unsafe {
wrmsr(IA32_TSC_DEADLINE, 0);
let mut lvt: u64 = rdmsr(IA32_X2APIC_LVT_TIMER);
lvt &=!0xff;
lvt |= vector as u64;
// Unmask timer IRQ
lvt.set_bit(16, false);
// Enable TSC deadline mode
lvt.set_bit(17, false);
lvt.set_bit(18, true);
wrmsr(IA32_X2APIC_LVT_TIMER, lvt);
}
}
/// Set tsc deadline.
fn tsc_set(&self, value: u64) {
unsafe {
crate::fence::mfence();
wrmsr(IA32_TSC_DEADLINE, value);
}
}
/// End Of Interrupt -- Acknowledge interrupt delivery.
fn eoi(&mut self) {
unsafe {
wrmsr(IA32_X2APIC_EOI, 0);
}
}
/// Send a INIT IPI to a core.
unsafe fn ipi_init(&mut self, core: ApicId) {
let icr = Icr::for_x2apic(
0,
core,
DestinationShorthand::NoShorthand,
DeliveryMode::Init,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Assert,
TriggerMode::Level,
);
self.send_ipi(icr);
}
/// Deassert INIT IPI.
unsafe fn ipi_init_deassert(&mut self) {
let icr = Icr::for_x2apic(
0,
ApicId::X2Apic(0),
// INIT deassert is always sent to everyone, so we are supposed to specify:
DestinationShorthand::AllIncludingSelf,
DeliveryMode::Init,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Deassert,
TriggerMode::Level,
);
self.send_ipi(icr);
}
/// Send a STARTUP IPI to a core.
unsafe fn ipi_startup(&mut self, core: ApicId, start_page: u8) {
let icr = Icr::for_x2apic(
start_page,
core,
DestinationShorthand::NoShorthand,
DeliveryMode::StartUp,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Assert,
TriggerMode::Edge,
);
self.send_ipi(icr);
}
/// Send a generic IPI.
unsafe fn send_ipi(&mut self, icr: Icr) {
wrmsr(IA32_X2APIC_ESR, 0);
wrmsr(IA32_X2APIC_ESR, 0);
wrmsr(IA32_X2APIC_ICR, icr.0);
loop {
let icr = rdmsr(IA32_X2APIC_ICR);
if (icr >> 12 & 0x1) == 0 {
break;
}
if rdmsr(IA32_X2APIC_ESR) > 0 {
break;
}
}
}
}
|
random_line_split
|
|
x2apic.rs
|
//! x2APIC, the most recent APIC on x86 for large servers with more than 255 cores.
use bit_field::BitField;
use super::*;
use crate::msr::{
rdmsr, wrmsr, IA32_APIC_BASE, IA32_TSC_DEADLINE, IA32_X2APIC_APICID, IA32_X2APIC_EOI,
IA32_X2APIC_ESR, IA32_X2APIC_ICR, IA32_X2APIC_LDR, IA32_X2APIC_LVT_LINT0,
IA32_X2APIC_LVT_TIMER, IA32_X2APIC_SELF_IPI, IA32_X2APIC_SIVR, IA32_X2APIC_VERSION,
};
/// Represents an x2APIC driver instance.
#[derive(Debug)]
pub struct
|
{
/// Initial BASE msr register value.
base: u64,
}
impl Default for X2APIC {
fn default() -> Self {
unsafe {
X2APIC {
base: rdmsr(IA32_APIC_BASE),
}
}
}
}
impl X2APIC {
/// Create a new x2APIC driver object for the local core.
pub fn new() -> X2APIC {
Default::default()
}
/// Attach to APIC (enable x2APIC mode, initialize LINT0)
pub fn attach(&mut self) {
// Enable
unsafe {
// Enable x2APIC mode globally
self.base = rdmsr(IA32_APIC_BASE);
self.base.set_bit(10, true); // Enable x2APIC
self.base.set_bit(11, true); // Enable xAPIC
wrmsr(IA32_APIC_BASE, self.base);
// Enable this XAPIC (set bit 8, spurious IRQ vector 15)
let svr: u64 = 1 << 8 | 15;
wrmsr(IA32_X2APIC_SIVR, svr);
// TODO: Fix magic number?
let lint0 = 1 << 16 | (1 << 15) | (0b111 << 8) | 0x20;
wrmsr(IA32_X2APIC_LVT_LINT0, lint0);
let _esr = rdmsr(IA32_X2APIC_ESR);
}
}
/// Detach from APIC (disable x2APIC and xAPIC mode).
pub fn detach(&mut self) {
unsafe {
self.base = rdmsr(IA32_APIC_BASE);
self.base.set_bit(10, false); // x2APIC
self.base.set_bit(11, false); // xAPIC
wrmsr(IA32_APIC_BASE, self.base);
}
}
/// Send an IPI to yourself.
///
/// # Safety
/// Will interrupt core with `vector`.
pub unsafe fn send_self_ipi(&self, vector: u64) {
wrmsr(IA32_X2APIC_SELF_IPI, vector);
}
}
/// Abstracts common interface of APIC (x2APIC, xAPIC) hardware devices.
impl ApicControl for X2APIC {
/// Is a bootstrap processor?
fn bsp(&self) -> bool {
(self.base & (1 << 8)) > 0
}
/// Read local x2APIC ID.
fn id(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_APICID) as u32 }
}
/// In x2APIC mode, the 32-bit logical x2APIC ID, can be read from LDR.
fn logical_id(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_LDR) as u32 }
}
/// Read APIC version.
fn version(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_VERSION) as u32 }
}
/// Enable TSC timer
fn tsc_enable(&mut self, vector: u8) {
unsafe {
wrmsr(IA32_TSC_DEADLINE, 0);
let mut lvt: u64 = rdmsr(IA32_X2APIC_LVT_TIMER);
lvt &=!0xff;
lvt |= vector as u64;
// Unmask timer IRQ
lvt.set_bit(16, false);
// Enable TSC deadline mode
lvt.set_bit(17, false);
lvt.set_bit(18, true);
wrmsr(IA32_X2APIC_LVT_TIMER, lvt);
}
}
/// Set tsc deadline.
fn tsc_set(&self, value: u64) {
unsafe {
crate::fence::mfence();
wrmsr(IA32_TSC_DEADLINE, value);
}
}
/// End Of Interrupt -- Acknowledge interrupt delivery.
fn eoi(&mut self) {
unsafe {
wrmsr(IA32_X2APIC_EOI, 0);
}
}
/// Send a INIT IPI to a core.
unsafe fn ipi_init(&mut self, core: ApicId) {
let icr = Icr::for_x2apic(
0,
core,
DestinationShorthand::NoShorthand,
DeliveryMode::Init,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Assert,
TriggerMode::Level,
);
self.send_ipi(icr);
}
/// Deassert INIT IPI.
unsafe fn ipi_init_deassert(&mut self) {
let icr = Icr::for_x2apic(
0,
ApicId::X2Apic(0),
// INIT deassert is always sent to everyone, so we are supposed to specify:
DestinationShorthand::AllIncludingSelf,
DeliveryMode::Init,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Deassert,
TriggerMode::Level,
);
self.send_ipi(icr);
}
/// Send a STARTUP IPI to a core.
unsafe fn ipi_startup(&mut self, core: ApicId, start_page: u8) {
let icr = Icr::for_x2apic(
start_page,
core,
DestinationShorthand::NoShorthand,
DeliveryMode::StartUp,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Assert,
TriggerMode::Edge,
);
self.send_ipi(icr);
}
/// Send a generic IPI.
unsafe fn send_ipi(&mut self, icr: Icr) {
wrmsr(IA32_X2APIC_ESR, 0);
wrmsr(IA32_X2APIC_ESR, 0);
wrmsr(IA32_X2APIC_ICR, icr.0);
loop {
let icr = rdmsr(IA32_X2APIC_ICR);
if (icr >> 12 & 0x1) == 0 {
break;
}
if rdmsr(IA32_X2APIC_ESR) > 0 {
break;
}
}
}
}
|
X2APIC
|
identifier_name
|
x2apic.rs
|
//! x2APIC, the most recent APIC on x86 for large servers with more than 255 cores.
use bit_field::BitField;
use super::*;
use crate::msr::{
rdmsr, wrmsr, IA32_APIC_BASE, IA32_TSC_DEADLINE, IA32_X2APIC_APICID, IA32_X2APIC_EOI,
IA32_X2APIC_ESR, IA32_X2APIC_ICR, IA32_X2APIC_LDR, IA32_X2APIC_LVT_LINT0,
IA32_X2APIC_LVT_TIMER, IA32_X2APIC_SELF_IPI, IA32_X2APIC_SIVR, IA32_X2APIC_VERSION,
};
/// Represents an x2APIC driver instance.
#[derive(Debug)]
pub struct X2APIC {
/// Initial BASE msr register value.
base: u64,
}
impl Default for X2APIC {
fn default() -> Self {
unsafe {
X2APIC {
base: rdmsr(IA32_APIC_BASE),
}
}
}
}
impl X2APIC {
/// Create a new x2APIC driver object for the local core.
pub fn new() -> X2APIC {
Default::default()
}
/// Attach to APIC (enable x2APIC mode, initialize LINT0)
pub fn attach(&mut self) {
// Enable
unsafe {
// Enable x2APIC mode globally
self.base = rdmsr(IA32_APIC_BASE);
self.base.set_bit(10, true); // Enable x2APIC
self.base.set_bit(11, true); // Enable xAPIC
wrmsr(IA32_APIC_BASE, self.base);
// Enable this XAPIC (set bit 8, spurious IRQ vector 15)
let svr: u64 = 1 << 8 | 15;
wrmsr(IA32_X2APIC_SIVR, svr);
// TODO: Fix magic number?
let lint0 = 1 << 16 | (1 << 15) | (0b111 << 8) | 0x20;
wrmsr(IA32_X2APIC_LVT_LINT0, lint0);
let _esr = rdmsr(IA32_X2APIC_ESR);
}
}
/// Detach from APIC (disable x2APIC and xAPIC mode).
pub fn detach(&mut self) {
unsafe {
self.base = rdmsr(IA32_APIC_BASE);
self.base.set_bit(10, false); // x2APIC
self.base.set_bit(11, false); // xAPIC
wrmsr(IA32_APIC_BASE, self.base);
}
}
/// Send an IPI to yourself.
///
/// # Safety
/// Will interrupt core with `vector`.
pub unsafe fn send_self_ipi(&self, vector: u64) {
wrmsr(IA32_X2APIC_SELF_IPI, vector);
}
}
/// Abstracts common interface of APIC (x2APIC, xAPIC) hardware devices.
impl ApicControl for X2APIC {
/// Is a bootstrap processor?
fn bsp(&self) -> bool {
(self.base & (1 << 8)) > 0
}
/// Read local x2APIC ID.
fn id(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_APICID) as u32 }
}
/// In x2APIC mode, the 32-bit logical x2APIC ID, can be read from LDR.
fn logical_id(&self) -> u32
|
/// Read APIC version.
fn version(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_VERSION) as u32 }
}
/// Enable TSC timer
fn tsc_enable(&mut self, vector: u8) {
unsafe {
wrmsr(IA32_TSC_DEADLINE, 0);
let mut lvt: u64 = rdmsr(IA32_X2APIC_LVT_TIMER);
lvt &=!0xff;
lvt |= vector as u64;
// Unmask timer IRQ
lvt.set_bit(16, false);
// Enable TSC deadline mode
lvt.set_bit(17, false);
lvt.set_bit(18, true);
wrmsr(IA32_X2APIC_LVT_TIMER, lvt);
}
}
/// Set tsc deadline.
fn tsc_set(&self, value: u64) {
unsafe {
crate::fence::mfence();
wrmsr(IA32_TSC_DEADLINE, value);
}
}
/// End Of Interrupt -- Acknowledge interrupt delivery.
fn eoi(&mut self) {
unsafe {
wrmsr(IA32_X2APIC_EOI, 0);
}
}
/// Send a INIT IPI to a core.
unsafe fn ipi_init(&mut self, core: ApicId) {
let icr = Icr::for_x2apic(
0,
core,
DestinationShorthand::NoShorthand,
DeliveryMode::Init,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Assert,
TriggerMode::Level,
);
self.send_ipi(icr);
}
/// Deassert INIT IPI.
unsafe fn ipi_init_deassert(&mut self) {
let icr = Icr::for_x2apic(
0,
ApicId::X2Apic(0),
// INIT deassert is always sent to everyone, so we are supposed to specify:
DestinationShorthand::AllIncludingSelf,
DeliveryMode::Init,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Deassert,
TriggerMode::Level,
);
self.send_ipi(icr);
}
/// Send a STARTUP IPI to a core.
unsafe fn ipi_startup(&mut self, core: ApicId, start_page: u8) {
let icr = Icr::for_x2apic(
start_page,
core,
DestinationShorthand::NoShorthand,
DeliveryMode::StartUp,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Assert,
TriggerMode::Edge,
);
self.send_ipi(icr);
}
/// Send a generic IPI.
unsafe fn send_ipi(&mut self, icr: Icr) {
wrmsr(IA32_X2APIC_ESR, 0);
wrmsr(IA32_X2APIC_ESR, 0);
wrmsr(IA32_X2APIC_ICR, icr.0);
loop {
let icr = rdmsr(IA32_X2APIC_ICR);
if (icr >> 12 & 0x1) == 0 {
break;
}
if rdmsr(IA32_X2APIC_ESR) > 0 {
break;
}
}
}
}
|
{
unsafe { rdmsr(IA32_X2APIC_LDR) as u32 }
}
|
identifier_body
|
x2apic.rs
|
//! x2APIC, the most recent APIC on x86 for large servers with more than 255 cores.
use bit_field::BitField;
use super::*;
use crate::msr::{
rdmsr, wrmsr, IA32_APIC_BASE, IA32_TSC_DEADLINE, IA32_X2APIC_APICID, IA32_X2APIC_EOI,
IA32_X2APIC_ESR, IA32_X2APIC_ICR, IA32_X2APIC_LDR, IA32_X2APIC_LVT_LINT0,
IA32_X2APIC_LVT_TIMER, IA32_X2APIC_SELF_IPI, IA32_X2APIC_SIVR, IA32_X2APIC_VERSION,
};
/// Represents an x2APIC driver instance.
#[derive(Debug)]
pub struct X2APIC {
/// Initial BASE msr register value.
base: u64,
}
impl Default for X2APIC {
fn default() -> Self {
unsafe {
X2APIC {
base: rdmsr(IA32_APIC_BASE),
}
}
}
}
impl X2APIC {
/// Create a new x2APIC driver object for the local core.
pub fn new() -> X2APIC {
Default::default()
}
/// Attach to APIC (enable x2APIC mode, initialize LINT0)
pub fn attach(&mut self) {
// Enable
unsafe {
// Enable x2APIC mode globally
self.base = rdmsr(IA32_APIC_BASE);
self.base.set_bit(10, true); // Enable x2APIC
self.base.set_bit(11, true); // Enable xAPIC
wrmsr(IA32_APIC_BASE, self.base);
// Enable this XAPIC (set bit 8, spurious IRQ vector 15)
let svr: u64 = 1 << 8 | 15;
wrmsr(IA32_X2APIC_SIVR, svr);
// TODO: Fix magic number?
let lint0 = 1 << 16 | (1 << 15) | (0b111 << 8) | 0x20;
wrmsr(IA32_X2APIC_LVT_LINT0, lint0);
let _esr = rdmsr(IA32_X2APIC_ESR);
}
}
/// Detach from APIC (disable x2APIC and xAPIC mode).
pub fn detach(&mut self) {
unsafe {
self.base = rdmsr(IA32_APIC_BASE);
self.base.set_bit(10, false); // x2APIC
self.base.set_bit(11, false); // xAPIC
wrmsr(IA32_APIC_BASE, self.base);
}
}
/// Send an IPI to yourself.
///
/// # Safety
/// Will interrupt core with `vector`.
pub unsafe fn send_self_ipi(&self, vector: u64) {
wrmsr(IA32_X2APIC_SELF_IPI, vector);
}
}
/// Abstracts common interface of APIC (x2APIC, xAPIC) hardware devices.
impl ApicControl for X2APIC {
/// Is a bootstrap processor?
fn bsp(&self) -> bool {
(self.base & (1 << 8)) > 0
}
/// Read local x2APIC ID.
fn id(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_APICID) as u32 }
}
/// In x2APIC mode, the 32-bit logical x2APIC ID, can be read from LDR.
fn logical_id(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_LDR) as u32 }
}
/// Read APIC version.
fn version(&self) -> u32 {
unsafe { rdmsr(IA32_X2APIC_VERSION) as u32 }
}
/// Enable TSC timer
fn tsc_enable(&mut self, vector: u8) {
unsafe {
wrmsr(IA32_TSC_DEADLINE, 0);
let mut lvt: u64 = rdmsr(IA32_X2APIC_LVT_TIMER);
lvt &=!0xff;
lvt |= vector as u64;
// Unmask timer IRQ
lvt.set_bit(16, false);
// Enable TSC deadline mode
lvt.set_bit(17, false);
lvt.set_bit(18, true);
wrmsr(IA32_X2APIC_LVT_TIMER, lvt);
}
}
/// Set tsc deadline.
fn tsc_set(&self, value: u64) {
unsafe {
crate::fence::mfence();
wrmsr(IA32_TSC_DEADLINE, value);
}
}
/// End Of Interrupt -- Acknowledge interrupt delivery.
fn eoi(&mut self) {
unsafe {
wrmsr(IA32_X2APIC_EOI, 0);
}
}
/// Send a INIT IPI to a core.
unsafe fn ipi_init(&mut self, core: ApicId) {
let icr = Icr::for_x2apic(
0,
core,
DestinationShorthand::NoShorthand,
DeliveryMode::Init,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Assert,
TriggerMode::Level,
);
self.send_ipi(icr);
}
/// Deassert INIT IPI.
unsafe fn ipi_init_deassert(&mut self) {
let icr = Icr::for_x2apic(
0,
ApicId::X2Apic(0),
// INIT deassert is always sent to everyone, so we are supposed to specify:
DestinationShorthand::AllIncludingSelf,
DeliveryMode::Init,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Deassert,
TriggerMode::Level,
);
self.send_ipi(icr);
}
/// Send a STARTUP IPI to a core.
unsafe fn ipi_startup(&mut self, core: ApicId, start_page: u8) {
let icr = Icr::for_x2apic(
start_page,
core,
DestinationShorthand::NoShorthand,
DeliveryMode::StartUp,
DestinationMode::Physical,
DeliveryStatus::Idle,
Level::Assert,
TriggerMode::Edge,
);
self.send_ipi(icr);
}
/// Send a generic IPI.
unsafe fn send_ipi(&mut self, icr: Icr) {
wrmsr(IA32_X2APIC_ESR, 0);
wrmsr(IA32_X2APIC_ESR, 0);
wrmsr(IA32_X2APIC_ICR, icr.0);
loop {
let icr = rdmsr(IA32_X2APIC_ICR);
if (icr >> 12 & 0x1) == 0 {
break;
}
if rdmsr(IA32_X2APIC_ESR) > 0
|
}
}
}
|
{
break;
}
|
conditional_block
|
htmlformcontrolscollection.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods;
use crate::dom::bindings::codegen::Bindings::HTMLFormControlsCollectionBinding::HTMLFormControlsCollectionMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::{GetRootNodeOptions, NodeMethods};
use crate::dom::bindings::codegen::UnionTypes::RadioNodeListOrElement;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::element::Element;
use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::htmlformelement::HTMLFormElement;
use crate::dom::node::Node;
use crate::dom::radionodelist::RadioNodeList;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct HTMLFormControlsCollection {
collection: HTMLCollection,
form: Dom<HTMLFormElement>,
}
impl HTMLFormControlsCollection {
fn new_inherited(
form: &HTMLFormElement,
filter: Box<dyn CollectionFilter +'static>,
) -> HTMLFormControlsCollection {
let root_of_form = form
.upcast::<Node>()
.GetRootNode(&GetRootNodeOptions::empty());
HTMLFormControlsCollection {
collection: HTMLCollection::new_inherited(&*root_of_form, filter),
form: Dom::from_ref(form),
}
}
pub fn new(
window: &Window,
form: &HTMLFormElement,
filter: Box<dyn CollectionFilter +'static>,
) -> DomRoot<HTMLFormControlsCollection> {
reflect_dom_object(
Box::new(HTMLFormControlsCollection::new_inherited(form, filter)),
window,
)
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLFormControlsCollection) implements Length
#[allow(non_snake_case)]
pub fn Length(&self) -> u32 {
self.collection.Length()
}
}
impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection {
// https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem
fn NamedItem(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
// Step 1
if name.is_empty() {
return None;
}
let name = Atom::from(name);
let mut filter_map = self.collection.elements_iter().filter_map(|elem| {
if elem.get_name().map_or(false, |n| n == name) ||
elem.get_id().map_or(false, |i| i == name)
{
Some(elem)
} else {
None
}
});
if let Some(elem) = filter_map.next() {
let mut peekable = filter_map.peekable();
// Step 2
if peekable.peek().is_none() {
Some(RadioNodeListOrElement::Element(elem))
} else {
// Step 4-5
let global = self.global();
let window = global.as_window();
// There is only one way to get an HTMLCollection,
// specifically HTMLFormElement::Elements(),
// and the collection filter excludes image inputs.
Some(RadioNodeListOrElement::RadioNodeList(
RadioNodeList::new_controls_except_image_inputs(window, &*self.form, &name),
))
}
// Step 3
} else {
None
}
}
// https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem
fn NamedGetter(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
self.NamedItem(name)
|
fn SupportedPropertyNames(&self) -> Vec<DOMString> {
self.collection.SupportedPropertyNames()
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLFormControlsCollection) implements IndexedGetter.
// https://github.com/servo/servo/issues/5875
//
// https://dom.spec.whatwg.org/#dom-htmlcollection-item
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Element>> {
self.collection.IndexedGetter(index)
}
}
|
}
// https://html.spec.whatwg.org/multipage/#the-htmlformcontrolscollection-interface:supported-property-names
|
random_line_split
|
htmlformcontrolscollection.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods;
use crate::dom::bindings::codegen::Bindings::HTMLFormControlsCollectionBinding::HTMLFormControlsCollectionMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::{GetRootNodeOptions, NodeMethods};
use crate::dom::bindings::codegen::UnionTypes::RadioNodeListOrElement;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::element::Element;
use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::htmlformelement::HTMLFormElement;
use crate::dom::node::Node;
use crate::dom::radionodelist::RadioNodeList;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct HTMLFormControlsCollection {
collection: HTMLCollection,
form: Dom<HTMLFormElement>,
}
impl HTMLFormControlsCollection {
fn new_inherited(
form: &HTMLFormElement,
filter: Box<dyn CollectionFilter +'static>,
) -> HTMLFormControlsCollection {
let root_of_form = form
.upcast::<Node>()
.GetRootNode(&GetRootNodeOptions::empty());
HTMLFormControlsCollection {
collection: HTMLCollection::new_inherited(&*root_of_form, filter),
form: Dom::from_ref(form),
}
}
pub fn new(
window: &Window,
form: &HTMLFormElement,
filter: Box<dyn CollectionFilter +'static>,
) -> DomRoot<HTMLFormControlsCollection> {
reflect_dom_object(
Box::new(HTMLFormControlsCollection::new_inherited(form, filter)),
window,
)
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLFormControlsCollection) implements Length
#[allow(non_snake_case)]
pub fn Length(&self) -> u32 {
self.collection.Length()
}
}
impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection {
// https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem
fn NamedItem(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
// Step 1
if name.is_empty() {
return None;
}
let name = Atom::from(name);
let mut filter_map = self.collection.elements_iter().filter_map(|elem| {
if elem.get_name().map_or(false, |n| n == name) ||
elem.get_id().map_or(false, |i| i == name)
{
Some(elem)
} else {
None
}
});
if let Some(elem) = filter_map.next() {
let mut peekable = filter_map.peekable();
// Step 2
if peekable.peek().is_none() {
Some(RadioNodeListOrElement::Element(elem))
} else {
// Step 4-5
let global = self.global();
let window = global.as_window();
// There is only one way to get an HTMLCollection,
// specifically HTMLFormElement::Elements(),
// and the collection filter excludes image inputs.
Some(RadioNodeListOrElement::RadioNodeList(
RadioNodeList::new_controls_except_image_inputs(window, &*self.form, &name),
))
}
// Step 3
} else
|
}
// https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem
fn NamedGetter(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
self.NamedItem(name)
}
// https://html.spec.whatwg.org/multipage/#the-htmlformcontrolscollection-interface:supported-property-names
fn SupportedPropertyNames(&self) -> Vec<DOMString> {
self.collection.SupportedPropertyNames()
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLFormControlsCollection) implements IndexedGetter.
// https://github.com/servo/servo/issues/5875
//
// https://dom.spec.whatwg.org/#dom-htmlcollection-item
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Element>> {
self.collection.IndexedGetter(index)
}
}
|
{
None
}
|
conditional_block
|
htmlformcontrolscollection.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods;
use crate::dom::bindings::codegen::Bindings::HTMLFormControlsCollectionBinding::HTMLFormControlsCollectionMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::{GetRootNodeOptions, NodeMethods};
use crate::dom::bindings::codegen::UnionTypes::RadioNodeListOrElement;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::element::Element;
use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection};
use crate::dom::htmlformelement::HTMLFormElement;
use crate::dom::node::Node;
use crate::dom::radionodelist::RadioNodeList;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct
|
{
collection: HTMLCollection,
form: Dom<HTMLFormElement>,
}
impl HTMLFormControlsCollection {
fn new_inherited(
form: &HTMLFormElement,
filter: Box<dyn CollectionFilter +'static>,
) -> HTMLFormControlsCollection {
let root_of_form = form
.upcast::<Node>()
.GetRootNode(&GetRootNodeOptions::empty());
HTMLFormControlsCollection {
collection: HTMLCollection::new_inherited(&*root_of_form, filter),
form: Dom::from_ref(form),
}
}
pub fn new(
window: &Window,
form: &HTMLFormElement,
filter: Box<dyn CollectionFilter +'static>,
) -> DomRoot<HTMLFormControlsCollection> {
reflect_dom_object(
Box::new(HTMLFormControlsCollection::new_inherited(form, filter)),
window,
)
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLFormControlsCollection) implements Length
#[allow(non_snake_case)]
pub fn Length(&self) -> u32 {
self.collection.Length()
}
}
impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection {
// https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem
fn NamedItem(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
// Step 1
if name.is_empty() {
return None;
}
let name = Atom::from(name);
let mut filter_map = self.collection.elements_iter().filter_map(|elem| {
if elem.get_name().map_or(false, |n| n == name) ||
elem.get_id().map_or(false, |i| i == name)
{
Some(elem)
} else {
None
}
});
if let Some(elem) = filter_map.next() {
let mut peekable = filter_map.peekable();
// Step 2
if peekable.peek().is_none() {
Some(RadioNodeListOrElement::Element(elem))
} else {
// Step 4-5
let global = self.global();
let window = global.as_window();
// There is only one way to get an HTMLCollection,
// specifically HTMLFormElement::Elements(),
// and the collection filter excludes image inputs.
Some(RadioNodeListOrElement::RadioNodeList(
RadioNodeList::new_controls_except_image_inputs(window, &*self.form, &name),
))
}
// Step 3
} else {
None
}
}
// https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem
fn NamedGetter(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
self.NamedItem(name)
}
// https://html.spec.whatwg.org/multipage/#the-htmlformcontrolscollection-interface:supported-property-names
fn SupportedPropertyNames(&self) -> Vec<DOMString> {
self.collection.SupportedPropertyNames()
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLFormControlsCollection) implements IndexedGetter.
// https://github.com/servo/servo/issues/5875
//
// https://dom.spec.whatwg.org/#dom-htmlcollection-item
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Element>> {
self.collection.IndexedGetter(index)
}
}
|
HTMLFormControlsCollection
|
identifier_name
|
lib.rs
|
#![crate_type= "lib"]
#![cfg_attr(feature = "nightly", feature(plugin))]
//#![cfg_attr(feature = "lints", plugin(clippy))]
//#![cfg_attr(feature = "lints", allow(option_unwrap_used))]
//#![cfg_attr(feature = "lints", allow(explicit_iter_loop))]
//#![cfg_attr(feature = "lints", deny(warnings))]
// Fix until clippy on crates.io is updated to include needless_lifetimes lint
//#![cfg_attr(feature = "lints", allow(unknown_lints))]
|
extern crate strsim;
#[cfg(feature = "color")]
extern crate ansi_term;
#[cfg(feature = "yaml")]
extern crate yaml_rust;
#[cfg(feature = "yaml")]
pub use yaml_rust::YamlLoader;
pub use args::{Arg, SubCommand, ArgMatches, ArgGroup};
pub use app::{App, AppSettings, ClapError, ClapErrorType};
pub use fmt::Format;
#[macro_use]
mod macros;
mod app;
mod args;
mod usageparser;
mod fmt;
|
// DOCS
#[cfg(feature = "suggestions")]
|
random_line_split
|
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use counter_style::{Symbols, parse_counter_style_name};
use cssparser::Parser;
use parser::{Parse, ParserContext};
use style_traits::{ParseError, StyleParseErrorKind};
use super::CustomIdent;
pub mod background;
pub mod basic_shape;
pub mod border;
#[path = "box.rs"]
pub mod box_;
pub mod column;
pub mod counters;
pub mod effects;
pub mod flex;
pub mod font;
#[cfg(feature = "gecko")]
pub mod gecko;
pub mod grid;
pub mod image;
pub mod position;
pub mod rect;
pub mod size;
pub mod svg;
pub mod text;
pub mod transform;
// https://drafts.csswg.org/css-counter-styles/#typedef-symbols-type
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq)]
#[derive(ToComputedValue, ToCss)]
pub enum SymbolsType {
Cyclic,
Numeric,
Alphabetic,
Symbolic,
Fixed,
}
#[cfg(feature = "gecko")]
impl SymbolsType {
/// Convert symbols type to their corresponding Gecko values.
pub fn to_gecko_keyword(self) -> u8 {
use gecko_bindings::structs;
match self {
SymbolsType::Cyclic => structs::NS_STYLE_COUNTER_SYSTEM_CYCLIC as u8,
SymbolsType::Numeric => structs::NS_STYLE_COUNTER_SYSTEM_NUMERIC as u8,
SymbolsType::Alphabetic => structs::NS_STYLE_COUNTER_SYSTEM_ALPHABETIC as u8,
SymbolsType::Symbolic => structs::NS_STYLE_COUNTER_SYSTEM_SYMBOLIC as u8,
SymbolsType::Fixed => structs::NS_STYLE_COUNTER_SYSTEM_FIXED as u8,
}
}
/// Convert Gecko value to symbol type.
pub fn from_gecko_keyword(gecko_value: u32) -> SymbolsType {
use gecko_bindings::structs;
match gecko_value {
structs::NS_STYLE_COUNTER_SYSTEM_CYCLIC => SymbolsType::Cyclic,
structs::NS_STYLE_COUNTER_SYSTEM_NUMERIC => SymbolsType::Numeric,
structs::NS_STYLE_COUNTER_SYSTEM_ALPHABETIC => SymbolsType::Alphabetic,
structs::NS_STYLE_COUNTER_SYSTEM_SYMBOLIC => SymbolsType::Symbolic,
structs::NS_STYLE_COUNTER_SYSTEM_FIXED => SymbolsType::Fixed,
x => panic!("Unexpected value for symbol type {}", x)
}
}
}
/// <https://drafts.csswg.org/css-counter-styles/#typedef-counter-style>
///
/// Since wherever <counter-style> is used, 'none' is a valid value as
/// well, we combine them into one type to make code simpler.
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Debug, Eq, PartialEq, ToComputedValue, ToCss)]
pub enum CounterStyleOrNone {
/// `none`
None,
/// `<counter-style-name>`
Name(CustomIdent),
/// `symbols()`
#[css(function)]
Symbols(SymbolsType, Symbols),
}
impl CounterStyleOrNone {
/// disc value
pub fn disc() -> Self {
CounterStyleOrNone::Name(CustomIdent(atom!("disc")))
}
/// decimal value
pub fn
|
() -> Self {
CounterStyleOrNone::Name(CustomIdent(atom!("decimal")))
}
}
impl Parse for CounterStyleOrNone {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
if let Ok(name) = input.try(|i| parse_counter_style_name(i)) {
return Ok(CounterStyleOrNone::Name(name));
}
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(CounterStyleOrNone::None);
}
if input.try(|i| i.expect_function_matching("symbols")).is_ok() {
return input.parse_nested_block(|input| {
let symbols_type = input.try(|i| SymbolsType::parse(i))
.unwrap_or(SymbolsType::Symbolic);
let symbols = Symbols::parse(context, input)?;
// There must be at least two symbols for alphabetic or
// numeric system.
if (symbols_type == SymbolsType::Alphabetic ||
symbols_type == SymbolsType::Numeric) && symbols.0.len() < 2 {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
// Identifier is not allowed in symbols() function.
if symbols.0.iter().any(|sym|!sym.is_allowed_in_symbols()) {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(CounterStyleOrNone::Symbols(symbols_type, symbols))
});
}
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
/// A wrapper of Non-negative values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf)]
#[derive(PartialEq, PartialOrd, ToAnimatedZero, ToComputedValue, ToCss)]
pub struct NonNegative<T>(pub T);
/// A wrapper of greater-than-or-equal-to-one values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf)]
#[derive(PartialEq, PartialOrd, ToAnimatedZero, ToComputedValue, ToCss)]
pub struct GreaterThanOrEqualToOne<T>(pub T);
|
decimal
|
identifier_name
|
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use counter_style::{Symbols, parse_counter_style_name};
use cssparser::Parser;
use parser::{Parse, ParserContext};
use style_traits::{ParseError, StyleParseErrorKind};
use super::CustomIdent;
pub mod background;
pub mod basic_shape;
pub mod border;
#[path = "box.rs"]
pub mod box_;
pub mod column;
pub mod counters;
pub mod effects;
pub mod flex;
pub mod font;
#[cfg(feature = "gecko")]
pub mod gecko;
pub mod grid;
pub mod image;
pub mod position;
pub mod rect;
pub mod size;
pub mod svg;
pub mod text;
pub mod transform;
// https://drafts.csswg.org/css-counter-styles/#typedef-symbols-type
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq)]
#[derive(ToComputedValue, ToCss)]
pub enum SymbolsType {
Cyclic,
Numeric,
Alphabetic,
Symbolic,
Fixed,
}
#[cfg(feature = "gecko")]
impl SymbolsType {
/// Convert symbols type to their corresponding Gecko values.
pub fn to_gecko_keyword(self) -> u8 {
use gecko_bindings::structs;
match self {
SymbolsType::Cyclic => structs::NS_STYLE_COUNTER_SYSTEM_CYCLIC as u8,
SymbolsType::Numeric => structs::NS_STYLE_COUNTER_SYSTEM_NUMERIC as u8,
SymbolsType::Alphabetic => structs::NS_STYLE_COUNTER_SYSTEM_ALPHABETIC as u8,
SymbolsType::Symbolic => structs::NS_STYLE_COUNTER_SYSTEM_SYMBOLIC as u8,
SymbolsType::Fixed => structs::NS_STYLE_COUNTER_SYSTEM_FIXED as u8,
}
}
/// Convert Gecko value to symbol type.
pub fn from_gecko_keyword(gecko_value: u32) -> SymbolsType {
use gecko_bindings::structs;
match gecko_value {
structs::NS_STYLE_COUNTER_SYSTEM_CYCLIC => SymbolsType::Cyclic,
structs::NS_STYLE_COUNTER_SYSTEM_NUMERIC => SymbolsType::Numeric,
structs::NS_STYLE_COUNTER_SYSTEM_ALPHABETIC => SymbolsType::Alphabetic,
structs::NS_STYLE_COUNTER_SYSTEM_SYMBOLIC => SymbolsType::Symbolic,
structs::NS_STYLE_COUNTER_SYSTEM_FIXED => SymbolsType::Fixed,
x => panic!("Unexpected value for symbol type {}", x)
}
}
}
/// <https://drafts.csswg.org/css-counter-styles/#typedef-counter-style>
///
/// Since wherever <counter-style> is used, 'none' is a valid value as
/// well, we combine them into one type to make code simpler.
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Debug, Eq, PartialEq, ToComputedValue, ToCss)]
pub enum CounterStyleOrNone {
/// `none`
None,
/// `<counter-style-name>`
Name(CustomIdent),
/// `symbols()`
#[css(function)]
Symbols(SymbolsType, Symbols),
}
impl CounterStyleOrNone {
/// disc value
pub fn disc() -> Self {
CounterStyleOrNone::Name(CustomIdent(atom!("disc")))
}
/// decimal value
pub fn decimal() -> Self {
CounterStyleOrNone::Name(CustomIdent(atom!("decimal")))
}
}
impl Parse for CounterStyleOrNone {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>>
|
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(CounterStyleOrNone::Symbols(symbols_type, symbols))
});
}
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
/// A wrapper of Non-negative values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf)]
#[derive(PartialEq, PartialOrd, ToAnimatedZero, ToComputedValue, ToCss)]
pub struct NonNegative<T>(pub T);
/// A wrapper of greater-than-or-equal-to-one values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf)]
#[derive(PartialEq, PartialOrd, ToAnimatedZero, ToComputedValue, ToCss)]
pub struct GreaterThanOrEqualToOne<T>(pub T);
|
{
if let Ok(name) = input.try(|i| parse_counter_style_name(i)) {
return Ok(CounterStyleOrNone::Name(name));
}
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(CounterStyleOrNone::None);
}
if input.try(|i| i.expect_function_matching("symbols")).is_ok() {
return input.parse_nested_block(|input| {
let symbols_type = input.try(|i| SymbolsType::parse(i))
.unwrap_or(SymbolsType::Symbolic);
let symbols = Symbols::parse(context, input)?;
// There must be at least two symbols for alphabetic or
// numeric system.
if (symbols_type == SymbolsType::Alphabetic ||
symbols_type == SymbolsType::Numeric) && symbols.0.len() < 2 {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
// Identifier is not allowed in symbols() function.
if symbols.0.iter().any(|sym| !sym.is_allowed_in_symbols()) {
|
identifier_body
|
mod.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/. */
//! Generic types that share their serialization implementations
//! for both specified and computed values.
use counter_style::{Symbols, parse_counter_style_name};
use cssparser::Parser;
use parser::{Parse, ParserContext};
use style_traits::{ParseError, StyleParseErrorKind};
use super::CustomIdent;
pub mod background;
pub mod basic_shape;
pub mod border;
#[path = "box.rs"]
pub mod box_;
pub mod column;
pub mod counters;
|
#[cfg(feature = "gecko")]
pub mod gecko;
pub mod grid;
pub mod image;
pub mod position;
pub mod rect;
pub mod size;
pub mod svg;
pub mod text;
pub mod transform;
// https://drafts.csswg.org/css-counter-styles/#typedef-symbols-type
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq)]
#[derive(ToComputedValue, ToCss)]
pub enum SymbolsType {
Cyclic,
Numeric,
Alphabetic,
Symbolic,
Fixed,
}
#[cfg(feature = "gecko")]
impl SymbolsType {
/// Convert symbols type to their corresponding Gecko values.
pub fn to_gecko_keyword(self) -> u8 {
use gecko_bindings::structs;
match self {
SymbolsType::Cyclic => structs::NS_STYLE_COUNTER_SYSTEM_CYCLIC as u8,
SymbolsType::Numeric => structs::NS_STYLE_COUNTER_SYSTEM_NUMERIC as u8,
SymbolsType::Alphabetic => structs::NS_STYLE_COUNTER_SYSTEM_ALPHABETIC as u8,
SymbolsType::Symbolic => structs::NS_STYLE_COUNTER_SYSTEM_SYMBOLIC as u8,
SymbolsType::Fixed => structs::NS_STYLE_COUNTER_SYSTEM_FIXED as u8,
}
}
/// Convert Gecko value to symbol type.
pub fn from_gecko_keyword(gecko_value: u32) -> SymbolsType {
use gecko_bindings::structs;
match gecko_value {
structs::NS_STYLE_COUNTER_SYSTEM_CYCLIC => SymbolsType::Cyclic,
structs::NS_STYLE_COUNTER_SYSTEM_NUMERIC => SymbolsType::Numeric,
structs::NS_STYLE_COUNTER_SYSTEM_ALPHABETIC => SymbolsType::Alphabetic,
structs::NS_STYLE_COUNTER_SYSTEM_SYMBOLIC => SymbolsType::Symbolic,
structs::NS_STYLE_COUNTER_SYSTEM_FIXED => SymbolsType::Fixed,
x => panic!("Unexpected value for symbol type {}", x)
}
}
}
/// <https://drafts.csswg.org/css-counter-styles/#typedef-counter-style>
///
/// Since wherever <counter-style> is used, 'none' is a valid value as
/// well, we combine them into one type to make code simpler.
#[cfg_attr(feature = "gecko", derive(MallocSizeOf))]
#[derive(Clone, Debug, Eq, PartialEq, ToComputedValue, ToCss)]
pub enum CounterStyleOrNone {
/// `none`
None,
/// `<counter-style-name>`
Name(CustomIdent),
/// `symbols()`
#[css(function)]
Symbols(SymbolsType, Symbols),
}
impl CounterStyleOrNone {
/// disc value
pub fn disc() -> Self {
CounterStyleOrNone::Name(CustomIdent(atom!("disc")))
}
/// decimal value
pub fn decimal() -> Self {
CounterStyleOrNone::Name(CustomIdent(atom!("decimal")))
}
}
impl Parse for CounterStyleOrNone {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
if let Ok(name) = input.try(|i| parse_counter_style_name(i)) {
return Ok(CounterStyleOrNone::Name(name));
}
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(CounterStyleOrNone::None);
}
if input.try(|i| i.expect_function_matching("symbols")).is_ok() {
return input.parse_nested_block(|input| {
let symbols_type = input.try(|i| SymbolsType::parse(i))
.unwrap_or(SymbolsType::Symbolic);
let symbols = Symbols::parse(context, input)?;
// There must be at least two symbols for alphabetic or
// numeric system.
if (symbols_type == SymbolsType::Alphabetic ||
symbols_type == SymbolsType::Numeric) && symbols.0.len() < 2 {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
// Identifier is not allowed in symbols() function.
if symbols.0.iter().any(|sym|!sym.is_allowed_in_symbols()) {
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(CounterStyleOrNone::Symbols(symbols_type, symbols))
});
}
Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
}
/// A wrapper of Non-negative values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf)]
#[derive(PartialEq, PartialOrd, ToAnimatedZero, ToComputedValue, ToCss)]
pub struct NonNegative<T>(pub T);
/// A wrapper of greater-than-or-equal-to-one values.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf)]
#[derive(PartialEq, PartialOrd, ToAnimatedZero, ToComputedValue, ToCss)]
pub struct GreaterThanOrEqualToOne<T>(pub T);
|
pub mod effects;
pub mod flex;
pub mod font;
|
random_line_split
|
command.rs
|
//! This module provides the command enum.
use std::path::PathBuf;
use library::RepeatMode;
#[derive(Debug)]
/// The different commands that one can send to a server.
pub enum Command {
/// Does nothing, used to get the status from the server.
NoOp,
/// Switches between playing and paused.
PlayPause,
/// Stops the current song.
Stop,
/// Goes to the next song.
NextSong,
/// Goes to the previous song, even if the current song has already started since a while.
PreviousSong,
/// Opens a song from a path.
Song(PathBuf),
/// Stops the server.
StopServer,
/// Changes the repeat mode.
ChangeRepeatMode(RepeatMode),
/// Goes to the next album.
NextAlbum,
/// Goes to the previous album.
PreviousAlbum,
}
impl Command {
/// Serializes a command to a byte array.
pub fn to_u8(&self) -> [u8; 256] {
let mut ret = [0; 256];
ret[0] = match *self {
Command::NoOp => 0,
Command::PlayPause => 1,
Command::Stop => 2,
Command::NextSong => 3,
Command::PreviousSong => 4,
Command::Song(ref p) => {
// Fill the rest of the array with the path
let path = p.to_str().unwrap();
for (i, c) in path.chars().enumerate() {
ret[i+1] = c as u8;
}
5
},
Command::StopServer => 6,
Command::ChangeRepeatMode(RepeatMode::NoRepeat) => 7,
Command::ChangeRepeatMode(RepeatMode::RepeatOne) => 8,
Command::ChangeRepeatMode(RepeatMode::RepeatAll) => 9,
Command::NextAlbum => 10,
Command::PreviousAlbum => 11,
};
ret
}
/// Parses a byte array and returns the corresponding command.
pub fn from(v: &[u8; 256]) -> Result<Command, ()>
|
_ => Err(()),
}
}
}
|
{
match v[0] {
0 => Ok(Command::NoOp),
1 => Ok(Command::PlayPause),
2 => Ok(Command::Stop),
3 => Ok(Command::NextSong),
4 => Ok(Command::PreviousSong),
5 => {
use std::iter::FromIterator;
let mut iter = v[1..255].iter();
let index = (iter.position(|&x| x == 0 ).unwrap()) as usize;
let path = String::from_iter(v[1..index+1].iter().map(|x| *x as char));
Ok(Command::Song(PathBuf::from(path)))
},
6 => Ok(Command::StopServer),
7 => Ok(Command::ChangeRepeatMode(RepeatMode::NoRepeat)),
8 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatOne)),
9 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatAll)),
10 => Ok(Command::NextAlbum),
11 => Ok(Command::PreviousAlbum),
|
identifier_body
|
command.rs
|
//! This module provides the command enum.
use std::path::PathBuf;
use library::RepeatMode;
#[derive(Debug)]
/// The different commands that one can send to a server.
pub enum
|
{
/// Does nothing, used to get the status from the server.
NoOp,
/// Switches between playing and paused.
PlayPause,
/// Stops the current song.
Stop,
/// Goes to the next song.
NextSong,
/// Goes to the previous song, even if the current song has already started since a while.
PreviousSong,
/// Opens a song from a path.
Song(PathBuf),
/// Stops the server.
StopServer,
/// Changes the repeat mode.
ChangeRepeatMode(RepeatMode),
/// Goes to the next album.
NextAlbum,
/// Goes to the previous album.
PreviousAlbum,
}
impl Command {
/// Serializes a command to a byte array.
pub fn to_u8(&self) -> [u8; 256] {
let mut ret = [0; 256];
ret[0] = match *self {
Command::NoOp => 0,
Command::PlayPause => 1,
Command::Stop => 2,
Command::NextSong => 3,
Command::PreviousSong => 4,
Command::Song(ref p) => {
// Fill the rest of the array with the path
let path = p.to_str().unwrap();
for (i, c) in path.chars().enumerate() {
ret[i+1] = c as u8;
}
5
},
Command::StopServer => 6,
Command::ChangeRepeatMode(RepeatMode::NoRepeat) => 7,
Command::ChangeRepeatMode(RepeatMode::RepeatOne) => 8,
Command::ChangeRepeatMode(RepeatMode::RepeatAll) => 9,
Command::NextAlbum => 10,
Command::PreviousAlbum => 11,
};
ret
}
/// Parses a byte array and returns the corresponding command.
pub fn from(v: &[u8; 256]) -> Result<Command, ()> {
match v[0] {
0 => Ok(Command::NoOp),
1 => Ok(Command::PlayPause),
2 => Ok(Command::Stop),
3 => Ok(Command::NextSong),
4 => Ok(Command::PreviousSong),
5 => {
use std::iter::FromIterator;
let mut iter = v[1..255].iter();
let index = (iter.position(|&x| x == 0 ).unwrap()) as usize;
let path = String::from_iter(v[1..index+1].iter().map(|x| *x as char));
Ok(Command::Song(PathBuf::from(path)))
},
6 => Ok(Command::StopServer),
7 => Ok(Command::ChangeRepeatMode(RepeatMode::NoRepeat)),
8 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatOne)),
9 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatAll)),
10 => Ok(Command::NextAlbum),
11 => Ok(Command::PreviousAlbum),
_ => Err(()),
}
}
}
|
Command
|
identifier_name
|
command.rs
|
//! This module provides the command enum.
use std::path::PathBuf;
use library::RepeatMode;
#[derive(Debug)]
/// The different commands that one can send to a server.
pub enum Command {
/// Does nothing, used to get the status from the server.
NoOp,
/// Switches between playing and paused.
PlayPause,
/// Stops the current song.
Stop,
/// Goes to the next song.
NextSong,
/// Goes to the previous song, even if the current song has already started since a while.
PreviousSong,
/// Opens a song from a path.
Song(PathBuf),
/// Stops the server.
StopServer,
/// Changes the repeat mode.
ChangeRepeatMode(RepeatMode),
/// Goes to the next album.
NextAlbum,
/// Goes to the previous album.
PreviousAlbum,
}
impl Command {
/// Serializes a command to a byte array.
pub fn to_u8(&self) -> [u8; 256] {
let mut ret = [0; 256];
ret[0] = match *self {
Command::NoOp => 0,
Command::PlayPause => 1,
Command::Stop => 2,
Command::NextSong => 3,
Command::PreviousSong => 4,
Command::Song(ref p) => {
// Fill the rest of the array with the path
let path = p.to_str().unwrap();
for (i, c) in path.chars().enumerate() {
ret[i+1] = c as u8;
}
5
},
Command::StopServer => 6,
Command::ChangeRepeatMode(RepeatMode::NoRepeat) => 7,
Command::ChangeRepeatMode(RepeatMode::RepeatOne) => 8,
Command::ChangeRepeatMode(RepeatMode::RepeatAll) => 9,
Command::NextAlbum => 10,
Command::PreviousAlbum => 11,
};
ret
}
/// Parses a byte array and returns the corresponding command.
pub fn from(v: &[u8; 256]) -> Result<Command, ()> {
match v[0] {
0 => Ok(Command::NoOp),
1 => Ok(Command::PlayPause),
2 => Ok(Command::Stop),
3 => Ok(Command::NextSong),
4 => Ok(Command::PreviousSong),
5 =>
|
,
6 => Ok(Command::StopServer),
7 => Ok(Command::ChangeRepeatMode(RepeatMode::NoRepeat)),
8 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatOne)),
9 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatAll)),
10 => Ok(Command::NextAlbum),
11 => Ok(Command::PreviousAlbum),
_ => Err(()),
}
}
}
|
{
use std::iter::FromIterator;
let mut iter = v[1..255].iter();
let index = (iter.position(|&x| x == 0 ).unwrap()) as usize;
let path = String::from_iter(v[1..index+1].iter().map(|x| *x as char));
Ok(Command::Song(PathBuf::from(path)))
}
|
conditional_block
|
command.rs
|
//! This module provides the command enum.
use std::path::PathBuf;
|
#[derive(Debug)]
/// The different commands that one can send to a server.
pub enum Command {
/// Does nothing, used to get the status from the server.
NoOp,
/// Switches between playing and paused.
PlayPause,
/// Stops the current song.
Stop,
/// Goes to the next song.
NextSong,
/// Goes to the previous song, even if the current song has already started since a while.
PreviousSong,
/// Opens a song from a path.
Song(PathBuf),
/// Stops the server.
StopServer,
/// Changes the repeat mode.
ChangeRepeatMode(RepeatMode),
/// Goes to the next album.
NextAlbum,
/// Goes to the previous album.
PreviousAlbum,
}
impl Command {
/// Serializes a command to a byte array.
pub fn to_u8(&self) -> [u8; 256] {
let mut ret = [0; 256];
ret[0] = match *self {
Command::NoOp => 0,
Command::PlayPause => 1,
Command::Stop => 2,
Command::NextSong => 3,
Command::PreviousSong => 4,
Command::Song(ref p) => {
// Fill the rest of the array with the path
let path = p.to_str().unwrap();
for (i, c) in path.chars().enumerate() {
ret[i+1] = c as u8;
}
5
},
Command::StopServer => 6,
Command::ChangeRepeatMode(RepeatMode::NoRepeat) => 7,
Command::ChangeRepeatMode(RepeatMode::RepeatOne) => 8,
Command::ChangeRepeatMode(RepeatMode::RepeatAll) => 9,
Command::NextAlbum => 10,
Command::PreviousAlbum => 11,
};
ret
}
/// Parses a byte array and returns the corresponding command.
pub fn from(v: &[u8; 256]) -> Result<Command, ()> {
match v[0] {
0 => Ok(Command::NoOp),
1 => Ok(Command::PlayPause),
2 => Ok(Command::Stop),
3 => Ok(Command::NextSong),
4 => Ok(Command::PreviousSong),
5 => {
use std::iter::FromIterator;
let mut iter = v[1..255].iter();
let index = (iter.position(|&x| x == 0 ).unwrap()) as usize;
let path = String::from_iter(v[1..index+1].iter().map(|x| *x as char));
Ok(Command::Song(PathBuf::from(path)))
},
6 => Ok(Command::StopServer),
7 => Ok(Command::ChangeRepeatMode(RepeatMode::NoRepeat)),
8 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatOne)),
9 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatAll)),
10 => Ok(Command::NextAlbum),
11 => Ok(Command::PreviousAlbum),
_ => Err(()),
}
}
}
|
use library::RepeatMode;
|
random_line_split
|
build.rs
|
extern crate protobuf_build;
use std::env;
use std::path::PathBuf;
use std::fs::File;
use std::io::{Read, Write};
fn main() {
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let proto = root.join("proto");
let mut compiler = protobuf_build::Compiler::new(&proto, &out);
let files = ["keyexchange",
"authentication",
"mercury",
"metadata",
"pubsub",
"spirc"];
for file in &files {
compiler.compile(&((*file).to_owned() + ".proto")).unwrap();
// Hack for rust-lang/rust#18810
// Wrap the generated rust files with "pub mod {... }", so they
// can be included.
|
let mut contents = Vec::new();
src.read_to_end(&mut contents).unwrap();
contents
};
let mut dst = File::create(out.join(&((*file).to_owned() + ".rs"))).unwrap();
dst.write_all(format!("pub mod {} {{\n", file).as_bytes()).unwrap();
dst.write_all(&contents).unwrap();
dst.write_all("}".as_bytes()).unwrap();
}
}
|
let path = out.join(&((*file).to_owned() + ".rs"));
let contents = {
let mut src = File::open(path).unwrap();
|
random_line_split
|
build.rs
|
extern crate protobuf_build;
use std::env;
use std::path::PathBuf;
use std::fs::File;
use std::io::{Read, Write};
fn
|
() {
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let proto = root.join("proto");
let mut compiler = protobuf_build::Compiler::new(&proto, &out);
let files = ["keyexchange",
"authentication",
"mercury",
"metadata",
"pubsub",
"spirc"];
for file in &files {
compiler.compile(&((*file).to_owned() + ".proto")).unwrap();
// Hack for rust-lang/rust#18810
// Wrap the generated rust files with "pub mod {... }", so they
// can be included.
let path = out.join(&((*file).to_owned() + ".rs"));
let contents = {
let mut src = File::open(path).unwrap();
let mut contents = Vec::new();
src.read_to_end(&mut contents).unwrap();
contents
};
let mut dst = File::create(out.join(&((*file).to_owned() + ".rs"))).unwrap();
dst.write_all(format!("pub mod {} {{\n", file).as_bytes()).unwrap();
dst.write_all(&contents).unwrap();
dst.write_all("}".as_bytes()).unwrap();
}
}
|
main
|
identifier_name
|
build.rs
|
extern crate protobuf_build;
use std::env;
use std::path::PathBuf;
use std::fs::File;
use std::io::{Read, Write};
fn main()
|
let path = out.join(&((*file).to_owned() + ".rs"));
let contents = {
let mut src = File::open(path).unwrap();
let mut contents = Vec::new();
src.read_to_end(&mut contents).unwrap();
contents
};
let mut dst = File::create(out.join(&((*file).to_owned() + ".rs"))).unwrap();
dst.write_all(format!("pub mod {} {{\n", file).as_bytes()).unwrap();
dst.write_all(&contents).unwrap();
dst.write_all("}".as_bytes()).unwrap();
}
}
|
{
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let proto = root.join("proto");
let mut compiler = protobuf_build::Compiler::new(&proto, &out);
let files = ["keyexchange",
"authentication",
"mercury",
"metadata",
"pubsub",
"spirc"];
for file in &files {
compiler.compile(&((*file).to_owned() + ".proto")).unwrap();
// Hack for rust-lang/rust#18810
// Wrap the generated rust files with "pub mod { ... }", so they
// can be included.
|
identifier_body
|
minibuf.rs
|
//! Minibuffer input and completion.
use remacs_macros::lisp_fn;
use crate::{
buffers::{current_buffer, LispBufferOrName},
editfns::field_end,
eval::unbind_to,
keymap::get_keymap,
lisp::LispObject,
lists::{car_safe, cdr_safe, memq},
multibyte::LispStringRef,
obarray::{intern, lisp_intern},
remacs_sys::{
globals, Qcommandp, Qcustom_variable_p, Qfield, Qminibuffer_completion_table,
Qminibuffer_history, Qnil, Qt, Vminibuffer_list,
},
remacs_sys::{
make_buffer_string, minibuf_level, minibuf_prompt, minibuf_window, read_minibuf, specbind,
EmacsInt, Fcopy_sequence,
},
symbols::symbol_value,
textprop::get_char_property,
threads::{c_specpdl_index, ThreadState},
};
/// Return t if BUFFER is a minibuffer.
/// No argument or nil as argument means use current buffer as BUFFER.
/// BUFFER can be a buffer or a buffer name.
#[lisp_fn(min = "0")]
pub fn minibufferp(buffer_or_name: Option<LispBufferOrName>) -> bool {
let buffer = buffer_or_name.map_or_else(current_buffer, LispObject::from);
memq(buffer, unsafe { Vminibuffer_list }).is_not_nil()
}
/// Return the currently active minibuffer window, or nil if none.
#[lisp_fn]
pub fn active_minibuffer_window() -> LispObject {
unsafe {
if minibuf_level == 0 {
Qnil
} else {
minibuf_window
}
}
}
/// Specify which minibuffer window to use for the minibuffer.
/// This affects where the minibuffer is displayed if you put text in it
/// without invoking the usual minibuffer commands.
#[lisp_fn]
pub fn set_minibuffer_window(window: LispObject) -> LispObject {
window.as_minibuffer_or_error(); // just for the checks
unsafe {
minibuf_window = window;
}
window
}
/// Return current depth of activations of minibuffer,
/// a nonnegative integer.
#[lisp_fn]
pub fn minibuffer_depth() -> EmacsInt {
unsafe { minibuf_level }
}
/// Return the prompt string of the currently active
/// minibuffer. If no minibuffer is active return nil.
#[lisp_fn]
pub fn minibuffer_prompt() -> LispObject {
unsafe { Fcopy_sequence(minibuf_prompt) }
}
/// Return the buffer position of the end of the minibuffer prompt.
/// Return (point-min) if current buffer is not a minibuffer.
#[lisp_fn]
pub fn minibuffer_prompt_end() -> EmacsInt {
let buffer = ThreadState::current_buffer_unchecked();
let beg = buffer.beg() as EmacsInt;
if memq(buffer.into(), unsafe { Vminibuffer_list }).is_nil() {
return beg;
}
let end = field_end(Some(beg.into()), false, None);
let buffer_end = buffer.zv as EmacsInt;
if end == buffer_end && get_char_property(beg, Qfield, Qnil).is_nil() {
beg
} else {
end
}
}
/// Return the user input in a minibuffer as a string.
/// If the current buffer is not a minibuffer, return its entire contents.
#[lisp_fn]
pub fn minibuffer_contents() -> LispObject {
let prompt_end = minibuffer_prompt_end() as isize;
unsafe { make_buffer_string(prompt_end, ThreadState::current_buffer_unchecked().zv, true) }
}
/// Return the user input in a minibuffer as a string, without text-properties.
/// If the current buffer is not a minibuffer, return its entire contents.
#[lisp_fn]
pub fn minibuffer_contents_no_properties() -> LispObject {
let prompt_end = minibuffer_prompt_end() as isize;
unsafe {
make_buffer_string(
prompt_end,
ThreadState::current_buffer_unchecked().zv,
false,
)
}
}
/// Read a string from the minibuffer, prompting with string PROMPT.
/// The optional second arg INITIAL-CONTENTS is an obsolete alternative to
/// DEFAULT-VALUE. It normally should be nil in new code, except when
/// HIST is a cons. It is discussed in more detail below.
///
/// Third arg KEYMAP is a keymap to use whilst reading;
/// if omitted or nil, the default is `minibuffer-local-map'.
///
/// If fourth arg READ is non-nil, interpret the result as a Lisp object
/// and return that object:
/// in other words, do `(car (read-from-string INPUT-STRING))'
///
/// Fifth arg HIST, if non-nil, specifies a history list and optionally
/// the initial position in the list. It can be a symbol, which is the
/// history list variable to use, or a cons cell (HISTVAR. HISTPOS).
/// In that case, HISTVAR is the history list variable to use, and
/// HISTPOS is the initial position for use by the minibuffer history
/// commands. For consistency, you should also specify that element of
/// the history as the value of INITIAL-CONTENTS. Positions are counted
/// starting from 1 at the beginning of the list.
///
/// Sixth arg DEFAULT-VALUE, if non-nil, should be a string, which is used
/// as the default to `read' if READ is non-nil and the user enters
/// empty input. But if READ is nil, this function does _not_ return
/// DEFAULT-VALUE for empty input! Instead, it returns the empty string.
///
/// Whatever the value of READ, DEFAULT-VALUE is made available via the
/// minibuffer history commands. DEFAULT-VALUE can also be a list of
/// strings, in which case all the strings are available in the history,
/// and the first string is the default to `read' if READ is non-nil.
///
/// Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
///
/// If the variable `minibuffer-allow-text-properties' is non-nil,
/// then the string which is returned includes whatever text properties
/// were present in the minibuffer. Otherwise the value has no text properties.
///
/// The remainder of this documentation string describes the
/// INITIAL-CONTENTS argument in more detail. It is only relevant when
/// studying existing code, or when HIST is a cons. If non-nil,
/// INITIAL-CONTENTS is a string to be inserted into the minibuffer before
/// reading input. Normally, point is put at the end of that string.
/// However, if INITIAL-CONTENTS is (STRING. POSITION), the initial
/// input is STRING, but point is placed at _one-indexed_ position
/// POSITION in the minibuffer. Any integer value less than or equal to
/// one puts point at the beginning of the string. *Note* that this
/// behavior differs from the way such arguments are used in `completing-read'
/// and some related functions, which use zero-indexing for POSITION.
#[lisp_fn(min = "1")]
pub fn read_from_minibuffer(
prompt: LispStringRef,
initial_contents: LispObject,
mut keymap: LispObject,
read: bool,
hist: LispObject,
default_value: LispObject,
inherit_input_method: bool,
) -> LispObject {
keymap = if keymap.is_nil() {
unsafe { globals.Vminibuffer_local_map }
} else {
get_keymap(keymap, true, false)
};
let (mut histvar, mut histpos) = if hist.is_symbol() {
(hist, Qnil)
} else {
(car_safe(hist), cdr_safe(hist))
};
if histvar.is_nil() {
histvar = Qminibuffer_history
};
if histpos.is_nil() {
histpos = LispObject::from_natnum(0)
};
unsafe {
read_minibuf(
keymap,
initial_contents,
prompt.into(),
read,
histvar,
histpos,
default_value,
globals.minibuffer_allow_text_properties,
inherit_input_method,
)
}
}
// Functions that use the minibuffer to read various things.
/// Read a string in the minibuffer, with completion.
/// PROMPT is a string to prompt with; normally it ends in a colon and a space.
/// COLLECTION can be a list of strings, an alist, an obarray or a hash table.
/// COLLECTION can also be a function to do the completion itself.
/// PREDICATE limits completion to a subset of COLLECTION.
/// See `try-completion', `all-completions', `test-completion',
/// and `completion-boundaries', for more details on completion,
/// COLLECTION, and PREDICATE. See also Info nodes `(elisp)Basic Completion'
/// for the details about completion, and `(elisp)Programmed Completion' for
/// expectations from COLLECTION when it's a function.
///
/// REQUIRE-MATCH can take the following values:
/// - t means that the user is not allowed to exit unless
/// the input is (or completes to) an element of COLLECTION or is null.
/// - nil means that the user can exit with any input.
/// - `confirm' means that the user can exit with any input, but she needs
/// to confirm her choice if the input is not an element of COLLECTION.
/// - `confirm-after-completion' means that the user can exit with any
/// input, but she needs to confirm her choice if she called
/// `minibuffer-complete' right before `minibuffer-complete-and-exit'
/// and the input is not an element of COLLECTION.
/// - anything else behaves like t except that typing RET does not exit if it
/// does non-null completion.
///
/// If the input is null, `completing-read' returns DEF, or the first element
/// of the list of default values, or an empty string if DEF is nil,
/// regardless of the value of REQUIRE-MATCH.
///
/// If INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
/// with point positioned at the end.
/// If it is (STRING. POSITION), the initial input is STRING, but point
/// is placed at _zero-indexed_ position POSITION in STRING. (*Note*
/// that this is different from `read-from-minibuffer' and related
/// functions, which use one-indexing for POSITION.) This feature is
/// deprecated--it is best to pass nil for INITIAL-INPUT and supply the
/// default value DEF instead. The user can yank the default value into
/// the minibuffer easily using \\<minibuffer-local-map>\\[next-history-element].
///
/// HIST, if non-nil, specifies a history list and optionally the initial
/// position in the list. It can be a symbol, which is the history list
/// variable to use, or it can be a cons cell (HISTVAR. HISTPOS). In
/// that case, HISTVAR is the history list variable to use, and HISTPOS
/// is the initial position (the position in the list used by the
/// minibuffer history commands). For consistency, you should also
/// specify that element of the history as the value of
/// INITIAL-INPUT. (This is the only case in which you should use
/// INITIAL-INPUT instead of DEF.) Positions are counted starting from
/// 1 at the beginning of the list. The variable `history-length'
/// controls the maximum length of a history list.
///
/// DEF, if non-nil, is the default value or the list of default values.
///
/// If INHERIT-INPUT-METHOD is non-nil, the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
///
/// Completion ignores case if the ambient value of
/// `completion-ignore-case' is non-nil.
///
/// See also `completing-read-function'.
#[lisp_fn(min = "2")]
pub fn completing_read(
prompt: LispObject,
collection: LispObject,
predicate: LispObject,
require_match: LispObject,
initial_input: LispObject,
hist: LispObject,
def: LispObject,
inherit_input_method: LispObject,
) -> LispObject {
call!(
symbol_value(intern("completing-read-function")),
prompt,
collection,
predicate,
require_match,
initial_input,
hist,
def,
inherit_input_method
)
}
/// Read a string from the minibuffer, prompting with string PROMPT.
/// If non-nil, second arg INITIAL-INPUT is a string to insert before reading.
/// This argument has been superseded by DEFAULT-VALUE and should normally be nil
/// in new code. It behaves as INITIAL-CONTENTS in `read-from-minibuffer' (which
/// see).
/// The third arg HISTORY, if non-nil, specifies a history list
/// and optionally the initial position in the list.
/// See `read-from-minibuffer' for details of HISTORY argument.
/// Fourth arg DEFAULT-VALUE is the default value or the list of default values.
/// If non-nil, it is used for history commands, and as the value (or the first
/// element of the list of default values) to return if the user enters the
/// empty string.
/// Fifth arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
#[lisp_fn(min = "1")]
pub fn read_string(
prompt: LispStringRef,
initial_input: LispObject,
history: LispObject,
default_value: LispObject,
inherit_input_method: bool,
) -> LispObject {
let count = c_specpdl_index();
// Just in case we're in a recursive minibuffer, make it clear that the
// previous minibuffer's completion table does not apply to the new
// minibuffer.
// FIXME: `minibuffer-completion-table' should be buffer-local instead.
unsafe { specbind(Qminibuffer_completion_table, Qnil) };
let mut val: LispObject;
val = read_from_minibuffer(
prompt,
initial_input,
Qnil,
false,
history,
default_value,
inherit_input_method,
);
if let Some(s) = val.as_string() {
if s.is_empty() && default_value.is_not_nil() {
val = match default_value.into() {
None => default_value,
Some((a, _)) => a,
}
}
}
unbind_to(count, val)
}
pub fn read_command_or_variable(
prompt: LispObject,
default_value: LispObject,
symbol: LispObject,
) -> LispObject {
let default_string = if default_value.is_nil() {
Qnil
} else if let Some(s) = default_value.as_symbol() {
s.symbol_name()
} else {
default_value
};
let name = completing_read(
prompt,
unsafe { globals.Vobarray },
symbol,
Qt,
Qnil,
Qnil,
default_string,
Qnil,
);
if name.is_nil()
|
else {
lisp_intern(name.into(), None)
}
}
/// Read the name of a command and return as a symbol. */
/// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element */
/// if it is a list.
#[lisp_fn(min = "1")]
pub fn read_command(prompt: LispObject, default_value: LispObject) -> LispObject {
read_command_or_variable(prompt, default_value, Qcommandp)
}
/// Read the name of a user option and return it as a symbol.
/// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element
/// if it is a list.
/// A user option, or customizable variable, is one for which
/// `custom-variable-p' returns non-nil.
#[lisp_fn(min = "1")]
pub fn read_variable(prompt: LispObject, default_value: LispObject) -> LispObject {
read_command_or_variable(prompt, default_value, Qcustom_variable_p)
}
/// Read a string from the terminal, not allowing blanks.
/// Prompt with PROMPT. Whitespace terminates the input. If INITIAL is
/// non-nil, it should be a string, which is used as initial input, with
/// point positioned at the end, so that SPACE will accept the input.
/// (Actually, INITIAL can also be a cons of a string and an integer.
/// Such values are treated as in `read-from-minibuffer', but are normally
/// not useful in this function.)
/// Third arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of`enable-multibyte-characters'.
#[lisp_fn(min = "1")]
pub fn read_no_blanks_input(
prompt: LispStringRef,
initial: LispObject,
inherit_input_method: LispObject,
) -> LispObject {
unsafe {
read_minibuf(
globals.Vminibuffer_local_ns_map,
initial,
prompt.into(),
false,
Qminibuffer_history,
LispObject::from_fixnum(0),
Qnil,
false,
inherit_input_method.is_not_nil(),
)
}
}
include!(concat!(env!("OUT_DIR"), "/minibuf_exports.rs"));
|
{
name
}
|
conditional_block
|
minibuf.rs
|
//! Minibuffer input and completion.
use remacs_macros::lisp_fn;
use crate::{
buffers::{current_buffer, LispBufferOrName},
editfns::field_end,
eval::unbind_to,
keymap::get_keymap,
lisp::LispObject,
lists::{car_safe, cdr_safe, memq},
multibyte::LispStringRef,
obarray::{intern, lisp_intern},
remacs_sys::{
globals, Qcommandp, Qcustom_variable_p, Qfield, Qminibuffer_completion_table,
Qminibuffer_history, Qnil, Qt, Vminibuffer_list,
},
remacs_sys::{
make_buffer_string, minibuf_level, minibuf_prompt, minibuf_window, read_minibuf, specbind,
EmacsInt, Fcopy_sequence,
},
symbols::symbol_value,
textprop::get_char_property,
threads::{c_specpdl_index, ThreadState},
};
/// Return t if BUFFER is a minibuffer.
/// No argument or nil as argument means use current buffer as BUFFER.
/// BUFFER can be a buffer or a buffer name.
#[lisp_fn(min = "0")]
pub fn minibufferp(buffer_or_name: Option<LispBufferOrName>) -> bool {
let buffer = buffer_or_name.map_or_else(current_buffer, LispObject::from);
memq(buffer, unsafe { Vminibuffer_list }).is_not_nil()
}
/// Return the currently active minibuffer window, or nil if none.
#[lisp_fn]
pub fn active_minibuffer_window() -> LispObject {
unsafe {
if minibuf_level == 0 {
Qnil
} else {
minibuf_window
}
}
}
/// Specify which minibuffer window to use for the minibuffer.
/// This affects where the minibuffer is displayed if you put text in it
/// without invoking the usual minibuffer commands.
#[lisp_fn]
pub fn set_minibuffer_window(window: LispObject) -> LispObject {
window.as_minibuffer_or_error(); // just for the checks
unsafe {
minibuf_window = window;
}
window
}
/// Return current depth of activations of minibuffer,
/// a nonnegative integer.
#[lisp_fn]
pub fn minibuffer_depth() -> EmacsInt {
unsafe { minibuf_level }
}
/// Return the prompt string of the currently active
/// minibuffer. If no minibuffer is active return nil.
#[lisp_fn]
pub fn minibuffer_prompt() -> LispObject {
unsafe { Fcopy_sequence(minibuf_prompt) }
}
/// Return the buffer position of the end of the minibuffer prompt.
/// Return (point-min) if current buffer is not a minibuffer.
#[lisp_fn]
pub fn minibuffer_prompt_end() -> EmacsInt {
let buffer = ThreadState::current_buffer_unchecked();
let beg = buffer.beg() as EmacsInt;
if memq(buffer.into(), unsafe { Vminibuffer_list }).is_nil() {
return beg;
}
let end = field_end(Some(beg.into()), false, None);
let buffer_end = buffer.zv as EmacsInt;
if end == buffer_end && get_char_property(beg, Qfield, Qnil).is_nil() {
beg
} else {
end
}
}
/// Return the user input in a minibuffer as a string.
/// If the current buffer is not a minibuffer, return its entire contents.
#[lisp_fn]
pub fn minibuffer_contents() -> LispObject {
let prompt_end = minibuffer_prompt_end() as isize;
|
unsafe { make_buffer_string(prompt_end, ThreadState::current_buffer_unchecked().zv, true) }
}
/// Return the user input in a minibuffer as a string, without text-properties.
/// If the current buffer is not a minibuffer, return its entire contents.
#[lisp_fn]
pub fn minibuffer_contents_no_properties() -> LispObject {
let prompt_end = minibuffer_prompt_end() as isize;
unsafe {
make_buffer_string(
prompt_end,
ThreadState::current_buffer_unchecked().zv,
false,
)
}
}
/// Read a string from the minibuffer, prompting with string PROMPT.
/// The optional second arg INITIAL-CONTENTS is an obsolete alternative to
/// DEFAULT-VALUE. It normally should be nil in new code, except when
/// HIST is a cons. It is discussed in more detail below.
///
/// Third arg KEYMAP is a keymap to use whilst reading;
/// if omitted or nil, the default is `minibuffer-local-map'.
///
/// If fourth arg READ is non-nil, interpret the result as a Lisp object
/// and return that object:
/// in other words, do `(car (read-from-string INPUT-STRING))'
///
/// Fifth arg HIST, if non-nil, specifies a history list and optionally
/// the initial position in the list. It can be a symbol, which is the
/// history list variable to use, or a cons cell (HISTVAR. HISTPOS).
/// In that case, HISTVAR is the history list variable to use, and
/// HISTPOS is the initial position for use by the minibuffer history
/// commands. For consistency, you should also specify that element of
/// the history as the value of INITIAL-CONTENTS. Positions are counted
/// starting from 1 at the beginning of the list.
///
/// Sixth arg DEFAULT-VALUE, if non-nil, should be a string, which is used
/// as the default to `read' if READ is non-nil and the user enters
/// empty input. But if READ is nil, this function does _not_ return
/// DEFAULT-VALUE for empty input! Instead, it returns the empty string.
///
/// Whatever the value of READ, DEFAULT-VALUE is made available via the
/// minibuffer history commands. DEFAULT-VALUE can also be a list of
/// strings, in which case all the strings are available in the history,
/// and the first string is the default to `read' if READ is non-nil.
///
/// Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
///
/// If the variable `minibuffer-allow-text-properties' is non-nil,
/// then the string which is returned includes whatever text properties
/// were present in the minibuffer. Otherwise the value has no text properties.
///
/// The remainder of this documentation string describes the
/// INITIAL-CONTENTS argument in more detail. It is only relevant when
/// studying existing code, or when HIST is a cons. If non-nil,
/// INITIAL-CONTENTS is a string to be inserted into the minibuffer before
/// reading input. Normally, point is put at the end of that string.
/// However, if INITIAL-CONTENTS is (STRING. POSITION), the initial
/// input is STRING, but point is placed at _one-indexed_ position
/// POSITION in the minibuffer. Any integer value less than or equal to
/// one puts point at the beginning of the string. *Note* that this
/// behavior differs from the way such arguments are used in `completing-read'
/// and some related functions, which use zero-indexing for POSITION.
#[lisp_fn(min = "1")]
pub fn read_from_minibuffer(
prompt: LispStringRef,
initial_contents: LispObject,
mut keymap: LispObject,
read: bool,
hist: LispObject,
default_value: LispObject,
inherit_input_method: bool,
) -> LispObject {
keymap = if keymap.is_nil() {
unsafe { globals.Vminibuffer_local_map }
} else {
get_keymap(keymap, true, false)
};
let (mut histvar, mut histpos) = if hist.is_symbol() {
(hist, Qnil)
} else {
(car_safe(hist), cdr_safe(hist))
};
if histvar.is_nil() {
histvar = Qminibuffer_history
};
if histpos.is_nil() {
histpos = LispObject::from_natnum(0)
};
unsafe {
read_minibuf(
keymap,
initial_contents,
prompt.into(),
read,
histvar,
histpos,
default_value,
globals.minibuffer_allow_text_properties,
inherit_input_method,
)
}
}
// Functions that use the minibuffer to read various things.
/// Read a string in the minibuffer, with completion.
/// PROMPT is a string to prompt with; normally it ends in a colon and a space.
/// COLLECTION can be a list of strings, an alist, an obarray or a hash table.
/// COLLECTION can also be a function to do the completion itself.
/// PREDICATE limits completion to a subset of COLLECTION.
/// See `try-completion', `all-completions', `test-completion',
/// and `completion-boundaries', for more details on completion,
/// COLLECTION, and PREDICATE. See also Info nodes `(elisp)Basic Completion'
/// for the details about completion, and `(elisp)Programmed Completion' for
/// expectations from COLLECTION when it's a function.
///
/// REQUIRE-MATCH can take the following values:
/// - t means that the user is not allowed to exit unless
/// the input is (or completes to) an element of COLLECTION or is null.
/// - nil means that the user can exit with any input.
/// - `confirm' means that the user can exit with any input, but she needs
/// to confirm her choice if the input is not an element of COLLECTION.
/// - `confirm-after-completion' means that the user can exit with any
/// input, but she needs to confirm her choice if she called
/// `minibuffer-complete' right before `minibuffer-complete-and-exit'
/// and the input is not an element of COLLECTION.
/// - anything else behaves like t except that typing RET does not exit if it
/// does non-null completion.
///
/// If the input is null, `completing-read' returns DEF, or the first element
/// of the list of default values, or an empty string if DEF is nil,
/// regardless of the value of REQUIRE-MATCH.
///
/// If INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
/// with point positioned at the end.
/// If it is (STRING. POSITION), the initial input is STRING, but point
/// is placed at _zero-indexed_ position POSITION in STRING. (*Note*
/// that this is different from `read-from-minibuffer' and related
/// functions, which use one-indexing for POSITION.) This feature is
/// deprecated--it is best to pass nil for INITIAL-INPUT and supply the
/// default value DEF instead. The user can yank the default value into
/// the minibuffer easily using \\<minibuffer-local-map>\\[next-history-element].
///
/// HIST, if non-nil, specifies a history list and optionally the initial
/// position in the list. It can be a symbol, which is the history list
/// variable to use, or it can be a cons cell (HISTVAR. HISTPOS). In
/// that case, HISTVAR is the history list variable to use, and HISTPOS
/// is the initial position (the position in the list used by the
/// minibuffer history commands). For consistency, you should also
/// specify that element of the history as the value of
/// INITIAL-INPUT. (This is the only case in which you should use
/// INITIAL-INPUT instead of DEF.) Positions are counted starting from
/// 1 at the beginning of the list. The variable `history-length'
/// controls the maximum length of a history list.
///
/// DEF, if non-nil, is the default value or the list of default values.
///
/// If INHERIT-INPUT-METHOD is non-nil, the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
///
/// Completion ignores case if the ambient value of
/// `completion-ignore-case' is non-nil.
///
/// See also `completing-read-function'.
#[lisp_fn(min = "2")]
pub fn completing_read(
prompt: LispObject,
collection: LispObject,
predicate: LispObject,
require_match: LispObject,
initial_input: LispObject,
hist: LispObject,
def: LispObject,
inherit_input_method: LispObject,
) -> LispObject {
call!(
symbol_value(intern("completing-read-function")),
prompt,
collection,
predicate,
require_match,
initial_input,
hist,
def,
inherit_input_method
)
}
/// Read a string from the minibuffer, prompting with string PROMPT.
/// If non-nil, second arg INITIAL-INPUT is a string to insert before reading.
/// This argument has been superseded by DEFAULT-VALUE and should normally be nil
/// in new code. It behaves as INITIAL-CONTENTS in `read-from-minibuffer' (which
/// see).
/// The third arg HISTORY, if non-nil, specifies a history list
/// and optionally the initial position in the list.
/// See `read-from-minibuffer' for details of HISTORY argument.
/// Fourth arg DEFAULT-VALUE is the default value or the list of default values.
/// If non-nil, it is used for history commands, and as the value (or the first
/// element of the list of default values) to return if the user enters the
/// empty string.
/// Fifth arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
#[lisp_fn(min = "1")]
pub fn read_string(
prompt: LispStringRef,
initial_input: LispObject,
history: LispObject,
default_value: LispObject,
inherit_input_method: bool,
) -> LispObject {
let count = c_specpdl_index();
// Just in case we're in a recursive minibuffer, make it clear that the
// previous minibuffer's completion table does not apply to the new
// minibuffer.
// FIXME: `minibuffer-completion-table' should be buffer-local instead.
unsafe { specbind(Qminibuffer_completion_table, Qnil) };
let mut val: LispObject;
val = read_from_minibuffer(
prompt,
initial_input,
Qnil,
false,
history,
default_value,
inherit_input_method,
);
if let Some(s) = val.as_string() {
if s.is_empty() && default_value.is_not_nil() {
val = match default_value.into() {
None => default_value,
Some((a, _)) => a,
}
}
}
unbind_to(count, val)
}
pub fn read_command_or_variable(
prompt: LispObject,
default_value: LispObject,
symbol: LispObject,
) -> LispObject {
let default_string = if default_value.is_nil() {
Qnil
} else if let Some(s) = default_value.as_symbol() {
s.symbol_name()
} else {
default_value
};
let name = completing_read(
prompt,
unsafe { globals.Vobarray },
symbol,
Qt,
Qnil,
Qnil,
default_string,
Qnil,
);
if name.is_nil() {
name
} else {
lisp_intern(name.into(), None)
}
}
/// Read the name of a command and return as a symbol. */
/// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element */
/// if it is a list.
#[lisp_fn(min = "1")]
pub fn read_command(prompt: LispObject, default_value: LispObject) -> LispObject {
read_command_or_variable(prompt, default_value, Qcommandp)
}
/// Read the name of a user option and return it as a symbol.
/// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element
/// if it is a list.
/// A user option, or customizable variable, is one for which
/// `custom-variable-p' returns non-nil.
#[lisp_fn(min = "1")]
pub fn read_variable(prompt: LispObject, default_value: LispObject) -> LispObject {
read_command_or_variable(prompt, default_value, Qcustom_variable_p)
}
/// Read a string from the terminal, not allowing blanks.
/// Prompt with PROMPT. Whitespace terminates the input. If INITIAL is
/// non-nil, it should be a string, which is used as initial input, with
/// point positioned at the end, so that SPACE will accept the input.
/// (Actually, INITIAL can also be a cons of a string and an integer.
/// Such values are treated as in `read-from-minibuffer', but are normally
/// not useful in this function.)
/// Third arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of`enable-multibyte-characters'.
#[lisp_fn(min = "1")]
pub fn read_no_blanks_input(
prompt: LispStringRef,
initial: LispObject,
inherit_input_method: LispObject,
) -> LispObject {
unsafe {
read_minibuf(
globals.Vminibuffer_local_ns_map,
initial,
prompt.into(),
false,
Qminibuffer_history,
LispObject::from_fixnum(0),
Qnil,
false,
inherit_input_method.is_not_nil(),
)
}
}
include!(concat!(env!("OUT_DIR"), "/minibuf_exports.rs"));
|
random_line_split
|
|
minibuf.rs
|
//! Minibuffer input and completion.
use remacs_macros::lisp_fn;
use crate::{
buffers::{current_buffer, LispBufferOrName},
editfns::field_end,
eval::unbind_to,
keymap::get_keymap,
lisp::LispObject,
lists::{car_safe, cdr_safe, memq},
multibyte::LispStringRef,
obarray::{intern, lisp_intern},
remacs_sys::{
globals, Qcommandp, Qcustom_variable_p, Qfield, Qminibuffer_completion_table,
Qminibuffer_history, Qnil, Qt, Vminibuffer_list,
},
remacs_sys::{
make_buffer_string, minibuf_level, minibuf_prompt, minibuf_window, read_minibuf, specbind,
EmacsInt, Fcopy_sequence,
},
symbols::symbol_value,
textprop::get_char_property,
threads::{c_specpdl_index, ThreadState},
};
/// Return t if BUFFER is a minibuffer.
/// No argument or nil as argument means use current buffer as BUFFER.
/// BUFFER can be a buffer or a buffer name.
#[lisp_fn(min = "0")]
pub fn minibufferp(buffer_or_name: Option<LispBufferOrName>) -> bool {
let buffer = buffer_or_name.map_or_else(current_buffer, LispObject::from);
memq(buffer, unsafe { Vminibuffer_list }).is_not_nil()
}
/// Return the currently active minibuffer window, or nil if none.
#[lisp_fn]
pub fn active_minibuffer_window() -> LispObject {
unsafe {
if minibuf_level == 0 {
Qnil
} else {
minibuf_window
}
}
}
/// Specify which minibuffer window to use for the minibuffer.
/// This affects where the minibuffer is displayed if you put text in it
/// without invoking the usual minibuffer commands.
#[lisp_fn]
pub fn set_minibuffer_window(window: LispObject) -> LispObject {
window.as_minibuffer_or_error(); // just for the checks
unsafe {
minibuf_window = window;
}
window
}
/// Return current depth of activations of minibuffer,
/// a nonnegative integer.
#[lisp_fn]
pub fn minibuffer_depth() -> EmacsInt {
unsafe { minibuf_level }
}
/// Return the prompt string of the currently active
/// minibuffer. If no minibuffer is active return nil.
#[lisp_fn]
pub fn minibuffer_prompt() -> LispObject {
unsafe { Fcopy_sequence(minibuf_prompt) }
}
/// Return the buffer position of the end of the minibuffer prompt.
/// Return (point-min) if current buffer is not a minibuffer.
#[lisp_fn]
pub fn minibuffer_prompt_end() -> EmacsInt {
let buffer = ThreadState::current_buffer_unchecked();
let beg = buffer.beg() as EmacsInt;
if memq(buffer.into(), unsafe { Vminibuffer_list }).is_nil() {
return beg;
}
let end = field_end(Some(beg.into()), false, None);
let buffer_end = buffer.zv as EmacsInt;
if end == buffer_end && get_char_property(beg, Qfield, Qnil).is_nil() {
beg
} else {
end
}
}
/// Return the user input in a minibuffer as a string.
/// If the current buffer is not a minibuffer, return its entire contents.
#[lisp_fn]
pub fn minibuffer_contents() -> LispObject {
let prompt_end = minibuffer_prompt_end() as isize;
unsafe { make_buffer_string(prompt_end, ThreadState::current_buffer_unchecked().zv, true) }
}
/// Return the user input in a minibuffer as a string, without text-properties.
/// If the current buffer is not a minibuffer, return its entire contents.
#[lisp_fn]
pub fn minibuffer_contents_no_properties() -> LispObject {
let prompt_end = minibuffer_prompt_end() as isize;
unsafe {
make_buffer_string(
prompt_end,
ThreadState::current_buffer_unchecked().zv,
false,
)
}
}
/// Read a string from the minibuffer, prompting with string PROMPT.
/// The optional second arg INITIAL-CONTENTS is an obsolete alternative to
/// DEFAULT-VALUE. It normally should be nil in new code, except when
/// HIST is a cons. It is discussed in more detail below.
///
/// Third arg KEYMAP is a keymap to use whilst reading;
/// if omitted or nil, the default is `minibuffer-local-map'.
///
/// If fourth arg READ is non-nil, interpret the result as a Lisp object
/// and return that object:
/// in other words, do `(car (read-from-string INPUT-STRING))'
///
/// Fifth arg HIST, if non-nil, specifies a history list and optionally
/// the initial position in the list. It can be a symbol, which is the
/// history list variable to use, or a cons cell (HISTVAR. HISTPOS).
/// In that case, HISTVAR is the history list variable to use, and
/// HISTPOS is the initial position for use by the minibuffer history
/// commands. For consistency, you should also specify that element of
/// the history as the value of INITIAL-CONTENTS. Positions are counted
/// starting from 1 at the beginning of the list.
///
/// Sixth arg DEFAULT-VALUE, if non-nil, should be a string, which is used
/// as the default to `read' if READ is non-nil and the user enters
/// empty input. But if READ is nil, this function does _not_ return
/// DEFAULT-VALUE for empty input! Instead, it returns the empty string.
///
/// Whatever the value of READ, DEFAULT-VALUE is made available via the
/// minibuffer history commands. DEFAULT-VALUE can also be a list of
/// strings, in which case all the strings are available in the history,
/// and the first string is the default to `read' if READ is non-nil.
///
/// Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
///
/// If the variable `minibuffer-allow-text-properties' is non-nil,
/// then the string which is returned includes whatever text properties
/// were present in the minibuffer. Otherwise the value has no text properties.
///
/// The remainder of this documentation string describes the
/// INITIAL-CONTENTS argument in more detail. It is only relevant when
/// studying existing code, or when HIST is a cons. If non-nil,
/// INITIAL-CONTENTS is a string to be inserted into the minibuffer before
/// reading input. Normally, point is put at the end of that string.
/// However, if INITIAL-CONTENTS is (STRING. POSITION), the initial
/// input is STRING, but point is placed at _one-indexed_ position
/// POSITION in the minibuffer. Any integer value less than or equal to
/// one puts point at the beginning of the string. *Note* that this
/// behavior differs from the way such arguments are used in `completing-read'
/// and some related functions, which use zero-indexing for POSITION.
#[lisp_fn(min = "1")]
pub fn read_from_minibuffer(
prompt: LispStringRef,
initial_contents: LispObject,
mut keymap: LispObject,
read: bool,
hist: LispObject,
default_value: LispObject,
inherit_input_method: bool,
) -> LispObject {
keymap = if keymap.is_nil() {
unsafe { globals.Vminibuffer_local_map }
} else {
get_keymap(keymap, true, false)
};
let (mut histvar, mut histpos) = if hist.is_symbol() {
(hist, Qnil)
} else {
(car_safe(hist), cdr_safe(hist))
};
if histvar.is_nil() {
histvar = Qminibuffer_history
};
if histpos.is_nil() {
histpos = LispObject::from_natnum(0)
};
unsafe {
read_minibuf(
keymap,
initial_contents,
prompt.into(),
read,
histvar,
histpos,
default_value,
globals.minibuffer_allow_text_properties,
inherit_input_method,
)
}
}
// Functions that use the minibuffer to read various things.
/// Read a string in the minibuffer, with completion.
/// PROMPT is a string to prompt with; normally it ends in a colon and a space.
/// COLLECTION can be a list of strings, an alist, an obarray or a hash table.
/// COLLECTION can also be a function to do the completion itself.
/// PREDICATE limits completion to a subset of COLLECTION.
/// See `try-completion', `all-completions', `test-completion',
/// and `completion-boundaries', for more details on completion,
/// COLLECTION, and PREDICATE. See also Info nodes `(elisp)Basic Completion'
/// for the details about completion, and `(elisp)Programmed Completion' for
/// expectations from COLLECTION when it's a function.
///
/// REQUIRE-MATCH can take the following values:
/// - t means that the user is not allowed to exit unless
/// the input is (or completes to) an element of COLLECTION or is null.
/// - nil means that the user can exit with any input.
/// - `confirm' means that the user can exit with any input, but she needs
/// to confirm her choice if the input is not an element of COLLECTION.
/// - `confirm-after-completion' means that the user can exit with any
/// input, but she needs to confirm her choice if she called
/// `minibuffer-complete' right before `minibuffer-complete-and-exit'
/// and the input is not an element of COLLECTION.
/// - anything else behaves like t except that typing RET does not exit if it
/// does non-null completion.
///
/// If the input is null, `completing-read' returns DEF, or the first element
/// of the list of default values, or an empty string if DEF is nil,
/// regardless of the value of REQUIRE-MATCH.
///
/// If INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
/// with point positioned at the end.
/// If it is (STRING. POSITION), the initial input is STRING, but point
/// is placed at _zero-indexed_ position POSITION in STRING. (*Note*
/// that this is different from `read-from-minibuffer' and related
/// functions, which use one-indexing for POSITION.) This feature is
/// deprecated--it is best to pass nil for INITIAL-INPUT and supply the
/// default value DEF instead. The user can yank the default value into
/// the minibuffer easily using \\<minibuffer-local-map>\\[next-history-element].
///
/// HIST, if non-nil, specifies a history list and optionally the initial
/// position in the list. It can be a symbol, which is the history list
/// variable to use, or it can be a cons cell (HISTVAR. HISTPOS). In
/// that case, HISTVAR is the history list variable to use, and HISTPOS
/// is the initial position (the position in the list used by the
/// minibuffer history commands). For consistency, you should also
/// specify that element of the history as the value of
/// INITIAL-INPUT. (This is the only case in which you should use
/// INITIAL-INPUT instead of DEF.) Positions are counted starting from
/// 1 at the beginning of the list. The variable `history-length'
/// controls the maximum length of a history list.
///
/// DEF, if non-nil, is the default value or the list of default values.
///
/// If INHERIT-INPUT-METHOD is non-nil, the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
///
/// Completion ignores case if the ambient value of
/// `completion-ignore-case' is non-nil.
///
/// See also `completing-read-function'.
#[lisp_fn(min = "2")]
pub fn completing_read(
prompt: LispObject,
collection: LispObject,
predicate: LispObject,
require_match: LispObject,
initial_input: LispObject,
hist: LispObject,
def: LispObject,
inherit_input_method: LispObject,
) -> LispObject {
call!(
symbol_value(intern("completing-read-function")),
prompt,
collection,
predicate,
require_match,
initial_input,
hist,
def,
inherit_input_method
)
}
/// Read a string from the minibuffer, prompting with string PROMPT.
/// If non-nil, second arg INITIAL-INPUT is a string to insert before reading.
/// This argument has been superseded by DEFAULT-VALUE and should normally be nil
/// in new code. It behaves as INITIAL-CONTENTS in `read-from-minibuffer' (which
/// see).
/// The third arg HISTORY, if non-nil, specifies a history list
/// and optionally the initial position in the list.
/// See `read-from-minibuffer' for details of HISTORY argument.
/// Fourth arg DEFAULT-VALUE is the default value or the list of default values.
/// If non-nil, it is used for history commands, and as the value (or the first
/// element of the list of default values) to return if the user enters the
/// empty string.
/// Fifth arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
#[lisp_fn(min = "1")]
pub fn read_string(
prompt: LispStringRef,
initial_input: LispObject,
history: LispObject,
default_value: LispObject,
inherit_input_method: bool,
) -> LispObject {
let count = c_specpdl_index();
// Just in case we're in a recursive minibuffer, make it clear that the
// previous minibuffer's completion table does not apply to the new
// minibuffer.
// FIXME: `minibuffer-completion-table' should be buffer-local instead.
unsafe { specbind(Qminibuffer_completion_table, Qnil) };
let mut val: LispObject;
val = read_from_minibuffer(
prompt,
initial_input,
Qnil,
false,
history,
default_value,
inherit_input_method,
);
if let Some(s) = val.as_string() {
if s.is_empty() && default_value.is_not_nil() {
val = match default_value.into() {
None => default_value,
Some((a, _)) => a,
}
}
}
unbind_to(count, val)
}
pub fn read_command_or_variable(
prompt: LispObject,
default_value: LispObject,
symbol: LispObject,
) -> LispObject {
let default_string = if default_value.is_nil() {
Qnil
} else if let Some(s) = default_value.as_symbol() {
s.symbol_name()
} else {
default_value
};
let name = completing_read(
prompt,
unsafe { globals.Vobarray },
symbol,
Qt,
Qnil,
Qnil,
default_string,
Qnil,
);
if name.is_nil() {
name
} else {
lisp_intern(name.into(), None)
}
}
/// Read the name of a command and return as a symbol. */
/// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element */
/// if it is a list.
#[lisp_fn(min = "1")]
pub fn read_command(prompt: LispObject, default_value: LispObject) -> LispObject {
read_command_or_variable(prompt, default_value, Qcommandp)
}
/// Read the name of a user option and return it as a symbol.
/// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element
/// if it is a list.
/// A user option, or customizable variable, is one for which
/// `custom-variable-p' returns non-nil.
#[lisp_fn(min = "1")]
pub fn read_variable(prompt: LispObject, default_value: LispObject) -> LispObject
|
/// Read a string from the terminal, not allowing blanks.
/// Prompt with PROMPT. Whitespace terminates the input. If INITIAL is
/// non-nil, it should be a string, which is used as initial input, with
/// point positioned at the end, so that SPACE will accept the input.
/// (Actually, INITIAL can also be a cons of a string and an integer.
/// Such values are treated as in `read-from-minibuffer', but are normally
/// not useful in this function.)
/// Third arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of`enable-multibyte-characters'.
#[lisp_fn(min = "1")]
pub fn read_no_blanks_input(
prompt: LispStringRef,
initial: LispObject,
inherit_input_method: LispObject,
) -> LispObject {
unsafe {
read_minibuf(
globals.Vminibuffer_local_ns_map,
initial,
prompt.into(),
false,
Qminibuffer_history,
LispObject::from_fixnum(0),
Qnil,
false,
inherit_input_method.is_not_nil(),
)
}
}
include!(concat!(env!("OUT_DIR"), "/minibuf_exports.rs"));
|
{
read_command_or_variable(prompt, default_value, Qcustom_variable_p)
}
|
identifier_body
|
minibuf.rs
|
//! Minibuffer input and completion.
use remacs_macros::lisp_fn;
use crate::{
buffers::{current_buffer, LispBufferOrName},
editfns::field_end,
eval::unbind_to,
keymap::get_keymap,
lisp::LispObject,
lists::{car_safe, cdr_safe, memq},
multibyte::LispStringRef,
obarray::{intern, lisp_intern},
remacs_sys::{
globals, Qcommandp, Qcustom_variable_p, Qfield, Qminibuffer_completion_table,
Qminibuffer_history, Qnil, Qt, Vminibuffer_list,
},
remacs_sys::{
make_buffer_string, minibuf_level, minibuf_prompt, minibuf_window, read_minibuf, specbind,
EmacsInt, Fcopy_sequence,
},
symbols::symbol_value,
textprop::get_char_property,
threads::{c_specpdl_index, ThreadState},
};
/// Return t if BUFFER is a minibuffer.
/// No argument or nil as argument means use current buffer as BUFFER.
/// BUFFER can be a buffer or a buffer name.
#[lisp_fn(min = "0")]
pub fn minibufferp(buffer_or_name: Option<LispBufferOrName>) -> bool {
let buffer = buffer_or_name.map_or_else(current_buffer, LispObject::from);
memq(buffer, unsafe { Vminibuffer_list }).is_not_nil()
}
/// Return the currently active minibuffer window, or nil if none.
#[lisp_fn]
pub fn active_minibuffer_window() -> LispObject {
unsafe {
if minibuf_level == 0 {
Qnil
} else {
minibuf_window
}
}
}
/// Specify which minibuffer window to use for the minibuffer.
/// This affects where the minibuffer is displayed if you put text in it
/// without invoking the usual minibuffer commands.
#[lisp_fn]
pub fn set_minibuffer_window(window: LispObject) -> LispObject {
window.as_minibuffer_or_error(); // just for the checks
unsafe {
minibuf_window = window;
}
window
}
/// Return current depth of activations of minibuffer,
/// a nonnegative integer.
#[lisp_fn]
pub fn minibuffer_depth() -> EmacsInt {
unsafe { minibuf_level }
}
/// Return the prompt string of the currently active
/// minibuffer. If no minibuffer is active return nil.
#[lisp_fn]
pub fn minibuffer_prompt() -> LispObject {
unsafe { Fcopy_sequence(minibuf_prompt) }
}
/// Return the buffer position of the end of the minibuffer prompt.
/// Return (point-min) if current buffer is not a minibuffer.
#[lisp_fn]
pub fn minibuffer_prompt_end() -> EmacsInt {
let buffer = ThreadState::current_buffer_unchecked();
let beg = buffer.beg() as EmacsInt;
if memq(buffer.into(), unsafe { Vminibuffer_list }).is_nil() {
return beg;
}
let end = field_end(Some(beg.into()), false, None);
let buffer_end = buffer.zv as EmacsInt;
if end == buffer_end && get_char_property(beg, Qfield, Qnil).is_nil() {
beg
} else {
end
}
}
/// Return the user input in a minibuffer as a string.
/// If the current buffer is not a minibuffer, return its entire contents.
#[lisp_fn]
pub fn minibuffer_contents() -> LispObject {
let prompt_end = minibuffer_prompt_end() as isize;
unsafe { make_buffer_string(prompt_end, ThreadState::current_buffer_unchecked().zv, true) }
}
/// Return the user input in a minibuffer as a string, without text-properties.
/// If the current buffer is not a minibuffer, return its entire contents.
#[lisp_fn]
pub fn minibuffer_contents_no_properties() -> LispObject {
let prompt_end = minibuffer_prompt_end() as isize;
unsafe {
make_buffer_string(
prompt_end,
ThreadState::current_buffer_unchecked().zv,
false,
)
}
}
/// Read a string from the minibuffer, prompting with string PROMPT.
/// The optional second arg INITIAL-CONTENTS is an obsolete alternative to
/// DEFAULT-VALUE. It normally should be nil in new code, except when
/// HIST is a cons. It is discussed in more detail below.
///
/// Third arg KEYMAP is a keymap to use whilst reading;
/// if omitted or nil, the default is `minibuffer-local-map'.
///
/// If fourth arg READ is non-nil, interpret the result as a Lisp object
/// and return that object:
/// in other words, do `(car (read-from-string INPUT-STRING))'
///
/// Fifth arg HIST, if non-nil, specifies a history list and optionally
/// the initial position in the list. It can be a symbol, which is the
/// history list variable to use, or a cons cell (HISTVAR. HISTPOS).
/// In that case, HISTVAR is the history list variable to use, and
/// HISTPOS is the initial position for use by the minibuffer history
/// commands. For consistency, you should also specify that element of
/// the history as the value of INITIAL-CONTENTS. Positions are counted
/// starting from 1 at the beginning of the list.
///
/// Sixth arg DEFAULT-VALUE, if non-nil, should be a string, which is used
/// as the default to `read' if READ is non-nil and the user enters
/// empty input. But if READ is nil, this function does _not_ return
/// DEFAULT-VALUE for empty input! Instead, it returns the empty string.
///
/// Whatever the value of READ, DEFAULT-VALUE is made available via the
/// minibuffer history commands. DEFAULT-VALUE can also be a list of
/// strings, in which case all the strings are available in the history,
/// and the first string is the default to `read' if READ is non-nil.
///
/// Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
///
/// If the variable `minibuffer-allow-text-properties' is non-nil,
/// then the string which is returned includes whatever text properties
/// were present in the minibuffer. Otherwise the value has no text properties.
///
/// The remainder of this documentation string describes the
/// INITIAL-CONTENTS argument in more detail. It is only relevant when
/// studying existing code, or when HIST is a cons. If non-nil,
/// INITIAL-CONTENTS is a string to be inserted into the minibuffer before
/// reading input. Normally, point is put at the end of that string.
/// However, if INITIAL-CONTENTS is (STRING. POSITION), the initial
/// input is STRING, but point is placed at _one-indexed_ position
/// POSITION in the minibuffer. Any integer value less than or equal to
/// one puts point at the beginning of the string. *Note* that this
/// behavior differs from the way such arguments are used in `completing-read'
/// and some related functions, which use zero-indexing for POSITION.
#[lisp_fn(min = "1")]
pub fn
|
(
prompt: LispStringRef,
initial_contents: LispObject,
mut keymap: LispObject,
read: bool,
hist: LispObject,
default_value: LispObject,
inherit_input_method: bool,
) -> LispObject {
keymap = if keymap.is_nil() {
unsafe { globals.Vminibuffer_local_map }
} else {
get_keymap(keymap, true, false)
};
let (mut histvar, mut histpos) = if hist.is_symbol() {
(hist, Qnil)
} else {
(car_safe(hist), cdr_safe(hist))
};
if histvar.is_nil() {
histvar = Qminibuffer_history
};
if histpos.is_nil() {
histpos = LispObject::from_natnum(0)
};
unsafe {
read_minibuf(
keymap,
initial_contents,
prompt.into(),
read,
histvar,
histpos,
default_value,
globals.minibuffer_allow_text_properties,
inherit_input_method,
)
}
}
// Functions that use the minibuffer to read various things.
/// Read a string in the minibuffer, with completion.
/// PROMPT is a string to prompt with; normally it ends in a colon and a space.
/// COLLECTION can be a list of strings, an alist, an obarray or a hash table.
/// COLLECTION can also be a function to do the completion itself.
/// PREDICATE limits completion to a subset of COLLECTION.
/// See `try-completion', `all-completions', `test-completion',
/// and `completion-boundaries', for more details on completion,
/// COLLECTION, and PREDICATE. See also Info nodes `(elisp)Basic Completion'
/// for the details about completion, and `(elisp)Programmed Completion' for
/// expectations from COLLECTION when it's a function.
///
/// REQUIRE-MATCH can take the following values:
/// - t means that the user is not allowed to exit unless
/// the input is (or completes to) an element of COLLECTION or is null.
/// - nil means that the user can exit with any input.
/// - `confirm' means that the user can exit with any input, but she needs
/// to confirm her choice if the input is not an element of COLLECTION.
/// - `confirm-after-completion' means that the user can exit with any
/// input, but she needs to confirm her choice if she called
/// `minibuffer-complete' right before `minibuffer-complete-and-exit'
/// and the input is not an element of COLLECTION.
/// - anything else behaves like t except that typing RET does not exit if it
/// does non-null completion.
///
/// If the input is null, `completing-read' returns DEF, or the first element
/// of the list of default values, or an empty string if DEF is nil,
/// regardless of the value of REQUIRE-MATCH.
///
/// If INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
/// with point positioned at the end.
/// If it is (STRING. POSITION), the initial input is STRING, but point
/// is placed at _zero-indexed_ position POSITION in STRING. (*Note*
/// that this is different from `read-from-minibuffer' and related
/// functions, which use one-indexing for POSITION.) This feature is
/// deprecated--it is best to pass nil for INITIAL-INPUT and supply the
/// default value DEF instead. The user can yank the default value into
/// the minibuffer easily using \\<minibuffer-local-map>\\[next-history-element].
///
/// HIST, if non-nil, specifies a history list and optionally the initial
/// position in the list. It can be a symbol, which is the history list
/// variable to use, or it can be a cons cell (HISTVAR. HISTPOS). In
/// that case, HISTVAR is the history list variable to use, and HISTPOS
/// is the initial position (the position in the list used by the
/// minibuffer history commands). For consistency, you should also
/// specify that element of the history as the value of
/// INITIAL-INPUT. (This is the only case in which you should use
/// INITIAL-INPUT instead of DEF.) Positions are counted starting from
/// 1 at the beginning of the list. The variable `history-length'
/// controls the maximum length of a history list.
///
/// DEF, if non-nil, is the default value or the list of default values.
///
/// If INHERIT-INPUT-METHOD is non-nil, the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
///
/// Completion ignores case if the ambient value of
/// `completion-ignore-case' is non-nil.
///
/// See also `completing-read-function'.
#[lisp_fn(min = "2")]
pub fn completing_read(
prompt: LispObject,
collection: LispObject,
predicate: LispObject,
require_match: LispObject,
initial_input: LispObject,
hist: LispObject,
def: LispObject,
inherit_input_method: LispObject,
) -> LispObject {
call!(
symbol_value(intern("completing-read-function")),
prompt,
collection,
predicate,
require_match,
initial_input,
hist,
def,
inherit_input_method
)
}
/// Read a string from the minibuffer, prompting with string PROMPT.
/// If non-nil, second arg INITIAL-INPUT is a string to insert before reading.
/// This argument has been superseded by DEFAULT-VALUE and should normally be nil
/// in new code. It behaves as INITIAL-CONTENTS in `read-from-minibuffer' (which
/// see).
/// The third arg HISTORY, if non-nil, specifies a history list
/// and optionally the initial position in the list.
/// See `read-from-minibuffer' for details of HISTORY argument.
/// Fourth arg DEFAULT-VALUE is the default value or the list of default values.
/// If non-nil, it is used for history commands, and as the value (or the first
/// element of the list of default values) to return if the user enters the
/// empty string.
/// Fifth arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of `enable-multibyte-characters'.
#[lisp_fn(min = "1")]
pub fn read_string(
prompt: LispStringRef,
initial_input: LispObject,
history: LispObject,
default_value: LispObject,
inherit_input_method: bool,
) -> LispObject {
let count = c_specpdl_index();
// Just in case we're in a recursive minibuffer, make it clear that the
// previous minibuffer's completion table does not apply to the new
// minibuffer.
// FIXME: `minibuffer-completion-table' should be buffer-local instead.
unsafe { specbind(Qminibuffer_completion_table, Qnil) };
let mut val: LispObject;
val = read_from_minibuffer(
prompt,
initial_input,
Qnil,
false,
history,
default_value,
inherit_input_method,
);
if let Some(s) = val.as_string() {
if s.is_empty() && default_value.is_not_nil() {
val = match default_value.into() {
None => default_value,
Some((a, _)) => a,
}
}
}
unbind_to(count, val)
}
pub fn read_command_or_variable(
prompt: LispObject,
default_value: LispObject,
symbol: LispObject,
) -> LispObject {
let default_string = if default_value.is_nil() {
Qnil
} else if let Some(s) = default_value.as_symbol() {
s.symbol_name()
} else {
default_value
};
let name = completing_read(
prompt,
unsafe { globals.Vobarray },
symbol,
Qt,
Qnil,
Qnil,
default_string,
Qnil,
);
if name.is_nil() {
name
} else {
lisp_intern(name.into(), None)
}
}
/// Read the name of a command and return as a symbol. */
/// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element */
/// if it is a list.
#[lisp_fn(min = "1")]
pub fn read_command(prompt: LispObject, default_value: LispObject) -> LispObject {
read_command_or_variable(prompt, default_value, Qcommandp)
}
/// Read the name of a user option and return it as a symbol.
/// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element
/// if it is a list.
/// A user option, or customizable variable, is one for which
/// `custom-variable-p' returns non-nil.
#[lisp_fn(min = "1")]
pub fn read_variable(prompt: LispObject, default_value: LispObject) -> LispObject {
read_command_or_variable(prompt, default_value, Qcustom_variable_p)
}
/// Read a string from the terminal, not allowing blanks.
/// Prompt with PROMPT. Whitespace terminates the input. If INITIAL is
/// non-nil, it should be a string, which is used as initial input, with
/// point positioned at the end, so that SPACE will accept the input.
/// (Actually, INITIAL can also be a cons of a string and an integer.
/// Such values are treated as in `read-from-minibuffer', but are normally
/// not useful in this function.)
/// Third arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
/// the current input method and the setting of`enable-multibyte-characters'.
#[lisp_fn(min = "1")]
pub fn read_no_blanks_input(
prompt: LispStringRef,
initial: LispObject,
inherit_input_method: LispObject,
) -> LispObject {
unsafe {
read_minibuf(
globals.Vminibuffer_local_ns_map,
initial,
prompt.into(),
false,
Qminibuffer_history,
LispObject::from_fixnum(0),
Qnil,
false,
inherit_input_method.is_not_nil(),
)
}
}
include!(concat!(env!("OUT_DIR"), "/minibuf_exports.rs"));
|
read_from_minibuffer
|
identifier_name
|
x86_64.rs
|
//! x86_64-specific definitions for 64-bit linux-like values
pub type c_char = i8;
pub type wchar_t = i32;
pub type nlink_t = u64;
pub type blksize_t = i64;
pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40;
pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4;
s! {
pub struct stat {
pub st_dev: ::dev_t,
pub st_ino: ::ino_t,
pub st_nlink: ::nlink_t,
pub st_mode: ::mode_t,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
__pad0: ::c_int,
pub st_rdev: ::dev_t,
pub st_size: ::off_t,
pub st_blksize: ::blksize_t,
pub st_blocks: ::blkcnt_t,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
|
}
pub struct pthread_attr_t {
__size: [u64; 7]
}
}
|
pub st_ctime_nsec: ::c_long,
__unused: [::c_long; 3],
|
random_line_split
|
cat.rs
|
use std::io::{Result, Read, Write, copy, stdout, stderr};
use std::env::args_os;
use std::process::exit;
use std::ffi::OsString;
use std::fs::File;
use std::path::Path;
extern crate concat;
use concat::concat;
fn main() {
let mut args = args_os();
let progname = args.next().unwrap_or_else(|| OsString::from("cat"));
let mut c = concat(args.map(InputSource::from));
let res = copy(&mut c, &mut stdout());
if let Err(e) = res
|
}
struct InputSource {
path: OsString,
file: Option<File>,
}
impl InputSource {
pub fn path(&self) -> &Path {
self.path.as_ref()
}
}
impl From<OsString> for InputSource {
fn from(path: OsString) -> InputSource {
InputSource {
path: path,
file: None,
}
}
}
impl Read for InputSource {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
if self.file.is_none() {
self.file = Some(try!(File::open(&self.path)));
}
self.file.as_mut().unwrap().read(buf)
}
}
|
{
match c.current() {
None => {
writeln!(&mut stderr(),
"{}: {}\n",
AsRef::<Path>::as_ref(&progname).display(),
e).unwrap();
},
Some(ref f) => {
writeln!(&mut stderr(),
"{}: {}: {}\n",
AsRef::<Path>::as_ref(&progname).display(),
f.path().display(),
e).unwrap();
},
};
exit(1);
}
|
conditional_block
|
cat.rs
|
use std::io::{Result, Read, Write, copy, stdout, stderr};
use std::env::args_os;
use std::process::exit;
use std::ffi::OsString;
use std::fs::File;
use std::path::Path;
extern crate concat;
use concat::concat;
fn main() {
let mut args = args_os();
let progname = args.next().unwrap_or_else(|| OsString::from("cat"));
let mut c = concat(args.map(InputSource::from));
let res = copy(&mut c, &mut stdout());
if let Err(e) = res {
match c.current() {
None => {
writeln!(&mut stderr(),
"{}: {}\n",
AsRef::<Path>::as_ref(&progname).display(),
e).unwrap();
},
Some(ref f) => {
writeln!(&mut stderr(),
"{}: {}: {}\n",
AsRef::<Path>::as_ref(&progname).display(),
f.path().display(),
e).unwrap();
},
};
exit(1);
}
}
struct InputSource {
path: OsString,
file: Option<File>,
}
impl InputSource {
pub fn
|
(&self) -> &Path {
self.path.as_ref()
}
}
impl From<OsString> for InputSource {
fn from(path: OsString) -> InputSource {
InputSource {
path: path,
file: None,
}
}
}
impl Read for InputSource {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
if self.file.is_none() {
self.file = Some(try!(File::open(&self.path)));
}
self.file.as_mut().unwrap().read(buf)
}
}
|
path
|
identifier_name
|
cat.rs
|
use std::io::{Result, Read, Write, copy, stdout, stderr};
use std::env::args_os;
use std::process::exit;
use std::ffi::OsString;
use std::fs::File;
use std::path::Path;
extern crate concat;
use concat::concat;
|
let mut c = concat(args.map(InputSource::from));
let res = copy(&mut c, &mut stdout());
if let Err(e) = res {
match c.current() {
None => {
writeln!(&mut stderr(),
"{}: {}\n",
AsRef::<Path>::as_ref(&progname).display(),
e).unwrap();
},
Some(ref f) => {
writeln!(&mut stderr(),
"{}: {}: {}\n",
AsRef::<Path>::as_ref(&progname).display(),
f.path().display(),
e).unwrap();
},
};
exit(1);
}
}
struct InputSource {
path: OsString,
file: Option<File>,
}
impl InputSource {
pub fn path(&self) -> &Path {
self.path.as_ref()
}
}
impl From<OsString> for InputSource {
fn from(path: OsString) -> InputSource {
InputSource {
path: path,
file: None,
}
}
}
impl Read for InputSource {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
if self.file.is_none() {
self.file = Some(try!(File::open(&self.path)));
}
self.file.as_mut().unwrap().read(buf)
}
}
|
fn main() {
let mut args = args_os();
let progname = args.next().unwrap_or_else(|| OsString::from("cat"));
|
random_line_split
|
ms.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::rc::Rc;
use std::any::Any;
use ::layout::{MsLayout, Layout};
use super::super::{
TokenPrivate, Token, PresentationPrivate, Presentation, SpecifiedTokenProps, PropertyCalculator,
SpecifiedPresentationProps, Element, InheritedProps, StyleProps, ElementType, TokenElement,
Property, InstanceId, Family, EmptyComputeCtx};
use ::platform::Context;
#[allow(const_err)]
const PROP_LQUOTE: Property<String, Ms, EmptyComputeCtx> = Property::Specified {
default: || String::from("\""),
reader: |s| s.ms_lquote(),
};
#[allow(const_err)]
const PROP_RQUOTE: Property<String, Ms, EmptyComputeCtx> = Property::Specified {
default: || String::from("\""),
reader: |s| s.ms_rquote(),
};
pub struct Ms {
instance_id: InstanceId,
lquote: Option<String>,
rquote: Option<String>,
token_props: SpecifiedTokenProps,
presentation_props: SpecifiedPresentationProps,
}
impl Ms {
pub fn new(text: String) -> Ms {
Ms {
instance_id: InstanceId::new(),
lquote: None,
rquote: None,
token_props: SpecifiedTokenProps {
text: Rc::new(text),
math_variant: None,
math_size: None,
dir: None,
},
presentation_props: SpecifiedPresentationProps {
math_color: None,
math_background: None,
}
}
}
}
impl Element for Ms {
fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps,
style: &Option<&StyleProps>) -> Box<Layout> {
let mut calculator = PropertyCalculator::new(
context, self, family, inherited, style.clone());
let lquote = calculator.calculate(&PROP_LQUOTE, self.lquote.as_ref());
let rquote = calculator.calculate(&PROP_RQUOTE, self.rquote.as_ref());
let token_layout = MsLayout {
token_element: self.layout_token_element(context, &mut calculator),
rquote,
lquote
};
Box::new(token_layout)
}
fn type_info(&self) -> ElementType {
ElementType::TokenElement(TokenElement::Ms)
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
fn instance_id(&self) -> &InstanceId {
&self.instance_id
}
}
impl PresentationPrivate<Ms> for Ms {
fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps {
&self.presentation_props
}
fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps {
&mut self.presentation_props
}
}
impl TokenPrivate<Ms> for Ms {
fn get_specified_token_props(&self) -> &SpecifiedTokenProps {
&self.token_props
}
fn
|
(&mut self) -> &mut SpecifiedTokenProps {
&mut self.token_props
}
}
impl Token<Ms> for Ms {}
impl Presentation<Ms> for Ms {}
#[cfg(test)]
mod test {
use super::*;
use ::test::skia::Snapshot;
use ::props::{Color, MathSize, MathVariant};
#[test]
fn it_works() {
let snap = Snapshot::default();
snap.snap_element(
&Ms::new(String::from("hello ms")),
"ms_text"
);
snap.snap_element(
Ms::new(String::from("hello fraktur"))
.with_math_variant(Some(MathVariant::Fraktur)),
"ms_text_fraktur"
);
snap.snap_element(
Ms::new(String::from("I am big"))
.with_math_size(Some(MathSize::BIG)),
"ms_big"
);
snap.snap_element(
Ms::new(String::from("I am red"))
.with_math_color(Some(Color::RGB(255, 0, 0))),
"ms_red"
);
snap.snap_element(
Ms::new(String::from("I am on fire"))
.with_math_background(Some(Color::RGB(255, 0, 0))),
"ms_red_bg"
);
}
}
|
get_specified_token_props_mut
|
identifier_name
|
ms.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::rc::Rc;
use std::any::Any;
use ::layout::{MsLayout, Layout};
use super::super::{
TokenPrivate, Token, PresentationPrivate, Presentation, SpecifiedTokenProps, PropertyCalculator,
SpecifiedPresentationProps, Element, InheritedProps, StyleProps, ElementType, TokenElement,
Property, InstanceId, Family, EmptyComputeCtx};
use ::platform::Context;
#[allow(const_err)]
const PROP_LQUOTE: Property<String, Ms, EmptyComputeCtx> = Property::Specified {
default: || String::from("\""),
reader: |s| s.ms_lquote(),
};
#[allow(const_err)]
const PROP_RQUOTE: Property<String, Ms, EmptyComputeCtx> = Property::Specified {
default: || String::from("\""),
reader: |s| s.ms_rquote(),
};
pub struct Ms {
instance_id: InstanceId,
lquote: Option<String>,
rquote: Option<String>,
token_props: SpecifiedTokenProps,
presentation_props: SpecifiedPresentationProps,
}
impl Ms {
pub fn new(text: String) -> Ms {
Ms {
instance_id: InstanceId::new(),
lquote: None,
rquote: None,
token_props: SpecifiedTokenProps {
text: Rc::new(text),
math_variant: None,
math_size: None,
dir: None,
},
presentation_props: SpecifiedPresentationProps {
math_color: None,
math_background: None,
}
}
}
}
impl Element for Ms {
fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps,
style: &Option<&StyleProps>) -> Box<Layout> {
let mut calculator = PropertyCalculator::new(
context, self, family, inherited, style.clone());
let lquote = calculator.calculate(&PROP_LQUOTE, self.lquote.as_ref());
let rquote = calculator.calculate(&PROP_RQUOTE, self.rquote.as_ref());
let token_layout = MsLayout {
token_element: self.layout_token_element(context, &mut calculator),
rquote,
lquote
};
Box::new(token_layout)
}
fn type_info(&self) -> ElementType {
ElementType::TokenElement(TokenElement::Ms)
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
fn instance_id(&self) -> &InstanceId {
&self.instance_id
}
}
impl PresentationPrivate<Ms> for Ms {
fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps {
&self.presentation_props
}
fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps {
&mut self.presentation_props
}
}
impl TokenPrivate<Ms> for Ms {
fn get_specified_token_props(&self) -> &SpecifiedTokenProps {
&self.token_props
}
fn get_specified_token_props_mut(&mut self) -> &mut SpecifiedTokenProps {
&mut self.token_props
}
}
impl Token<Ms> for Ms {}
impl Presentation<Ms> for Ms {}
#[cfg(test)]
mod test {
use super::*;
|
fn it_works() {
let snap = Snapshot::default();
snap.snap_element(
&Ms::new(String::from("hello ms")),
"ms_text"
);
snap.snap_element(
Ms::new(String::from("hello fraktur"))
.with_math_variant(Some(MathVariant::Fraktur)),
"ms_text_fraktur"
);
snap.snap_element(
Ms::new(String::from("I am big"))
.with_math_size(Some(MathSize::BIG)),
"ms_big"
);
snap.snap_element(
Ms::new(String::from("I am red"))
.with_math_color(Some(Color::RGB(255, 0, 0))),
"ms_red"
);
snap.snap_element(
Ms::new(String::from("I am on fire"))
.with_math_background(Some(Color::RGB(255, 0, 0))),
"ms_red_bg"
);
}
}
|
use ::test::skia::Snapshot;
use ::props::{Color, MathSize, MathVariant};
#[test]
|
random_line_split
|
ms.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::rc::Rc;
use std::any::Any;
use ::layout::{MsLayout, Layout};
use super::super::{
TokenPrivate, Token, PresentationPrivate, Presentation, SpecifiedTokenProps, PropertyCalculator,
SpecifiedPresentationProps, Element, InheritedProps, StyleProps, ElementType, TokenElement,
Property, InstanceId, Family, EmptyComputeCtx};
use ::platform::Context;
#[allow(const_err)]
const PROP_LQUOTE: Property<String, Ms, EmptyComputeCtx> = Property::Specified {
default: || String::from("\""),
reader: |s| s.ms_lquote(),
};
#[allow(const_err)]
const PROP_RQUOTE: Property<String, Ms, EmptyComputeCtx> = Property::Specified {
default: || String::from("\""),
reader: |s| s.ms_rquote(),
};
pub struct Ms {
instance_id: InstanceId,
lquote: Option<String>,
rquote: Option<String>,
token_props: SpecifiedTokenProps,
presentation_props: SpecifiedPresentationProps,
}
impl Ms {
pub fn new(text: String) -> Ms {
Ms {
instance_id: InstanceId::new(),
lquote: None,
rquote: None,
token_props: SpecifiedTokenProps {
text: Rc::new(text),
math_variant: None,
math_size: None,
dir: None,
},
presentation_props: SpecifiedPresentationProps {
math_color: None,
math_background: None,
}
}
}
}
impl Element for Ms {
fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps,
style: &Option<&StyleProps>) -> Box<Layout> {
let mut calculator = PropertyCalculator::new(
context, self, family, inherited, style.clone());
let lquote = calculator.calculate(&PROP_LQUOTE, self.lquote.as_ref());
let rquote = calculator.calculate(&PROP_RQUOTE, self.rquote.as_ref());
let token_layout = MsLayout {
token_element: self.layout_token_element(context, &mut calculator),
rquote,
lquote
};
Box::new(token_layout)
}
fn type_info(&self) -> ElementType {
ElementType::TokenElement(TokenElement::Ms)
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
fn instance_id(&self) -> &InstanceId {
&self.instance_id
}
}
impl PresentationPrivate<Ms> for Ms {
fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps {
&self.presentation_props
}
fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps {
&mut self.presentation_props
}
}
impl TokenPrivate<Ms> for Ms {
fn get_specified_token_props(&self) -> &SpecifiedTokenProps
|
fn get_specified_token_props_mut(&mut self) -> &mut SpecifiedTokenProps {
&mut self.token_props
}
}
impl Token<Ms> for Ms {}
impl Presentation<Ms> for Ms {}
#[cfg(test)]
mod test {
use super::*;
use ::test::skia::Snapshot;
use ::props::{Color, MathSize, MathVariant};
#[test]
fn it_works() {
let snap = Snapshot::default();
snap.snap_element(
&Ms::new(String::from("hello ms")),
"ms_text"
);
snap.snap_element(
Ms::new(String::from("hello fraktur"))
.with_math_variant(Some(MathVariant::Fraktur)),
"ms_text_fraktur"
);
snap.snap_element(
Ms::new(String::from("I am big"))
.with_math_size(Some(MathSize::BIG)),
"ms_big"
);
snap.snap_element(
Ms::new(String::from("I am red"))
.with_math_color(Some(Color::RGB(255, 0, 0))),
"ms_red"
);
snap.snap_element(
Ms::new(String::from("I am on fire"))
.with_math_background(Some(Color::RGB(255, 0, 0))),
"ms_red_bg"
);
}
}
|
{
&self.token_props
}
|
identifier_body
|
set_cookie.rs
|
use header::{Header, HeaderFormat};
use std::fmt::{self, Display};
use std::str::from_utf8;
use cookie::Cookie;
use cookie::CookieJar;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Informally, the Set-Cookie response header contains the header name
/// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with
/// a name-value-pair, followed by zero or more attribute-value pairs.
///
/// # ABNF
/// ```plain
/// set-cookie-header = "Set-Cookie:" SP set-cookie-string
/// set-cookie-string = cookie-pair *( ";" SP cookie-av )
/// cookie-pair = cookie-name "=" cookie-value
/// cookie-name = token
/// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
/// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
/// ; US-ASCII characters excluding CTLs,
/// ; whitespace DQUOTE, comma, semicolon,
/// ; and backslash
/// token = <token, defined in [RFC2616], Section 2.2>
///
/// cookie-av = expires-av / max-age-av / domain-av /
/// path-av / secure-av / httponly-av /
/// extension-av
/// expires-av = "Expires=" sane-cookie-date
/// sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
/// max-age-av = "Max-Age=" non-zero-digit *DIGIT
/// ; In practice, both expires-av and max-age-av
/// ; are limited to dates representable by the
/// ; user agent.
/// non-zero-digit = %x31-39
/// ; digits 1 through 9
/// domain-av = "Domain=" domain-value
/// domain-value = <subdomain>
|
/// ; defined in [RFC1034], Section 3.5, as
/// ; enhanced by [RFC1123], Section 2.1
/// path-av = "Path=" path-value
/// path-value = <any CHAR except CTLs or ";">
/// secure-av = "Secure"
/// httponly-av = "HttpOnly"
/// extension-av = <any CHAR except CTLs or ";">
/// ```
///
/// # Example values
/// * `SID=31d4d96e407aad42`
/// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT`
/// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT`
/// * `lang=en-US; Path=/; Domain=example.com`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate cookie;
/// # fn main() {
/// // extern crate cookie;
///
/// use hyper::header::{Headers, SetCookie};
/// use cookie::Cookie as CookiePair;
///
/// let mut headers = Headers::new();
/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
///
/// cookie.path = Some("/path".to_owned());
/// cookie.domain = Some("example.com".to_owned());
///
/// headers.set(
/// SetCookie(vec![
/// cookie,
/// CookiePair::new("baz".to_owned(), "quux".to_owned()),
/// ])
/// );
/// # }
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<Cookie>);
__hyper__deref!(SetCookie => Vec<Cookie>);
impl Header for SetCookie {
fn header_name() -> &'static str {
"Set-Cookie"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..]) {
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
}
if!set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
}
}
impl HeaderFormat for SetCookie {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i!= 0 {
try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse() {
let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][..]);
let mut c1 = Cookie::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
#[test]
fn test_fmt() {
use header::Headers;
let mut cookie = Cookie::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, Cookie::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n");
}
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = Cookie::new("foo".to_owned(), "bar".to_owned());
jar.encrypted().add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
}
|
random_line_split
|
|
set_cookie.rs
|
use header::{Header, HeaderFormat};
use std::fmt::{self, Display};
use std::str::from_utf8;
use cookie::Cookie;
use cookie::CookieJar;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Informally, the Set-Cookie response header contains the header name
/// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with
/// a name-value-pair, followed by zero or more attribute-value pairs.
///
/// # ABNF
/// ```plain
/// set-cookie-header = "Set-Cookie:" SP set-cookie-string
/// set-cookie-string = cookie-pair *( ";" SP cookie-av )
/// cookie-pair = cookie-name "=" cookie-value
/// cookie-name = token
/// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
/// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
/// ; US-ASCII characters excluding CTLs,
/// ; whitespace DQUOTE, comma, semicolon,
/// ; and backslash
/// token = <token, defined in [RFC2616], Section 2.2>
///
/// cookie-av = expires-av / max-age-av / domain-av /
/// path-av / secure-av / httponly-av /
/// extension-av
/// expires-av = "Expires=" sane-cookie-date
/// sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
/// max-age-av = "Max-Age=" non-zero-digit *DIGIT
/// ; In practice, both expires-av and max-age-av
/// ; are limited to dates representable by the
/// ; user agent.
/// non-zero-digit = %x31-39
/// ; digits 1 through 9
/// domain-av = "Domain=" domain-value
/// domain-value = <subdomain>
/// ; defined in [RFC1034], Section 3.5, as
/// ; enhanced by [RFC1123], Section 2.1
/// path-av = "Path=" path-value
/// path-value = <any CHAR except CTLs or ";">
/// secure-av = "Secure"
/// httponly-av = "HttpOnly"
/// extension-av = <any CHAR except CTLs or ";">
/// ```
///
/// # Example values
/// * `SID=31d4d96e407aad42`
/// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT`
/// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT`
/// * `lang=en-US; Path=/; Domain=example.com`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate cookie;
/// # fn main() {
/// // extern crate cookie;
///
/// use hyper::header::{Headers, SetCookie};
/// use cookie::Cookie as CookiePair;
///
/// let mut headers = Headers::new();
/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
///
/// cookie.path = Some("/path".to_owned());
/// cookie.domain = Some("example.com".to_owned());
///
/// headers.set(
/// SetCookie(vec![
/// cookie,
/// CookiePair::new("baz".to_owned(), "quux".to_owned()),
/// ])
/// );
/// # }
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<Cookie>);
__hyper__deref!(SetCookie => Vec<Cookie>);
impl Header for SetCookie {
fn header_name() -> &'static str {
"Set-Cookie"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..]) {
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
}
if!set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
}
}
impl HeaderFormat for SetCookie {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i!= 0 {
try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse() {
let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][..]);
let mut c1 = Cookie::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
#[test]
fn test_fmt() {
use header::Headers;
let mut cookie = Cookie::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, Cookie::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n");
}
#[test]
fn
|
() {
let jar = CookieJar::new(b"secret");
let cookie = Cookie::new("foo".to_owned(), "bar".to_owned());
jar.encrypted().add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
}
|
cookie_jar
|
identifier_name
|
set_cookie.rs
|
use header::{Header, HeaderFormat};
use std::fmt::{self, Display};
use std::str::from_utf8;
use cookie::Cookie;
use cookie::CookieJar;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Informally, the Set-Cookie response header contains the header name
/// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with
/// a name-value-pair, followed by zero or more attribute-value pairs.
///
/// # ABNF
/// ```plain
/// set-cookie-header = "Set-Cookie:" SP set-cookie-string
/// set-cookie-string = cookie-pair *( ";" SP cookie-av )
/// cookie-pair = cookie-name "=" cookie-value
/// cookie-name = token
/// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
/// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
/// ; US-ASCII characters excluding CTLs,
/// ; whitespace DQUOTE, comma, semicolon,
/// ; and backslash
/// token = <token, defined in [RFC2616], Section 2.2>
///
/// cookie-av = expires-av / max-age-av / domain-av /
/// path-av / secure-av / httponly-av /
/// extension-av
/// expires-av = "Expires=" sane-cookie-date
/// sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
/// max-age-av = "Max-Age=" non-zero-digit *DIGIT
/// ; In practice, both expires-av and max-age-av
/// ; are limited to dates representable by the
/// ; user agent.
/// non-zero-digit = %x31-39
/// ; digits 1 through 9
/// domain-av = "Domain=" domain-value
/// domain-value = <subdomain>
/// ; defined in [RFC1034], Section 3.5, as
/// ; enhanced by [RFC1123], Section 2.1
/// path-av = "Path=" path-value
/// path-value = <any CHAR except CTLs or ";">
/// secure-av = "Secure"
/// httponly-av = "HttpOnly"
/// extension-av = <any CHAR except CTLs or ";">
/// ```
///
/// # Example values
/// * `SID=31d4d96e407aad42`
/// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT`
/// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT`
/// * `lang=en-US; Path=/; Domain=example.com`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate cookie;
/// # fn main() {
/// // extern crate cookie;
///
/// use hyper::header::{Headers, SetCookie};
/// use cookie::Cookie as CookiePair;
///
/// let mut headers = Headers::new();
/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
///
/// cookie.path = Some("/path".to_owned());
/// cookie.domain = Some("example.com".to_owned());
///
/// headers.set(
/// SetCookie(vec![
/// cookie,
/// CookiePair::new("baz".to_owned(), "quux".to_owned()),
/// ])
/// );
/// # }
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<Cookie>);
__hyper__deref!(SetCookie => Vec<Cookie>);
impl Header for SetCookie {
fn header_name() -> &'static str {
"Set-Cookie"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..])
|
}
if!set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
}
}
impl HeaderFormat for SetCookie {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i!= 0 {
try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse() {
let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][..]);
let mut c1 = Cookie::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
#[test]
fn test_fmt() {
use header::Headers;
let mut cookie = Cookie::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, Cookie::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n");
}
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = Cookie::new("foo".to_owned(), "bar".to_owned());
jar.encrypted().add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
}
|
{
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
|
conditional_block
|
set_cookie.rs
|
use header::{Header, HeaderFormat};
use std::fmt::{self, Display};
use std::str::from_utf8;
use cookie::Cookie;
use cookie::CookieJar;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Informally, the Set-Cookie response header contains the header name
/// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with
/// a name-value-pair, followed by zero or more attribute-value pairs.
///
/// # ABNF
/// ```plain
/// set-cookie-header = "Set-Cookie:" SP set-cookie-string
/// set-cookie-string = cookie-pair *( ";" SP cookie-av )
/// cookie-pair = cookie-name "=" cookie-value
/// cookie-name = token
/// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
/// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
/// ; US-ASCII characters excluding CTLs,
/// ; whitespace DQUOTE, comma, semicolon,
/// ; and backslash
/// token = <token, defined in [RFC2616], Section 2.2>
///
/// cookie-av = expires-av / max-age-av / domain-av /
/// path-av / secure-av / httponly-av /
/// extension-av
/// expires-av = "Expires=" sane-cookie-date
/// sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
/// max-age-av = "Max-Age=" non-zero-digit *DIGIT
/// ; In practice, both expires-av and max-age-av
/// ; are limited to dates representable by the
/// ; user agent.
/// non-zero-digit = %x31-39
/// ; digits 1 through 9
/// domain-av = "Domain=" domain-value
/// domain-value = <subdomain>
/// ; defined in [RFC1034], Section 3.5, as
/// ; enhanced by [RFC1123], Section 2.1
/// path-av = "Path=" path-value
/// path-value = <any CHAR except CTLs or ";">
/// secure-av = "Secure"
/// httponly-av = "HttpOnly"
/// extension-av = <any CHAR except CTLs or ";">
/// ```
///
/// # Example values
/// * `SID=31d4d96e407aad42`
/// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT`
/// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT`
/// * `lang=en-US; Path=/; Domain=example.com`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate cookie;
/// # fn main() {
/// // extern crate cookie;
///
/// use hyper::header::{Headers, SetCookie};
/// use cookie::Cookie as CookiePair;
///
/// let mut headers = Headers::new();
/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
///
/// cookie.path = Some("/path".to_owned());
/// cookie.domain = Some("example.com".to_owned());
///
/// headers.set(
/// SetCookie(vec![
/// cookie,
/// CookiePair::new("baz".to_owned(), "quux".to_owned()),
/// ])
/// );
/// # }
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<Cookie>);
__hyper__deref!(SetCookie => Vec<Cookie>);
impl Header for SetCookie {
fn header_name() -> &'static str {
"Set-Cookie"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..]) {
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
}
if!set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
}
}
impl HeaderFormat for SetCookie {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i!= 0 {
try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse()
|
#[test]
fn test_fmt() {
use header::Headers;
let mut cookie = Cookie::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, Cookie::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n");
}
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = Cookie::new("foo".to_owned(), "bar".to_owned());
jar.encrypted().add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
}
|
{
let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][..]);
let mut c1 = Cookie::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
|
identifier_body
|
test_support.rs
|
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2020, HST authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------------------
use std::collections::HashSet;
use std::fmt::Debug;
use std::fmt::Display;
use bit_array::BitArray;
use proptest::arbitrary::any;
use proptest::arbitrary::Arbitrary;
use proptest::collection::hash_set;
use proptest::collection::vec;
use proptest::strategy::BoxedStrategy;
use proptest::strategy::Strategy;
use crate::event::DisjointSum;
use crate::event::EventSet;
use crate::primitives::PrimitiveEvents;
/// An event that is identified by a number. Makes it easy to construct distinct events in
/// test cases.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct NumberedEvent(pub u16);
impl From<u16> for NumberedEvent {
fn from(from: u16) -> NumberedEvent {
NumberedEvent(from)
}
}
const SUBSCRIPT_DIGITS: [char; 10] = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉'];
impl Debug for NumberedEvent {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
(self as &dyn Display).fmt(f)
}
}
impl Display for NumberedEvent {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let digits: String = self
.0
.to_string()
.chars()
.map(|ch| SUBSCRIPT_DIGITS[ch.to_digit(10).unwrap() as usize])
.collect();
write!(f, "E{}", digits)
}
}
impl Arbitrary for NumberedEvent {
type Parameters = ();
type Strategy = BoxedStrategy<NumberedEvent>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
any::<u16>().prop_map_into().boxed()
}
}
#[test]
fn can_display_events() {
assert_eq!(NumberedEvent(0).to_string(), "E₀");
assert_eq!(NumberedEvent(10).to_string(), "E₁₀");
assert_eq!(NumberedEvent(01234).to_string(), "E₁₂₃₄");
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct NumberedEvents(BitArray<usize, typenum::U65536>);
impl NumberedEvents {
pub fn add(&mut self, event: NumberedEvent) {
let index = event.0 as usize;
self.0.set(index, true);
}
pub fn contains(&self, event: NumberedEvent) -> bool {
let index = event.0 as usize;
self.0[index]
}
}
impl Display for NumberedEvents {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_set()
.entries(
self.0
.iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
.map(NumberedEvent::from),
)
.finish()
}
}
impl Debug for NumberedEvents {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "NumberedEvents ")?;
f.debug_set()
.entries(
self.0
.iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
.map(NumberedEvent::from),
)
.finish()
}
}
impl From<NumberedEvent> for NumberedEvents {
fn from(event: NumberedEvent) -> NumberedEvents {
let mut events = NumberedEvents::empty();
events.add(event);
events
}
}
impl From<HashSet<NumberedEvent>> for NumberedEvents {
fn from(set: HashSet<NumberedEvent>) -> NumberedEvents {
let mut events = NumberedEvents::empty();
for event in set {
events.add(event);
}
events
}
}
impl EventSet for NumberedEvents {
fn empty() -> Self {
NumberedEvents(BitArray::from_elem(false))
}
fn intersect(&mut self, other: &Self) {
self.0.intersect(&other.0);
}
fn is_empty(&self) -> bool {
self.0.none()
}
fn negate(&mut self) {
self.0.negate();
}
fn subtract(&mut self, other: &Self) {
self.0.difference(&other.0);
}
fn union(&mut self, other: &Self) {
self.0.union(&other.0);
}
fn universe() -> Self {
NumberedEvents(BitArray::from_elem(true))
}
}
impl IntoIterator for NumberedEvents {
type Item = NumberedEvents;
type IntoIter = Box<dyn Iterator<Item = NumberedEvents>>;
fn into_iter(self) -> Self::IntoIter {
Box::new(
self.0
.into_iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
.map(NumberedEvent::from)
.map(NumberedEvents::from),
)
}
}
impl Arbitrary for NumberedEvents {
type Parameters = ();
type Strategy = BoxedStrategy<NumberedEvents>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
hash_set(any::<NumberedEvent>(), 0..32)
.prop_map_into()
.boxed()
}
}
#[derive(Debug)]
pub struct NonemptyNumberedEvents(NumberedEvents);
impl From<NonemptyNumberedEvents> for NumberedEvents {
fn from(events: NonemptyNumberedEvents) -> NumberedEvents {
events.0
}
}
impl Arbitrary for NonemptyNumberedEvents {
type Parameters = ();
type Strategy = BoxedStrategy<NonemptyNumberedEvents>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
hash_set(any::<NumberedEvent>(), 1..32)
.prop_map_into()
.prop_map(NonemptyNumberedEvents)
.boxed()
}
}
#[cfg(test)]
mod numbered_events_tests {
use proptest_attr_macro::proptest;
use super::*;
#[proptest]
fn can_intersect(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut intersection = a.clone();
intersection.intersect(&b);
assert_eq!(
intersection.contains(event),
a.contains(event) && b.contains(event)
);
}
#[proptest]
fn intersection_is_commutative(a: NumberedEvents, b: NumberedEvents) {
let mut i1 = a.clone();
i1.intersect(&b);
let mut i2 = b.clone();
i2.intersect(&a);
assert_eq!(i1, i2);
}
#[proptest]
fn can_negate(a: NumberedEvents, event: NumberedEvent) {
let mut negation = a.clone();
negation.negate();
assert_eq!(negation.contains(event),!a.contains(event));
}
#[proptest]
fn negation_is_reversible(a: NumberedE
|
ut negated_twice = a.clone();
negated_twice.negate();
negated_twice.negate();
assert_eq!(a, negated_twice);
}
#[proptest]
fn can_subtract(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut difference = a.clone();
difference.subtract(&b);
assert_eq!(
difference.contains(event),
a.contains(event) &&!b.contains(event)
);
}
#[proptest]
fn can_union(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut union = a.clone();
union.union(&b);
assert_eq!(
union.contains(event),
a.contains(event) || b.contains(event)
);
}
#[proptest]
fn union_is_commutative(a: NumberedEvents, b: NumberedEvents) {
let mut u1 = a.clone();
u1.union(&b);
let mut u2 = b.clone();
u2.union(&a);
assert_eq!(u1, u2);
}
}
/// An event type that is useful in test cases. It can be a NumberedEvent or any of the
/// built-in event types.
pub type TestEvents = DisjointSum<PrimitiveEvents, NumberedEvents>;
impl From<NumberedEvent> for TestEvents {
fn from(event: NumberedEvent) -> TestEvents {
TestEvents::from_b(event.into())
}
}
impl From<NumberedEvents> for TestEvents {
fn from(events: NumberedEvents) -> TestEvents {
TestEvents::from_b(events)
}
}
/// A proptest helper type that generates a non-empty vector of values.
#[derive(Clone, Debug)]
pub struct NonemptyVec<T> {
pub vec: Vec<T>,
}
impl<T> Arbitrary for NonemptyVec<T>
where
T: Arbitrary + Clone + Debug +'static,
{
type Parameters = ();
type Strategy = BoxedStrategy<NonemptyVec<T>>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
vec(any::<T>(), 1..16)
.prop_map(|vec| NonemptyVec { vec })
.boxed()
}
}
|
vents) {
let m
|
identifier_name
|
test_support.rs
|
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2020, HST authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------------------
use std::collections::HashSet;
use std::fmt::Debug;
use std::fmt::Display;
use bit_array::BitArray;
use proptest::arbitrary::any;
use proptest::arbitrary::Arbitrary;
use proptest::collection::hash_set;
use proptest::collection::vec;
use proptest::strategy::BoxedStrategy;
use proptest::strategy::Strategy;
use crate::event::DisjointSum;
use crate::event::EventSet;
use crate::primitives::PrimitiveEvents;
/// An event that is identified by a number. Makes it easy to construct distinct events in
/// test cases.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct NumberedEvent(pub u16);
impl From<u16> for NumberedEvent {
fn from(from: u16) -> NumberedEvent {
NumberedEvent(from)
}
}
const SUBSCRIPT_DIGITS: [char; 10] = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉'];
impl Debug for NumberedEvent {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
(self as &d
|
NumberedEvent {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let digits: String = self
.0
.to_string()
.chars()
.map(|ch| SUBSCRIPT_DIGITS[ch.to_digit(10).unwrap() as usize])
.collect();
write!(f, "E{}", digits)
}
}
impl Arbitrary for NumberedEvent {
type Parameters = ();
type Strategy = BoxedStrategy<NumberedEvent>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
any::<u16>().prop_map_into().boxed()
}
}
#[test]
fn can_display_events() {
assert_eq!(NumberedEvent(0).to_string(), "E₀");
assert_eq!(NumberedEvent(10).to_string(), "E₁₀");
assert_eq!(NumberedEvent(01234).to_string(), "E₁₂₃₄");
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct NumberedEvents(BitArray<usize, typenum::U65536>);
impl NumberedEvents {
pub fn add(&mut self, event: NumberedEvent) {
let index = event.0 as usize;
self.0.set(index, true);
}
pub fn contains(&self, event: NumberedEvent) -> bool {
let index = event.0 as usize;
self.0[index]
}
}
impl Display for NumberedEvents {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_set()
.entries(
self.0
.iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
.map(NumberedEvent::from),
)
.finish()
}
}
impl Debug for NumberedEvents {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "NumberedEvents ")?;
f.debug_set()
.entries(
self.0
.iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
.map(NumberedEvent::from),
)
.finish()
}
}
impl From<NumberedEvent> for NumberedEvents {
fn from(event: NumberedEvent) -> NumberedEvents {
let mut events = NumberedEvents::empty();
events.add(event);
events
}
}
impl From<HashSet<NumberedEvent>> for NumberedEvents {
fn from(set: HashSet<NumberedEvent>) -> NumberedEvents {
let mut events = NumberedEvents::empty();
for event in set {
events.add(event);
}
events
}
}
impl EventSet for NumberedEvents {
fn empty() -> Self {
NumberedEvents(BitArray::from_elem(false))
}
fn intersect(&mut self, other: &Self) {
self.0.intersect(&other.0);
}
fn is_empty(&self) -> bool {
self.0.none()
}
fn negate(&mut self) {
self.0.negate();
}
fn subtract(&mut self, other: &Self) {
self.0.difference(&other.0);
}
fn union(&mut self, other: &Self) {
self.0.union(&other.0);
}
fn universe() -> Self {
NumberedEvents(BitArray::from_elem(true))
}
}
impl IntoIterator for NumberedEvents {
type Item = NumberedEvents;
type IntoIter = Box<dyn Iterator<Item = NumberedEvents>>;
fn into_iter(self) -> Self::IntoIter {
Box::new(
self.0
.into_iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
.map(NumberedEvent::from)
.map(NumberedEvents::from),
)
}
}
impl Arbitrary for NumberedEvents {
type Parameters = ();
type Strategy = BoxedStrategy<NumberedEvents>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
hash_set(any::<NumberedEvent>(), 0..32)
.prop_map_into()
.boxed()
}
}
#[derive(Debug)]
pub struct NonemptyNumberedEvents(NumberedEvents);
impl From<NonemptyNumberedEvents> for NumberedEvents {
fn from(events: NonemptyNumberedEvents) -> NumberedEvents {
events.0
}
}
impl Arbitrary for NonemptyNumberedEvents {
type Parameters = ();
type Strategy = BoxedStrategy<NonemptyNumberedEvents>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
hash_set(any::<NumberedEvent>(), 1..32)
.prop_map_into()
.prop_map(NonemptyNumberedEvents)
.boxed()
}
}
#[cfg(test)]
mod numbered_events_tests {
use proptest_attr_macro::proptest;
use super::*;
#[proptest]
fn can_intersect(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut intersection = a.clone();
intersection.intersect(&b);
assert_eq!(
intersection.contains(event),
a.contains(event) && b.contains(event)
);
}
#[proptest]
fn intersection_is_commutative(a: NumberedEvents, b: NumberedEvents) {
let mut i1 = a.clone();
i1.intersect(&b);
let mut i2 = b.clone();
i2.intersect(&a);
assert_eq!(i1, i2);
}
#[proptest]
fn can_negate(a: NumberedEvents, event: NumberedEvent) {
let mut negation = a.clone();
negation.negate();
assert_eq!(negation.contains(event),!a.contains(event));
}
#[proptest]
fn negation_is_reversible(a: NumberedEvents) {
let mut negated_twice = a.clone();
negated_twice.negate();
negated_twice.negate();
assert_eq!(a, negated_twice);
}
#[proptest]
fn can_subtract(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut difference = a.clone();
difference.subtract(&b);
assert_eq!(
difference.contains(event),
a.contains(event) &&!b.contains(event)
);
}
#[proptest]
fn can_union(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut union = a.clone();
union.union(&b);
assert_eq!(
union.contains(event),
a.contains(event) || b.contains(event)
);
}
#[proptest]
fn union_is_commutative(a: NumberedEvents, b: NumberedEvents) {
let mut u1 = a.clone();
u1.union(&b);
let mut u2 = b.clone();
u2.union(&a);
assert_eq!(u1, u2);
}
}
/// An event type that is useful in test cases. It can be a NumberedEvent or any of the
/// built-in event types.
pub type TestEvents = DisjointSum<PrimitiveEvents, NumberedEvents>;
impl From<NumberedEvent> for TestEvents {
fn from(event: NumberedEvent) -> TestEvents {
TestEvents::from_b(event.into())
}
}
impl From<NumberedEvents> for TestEvents {
fn from(events: NumberedEvents) -> TestEvents {
TestEvents::from_b(events)
}
}
/// A proptest helper type that generates a non-empty vector of values.
#[derive(Clone, Debug)]
pub struct NonemptyVec<T> {
pub vec: Vec<T>,
}
impl<T> Arbitrary for NonemptyVec<T>
where
T: Arbitrary + Clone + Debug +'static,
{
type Parameters = ();
type Strategy = BoxedStrategy<NonemptyVec<T>>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
vec(any::<T>(), 1..16)
.prop_map(|vec| NonemptyVec { vec })
.boxed()
}
}
|
yn Display).fmt(f)
}
}
impl Display for
|
identifier_body
|
test_support.rs
|
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2020, HST authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------------------
use std::collections::HashSet;
use std::fmt::Debug;
use std::fmt::Display;
use bit_array::BitArray;
use proptest::arbitrary::any;
use proptest::arbitrary::Arbitrary;
use proptest::collection::hash_set;
use proptest::collection::vec;
use proptest::strategy::BoxedStrategy;
use proptest::strategy::Strategy;
use crate::event::DisjointSum;
use crate::event::EventSet;
use crate::primitives::PrimitiveEvents;
/// An event that is identified by a number. Makes it easy to construct distinct events in
/// test cases.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct NumberedEvent(pub u16);
impl From<u16> for NumberedEvent {
fn from(from: u16) -> NumberedEvent {
NumberedEvent(from)
}
}
const SUBSCRIPT_DIGITS: [char; 10] = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉'];
impl Debug for NumberedEvent {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
(self as &dyn Display).fmt(f)
}
}
impl Display for NumberedEvent {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let digits: String = self
.0
.to_string()
.chars()
.map(|ch| SUBSCRIPT_DIGITS[ch.to_digit(10).unwrap() as usize])
.collect();
write!(f, "E{}", digits)
}
}
impl Arbitrary for NumberedEvent {
type Parameters = ();
type Strategy = BoxedStrategy<NumberedEvent>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
any::<u16>().prop_map_into().boxed()
}
}
#[test]
fn can_display_events() {
assert_eq!(NumberedEvent(0).to_string(), "E₀");
assert_eq!(NumberedEvent(10).to_string(), "E₁₀");
assert_eq!(NumberedEvent(01234).to_string(), "E₁₂₃₄");
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct NumberedEvents(BitArray<usize, typenum::U65536>);
impl NumberedEvents {
pub fn add(&mut self, event: NumberedEvent) {
let index = event.0 as usize;
self.0.set(index, true);
}
pub fn contains(&self, event: NumberedEvent) -> bool {
let index = event.0 as usize;
self.0[index]
}
}
impl Display for NumberedEvents {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_set()
.entries(
self.0
.iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
.map(NumberedEvent::from),
)
.finish()
}
}
impl Debug for NumberedEvents {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "NumberedEvents ")?;
f.debug_set()
.entries(
self.0
.iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
|
}
}
impl From<NumberedEvent> for NumberedEvents {
fn from(event: NumberedEvent) -> NumberedEvents {
let mut events = NumberedEvents::empty();
events.add(event);
events
}
}
impl From<HashSet<NumberedEvent>> for NumberedEvents {
fn from(set: HashSet<NumberedEvent>) -> NumberedEvents {
let mut events = NumberedEvents::empty();
for event in set {
events.add(event);
}
events
}
}
impl EventSet for NumberedEvents {
fn empty() -> Self {
NumberedEvents(BitArray::from_elem(false))
}
fn intersect(&mut self, other: &Self) {
self.0.intersect(&other.0);
}
fn is_empty(&self) -> bool {
self.0.none()
}
fn negate(&mut self) {
self.0.negate();
}
fn subtract(&mut self, other: &Self) {
self.0.difference(&other.0);
}
fn union(&mut self, other: &Self) {
self.0.union(&other.0);
}
fn universe() -> Self {
NumberedEvents(BitArray::from_elem(true))
}
}
impl IntoIterator for NumberedEvents {
type Item = NumberedEvents;
type IntoIter = Box<dyn Iterator<Item = NumberedEvents>>;
fn into_iter(self) -> Self::IntoIter {
Box::new(
self.0
.into_iter()
.enumerate()
.filter(|(_index, value)| *value)
.map(|(index, _value)| index as u16)
.map(NumberedEvent::from)
.map(NumberedEvents::from),
)
}
}
impl Arbitrary for NumberedEvents {
type Parameters = ();
type Strategy = BoxedStrategy<NumberedEvents>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
hash_set(any::<NumberedEvent>(), 0..32)
.prop_map_into()
.boxed()
}
}
#[derive(Debug)]
pub struct NonemptyNumberedEvents(NumberedEvents);
impl From<NonemptyNumberedEvents> for NumberedEvents {
fn from(events: NonemptyNumberedEvents) -> NumberedEvents {
events.0
}
}
impl Arbitrary for NonemptyNumberedEvents {
type Parameters = ();
type Strategy = BoxedStrategy<NonemptyNumberedEvents>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
hash_set(any::<NumberedEvent>(), 1..32)
.prop_map_into()
.prop_map(NonemptyNumberedEvents)
.boxed()
}
}
#[cfg(test)]
mod numbered_events_tests {
use proptest_attr_macro::proptest;
use super::*;
#[proptest]
fn can_intersect(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut intersection = a.clone();
intersection.intersect(&b);
assert_eq!(
intersection.contains(event),
a.contains(event) && b.contains(event)
);
}
#[proptest]
fn intersection_is_commutative(a: NumberedEvents, b: NumberedEvents) {
let mut i1 = a.clone();
i1.intersect(&b);
let mut i2 = b.clone();
i2.intersect(&a);
assert_eq!(i1, i2);
}
#[proptest]
fn can_negate(a: NumberedEvents, event: NumberedEvent) {
let mut negation = a.clone();
negation.negate();
assert_eq!(negation.contains(event),!a.contains(event));
}
#[proptest]
fn negation_is_reversible(a: NumberedEvents) {
let mut negated_twice = a.clone();
negated_twice.negate();
negated_twice.negate();
assert_eq!(a, negated_twice);
}
#[proptest]
fn can_subtract(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut difference = a.clone();
difference.subtract(&b);
assert_eq!(
difference.contains(event),
a.contains(event) &&!b.contains(event)
);
}
#[proptest]
fn can_union(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) {
let mut union = a.clone();
union.union(&b);
assert_eq!(
union.contains(event),
a.contains(event) || b.contains(event)
);
}
#[proptest]
fn union_is_commutative(a: NumberedEvents, b: NumberedEvents) {
let mut u1 = a.clone();
u1.union(&b);
let mut u2 = b.clone();
u2.union(&a);
assert_eq!(u1, u2);
}
}
/// An event type that is useful in test cases. It can be a NumberedEvent or any of the
/// built-in event types.
pub type TestEvents = DisjointSum<PrimitiveEvents, NumberedEvents>;
impl From<NumberedEvent> for TestEvents {
fn from(event: NumberedEvent) -> TestEvents {
TestEvents::from_b(event.into())
}
}
impl From<NumberedEvents> for TestEvents {
fn from(events: NumberedEvents) -> TestEvents {
TestEvents::from_b(events)
}
}
/// A proptest helper type that generates a non-empty vector of values.
#[derive(Clone, Debug)]
pub struct NonemptyVec<T> {
pub vec: Vec<T>,
}
impl<T> Arbitrary for NonemptyVec<T>
where
T: Arbitrary + Clone + Debug +'static,
{
type Parameters = ();
type Strategy = BoxedStrategy<NonemptyVec<T>>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
vec(any::<T>(), 1..16)
.prop_map(|vec| NonemptyVec { vec })
.boxed()
}
}
|
.map(NumberedEvent::from),
)
.finish()
|
random_line_split
|
document_highlight.rs
|
use languageserver_types::{DocumentHighlight, TextDocumentPositionParams};
use super::*;
use crate::completion;
pub fn
|
(io: &mut IoHandler, thread: &RootedThread) {
let thread = thread.clone();
let f = move |params: TextDocumentPositionParams| {
let thread = thread.clone();
async move {
retrieve_expr(&thread, ¶ms.text_document.uri, |module| {
let expr = module.expr.expr();
let source = &module.source;
let byte_index = position_to_byte_index(&source, ¶ms.position)?;
let symbol_spans = completion::find_all_symbols(source.span(), expr, byte_index)
.map(|t| t.1)
.unwrap_or(Vec::new());
symbol_spans
.into_iter()
.map(|span| {
Ok(DocumentHighlight {
kind: None,
range: byte_span_to_range(&source, span)?,
})
})
.collect::<Result<_, _>>()
.map(Some)
})
.await
}
};
io.add_async_method(request!("textDocument/documentHighlight"), f);
}
|
register
|
identifier_name
|
document_highlight.rs
|
use languageserver_types::{DocumentHighlight, TextDocumentPositionParams};
use super::*;
use crate::completion;
pub fn register(io: &mut IoHandler, thread: &RootedThread)
|
kind: None,
range: byte_span_to_range(&source, span)?,
})
})
.collect::<Result<_, _>>()
.map(Some)
})
.await
}
};
io.add_async_method(request!("textDocument/documentHighlight"), f);
}
|
{
let thread = thread.clone();
let f = move |params: TextDocumentPositionParams| {
let thread = thread.clone();
async move {
retrieve_expr(&thread, ¶ms.text_document.uri, |module| {
let expr = module.expr.expr();
let source = &module.source;
let byte_index = position_to_byte_index(&source, ¶ms.position)?;
let symbol_spans = completion::find_all_symbols(source.span(), expr, byte_index)
.map(|t| t.1)
.unwrap_or(Vec::new());
symbol_spans
.into_iter()
.map(|span| {
Ok(DocumentHighlight {
|
identifier_body
|
document_highlight.rs
|
use languageserver_types::{DocumentHighlight, TextDocumentPositionParams};
use super::*;
use crate::completion;
pub fn register(io: &mut IoHandler, thread: &RootedThread) {
let thread = thread.clone();
let f = move |params: TextDocumentPositionParams| {
let thread = thread.clone();
async move {
retrieve_expr(&thread, ¶ms.text_document.uri, |module| {
let expr = module.expr.expr();
let source = &module.source;
let byte_index = position_to_byte_index(&source, ¶ms.position)?;
let symbol_spans = completion::find_all_symbols(source.span(), expr, byte_index)
.map(|t| t.1)
.unwrap_or(Vec::new());
symbol_spans
.into_iter()
.map(|span| {
Ok(DocumentHighlight {
kind: None,
range: byte_span_to_range(&source, span)?,
})
|
.map(Some)
})
.await
}
};
io.add_async_method(request!("textDocument/documentHighlight"), f);
}
|
})
.collect::<Result<_, _>>()
|
random_line_split
|
lookup_json.rs
|
use global::Context;
use lookup_service::lookup_api;
use rustc_serialize::json;
use iron::prelude::*;
use config;
pub fn
|
(context: &mut Context, table: &str) -> Result<String, String> {
match lookup_api::get_lookup_data(context, table) {
Ok(lookup_data) => {
let json = if config::PRETTY_JSON {
format!("{}", json::as_pretty_json(&lookup_data))
} else {
json::encode(&lookup_data).unwrap()
};
Ok(json)
}
Err(e) => Err(format!("{}", e)),
}
}
pub fn json_get_lookup_tabs(context: &mut Context, table: &str) -> Result<String, String> {
match lookup_api::get_lookup_tabs(context, table) {
Ok(lookup_data) => {
let json = if config::PRETTY_JSON {
format!("{}", json::as_pretty_json(&lookup_data))
} else {
json::encode(&lookup_data).unwrap()
};
Ok(json)
}
Err(e) => Err(format!("{}", e)),
}
}
|
json_get_lookup_data
|
identifier_name
|
lookup_json.rs
|
use global::Context;
use lookup_service::lookup_api;
use rustc_serialize::json;
use iron::prelude::*;
use config;
pub fn json_get_lookup_data(context: &mut Context, table: &str) -> Result<String, String> {
match lookup_api::get_lookup_data(context, table) {
Ok(lookup_data) => {
let json = if config::PRETTY_JSON {
format!("{}", json::as_pretty_json(&lookup_data))
} else {
json::encode(&lookup_data).unwrap()
};
Ok(json)
}
Err(e) => Err(format!("{}", e)),
}
}
pub fn json_get_lookup_tabs(context: &mut Context, table: &str) -> Result<String, String> {
match lookup_api::get_lookup_tabs(context, table) {
Ok(lookup_data) =>
|
Err(e) => Err(format!("{}", e)),
}
}
|
{
let json = if config::PRETTY_JSON {
format!("{}", json::as_pretty_json(&lookup_data))
} else {
json::encode(&lookup_data).unwrap()
};
Ok(json)
}
|
conditional_block
|
lookup_json.rs
|
use global::Context;
use lookup_service::lookup_api;
use rustc_serialize::json;
use iron::prelude::*;
use config;
pub fn json_get_lookup_data(context: &mut Context, table: &str) -> Result<String, String>
|
pub fn json_get_lookup_tabs(context: &mut Context, table: &str) -> Result<String, String> {
match lookup_api::get_lookup_tabs(context, table) {
Ok(lookup_data) => {
let json = if config::PRETTY_JSON {
format!("{}", json::as_pretty_json(&lookup_data))
} else {
json::encode(&lookup_data).unwrap()
};
Ok(json)
}
Err(e) => Err(format!("{}", e)),
}
}
|
{
match lookup_api::get_lookup_data(context, table) {
Ok(lookup_data) => {
let json = if config::PRETTY_JSON {
format!("{}", json::as_pretty_json(&lookup_data))
} else {
json::encode(&lookup_data).unwrap()
};
Ok(json)
}
Err(e) => Err(format!("{}", e)),
}
}
|
identifier_body
|
lookup_json.rs
|
use global::Context;
use lookup_service::lookup_api;
use rustc_serialize::json;
use iron::prelude::*;
use config;
pub fn json_get_lookup_data(context: &mut Context, table: &str) -> Result<String, String> {
match lookup_api::get_lookup_data(context, table) {
Ok(lookup_data) => {
let json = if config::PRETTY_JSON {
format!("{}", json::as_pretty_json(&lookup_data))
} else {
json::encode(&lookup_data).unwrap()
};
Ok(json)
}
Err(e) => Err(format!("{}", e)),
|
}
pub fn json_get_lookup_tabs(context: &mut Context, table: &str) -> Result<String, String> {
match lookup_api::get_lookup_tabs(context, table) {
Ok(lookup_data) => {
let json = if config::PRETTY_JSON {
format!("{}", json::as_pretty_json(&lookup_data))
} else {
json::encode(&lookup_data).unwrap()
};
Ok(json)
}
Err(e) => Err(format!("{}", e)),
}
}
|
}
|
random_line_split
|
texture_swap.rs
|
extern crate rand;
extern crate piston_window;
extern crate image as im;
use im::GenericImage;
use piston_window::*;
fn main() {
let texture_count = 1024;
let frames = 200;
let size = 32.0;
let window: PistonWindow = WindowSettings::new("piston", [1024; 2]).into();
let textures = {
let mut factory = window.factory.borrow_mut();
let factory = &mut *factory;
(0..texture_count).map(|_| {
let mut img = im::ImageBuffer::new(2, 2);
for x in 0..2 {
for y in 0..2 {
img.put_pixel(x, y,
im::Rgba([rand::random(), rand::random(), rand::random(), 255]));
}
}
Texture::from_image(
factory,
&img,
&TextureSettings::new()
).unwrap()
}).collect::<Vec<Texture<_>>>()
};
let mut positions = (0..texture_count)
.map(|_| (rand::random(), rand::random()))
.collect::<Vec<(f64, f64)>>();
let mut counter = 0;
for e in window.bench_mode(true) {
if let Some(_) = e.render_args() {
counter += 1;
if counter > frames
|
}
e.draw_2d(|c, g| {
clear([0.0, 0.0, 0.0, 1.0], g);
for p in &mut positions {
let (x, y) = *p;
*p = (x + (rand::random::<f64>() - 0.5) * 0.01,
y + (rand::random::<f64>() - 0.5) * 0.01);
}
for i in (0..texture_count) {
let p = positions[i];
image(&textures[i], c.transform
.trans(p.0 * 1024.0, p.1 * 1024.0).zoom(size), g);
}
});
}
}
|
{ break; }
|
conditional_block
|
texture_swap.rs
|
extern crate rand;
extern crate piston_window;
extern crate image as im;
use im::GenericImage;
use piston_window::*;
fn main() {
let texture_count = 1024;
let frames = 200;
let size = 32.0;
let window: PistonWindow = WindowSettings::new("piston", [1024; 2]).into();
let textures = {
let mut factory = window.factory.borrow_mut();
let factory = &mut *factory;
(0..texture_count).map(|_| {
let mut img = im::ImageBuffer::new(2, 2);
for x in 0..2 {
for y in 0..2 {
img.put_pixel(x, y,
im::Rgba([rand::random(), rand::random(), rand::random(), 255]));
}
}
Texture::from_image(
factory,
&img,
&TextureSettings::new()
).unwrap()
}).collect::<Vec<Texture<_>>>()
};
let mut positions = (0..texture_count)
.map(|_| (rand::random(), rand::random()))
.collect::<Vec<(f64, f64)>>();
let mut counter = 0;
for e in window.bench_mode(true) {
if let Some(_) = e.render_args() {
counter += 1;
if counter > frames { break; }
}
e.draw_2d(|c, g| {
clear([0.0, 0.0, 0.0, 1.0], g);
for p in &mut positions {
let (x, y) = *p;
*p = (x + (rand::random::<f64>() - 0.5) * 0.01,
y + (rand::random::<f64>() - 0.5) * 0.01);
}
for i in (0..texture_count) {
let p = positions[i];
image(&textures[i], c.transform
.trans(p.0 * 1024.0, p.1 * 1024.0).zoom(size), g);
|
}
});
}
}
|
random_line_split
|
|
texture_swap.rs
|
extern crate rand;
extern crate piston_window;
extern crate image as im;
use im::GenericImage;
use piston_window::*;
fn
|
() {
let texture_count = 1024;
let frames = 200;
let size = 32.0;
let window: PistonWindow = WindowSettings::new("piston", [1024; 2]).into();
let textures = {
let mut factory = window.factory.borrow_mut();
let factory = &mut *factory;
(0..texture_count).map(|_| {
let mut img = im::ImageBuffer::new(2, 2);
for x in 0..2 {
for y in 0..2 {
img.put_pixel(x, y,
im::Rgba([rand::random(), rand::random(), rand::random(), 255]));
}
}
Texture::from_image(
factory,
&img,
&TextureSettings::new()
).unwrap()
}).collect::<Vec<Texture<_>>>()
};
let mut positions = (0..texture_count)
.map(|_| (rand::random(), rand::random()))
.collect::<Vec<(f64, f64)>>();
let mut counter = 0;
for e in window.bench_mode(true) {
if let Some(_) = e.render_args() {
counter += 1;
if counter > frames { break; }
}
e.draw_2d(|c, g| {
clear([0.0, 0.0, 0.0, 1.0], g);
for p in &mut positions {
let (x, y) = *p;
*p = (x + (rand::random::<f64>() - 0.5) * 0.01,
y + (rand::random::<f64>() - 0.5) * 0.01);
}
for i in (0..texture_count) {
let p = positions[i];
image(&textures[i], c.transform
.trans(p.0 * 1024.0, p.1 * 1024.0).zoom(size), g);
}
});
}
}
|
main
|
identifier_name
|
texture_swap.rs
|
extern crate rand;
extern crate piston_window;
extern crate image as im;
use im::GenericImage;
use piston_window::*;
fn main()
|
&img,
&TextureSettings::new()
).unwrap()
}).collect::<Vec<Texture<_>>>()
};
let mut positions = (0..texture_count)
.map(|_| (rand::random(), rand::random()))
.collect::<Vec<(f64, f64)>>();
let mut counter = 0;
for e in window.bench_mode(true) {
if let Some(_) = e.render_args() {
counter += 1;
if counter > frames { break; }
}
e.draw_2d(|c, g| {
clear([0.0, 0.0, 0.0, 1.0], g);
for p in &mut positions {
let (x, y) = *p;
*p = (x + (rand::random::<f64>() - 0.5) * 0.01,
y + (rand::random::<f64>() - 0.5) * 0.01);
}
for i in (0..texture_count) {
let p = positions[i];
image(&textures[i], c.transform
.trans(p.0 * 1024.0, p.1 * 1024.0).zoom(size), g);
}
});
}
}
|
{
let texture_count = 1024;
let frames = 200;
let size = 32.0;
let window: PistonWindow = WindowSettings::new("piston", [1024; 2]).into();
let textures = {
let mut factory = window.factory.borrow_mut();
let factory = &mut *factory;
(0..texture_count).map(|_| {
let mut img = im::ImageBuffer::new(2, 2);
for x in 0..2 {
for y in 0..2 {
img.put_pixel(x, y,
im::Rgba([rand::random(), rand::random(), rand::random(), 255]));
}
}
Texture::from_image(
factory,
|
identifier_body
|
test_utils.rs
|
// ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::mem::size_of;
use std::slice::from_raw_parts;
use communication::MemoryRegion;
use {Address, Node};
pub(crate) fn simple_node_content<T>(address: Address, content: &[T]) -> Node {
Node::new(
address,
MemoryRegion::new(unsafe {
from_raw_parts(
content.as_ptr() as *const u8,
content.len() * size_of::<T>(),
)
}),
)
}
pub(crate) fn simple_node(address: Address) -> Node
|
{
Node::new(address, MemoryRegion::new(&[0; 1]))
}
|
identifier_body
|
|
test_utils.rs
|
// ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::mem::size_of;
use std::slice::from_raw_parts;
use communication::MemoryRegion;
use {Address, Node};
pub(crate) fn
|
<T>(address: Address, content: &[T]) -> Node {
Node::new(
address,
MemoryRegion::new(unsafe {
from_raw_parts(
content.as_ptr() as *const u8,
content.len() * size_of::<T>(),
)
}),
)
}
pub(crate) fn simple_node(address: Address) -> Node {
Node::new(address, MemoryRegion::new(&[0; 1]))
}
|
simple_node_content
|
identifier_name
|
test_utils.rs
|
// ams - Advanced Memory Scanner
// Copyright (C) 2018 th0rex
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
|
use std::slice::from_raw_parts;
use communication::MemoryRegion;
use {Address, Node};
pub(crate) fn simple_node_content<T>(address: Address, content: &[T]) -> Node {
Node::new(
address,
MemoryRegion::new(unsafe {
from_raw_parts(
content.as_ptr() as *const u8,
content.len() * size_of::<T>(),
)
}),
)
}
pub(crate) fn simple_node(address: Address) -> Node {
Node::new(address, MemoryRegion::new(&[0; 1]))
}
|
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::mem::size_of;
|
random_line_split
|
threaded.rs
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use threadpool::ThreadPool;
use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory};
use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory};
use {ApplicationError, ApplicationErrorKind};
use super::TProcessor;
/// Fixed-size thread-pool blocking Thrift server.
///
/// A `TServer` listens on a given address and submits accepted connections
/// to an **unbounded** queue. Connections from this queue are serviced by
/// the first available worker thread from a **fixed-size** thread pool. Each
/// accepted connection is handled by that worker thread, and communication
/// over this thread occurs sequentially and synchronously (i.e. calls block).
/// Accepted connections have an input half and an output half, each of which
/// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate
/// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol`
/// and `TTransport` may be used.
///
/// # Examples
///
/// Creating and running a `TServer` using Thrift-compiler-generated
/// service code.
///
/// ```no_run
/// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory};
/// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory};
/// use thrift::protocol::{TInputProtocol, TOutputProtocol};
/// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory,
/// TReadTransportFactory, TWriteTransportFactory};
/// use thrift::server::{TProcessor, TServer};
///
/// //
/// // auto-generated
/// //
///
/// // processor for `SimpleService`
/// struct SimpleServiceSyncProcessor;
/// impl SimpleServiceSyncProcessor {
/// fn new<H: SimpleServiceSyncHandler>(processor: H) -> SimpleServiceSyncProcessor {
/// unimplemented!();
/// }
/// }
///
/// // `TProcessor` implementation for `SimpleService`
/// impl TProcessor for SimpleServiceSyncProcessor {
/// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> {
/// unimplemented!();
/// }
/// }
///
/// // service functions for SimpleService
/// trait SimpleServiceSyncHandler {
/// fn service_call(&self) -> thrift::Result<()>;
/// }
///
/// //
/// // user-code follows
/// //
///
/// // define a handler that will be invoked when `service_call` is received
/// struct SimpleServiceHandlerImpl;
/// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl {
/// fn service_call(&self) -> thrift::Result<()> {
/// unimplemented!();
/// }
/// }
///
/// // instantiate the processor
/// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {});
///
/// // instantiate the server
/// let i_tr_fact: Box<TReadTransportFactory> = Box::new(TBufferedReadTransportFactory::new());
/// let i_pr_fact: Box<TInputProtocolFactory> = Box::new(TBinaryInputProtocolFactory::new());
/// let o_tr_fact: Box<TWriteTransportFactory> = Box::new(TBufferedWriteTransportFactory::new());
/// let o_pr_fact: Box<TOutputProtocolFactory> = Box::new(TBinaryOutputProtocolFactory::new());
///
/// let mut server = TServer::new(
/// i_tr_fact,
/// i_pr_fact,
/// o_tr_fact,
/// o_pr_fact,
/// processor,
/// 10
/// );
///
/// // start listening for incoming connections
/// match server.listen("127.0.0.1:8080") {
/// Ok(_) => println!("listen completed"),
/// Err(e) => println!("listen failed with error {:?}", e),
/// }
/// ```
#[derive(Debug)]
pub struct TServer<PRC, RTF, IPF, WTF, OPF>
where
PRC: TProcessor + Send + Sync +'static,
RTF: TReadTransportFactory +'static,
IPF: TInputProtocolFactory +'static,
WTF: TWriteTransportFactory +'static,
OPF: TOutputProtocolFactory +'static,
{
r_trans_factory: RTF,
i_proto_factory: IPF,
w_trans_factory: WTF,
o_proto_factory: OPF,
processor: Arc<PRC>,
worker_pool: ThreadPool,
}
impl<PRC, RTF, IPF, WTF, OPF> TServer<PRC, RTF, IPF, WTF, OPF>
where
PRC: TProcessor + Send + Sync +'static,
RTF: TReadTransportFactory +'static,
IPF: TInputProtocolFactory +'static,
WTF: TWriteTransportFactory +'static,
OPF: TOutputProtocolFactory +'static,
{
/// Create a `TServer`.
///
/// Each accepted connection has an input and output half, each of which
/// requires a `TTransport` and `TProtocol`. `TServer` uses
/// `read_transport_factory` and `input_protocol_factory` to create
/// implementations for the input, and `write_transport_factory` and
/// `output_protocol_factory` to create implementations for the output.
pub fn new(
read_transport_factory: RTF,
input_protocol_factory: IPF,
write_transport_factory: WTF,
output_protocol_factory: OPF,
processor: PRC,
num_workers: usize,
) -> TServer<PRC, RTF, IPF, WTF, OPF> {
TServer {
r_trans_factory: read_transport_factory,
i_proto_factory: input_protocol_factory,
w_trans_factory: write_transport_factory,
o_proto_factory: output_protocol_factory,
processor: Arc::new(processor),
worker_pool: ThreadPool::with_name("Thrift service processor".to_owned(), num_workers),
}
}
/// Listen for incoming connections on `listen_address`.
///
/// `listen_address` should be in the form `host:port`,
/// for example: `127.0.0.1:8080`.
///
/// Return `()` if successful.
///
/// Return `Err` when the server cannot bind to `listen_address` or there
/// is an unrecoverable error.
pub fn listen(&mut self, listen_address: &str) -> ::Result<()> {
let listener = TcpListener::bind(listen_address)?;
for stream in listener.incoming() {
match stream {
Ok(s) => {
let (i_prot, o_prot) = self.new_protocols_for_connection(s)?;
let processor = self.processor.clone();
self.worker_pool
.execute(move || handle_incoming_connection(processor, i_prot, o_prot));
}
Err(e) =>
|
}
}
Err(::Error::Application(ApplicationError {
kind: ApplicationErrorKind::Unknown,
message: "aborted listen loop".into(),
}))
}
fn new_protocols_for_connection(
&mut self,
stream: TcpStream,
) -> ::Result<(Box<dyn TInputProtocol + Send>, Box<dyn TOutputProtocol + Send>)> {
// create the shared tcp stream
let channel = TTcpChannel::with_stream(stream);
// split it into two - one to be owned by the
// input tran/proto and the other by the output
let (r_chan, w_chan) = channel.split()?;
// input protocol and transport
let r_tran = self.r_trans_factory.create(Box::new(r_chan));
let i_prot = self.i_proto_factory.create(r_tran);
// output protocol and transport
let w_tran = self.w_trans_factory.create(Box::new(w_chan));
let o_prot = self.o_proto_factory.create(w_tran);
Ok((i_prot, o_prot))
}
}
fn handle_incoming_connection<PRC>(
processor: Arc<PRC>,
i_prot: Box<dyn TInputProtocol>,
o_prot: Box<dyn TOutputProtocol>,
) where
PRC: TProcessor,
{
let mut i_prot = i_prot;
let mut o_prot = o_prot;
loop {
let r = processor.process(&mut *i_prot, &mut *o_prot);
if let Err(e) = r {
warn!("processor completed with error: {:?}", e);
break;
}
}
}
|
{
warn!("failed to accept remote connection with error {:?}", e);
}
|
conditional_block
|
threaded.rs
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use threadpool::ThreadPool;
use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory};
use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory};
use {ApplicationError, ApplicationErrorKind};
use super::TProcessor;
/// Fixed-size thread-pool blocking Thrift server.
///
/// A `TServer` listens on a given address and submits accepted connections
/// to an **unbounded** queue. Connections from this queue are serviced by
/// the first available worker thread from a **fixed-size** thread pool. Each
/// accepted connection is handled by that worker thread, and communication
/// over this thread occurs sequentially and synchronously (i.e. calls block).
/// Accepted connections have an input half and an output half, each of which
/// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate
/// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol`
/// and `TTransport` may be used.
///
/// # Examples
///
/// Creating and running a `TServer` using Thrift-compiler-generated
/// service code.
///
/// ```no_run
/// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory};
/// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory};
/// use thrift::protocol::{TInputProtocol, TOutputProtocol};
/// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory,
/// TReadTransportFactory, TWriteTransportFactory};
/// use thrift::server::{TProcessor, TServer};
///
/// //
/// // auto-generated
/// //
///
/// // processor for `SimpleService`
/// struct SimpleServiceSyncProcessor;
/// impl SimpleServiceSyncProcessor {
/// fn new<H: SimpleServiceSyncHandler>(processor: H) -> SimpleServiceSyncProcessor {
/// unimplemented!();
/// }
/// }
///
/// // `TProcessor` implementation for `SimpleService`
/// impl TProcessor for SimpleServiceSyncProcessor {
/// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> {
/// unimplemented!();
/// }
/// }
///
/// // service functions for SimpleService
/// trait SimpleServiceSyncHandler {
/// fn service_call(&self) -> thrift::Result<()>;
/// }
///
/// //
/// // user-code follows
/// //
///
/// // define a handler that will be invoked when `service_call` is received
/// struct SimpleServiceHandlerImpl;
/// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl {
/// fn service_call(&self) -> thrift::Result<()> {
/// unimplemented!();
/// }
/// }
///
/// // instantiate the processor
/// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {});
///
/// // instantiate the server
/// let i_tr_fact: Box<TReadTransportFactory> = Box::new(TBufferedReadTransportFactory::new());
/// let i_pr_fact: Box<TInputProtocolFactory> = Box::new(TBinaryInputProtocolFactory::new());
/// let o_tr_fact: Box<TWriteTransportFactory> = Box::new(TBufferedWriteTransportFactory::new());
/// let o_pr_fact: Box<TOutputProtocolFactory> = Box::new(TBinaryOutputProtocolFactory::new());
///
/// let mut server = TServer::new(
/// i_tr_fact,
/// i_pr_fact,
/// o_tr_fact,
/// o_pr_fact,
/// processor,
/// 10
/// );
///
/// // start listening for incoming connections
/// match server.listen("127.0.0.1:8080") {
/// Ok(_) => println!("listen completed"),
/// Err(e) => println!("listen failed with error {:?}", e),
/// }
/// ```
#[derive(Debug)]
pub struct TServer<PRC, RTF, IPF, WTF, OPF>
where
PRC: TProcessor + Send + Sync +'static,
RTF: TReadTransportFactory +'static,
IPF: TInputProtocolFactory +'static,
WTF: TWriteTransportFactory +'static,
OPF: TOutputProtocolFactory +'static,
{
r_trans_factory: RTF,
i_proto_factory: IPF,
w_trans_factory: WTF,
o_proto_factory: OPF,
processor: Arc<PRC>,
worker_pool: ThreadPool,
}
impl<PRC, RTF, IPF, WTF, OPF> TServer<PRC, RTF, IPF, WTF, OPF>
where
PRC: TProcessor + Send + Sync +'static,
RTF: TReadTransportFactory +'static,
IPF: TInputProtocolFactory +'static,
WTF: TWriteTransportFactory +'static,
OPF: TOutputProtocolFactory +'static,
{
/// Create a `TServer`.
///
/// Each accepted connection has an input and output half, each of which
/// requires a `TTransport` and `TProtocol`. `TServer` uses
/// `read_transport_factory` and `input_protocol_factory` to create
/// implementations for the input, and `write_transport_factory` and
/// `output_protocol_factory` to create implementations for the output.
pub fn new(
read_transport_factory: RTF,
input_protocol_factory: IPF,
write_transport_factory: WTF,
output_protocol_factory: OPF,
processor: PRC,
num_workers: usize,
) -> TServer<PRC, RTF, IPF, WTF, OPF> {
TServer {
r_trans_factory: read_transport_factory,
i_proto_factory: input_protocol_factory,
w_trans_factory: write_transport_factory,
o_proto_factory: output_protocol_factory,
processor: Arc::new(processor),
worker_pool: ThreadPool::with_name("Thrift service processor".to_owned(), num_workers),
}
}
/// Listen for incoming connections on `listen_address`.
///
/// `listen_address` should be in the form `host:port`,
/// for example: `127.0.0.1:8080`.
///
/// Return `()` if successful.
///
/// Return `Err` when the server cannot bind to `listen_address` or there
/// is an unrecoverable error.
pub fn listen(&mut self, listen_address: &str) -> ::Result<()> {
let listener = TcpListener::bind(listen_address)?;
for stream in listener.incoming() {
match stream {
Ok(s) => {
let (i_prot, o_prot) = self.new_protocols_for_connection(s)?;
let processor = self.processor.clone();
self.worker_pool
.execute(move || handle_incoming_connection(processor, i_prot, o_prot));
}
Err(e) => {
warn!("failed to accept remote connection with error {:?}", e);
}
}
}
Err(::Error::Application(ApplicationError {
kind: ApplicationErrorKind::Unknown,
message: "aborted listen loop".into(),
}))
}
fn new_protocols_for_connection(
&mut self,
stream: TcpStream,
) -> ::Result<(Box<dyn TInputProtocol + Send>, Box<dyn TOutputProtocol + Send>)> {
// create the shared tcp stream
let channel = TTcpChannel::with_stream(stream);
// split it into two - one to be owned by the
// input tran/proto and the other by the output
let (r_chan, w_chan) = channel.split()?;
// input protocol and transport
let r_tran = self.r_trans_factory.create(Box::new(r_chan));
let i_prot = self.i_proto_factory.create(r_tran);
// output protocol and transport
let w_tran = self.w_trans_factory.create(Box::new(w_chan));
let o_prot = self.o_proto_factory.create(w_tran);
Ok((i_prot, o_prot))
}
}
fn handle_incoming_connection<PRC>(
processor: Arc<PRC>,
i_prot: Box<dyn TInputProtocol>,
o_prot: Box<dyn TOutputProtocol>,
) where
PRC: TProcessor,
|
{
let mut i_prot = i_prot;
let mut o_prot = o_prot;
loop {
let r = processor.process(&mut *i_prot, &mut *o_prot);
if let Err(e) = r {
warn!("processor completed with error: {:?}", e);
break;
}
}
}
|
identifier_body
|
|
threaded.rs
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use threadpool::ThreadPool;
use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory};
use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory};
use {ApplicationError, ApplicationErrorKind};
use super::TProcessor;
/// Fixed-size thread-pool blocking Thrift server.
///
/// A `TServer` listens on a given address and submits accepted connections
/// to an **unbounded** queue. Connections from this queue are serviced by
/// the first available worker thread from a **fixed-size** thread pool. Each
/// accepted connection is handled by that worker thread, and communication
/// over this thread occurs sequentially and synchronously (i.e. calls block).
/// Accepted connections have an input half and an output half, each of which
/// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate
/// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol`
/// and `TTransport` may be used.
///
/// # Examples
///
/// Creating and running a `TServer` using Thrift-compiler-generated
/// service code.
///
/// ```no_run
/// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory};
/// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory};
/// use thrift::protocol::{TInputProtocol, TOutputProtocol};
/// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory,
/// TReadTransportFactory, TWriteTransportFactory};
/// use thrift::server::{TProcessor, TServer};
///
/// //
/// // auto-generated
/// //
///
/// // processor for `SimpleService`
/// struct SimpleServiceSyncProcessor;
/// impl SimpleServiceSyncProcessor {
/// fn new<H: SimpleServiceSyncHandler>(processor: H) -> SimpleServiceSyncProcessor {
/// unimplemented!();
/// }
/// }
///
/// // `TProcessor` implementation for `SimpleService`
/// impl TProcessor for SimpleServiceSyncProcessor {
/// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> {
/// unimplemented!();
/// }
/// }
///
/// // service functions for SimpleService
/// trait SimpleServiceSyncHandler {
/// fn service_call(&self) -> thrift::Result<()>;
/// }
///
/// //
/// // user-code follows
/// //
///
/// // define a handler that will be invoked when `service_call` is received
/// struct SimpleServiceHandlerImpl;
/// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl {
/// fn service_call(&self) -> thrift::Result<()> {
/// unimplemented!();
/// }
/// }
///
/// // instantiate the processor
/// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {});
///
/// // instantiate the server
/// let i_tr_fact: Box<TReadTransportFactory> = Box::new(TBufferedReadTransportFactory::new());
/// let i_pr_fact: Box<TInputProtocolFactory> = Box::new(TBinaryInputProtocolFactory::new());
/// let o_tr_fact: Box<TWriteTransportFactory> = Box::new(TBufferedWriteTransportFactory::new());
/// let o_pr_fact: Box<TOutputProtocolFactory> = Box::new(TBinaryOutputProtocolFactory::new());
///
/// let mut server = TServer::new(
/// i_tr_fact,
/// i_pr_fact,
/// o_tr_fact,
/// o_pr_fact,
/// processor,
/// 10
/// );
///
/// // start listening for incoming connections
/// match server.listen("127.0.0.1:8080") {
/// Ok(_) => println!("listen completed"),
/// Err(e) => println!("listen failed with error {:?}", e),
/// }
/// ```
#[derive(Debug)]
pub struct TServer<PRC, RTF, IPF, WTF, OPF>
where
PRC: TProcessor + Send + Sync +'static,
RTF: TReadTransportFactory +'static,
IPF: TInputProtocolFactory +'static,
WTF: TWriteTransportFactory +'static,
OPF: TOutputProtocolFactory +'static,
{
r_trans_factory: RTF,
i_proto_factory: IPF,
w_trans_factory: WTF,
o_proto_factory: OPF,
processor: Arc<PRC>,
worker_pool: ThreadPool,
}
impl<PRC, RTF, IPF, WTF, OPF> TServer<PRC, RTF, IPF, WTF, OPF>
where
PRC: TProcessor + Send + Sync +'static,
RTF: TReadTransportFactory +'static,
IPF: TInputProtocolFactory +'static,
WTF: TWriteTransportFactory +'static,
OPF: TOutputProtocolFactory +'static,
{
/// Create a `TServer`.
///
/// Each accepted connection has an input and output half, each of which
/// requires a `TTransport` and `TProtocol`. `TServer` uses
/// `read_transport_factory` and `input_protocol_factory` to create
/// implementations for the input, and `write_transport_factory` and
/// `output_protocol_factory` to create implementations for the output.
pub fn new(
read_transport_factory: RTF,
input_protocol_factory: IPF,
write_transport_factory: WTF,
output_protocol_factory: OPF,
processor: PRC,
num_workers: usize,
) -> TServer<PRC, RTF, IPF, WTF, OPF> {
TServer {
r_trans_factory: read_transport_factory,
i_proto_factory: input_protocol_factory,
w_trans_factory: write_transport_factory,
o_proto_factory: output_protocol_factory,
processor: Arc::new(processor),
worker_pool: ThreadPool::with_name("Thrift service processor".to_owned(), num_workers),
}
}
/// Listen for incoming connections on `listen_address`.
///
/// `listen_address` should be in the form `host:port`,
/// for example: `127.0.0.1:8080`.
///
/// Return `()` if successful.
///
/// Return `Err` when the server cannot bind to `listen_address` or there
/// is an unrecoverable error.
pub fn
|
(&mut self, listen_address: &str) -> ::Result<()> {
let listener = TcpListener::bind(listen_address)?;
for stream in listener.incoming() {
match stream {
Ok(s) => {
let (i_prot, o_prot) = self.new_protocols_for_connection(s)?;
let processor = self.processor.clone();
self.worker_pool
.execute(move || handle_incoming_connection(processor, i_prot, o_prot));
}
Err(e) => {
warn!("failed to accept remote connection with error {:?}", e);
}
}
}
Err(::Error::Application(ApplicationError {
kind: ApplicationErrorKind::Unknown,
message: "aborted listen loop".into(),
}))
}
fn new_protocols_for_connection(
&mut self,
stream: TcpStream,
) -> ::Result<(Box<dyn TInputProtocol + Send>, Box<dyn TOutputProtocol + Send>)> {
// create the shared tcp stream
let channel = TTcpChannel::with_stream(stream);
// split it into two - one to be owned by the
// input tran/proto and the other by the output
let (r_chan, w_chan) = channel.split()?;
// input protocol and transport
let r_tran = self.r_trans_factory.create(Box::new(r_chan));
let i_prot = self.i_proto_factory.create(r_tran);
// output protocol and transport
let w_tran = self.w_trans_factory.create(Box::new(w_chan));
let o_prot = self.o_proto_factory.create(w_tran);
Ok((i_prot, o_prot))
}
}
fn handle_incoming_connection<PRC>(
processor: Arc<PRC>,
i_prot: Box<dyn TInputProtocol>,
o_prot: Box<dyn TOutputProtocol>,
) where
PRC: TProcessor,
{
let mut i_prot = i_prot;
let mut o_prot = o_prot;
loop {
let r = processor.process(&mut *i_prot, &mut *o_prot);
if let Err(e) = r {
warn!("processor completed with error: {:?}", e);
break;
}
}
}
|
listen
|
identifier_name
|
threaded.rs
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use threadpool::ThreadPool;
use protocol::{TInputProtocol, TInputProtocolFactory, TOutputProtocol, TOutputProtocolFactory};
use transport::{TIoChannel, TReadTransportFactory, TTcpChannel, TWriteTransportFactory};
use {ApplicationError, ApplicationErrorKind};
use super::TProcessor;
/// Fixed-size thread-pool blocking Thrift server.
///
/// A `TServer` listens on a given address and submits accepted connections
/// to an **unbounded** queue. Connections from this queue are serviced by
/// the first available worker thread from a **fixed-size** thread pool. Each
/// accepted connection is handled by that worker thread, and communication
/// over this thread occurs sequentially and synchronously (i.e. calls block).
/// Accepted connections have an input half and an output half, each of which
/// uses a `TTransport` and `TInputProtocol`/`TOutputProtocol` to translate
/// messages to and from byes. Any combination of `TInputProtocol`, `TOutputProtocol`
/// and `TTransport` may be used.
///
/// # Examples
///
/// Creating and running a `TServer` using Thrift-compiler-generated
/// service code.
///
/// ```no_run
/// use thrift::protocol::{TInputProtocolFactory, TOutputProtocolFactory};
/// use thrift::protocol::{TBinaryInputProtocolFactory, TBinaryOutputProtocolFactory};
/// use thrift::protocol::{TInputProtocol, TOutputProtocol};
/// use thrift::transport::{TBufferedReadTransportFactory, TBufferedWriteTransportFactory,
/// TReadTransportFactory, TWriteTransportFactory};
/// use thrift::server::{TProcessor, TServer};
///
/// //
/// // auto-generated
/// //
///
/// // processor for `SimpleService`
/// struct SimpleServiceSyncProcessor;
/// impl SimpleServiceSyncProcessor {
/// fn new<H: SimpleServiceSyncHandler>(processor: H) -> SimpleServiceSyncProcessor {
/// unimplemented!();
/// }
/// }
///
/// // `TProcessor` implementation for `SimpleService`
/// impl TProcessor for SimpleServiceSyncProcessor {
/// fn process(&self, i: &mut TInputProtocol, o: &mut TOutputProtocol) -> thrift::Result<()> {
/// unimplemented!();
/// }
/// }
///
/// // service functions for SimpleService
/// trait SimpleServiceSyncHandler {
/// fn service_call(&self) -> thrift::Result<()>;
/// }
///
/// //
/// // user-code follows
/// //
///
/// // define a handler that will be invoked when `service_call` is received
/// struct SimpleServiceHandlerImpl;
/// impl SimpleServiceSyncHandler for SimpleServiceHandlerImpl {
/// fn service_call(&self) -> thrift::Result<()> {
/// unimplemented!();
/// }
/// }
///
/// // instantiate the processor
/// let processor = SimpleServiceSyncProcessor::new(SimpleServiceHandlerImpl {});
///
/// // instantiate the server
/// let i_tr_fact: Box<TReadTransportFactory> = Box::new(TBufferedReadTransportFactory::new());
/// let i_pr_fact: Box<TInputProtocolFactory> = Box::new(TBinaryInputProtocolFactory::new());
/// let o_tr_fact: Box<TWriteTransportFactory> = Box::new(TBufferedWriteTransportFactory::new());
/// let o_pr_fact: Box<TOutputProtocolFactory> = Box::new(TBinaryOutputProtocolFactory::new());
///
/// let mut server = TServer::new(
/// i_tr_fact,
/// i_pr_fact,
/// o_tr_fact,
/// o_pr_fact,
/// processor,
/// 10
/// );
///
/// // start listening for incoming connections
/// match server.listen("127.0.0.1:8080") {
/// Ok(_) => println!("listen completed"),
/// Err(e) => println!("listen failed with error {:?}", e),
/// }
/// ```
#[derive(Debug)]
pub struct TServer<PRC, RTF, IPF, WTF, OPF>
where
PRC: TProcessor + Send + Sync +'static,
RTF: TReadTransportFactory +'static,
IPF: TInputProtocolFactory +'static,
WTF: TWriteTransportFactory +'static,
OPF: TOutputProtocolFactory +'static,
{
r_trans_factory: RTF,
i_proto_factory: IPF,
w_trans_factory: WTF,
o_proto_factory: OPF,
processor: Arc<PRC>,
worker_pool: ThreadPool,
}
impl<PRC, RTF, IPF, WTF, OPF> TServer<PRC, RTF, IPF, WTF, OPF>
where
PRC: TProcessor + Send + Sync +'static,
RTF: TReadTransportFactory +'static,
IPF: TInputProtocolFactory +'static,
WTF: TWriteTransportFactory +'static,
OPF: TOutputProtocolFactory +'static,
{
/// Create a `TServer`.
///
/// Each accepted connection has an input and output half, each of which
/// requires a `TTransport` and `TProtocol`. `TServer` uses
/// `read_transport_factory` and `input_protocol_factory` to create
/// implementations for the input, and `write_transport_factory` and
/// `output_protocol_factory` to create implementations for the output.
pub fn new(
read_transport_factory: RTF,
input_protocol_factory: IPF,
write_transport_factory: WTF,
output_protocol_factory: OPF,
processor: PRC,
num_workers: usize,
) -> TServer<PRC, RTF, IPF, WTF, OPF> {
TServer {
r_trans_factory: read_transport_factory,
i_proto_factory: input_protocol_factory,
w_trans_factory: write_transport_factory,
o_proto_factory: output_protocol_factory,
processor: Arc::new(processor),
worker_pool: ThreadPool::with_name("Thrift service processor".to_owned(), num_workers),
}
}
/// Listen for incoming connections on `listen_address`.
///
/// `listen_address` should be in the form `host:port`,
/// for example: `127.0.0.1:8080`.
///
/// Return `()` if successful.
///
/// Return `Err` when the server cannot bind to `listen_address` or there
/// is an unrecoverable error.
pub fn listen(&mut self, listen_address: &str) -> ::Result<()> {
let listener = TcpListener::bind(listen_address)?;
for stream in listener.incoming() {
match stream {
Ok(s) => {
let (i_prot, o_prot) = self.new_protocols_for_connection(s)?;
let processor = self.processor.clone();
self.worker_pool
.execute(move || handle_incoming_connection(processor, i_prot, o_prot));
}
Err(e) => {
warn!("failed to accept remote connection with error {:?}", e);
}
}
}
Err(::Error::Application(ApplicationError {
kind: ApplicationErrorKind::Unknown,
message: "aborted listen loop".into(),
}))
}
fn new_protocols_for_connection(
&mut self,
stream: TcpStream,
) -> ::Result<(Box<dyn TInputProtocol + Send>, Box<dyn TOutputProtocol + Send>)> {
// create the shared tcp stream
let channel = TTcpChannel::with_stream(stream);
// split it into two - one to be owned by the
// input tran/proto and the other by the output
let (r_chan, w_chan) = channel.split()?;
// input protocol and transport
let r_tran = self.r_trans_factory.create(Box::new(r_chan));
let i_prot = self.i_proto_factory.create(r_tran);
// output protocol and transport
let w_tran = self.w_trans_factory.create(Box::new(w_chan));
let o_prot = self.o_proto_factory.create(w_tran);
Ok((i_prot, o_prot))
}
}
fn handle_incoming_connection<PRC>(
processor: Arc<PRC>,
i_prot: Box<dyn TInputProtocol>,
o_prot: Box<dyn TOutputProtocol>,
) where
PRC: TProcessor,
{
let mut i_prot = i_prot;
|
loop {
let r = processor.process(&mut *i_prot, &mut *o_prot);
if let Err(e) = r {
warn!("processor completed with error: {:?}", e);
break;
}
}
}
|
let mut o_prot = o_prot;
|
random_line_split
|
record-pat.rs
|
// run-pass
#![allow(non_camel_case_types)]
#![allow(non_shorthand_field_patterns)]
enum t1 { a(isize), b(usize), }
struct T2 {x: t1, y: isize}
enum t3 { c(T2, usize), }
fn m(input: t3) -> isize {
match input {
t3::c(T2 {x: t1::a(m),..}, _) => { return m; }
t3::c(T2 {x: t1::b(m), y: y}, z) => { return ((m + z) as isize) + y; }
}
}
pub fn main()
|
{
assert_eq!(m(t3::c(T2 {x: t1::a(10), y: 5}, 4)), 10);
assert_eq!(m(t3::c(T2 {x: t1::b(10), y: 5}, 4)), 19);
}
|
identifier_body
|
|
record-pat.rs
|
// run-pass
#![allow(non_camel_case_types)]
#![allow(non_shorthand_field_patterns)]
enum t1 { a(isize), b(usize), }
struct
|
{x: t1, y: isize}
enum t3 { c(T2, usize), }
fn m(input: t3) -> isize {
match input {
t3::c(T2 {x: t1::a(m),..}, _) => { return m; }
t3::c(T2 {x: t1::b(m), y: y}, z) => { return ((m + z) as isize) + y; }
}
}
pub fn main() {
assert_eq!(m(t3::c(T2 {x: t1::a(10), y: 5}, 4)), 10);
assert_eq!(m(t3::c(T2 {x: t1::b(10), y: 5}, 4)), 19);
}
|
T2
|
identifier_name
|
record-pat.rs
|
// run-pass
|
#![allow(non_camel_case_types)]
#![allow(non_shorthand_field_patterns)]
enum t1 { a(isize), b(usize), }
struct T2 {x: t1, y: isize}
enum t3 { c(T2, usize), }
fn m(input: t3) -> isize {
match input {
t3::c(T2 {x: t1::a(m),..}, _) => { return m; }
t3::c(T2 {x: t1::b(m), y: y}, z) => { return ((m + z) as isize) + y; }
}
}
pub fn main() {
assert_eq!(m(t3::c(T2 {x: t1::a(10), y: 5}, 4)), 10);
assert_eq!(m(t3::c(T2 {x: t1::b(10), y: 5}, 4)), 19);
}
|
random_line_split
|
|
load_block.rs
|
use {MultiFileDirectAccessor, InMemoryFileSystem};
use bip_disk::{DiskManagerBuilder, IDiskMessage, ODiskMessage, BlockMetadata, Block, BlockMut};
use bip_metainfo::{MetainfoBuilder, PieceLength, Metainfo};
use bytes::BytesMut;
use tokio_core::reactor::{Core};
use futures::future::{Loop};
use futures::stream::Stream;
use futures::sink::Sink;
#[test]
fn
|
() {
// Create some "files" as random bytes
let data_a = (::random_buffer(1023), "/path/to/file/a".into());
let data_b = (::random_buffer(2000), "/path/to/file/b".into());
// Create our accessor for our in memory files and create a torrent file for them
let files_accessor = MultiFileDirectAccessor::new("/my/downloads/".into(),
vec![data_a.clone(), data_b.clone()]);
let metainfo_bytes = MetainfoBuilder::new()
.set_piece_length(PieceLength::Custom(1024))
.build(1, files_accessor, |_| ()).unwrap();
let metainfo_file = Metainfo::from_bytes(metainfo_bytes).unwrap();
// Spin up a disk manager and add our created torrent to its
let filesystem = InMemoryFileSystem::new();
let disk_manager = DiskManagerBuilder::new()
.build(filesystem.clone());
let mut process_block = BytesMut::new();
process_block.extend_from_slice(&data_b.0[1..(50 + 1)]);
let mut load_block = BytesMut::with_capacity(50);
load_block.extend_from_slice(&[0u8; 50]);
let process_block = Block::new(BlockMetadata::new(metainfo_file.info().info_hash(), 1, 0, 50), process_block.freeze());
let load_block = BlockMut::new(BlockMetadata::new(metainfo_file.info().info_hash(), 1, 0, 50), load_block);
let (send, recv) = disk_manager.split();
let mut blocking_send = send.wait();
blocking_send.send(IDiskMessage::AddTorrent(metainfo_file)).unwrap();
let mut core = Core::new().unwrap();
let (pblock, lblock) = ::core_loop_with_timeout(&mut core, 500, ((blocking_send, Some(process_block), Some(load_block)), recv),
|(mut blocking_send, opt_pblock, opt_lblock), recv, msg| {
match msg {
ODiskMessage::TorrentAdded(_) => {
blocking_send.send(IDiskMessage::ProcessBlock(opt_pblock.unwrap())).unwrap();
Loop::Continue(((blocking_send, None, opt_lblock), recv))
},
ODiskMessage::BlockProcessed(block) => {
blocking_send.send(IDiskMessage::LoadBlock(opt_lblock.unwrap())).unwrap();
Loop::Continue(((blocking_send, Some(block), None), recv))
},
ODiskMessage::BlockLoaded(block) => Loop::Break((opt_pblock.unwrap(), block)),
unexpected @ _ => panic!("Unexpected Message: {:?}", unexpected)
}
}
);
// Verify lblock contains our data
assert_eq!(*pblock, *lblock);
}
|
positive_load_block
|
identifier_name
|
load_block.rs
|
use {MultiFileDirectAccessor, InMemoryFileSystem};
use bip_disk::{DiskManagerBuilder, IDiskMessage, ODiskMessage, BlockMetadata, Block, BlockMut};
use bip_metainfo::{MetainfoBuilder, PieceLength, Metainfo};
use bytes::BytesMut;
use tokio_core::reactor::{Core};
use futures::future::{Loop};
use futures::stream::Stream;
use futures::sink::Sink;
#[test]
fn positive_load_block()
|
let mut load_block = BytesMut::with_capacity(50);
load_block.extend_from_slice(&[0u8; 50]);
let process_block = Block::new(BlockMetadata::new(metainfo_file.info().info_hash(), 1, 0, 50), process_block.freeze());
let load_block = BlockMut::new(BlockMetadata::new(metainfo_file.info().info_hash(), 1, 0, 50), load_block);
let (send, recv) = disk_manager.split();
let mut blocking_send = send.wait();
blocking_send.send(IDiskMessage::AddTorrent(metainfo_file)).unwrap();
let mut core = Core::new().unwrap();
let (pblock, lblock) = ::core_loop_with_timeout(&mut core, 500, ((blocking_send, Some(process_block), Some(load_block)), recv),
|(mut blocking_send, opt_pblock, opt_lblock), recv, msg| {
match msg {
ODiskMessage::TorrentAdded(_) => {
blocking_send.send(IDiskMessage::ProcessBlock(opt_pblock.unwrap())).unwrap();
Loop::Continue(((blocking_send, None, opt_lblock), recv))
},
ODiskMessage::BlockProcessed(block) => {
blocking_send.send(IDiskMessage::LoadBlock(opt_lblock.unwrap())).unwrap();
Loop::Continue(((blocking_send, Some(block), None), recv))
},
ODiskMessage::BlockLoaded(block) => Loop::Break((opt_pblock.unwrap(), block)),
unexpected @ _ => panic!("Unexpected Message: {:?}", unexpected)
}
}
);
// Verify lblock contains our data
assert_eq!(*pblock, *lblock);
}
|
{
// Create some "files" as random bytes
let data_a = (::random_buffer(1023), "/path/to/file/a".into());
let data_b = (::random_buffer(2000), "/path/to/file/b".into());
// Create our accessor for our in memory files and create a torrent file for them
let files_accessor = MultiFileDirectAccessor::new("/my/downloads/".into(),
vec![data_a.clone(), data_b.clone()]);
let metainfo_bytes = MetainfoBuilder::new()
.set_piece_length(PieceLength::Custom(1024))
.build(1, files_accessor, |_| ()).unwrap();
let metainfo_file = Metainfo::from_bytes(metainfo_bytes).unwrap();
// Spin up a disk manager and add our created torrent to its
let filesystem = InMemoryFileSystem::new();
let disk_manager = DiskManagerBuilder::new()
.build(filesystem.clone());
let mut process_block = BytesMut::new();
process_block.extend_from_slice(&data_b.0[1..(50 + 1)]);
|
identifier_body
|
load_block.rs
|
use {MultiFileDirectAccessor, InMemoryFileSystem};
use bip_disk::{DiskManagerBuilder, IDiskMessage, ODiskMessage, BlockMetadata, Block, BlockMut};
use bip_metainfo::{MetainfoBuilder, PieceLength, Metainfo};
use bytes::BytesMut;
use tokio_core::reactor::{Core};
use futures::future::{Loop};
use futures::stream::Stream;
use futures::sink::Sink;
#[test]
fn positive_load_block() {
// Create some "files" as random bytes
let data_a = (::random_buffer(1023), "/path/to/file/a".into());
let data_b = (::random_buffer(2000), "/path/to/file/b".into());
// Create our accessor for our in memory files and create a torrent file for them
let files_accessor = MultiFileDirectAccessor::new("/my/downloads/".into(),
vec![data_a.clone(), data_b.clone()]);
let metainfo_bytes = MetainfoBuilder::new()
.set_piece_length(PieceLength::Custom(1024))
.build(1, files_accessor, |_| ()).unwrap();
let metainfo_file = Metainfo::from_bytes(metainfo_bytes).unwrap();
// Spin up a disk manager and add our created torrent to its
let filesystem = InMemoryFileSystem::new();
let disk_manager = DiskManagerBuilder::new()
.build(filesystem.clone());
let mut process_block = BytesMut::new();
process_block.extend_from_slice(&data_b.0[1..(50 + 1)]);
let mut load_block = BytesMut::with_capacity(50);
load_block.extend_from_slice(&[0u8; 50]);
let process_block = Block::new(BlockMetadata::new(metainfo_file.info().info_hash(), 1, 0, 50), process_block.freeze());
let load_block = BlockMut::new(BlockMetadata::new(metainfo_file.info().info_hash(), 1, 0, 50), load_block);
let (send, recv) = disk_manager.split();
let mut blocking_send = send.wait();
blocking_send.send(IDiskMessage::AddTorrent(metainfo_file)).unwrap();
let mut core = Core::new().unwrap();
let (pblock, lblock) = ::core_loop_with_timeout(&mut core, 500, ((blocking_send, Some(process_block), Some(load_block)), recv),
|(mut blocking_send, opt_pblock, opt_lblock), recv, msg| {
match msg {
ODiskMessage::TorrentAdded(_) => {
blocking_send.send(IDiskMessage::ProcessBlock(opt_pblock.unwrap())).unwrap();
Loop::Continue(((blocking_send, None, opt_lblock), recv))
},
ODiskMessage::BlockProcessed(block) => {
|
},
ODiskMessage::BlockLoaded(block) => Loop::Break((opt_pblock.unwrap(), block)),
unexpected @ _ => panic!("Unexpected Message: {:?}", unexpected)
}
}
);
// Verify lblock contains our data
assert_eq!(*pblock, *lblock);
}
|
blocking_send.send(IDiskMessage::LoadBlock(opt_lblock.unwrap())).unwrap();
Loop::Continue(((blocking_send, Some(block), None), recv))
|
random_line_split
|
rtdeps.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.
//! This module contains the linkage attributes to all runtime dependencies of
//! the standard library This varies per-platform, but these libraries are
//! necessary for running libstd.
// All platforms need to link to rustrt
#[link(name = "rustrt", kind = "static")]
extern {}
// LLVM implements the `frem` instruction as a call to `fmod`, which lives in
// libm. Hence, we must explicitly link to it.
//
// On linux librt and libdl are indirect dependencies via rustrt,
// and binutils 2.22+ won't add them automatically
#[cfg(target_os = "linux")]
#[link(name = "dl")]
#[link(name = "pthread")]
extern {}
#[cfg(target_os = "android")]
#[link(name = "dl")]
#[link(name = "log")]
extern {}
#[cfg(target_os = "freebsd")]
#[link(name = "execinfo")]
#[link(name = "pthread")]
|
extern {}
|
extern {}
#[cfg(target_os = "macos")]
#[link(name = "System")]
|
random_line_split
|
binary_digits.rs
|
// Implements http://rosettacode.org/wiki/Binary_digits
use std::iter::range_inclusive;
trait BinaryString {
fn to_binary_string(&self) -> String;
}
impl BinaryString for uint {
fn to_binary_string(&self) -> String {
format!("{:t}", *self)
}
}
#[cfg(not(test))]
fn main() {
for s in range_inclusive(0, 16u) {
println!("{}", s.to_binary_string());
}
}
#[test]
fn test_digits() {
let expected = ["0", "1", "10", "11",
"100", "101", "110", "111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"];
|
for (n, expected) in range_inclusive(0, 16u).zip(expected.iter()) {
assert_eq!(n.to_binary_string().as_slice(), *expected);
}
}
|
random_line_split
|
|
binary_digits.rs
|
// Implements http://rosettacode.org/wiki/Binary_digits
use std::iter::range_inclusive;
trait BinaryString {
fn to_binary_string(&self) -> String;
}
impl BinaryString for uint {
fn to_binary_string(&self) -> String {
format!("{:t}", *self)
}
}
#[cfg(not(test))]
fn
|
() {
for s in range_inclusive(0, 16u) {
println!("{}", s.to_binary_string());
}
}
#[test]
fn test_digits() {
let expected = ["0", "1", "10", "11",
"100", "101", "110", "111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"];
for (n, expected) in range_inclusive(0, 16u).zip(expected.iter()) {
assert_eq!(n.to_binary_string().as_slice(), *expected);
}
}
|
main
|
identifier_name
|
binary_digits.rs
|
// Implements http://rosettacode.org/wiki/Binary_digits
use std::iter::range_inclusive;
trait BinaryString {
fn to_binary_string(&self) -> String;
}
impl BinaryString for uint {
fn to_binary_string(&self) -> String {
format!("{:t}", *self)
}
}
#[cfg(not(test))]
fn main() {
for s in range_inclusive(0, 16u) {
println!("{}", s.to_binary_string());
}
}
#[test]
fn test_digits()
|
{
let expected = ["0", "1", "10", "11",
"100", "101", "110", "111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"];
for (n, expected) in range_inclusive(0, 16u).zip(expected.iter()) {
assert_eq!(n.to_binary_string().as_slice(), *expected);
}
}
|
identifier_body
|
|
crypto.rs
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Crypto primitives used by the remote attestation protocol.
//
// Should be kept in sync with the Java implementation of the remote attestation
// protocol.
use crate::message::EncryptedData;
use alloc::{format, vec, vec::Vec};
use anyhow::{anyhow, Context};
use core::convert::TryInto;
use ring::{
aead::{self, BoundKey},
agreement,
digest::{digest, SHA256},
hkdf::{Salt, HKDF_SHA256},
rand::{SecureRandom, SystemRandom},
signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, EcdsaVerificationAlgorithm, KeyPair},
};
/// Length of the encryption nonce.
/// `ring::aead` uses 96-bit (12-byte) nonces.
/// <https://briansmith.org/rustdoc/ring/aead/constant.NONCE_LEN.html>
pub const NONCE_LENGTH: usize = aead::NONCE_LEN;
pub const SHA256_HASH_LENGTH: usize = 32;
/// Algorithm used for encrypting/decrypting messages.
/// <https://datatracker.ietf.org/doc/html/rfc5288>
static AEAD_ALGORITHM: &aead::Algorithm = &aead::AES_256_GCM;
pub const AEAD_ALGORITHM_KEY_LENGTH: usize = 32;
/// Algorithm used for negotiating a session key.
/// <https://datatracker.ietf.org/doc/html/rfc7748>
static KEY_AGREEMENT_ALGORITHM: &agreement::Algorithm = &agreement::X25519;
pub const KEY_AGREEMENT_ALGORITHM_KEY_LENGTH: usize = 32;
/// Salt used for key derivation with HKDF.
/// <https://datatracker.ietf.org/doc/html/rfc5869>
pub const KEY_DERIVATION_SALT: &str = "Remote Attestation Protocol v1";
/// Purpose string used for deriving server session keys with HKDF.
pub const SERVER_KEY_PURPOSE: &str = "Remote Attestation Protocol Server Session Key";
/// Purpose string used for deriving client session keys with HKDF.
pub const CLIENT_KEY_PURPOSE: &str = "Remote Attestation Protocol Client Session Key";
/// Algorithm used to create cryptographic signatures.
static SIGNING_ALGORITHM: &EcdsaSigningAlgorithm =
&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING;
/// OpenSSL ECDSA-P256 key public key length, which is represented as
/// `0x04 | X: 32-byte | Y: 32-byte`.
/// Where X and Y are big-endian coordinates of an Elliptic Curve point.
/// <https://datatracker.ietf.org/doc/html/rfc6979>
pub const SIGNING_ALGORITHM_KEY_LENGTH: usize = 65;
// TODO(#2277): Use OpenSSL signature format (which is 72 bytes).
/// IEEE-P1363 encoded ECDSA-P256 signature length.
/// <https://datatracker.ietf.org/doc/html/rfc6979>
/// <https://standards.ieee.org/standard/1363-2000.html>
pub const SIGNATURE_LENGTH: usize = 64;
/// Algorithm used to verify cryptographic signatures.
static VERIFICATION_ALGORITHM: &EcdsaVerificationAlgorithm =
&ring::signature::ECDSA_P256_SHA256_FIXED;
/// Nonce implementation used by [`AeadEncryptor`].
/// It returns a single nonce once and then only returns errors.
struct OneNonceSequence(Option<aead::Nonce>);
impl OneNonceSequence {
fn new(nonce: [u8; NONCE_LENGTH]) -> Self {
let nonce = aead::Nonce::assume_unique_for_key(nonce);
Self(Some(nonce))
}
}
impl aead::NonceSequence for OneNonceSequence {
fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
self.0.take().ok_or(ring::error::Unspecified)
}
}
|
#[derive(PartialEq)]
pub(crate) struct DecryptionKey(pub(crate) [u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]);
/// Implementation of Authenticated Encryption with Associated Data (AEAD).
///
/// <https://datatracker.ietf.org/doc/html/rfc5116>
///
/// This implementation uses separate keys for encrypting data and decrypting peer encrypted data.
/// Which means that this implementation uses the same key for encryption, which peer uses for
/// decryption.
///
/// It is necessary to prevent the Loopback Attack, where malicious network takes an outgoing packet
/// and feeds it back as an incoming packet.
pub struct AeadEncryptor {
/// Key used for encrypting data.
encryption_key: EncryptionKey,
/// Key used for decrypting peer encrypted data.
decryption_key: DecryptionKey,
}
impl AeadEncryptor {
pub(crate) fn new(encryption_key: EncryptionKey, decryption_key: DecryptionKey) -> Self {
Self {
encryption_key,
decryption_key,
}
}
/// Encrypts `data` using `AeadEncryptor::encryption_key`.
pub fn encrypt(&mut self, data: &[u8]) -> anyhow::Result<EncryptedData> {
// Generate a random nonce.
let nonce = Self::generate_nonce().context("Couldn't generate nonce")?;
// Bind [`AeadEncryptor::key`] to a `nonce`.
let unbound_sealing_key = aead::UnboundKey::new(AEAD_ALGORITHM, &self.encryption_key.0)
.map_err(|error| anyhow!("Couldn't create sealing key: {:?}", error))?;
let mut sealing_key =
ring::aead::SealingKey::new(unbound_sealing_key, OneNonceSequence::new(nonce));
let mut encrypted_data = data.to_vec();
sealing_key
// Additional authenticated data is not required for the remotely attested channel,
// since after session key is established client and server exchange messages with a
// single encrypted field.
// And the nonce is authenticated by the AEAD algorithm itself.
// https://datatracker.ietf.org/doc/html/rfc5116#section-2.1
.seal_in_place_append_tag(aead::Aad::empty(), &mut encrypted_data)
.map_err(|error| anyhow!("Couldn't encrypt data: {:?}", error))?;
Ok(EncryptedData::new(nonce, encrypted_data))
}
/// Decrypts and authenticates `data` using `AeadEncryptor::decryption_key`.
/// `data` must contain an encrypted message prefixed with a random nonce of [`NONCE_LENGTH`]
/// length.
pub fn decrypt(&mut self, data: &EncryptedData) -> anyhow::Result<Vec<u8>> {
// Bind `AeadEncryptor::key` to the extracted `nonce`.
let unbound_opening_key =
aead::UnboundKey::new(AEAD_ALGORITHM, &self.decryption_key.0).unwrap();
let mut opening_key =
ring::aead::OpeningKey::new(unbound_opening_key, OneNonceSequence::new(data.nonce));
let mut decrypted_data = data.data.to_vec();
let decrypted_data = opening_key
// Additional authenticated data is not required for the remotely attested channel,
// since after session key is established client and server exchange messages with a
// single encrypted field.
// And the nonce is authenticated by the AEAD algorithm itself.
// https://datatracker.ietf.org/doc/html/rfc5116#section-2.1
.open_in_place(aead::Aad::empty(), &mut decrypted_data)
.map_err(|error| anyhow!("Couldn't decrypt data: {:?}", error))?;
Ok(decrypted_data.to_vec())
}
/// Generate a random nonce.
fn generate_nonce() -> anyhow::Result<[u8; NONCE_LENGTH]> {
get_random()
}
}
/// Implementation of the X25519 Elliptic Curve Diffie-Hellman (ECDH) key negotiation.
///
/// <https://datatracker.ietf.org/doc/html/rfc7748#section-6.1>
pub struct KeyNegotiator {
type_: KeyNegotiatorType,
private_key: agreement::EphemeralPrivateKey,
}
impl KeyNegotiator {
pub fn create(type_: KeyNegotiatorType) -> anyhow::Result<Self> {
let rng = ring::rand::SystemRandom::new();
let private_key = agreement::EphemeralPrivateKey::generate(KEY_AGREEMENT_ALGORITHM, &rng)
.map_err(|error| anyhow!("Couldn't generate private key: {:?}", error))?;
Ok(Self { type_, private_key })
}
pub fn public_key(&self) -> anyhow::Result<[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]> {
let public_key = self
.private_key
.compute_public_key()
.map_err(|error| anyhow!("Couldn't get public key: {:?}", error))?
.as_ref()
.to_vec();
public_key.as_slice().try_into().context(format!(
"Incorrect public key length, expected {}, found {}",
KEY_AGREEMENT_ALGORITHM_KEY_LENGTH,
public_key.len()
))
}
/// Derives session keys from self and peer public keys and creates an [`AeadEncryptor`].
///
/// HKDF is used to derive both server and client session keys. The information string provided
/// to HKDF consists of a purpose string, a server public key and a client public key (in that
/// specific order).
/// Server session key uses the [`SERVER_KEY_PURPOSE`] purpose string and client session key
/// uses [`CLIENT_KEY_PURPOSE`].
///
/// Depending on `encryptor_type` creates a different type of encryptor: either server encryptor
/// or client encryptor.
pub fn create_encryptor(
self,
peer_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<AeadEncryptor> {
let (encryption_key, decryption_key) = self
.derive_session_keys(peer_public_key)
.context("Couldn't derive session keys")?;
let encryptor = AeadEncryptor::new(encryption_key, decryption_key);
Ok(encryptor)
}
/// Implementation of the session keys derivation.
/// Returns a tuple with an encryption key and a decryption key.
pub(crate) fn derive_session_keys(
self,
peer_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<(EncryptionKey, DecryptionKey)> {
let type_ = self.type_.clone();
let self_public_key = self.public_key().context("Couldn't get self public key")?;
let (encryption_key, decryption_key) = agreement::agree_ephemeral(
self.private_key,
&agreement::UnparsedPublicKey::new(KEY_AGREEMENT_ALGORITHM, peer_public_key),
anyhow!("Couldn't derive session keys"),
|key_material| {
let key_material = key_material.try_into().context(format!(
"Incorrect key material length, expected {}, found {}",
KEY_AGREEMENT_ALGORITHM_KEY_LENGTH,
key_material.len()
))?;
let peer_public_key = *peer_public_key;
match type_ {
// On the server side `self_public_key` is the server key.
KeyNegotiatorType::Server => {
let encryption_key = Self::key_derivation_function(
key_material,
SERVER_KEY_PURPOSE,
&self_public_key,
&peer_public_key,
);
let decryption_key = Self::key_derivation_function(
key_material,
CLIENT_KEY_PURPOSE,
&self_public_key,
&peer_public_key,
);
Ok((encryption_key, decryption_key))
}
// On the client side `peer_public_key` is the server key.
KeyNegotiatorType::Client => {
let encryption_key = Self::key_derivation_function(
key_material,
CLIENT_KEY_PURPOSE,
&peer_public_key,
&self_public_key,
);
let decryption_key = Self::key_derivation_function(
key_material,
SERVER_KEY_PURPOSE,
&peer_public_key,
&self_public_key,
);
Ok((encryption_key, decryption_key))
}
}
},
)
.context("Couldn't agree on session keys")?;
Ok((
EncryptionKey(encryption_key.context("Couldn't derive encryption key")?),
DecryptionKey(decryption_key.context("Couldn't derive decryption key")?),
))
}
/// Derives a session key from `key_material` using HKDF.
///
/// <https://datatracker.ietf.org/doc/html/rfc5869>
///
/// <https://datatracker.ietf.org/doc/html/rfc7748#section-6.1>
///
/// In order to derive keys, uses the information string that consists of a purpose string, a
/// server public key and a client public key (in that specific order).
pub(crate) fn key_derivation_function(
key_material: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
key_purpose: &str,
server_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
client_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<[u8; AEAD_ALGORITHM_KEY_LENGTH]> {
// Session key is derived from a purpose string and two public keys.
let info = vec![key_purpose.as_bytes(), server_public_key, client_public_key];
// Initialize key derivation function.
let salt = Salt::new(HKDF_SHA256, KEY_DERIVATION_SALT.as_bytes());
let kdf = salt.extract(key_material);
// Derive session key.
let mut session_key: [u8; AEAD_ALGORITHM_KEY_LENGTH] = Default::default();
let output_key_material = kdf
.expand(&info, AEAD_ALGORITHM)
.map_err(|error| anyhow!("Couldn't run HKDF-Expand operation : {:?}", error))?;
output_key_material
.fill(&mut session_key)
.map_err(|error| {
anyhow!(
"Couldn't get the output of the HKDF-Expand operation: {:?}",
error
)
})?;
Ok(session_key)
}
}
/// Defines the type of key negotiator and the set of session keys created by it.
#[derive(Clone)]
pub enum KeyNegotiatorType {
/// Defines a key negotiator which provides server session key for encryption and client
/// session key for decryption.
Server,
/// Defines a key negotiator which provides client session key for encryption and server
/// session key for decryption.
Client,
}
pub struct Signer {
/// Parsed PKCS#8 v2 key pair representation.
key_pair: EcdsaKeyPair,
}
impl Signer {
pub fn create() -> anyhow::Result<Self> {
// TODO(#2557): Ensure SystemRandom work when building for x86_64 UEFI targets.
let rng = ring::rand::SystemRandom::new();
let key_pair_pkcs8 = EcdsaKeyPair::generate_pkcs8(SIGNING_ALGORITHM, &rng)
.map_err(|error| anyhow!("Couldn't generate PKCS#8 key pair: {:?}", error))?;
let key_pair = EcdsaKeyPair::from_pkcs8(SIGNING_ALGORITHM, key_pair_pkcs8.as_ref())
.map_err(|error| anyhow!("Couldn't parse generated key pair: {:?}", error))?;
Ok(Self { key_pair })
}
pub fn public_key(&self) -> anyhow::Result<[u8; SIGNING_ALGORITHM_KEY_LENGTH]> {
let public_key = self.key_pair.public_key().as_ref().to_vec();
public_key.as_slice().try_into().context(format!(
"Incorrect public key length, expected {}, found {}",
SIGNING_ALGORITHM_KEY_LENGTH,
public_key.len()
))
}
pub fn sign(&self, input: &[u8]) -> anyhow::Result<[u8; SIGNATURE_LENGTH]> {
let rng = ring::rand::SystemRandom::new();
let signature = self
.key_pair
.sign(&rng, input)
.map_err(|error| anyhow!("Couldn't sign input: {:?}", error))?
.as_ref()
.to_vec();
signature.as_slice().try_into().context(format!(
"Incorrect signature length, expected {}, found {}",
SIGNATURE_LENGTH,
signature.len()
))
}
}
pub struct SignatureVerifier {
public_key_bytes: [u8; SIGNING_ALGORITHM_KEY_LENGTH],
}
impl SignatureVerifier {
pub fn new(public_key_bytes: &[u8; SIGNING_ALGORITHM_KEY_LENGTH]) -> Self {
Self {
public_key_bytes: *public_key_bytes,
}
}
/// Verifies the signature validity.
pub fn verify(&self, input: &[u8], signature: &[u8; SIGNATURE_LENGTH]) -> anyhow::Result<()> {
let public_key =
ring::signature::UnparsedPublicKey::new(VERIFICATION_ALGORITHM, &self.public_key_bytes);
public_key
.verify(input, signature)
.map_err(|error| anyhow!("Signature verification failed: {:?}", error))?;
Ok(())
}
}
/// Computes a SHA-256 digest of `input` and returns it in a form of raw bytes.
pub fn get_sha256(input: &[u8]) -> [u8; SHA256_HASH_LENGTH] {
digest(&SHA256, input)
.as_ref()
.try_into()
.expect("Incorrect SHA-256 hash length")
}
/// Generates a random vector of `size` bytes.
pub fn get_random<const L: usize>() -> anyhow::Result<[u8; L]> {
let mut result: [u8; L] = [Default::default(); L];
let rng = SystemRandom::new();
rng.fill(&mut result[..])
.map_err(|error| anyhow!("Couldn't create random value: {:?}", error))?;
Ok(result)
}
|
/// Convenience struct for passing an encryption key as an argument.
#[derive(PartialEq)]
pub(crate) struct EncryptionKey(pub(crate) [u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]);
/// Convenience struct for passing a decryption key as an argument.
|
random_line_split
|
crypto.rs
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Crypto primitives used by the remote attestation protocol.
//
// Should be kept in sync with the Java implementation of the remote attestation
// protocol.
use crate::message::EncryptedData;
use alloc::{format, vec, vec::Vec};
use anyhow::{anyhow, Context};
use core::convert::TryInto;
use ring::{
aead::{self, BoundKey},
agreement,
digest::{digest, SHA256},
hkdf::{Salt, HKDF_SHA256},
rand::{SecureRandom, SystemRandom},
signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, EcdsaVerificationAlgorithm, KeyPair},
};
/// Length of the encryption nonce.
/// `ring::aead` uses 96-bit (12-byte) nonces.
/// <https://briansmith.org/rustdoc/ring/aead/constant.NONCE_LEN.html>
pub const NONCE_LENGTH: usize = aead::NONCE_LEN;
pub const SHA256_HASH_LENGTH: usize = 32;
/// Algorithm used for encrypting/decrypting messages.
/// <https://datatracker.ietf.org/doc/html/rfc5288>
static AEAD_ALGORITHM: &aead::Algorithm = &aead::AES_256_GCM;
pub const AEAD_ALGORITHM_KEY_LENGTH: usize = 32;
/// Algorithm used for negotiating a session key.
/// <https://datatracker.ietf.org/doc/html/rfc7748>
static KEY_AGREEMENT_ALGORITHM: &agreement::Algorithm = &agreement::X25519;
pub const KEY_AGREEMENT_ALGORITHM_KEY_LENGTH: usize = 32;
/// Salt used for key derivation with HKDF.
/// <https://datatracker.ietf.org/doc/html/rfc5869>
pub const KEY_DERIVATION_SALT: &str = "Remote Attestation Protocol v1";
/// Purpose string used for deriving server session keys with HKDF.
pub const SERVER_KEY_PURPOSE: &str = "Remote Attestation Protocol Server Session Key";
/// Purpose string used for deriving client session keys with HKDF.
pub const CLIENT_KEY_PURPOSE: &str = "Remote Attestation Protocol Client Session Key";
/// Algorithm used to create cryptographic signatures.
static SIGNING_ALGORITHM: &EcdsaSigningAlgorithm =
&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING;
/// OpenSSL ECDSA-P256 key public key length, which is represented as
/// `0x04 | X: 32-byte | Y: 32-byte`.
/// Where X and Y are big-endian coordinates of an Elliptic Curve point.
/// <https://datatracker.ietf.org/doc/html/rfc6979>
pub const SIGNING_ALGORITHM_KEY_LENGTH: usize = 65;
// TODO(#2277): Use OpenSSL signature format (which is 72 bytes).
/// IEEE-P1363 encoded ECDSA-P256 signature length.
/// <https://datatracker.ietf.org/doc/html/rfc6979>
/// <https://standards.ieee.org/standard/1363-2000.html>
pub const SIGNATURE_LENGTH: usize = 64;
/// Algorithm used to verify cryptographic signatures.
static VERIFICATION_ALGORITHM: &EcdsaVerificationAlgorithm =
&ring::signature::ECDSA_P256_SHA256_FIXED;
/// Nonce implementation used by [`AeadEncryptor`].
/// It returns a single nonce once and then only returns errors.
struct OneNonceSequence(Option<aead::Nonce>);
impl OneNonceSequence {
fn new(nonce: [u8; NONCE_LENGTH]) -> Self {
let nonce = aead::Nonce::assume_unique_for_key(nonce);
Self(Some(nonce))
}
}
impl aead::NonceSequence for OneNonceSequence {
fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
self.0.take().ok_or(ring::error::Unspecified)
}
}
/// Convenience struct for passing an encryption key as an argument.
#[derive(PartialEq)]
pub(crate) struct EncryptionKey(pub(crate) [u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]);
/// Convenience struct for passing a decryption key as an argument.
#[derive(PartialEq)]
pub(crate) struct DecryptionKey(pub(crate) [u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]);
/// Implementation of Authenticated Encryption with Associated Data (AEAD).
///
/// <https://datatracker.ietf.org/doc/html/rfc5116>
///
/// This implementation uses separate keys for encrypting data and decrypting peer encrypted data.
/// Which means that this implementation uses the same key for encryption, which peer uses for
/// decryption.
///
/// It is necessary to prevent the Loopback Attack, where malicious network takes an outgoing packet
/// and feeds it back as an incoming packet.
pub struct AeadEncryptor {
/// Key used for encrypting data.
encryption_key: EncryptionKey,
/// Key used for decrypting peer encrypted data.
decryption_key: DecryptionKey,
}
impl AeadEncryptor {
pub(crate) fn new(encryption_key: EncryptionKey, decryption_key: DecryptionKey) -> Self {
Self {
encryption_key,
decryption_key,
}
}
/// Encrypts `data` using `AeadEncryptor::encryption_key`.
pub fn encrypt(&mut self, data: &[u8]) -> anyhow::Result<EncryptedData> {
// Generate a random nonce.
let nonce = Self::generate_nonce().context("Couldn't generate nonce")?;
// Bind [`AeadEncryptor::key`] to a `nonce`.
let unbound_sealing_key = aead::UnboundKey::new(AEAD_ALGORITHM, &self.encryption_key.0)
.map_err(|error| anyhow!("Couldn't create sealing key: {:?}", error))?;
let mut sealing_key =
ring::aead::SealingKey::new(unbound_sealing_key, OneNonceSequence::new(nonce));
let mut encrypted_data = data.to_vec();
sealing_key
// Additional authenticated data is not required for the remotely attested channel,
// since after session key is established client and server exchange messages with a
// single encrypted field.
// And the nonce is authenticated by the AEAD algorithm itself.
// https://datatracker.ietf.org/doc/html/rfc5116#section-2.1
.seal_in_place_append_tag(aead::Aad::empty(), &mut encrypted_data)
.map_err(|error| anyhow!("Couldn't encrypt data: {:?}", error))?;
Ok(EncryptedData::new(nonce, encrypted_data))
}
/// Decrypts and authenticates `data` using `AeadEncryptor::decryption_key`.
/// `data` must contain an encrypted message prefixed with a random nonce of [`NONCE_LENGTH`]
/// length.
pub fn decrypt(&mut self, data: &EncryptedData) -> anyhow::Result<Vec<u8>> {
// Bind `AeadEncryptor::key` to the extracted `nonce`.
let unbound_opening_key =
aead::UnboundKey::new(AEAD_ALGORITHM, &self.decryption_key.0).unwrap();
let mut opening_key =
ring::aead::OpeningKey::new(unbound_opening_key, OneNonceSequence::new(data.nonce));
let mut decrypted_data = data.data.to_vec();
let decrypted_data = opening_key
// Additional authenticated data is not required for the remotely attested channel,
// since after session key is established client and server exchange messages with a
// single encrypted field.
// And the nonce is authenticated by the AEAD algorithm itself.
// https://datatracker.ietf.org/doc/html/rfc5116#section-2.1
.open_in_place(aead::Aad::empty(), &mut decrypted_data)
.map_err(|error| anyhow!("Couldn't decrypt data: {:?}", error))?;
Ok(decrypted_data.to_vec())
}
/// Generate a random nonce.
fn generate_nonce() -> anyhow::Result<[u8; NONCE_LENGTH]> {
get_random()
}
}
/// Implementation of the X25519 Elliptic Curve Diffie-Hellman (ECDH) key negotiation.
///
/// <https://datatracker.ietf.org/doc/html/rfc7748#section-6.1>
pub struct KeyNegotiator {
type_: KeyNegotiatorType,
private_key: agreement::EphemeralPrivateKey,
}
impl KeyNegotiator {
pub fn create(type_: KeyNegotiatorType) -> anyhow::Result<Self> {
let rng = ring::rand::SystemRandom::new();
let private_key = agreement::EphemeralPrivateKey::generate(KEY_AGREEMENT_ALGORITHM, &rng)
.map_err(|error| anyhow!("Couldn't generate private key: {:?}", error))?;
Ok(Self { type_, private_key })
}
pub fn public_key(&self) -> anyhow::Result<[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]> {
let public_key = self
.private_key
.compute_public_key()
.map_err(|error| anyhow!("Couldn't get public key: {:?}", error))?
.as_ref()
.to_vec();
public_key.as_slice().try_into().context(format!(
"Incorrect public key length, expected {}, found {}",
KEY_AGREEMENT_ALGORITHM_KEY_LENGTH,
public_key.len()
))
}
/// Derives session keys from self and peer public keys and creates an [`AeadEncryptor`].
///
/// HKDF is used to derive both server and client session keys. The information string provided
/// to HKDF consists of a purpose string, a server public key and a client public key (in that
/// specific order).
/// Server session key uses the [`SERVER_KEY_PURPOSE`] purpose string and client session key
/// uses [`CLIENT_KEY_PURPOSE`].
///
/// Depending on `encryptor_type` creates a different type of encryptor: either server encryptor
/// or client encryptor.
pub fn create_encryptor(
self,
peer_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<AeadEncryptor> {
let (encryption_key, decryption_key) = self
.derive_session_keys(peer_public_key)
.context("Couldn't derive session keys")?;
let encryptor = AeadEncryptor::new(encryption_key, decryption_key);
Ok(encryptor)
}
/// Implementation of the session keys derivation.
/// Returns a tuple with an encryption key and a decryption key.
pub(crate) fn derive_session_keys(
self,
peer_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<(EncryptionKey, DecryptionKey)> {
let type_ = self.type_.clone();
let self_public_key = self.public_key().context("Couldn't get self public key")?;
let (encryption_key, decryption_key) = agreement::agree_ephemeral(
self.private_key,
&agreement::UnparsedPublicKey::new(KEY_AGREEMENT_ALGORITHM, peer_public_key),
anyhow!("Couldn't derive session keys"),
|key_material| {
let key_material = key_material.try_into().context(format!(
"Incorrect key material length, expected {}, found {}",
KEY_AGREEMENT_ALGORITHM_KEY_LENGTH,
key_material.len()
))?;
let peer_public_key = *peer_public_key;
match type_ {
// On the server side `self_public_key` is the server key.
KeyNegotiatorType::Server => {
let encryption_key = Self::key_derivation_function(
key_material,
SERVER_KEY_PURPOSE,
&self_public_key,
&peer_public_key,
);
let decryption_key = Self::key_derivation_function(
key_material,
CLIENT_KEY_PURPOSE,
&self_public_key,
&peer_public_key,
);
Ok((encryption_key, decryption_key))
}
// On the client side `peer_public_key` is the server key.
KeyNegotiatorType::Client => {
let encryption_key = Self::key_derivation_function(
key_material,
CLIENT_KEY_PURPOSE,
&peer_public_key,
&self_public_key,
);
let decryption_key = Self::key_derivation_function(
key_material,
SERVER_KEY_PURPOSE,
&peer_public_key,
&self_public_key,
);
Ok((encryption_key, decryption_key))
}
}
},
)
.context("Couldn't agree on session keys")?;
Ok((
EncryptionKey(encryption_key.context("Couldn't derive encryption key")?),
DecryptionKey(decryption_key.context("Couldn't derive decryption key")?),
))
}
/// Derives a session key from `key_material` using HKDF.
///
/// <https://datatracker.ietf.org/doc/html/rfc5869>
///
/// <https://datatracker.ietf.org/doc/html/rfc7748#section-6.1>
///
/// In order to derive keys, uses the information string that consists of a purpose string, a
/// server public key and a client public key (in that specific order).
pub(crate) fn key_derivation_function(
key_material: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
key_purpose: &str,
server_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
client_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<[u8; AEAD_ALGORITHM_KEY_LENGTH]> {
// Session key is derived from a purpose string and two public keys.
let info = vec![key_purpose.as_bytes(), server_public_key, client_public_key];
// Initialize key derivation function.
let salt = Salt::new(HKDF_SHA256, KEY_DERIVATION_SALT.as_bytes());
let kdf = salt.extract(key_material);
// Derive session key.
let mut session_key: [u8; AEAD_ALGORITHM_KEY_LENGTH] = Default::default();
let output_key_material = kdf
.expand(&info, AEAD_ALGORITHM)
.map_err(|error| anyhow!("Couldn't run HKDF-Expand operation : {:?}", error))?;
output_key_material
.fill(&mut session_key)
.map_err(|error| {
anyhow!(
"Couldn't get the output of the HKDF-Expand operation: {:?}",
error
)
})?;
Ok(session_key)
}
}
/// Defines the type of key negotiator and the set of session keys created by it.
#[derive(Clone)]
pub enum KeyNegotiatorType {
/// Defines a key negotiator which provides server session key for encryption and client
/// session key for decryption.
Server,
/// Defines a key negotiator which provides client session key for encryption and server
/// session key for decryption.
Client,
}
pub struct Signer {
/// Parsed PKCS#8 v2 key pair representation.
key_pair: EcdsaKeyPair,
}
impl Signer {
pub fn create() -> anyhow::Result<Self> {
// TODO(#2557): Ensure SystemRandom work when building for x86_64 UEFI targets.
let rng = ring::rand::SystemRandom::new();
let key_pair_pkcs8 = EcdsaKeyPair::generate_pkcs8(SIGNING_ALGORITHM, &rng)
.map_err(|error| anyhow!("Couldn't generate PKCS#8 key pair: {:?}", error))?;
let key_pair = EcdsaKeyPair::from_pkcs8(SIGNING_ALGORITHM, key_pair_pkcs8.as_ref())
.map_err(|error| anyhow!("Couldn't parse generated key pair: {:?}", error))?;
Ok(Self { key_pair })
}
pub fn public_key(&self) -> anyhow::Result<[u8; SIGNING_ALGORITHM_KEY_LENGTH]> {
let public_key = self.key_pair.public_key().as_ref().to_vec();
public_key.as_slice().try_into().context(format!(
"Incorrect public key length, expected {}, found {}",
SIGNING_ALGORITHM_KEY_LENGTH,
public_key.len()
))
}
pub fn sign(&self, input: &[u8]) -> anyhow::Result<[u8; SIGNATURE_LENGTH]> {
let rng = ring::rand::SystemRandom::new();
let signature = self
.key_pair
.sign(&rng, input)
.map_err(|error| anyhow!("Couldn't sign input: {:?}", error))?
.as_ref()
.to_vec();
signature.as_slice().try_into().context(format!(
"Incorrect signature length, expected {}, found {}",
SIGNATURE_LENGTH,
signature.len()
))
}
}
pub struct SignatureVerifier {
public_key_bytes: [u8; SIGNING_ALGORITHM_KEY_LENGTH],
}
impl SignatureVerifier {
pub fn new(public_key_bytes: &[u8; SIGNING_ALGORITHM_KEY_LENGTH]) -> Self {
Self {
public_key_bytes: *public_key_bytes,
}
}
/// Verifies the signature validity.
pub fn verify(&self, input: &[u8], signature: &[u8; SIGNATURE_LENGTH]) -> anyhow::Result<()> {
let public_key =
ring::signature::UnparsedPublicKey::new(VERIFICATION_ALGORITHM, &self.public_key_bytes);
public_key
.verify(input, signature)
.map_err(|error| anyhow!("Signature verification failed: {:?}", error))?;
Ok(())
}
}
/// Computes a SHA-256 digest of `input` and returns it in a form of raw bytes.
pub fn get_sha256(input: &[u8]) -> [u8; SHA256_HASH_LENGTH] {
digest(&SHA256, input)
.as_ref()
.try_into()
.expect("Incorrect SHA-256 hash length")
}
/// Generates a random vector of `size` bytes.
pub fn
|
<const L: usize>() -> anyhow::Result<[u8; L]> {
let mut result: [u8; L] = [Default::default(); L];
let rng = SystemRandom::new();
rng.fill(&mut result[..])
.map_err(|error| anyhow!("Couldn't create random value: {:?}", error))?;
Ok(result)
}
|
get_random
|
identifier_name
|
crypto.rs
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Crypto primitives used by the remote attestation protocol.
//
// Should be kept in sync with the Java implementation of the remote attestation
// protocol.
use crate::message::EncryptedData;
use alloc::{format, vec, vec::Vec};
use anyhow::{anyhow, Context};
use core::convert::TryInto;
use ring::{
aead::{self, BoundKey},
agreement,
digest::{digest, SHA256},
hkdf::{Salt, HKDF_SHA256},
rand::{SecureRandom, SystemRandom},
signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, EcdsaVerificationAlgorithm, KeyPair},
};
/// Length of the encryption nonce.
/// `ring::aead` uses 96-bit (12-byte) nonces.
/// <https://briansmith.org/rustdoc/ring/aead/constant.NONCE_LEN.html>
pub const NONCE_LENGTH: usize = aead::NONCE_LEN;
pub const SHA256_HASH_LENGTH: usize = 32;
/// Algorithm used for encrypting/decrypting messages.
/// <https://datatracker.ietf.org/doc/html/rfc5288>
static AEAD_ALGORITHM: &aead::Algorithm = &aead::AES_256_GCM;
pub const AEAD_ALGORITHM_KEY_LENGTH: usize = 32;
/// Algorithm used for negotiating a session key.
/// <https://datatracker.ietf.org/doc/html/rfc7748>
static KEY_AGREEMENT_ALGORITHM: &agreement::Algorithm = &agreement::X25519;
pub const KEY_AGREEMENT_ALGORITHM_KEY_LENGTH: usize = 32;
/// Salt used for key derivation with HKDF.
/// <https://datatracker.ietf.org/doc/html/rfc5869>
pub const KEY_DERIVATION_SALT: &str = "Remote Attestation Protocol v1";
/// Purpose string used for deriving server session keys with HKDF.
pub const SERVER_KEY_PURPOSE: &str = "Remote Attestation Protocol Server Session Key";
/// Purpose string used for deriving client session keys with HKDF.
pub const CLIENT_KEY_PURPOSE: &str = "Remote Attestation Protocol Client Session Key";
/// Algorithm used to create cryptographic signatures.
static SIGNING_ALGORITHM: &EcdsaSigningAlgorithm =
&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING;
/// OpenSSL ECDSA-P256 key public key length, which is represented as
/// `0x04 | X: 32-byte | Y: 32-byte`.
/// Where X and Y are big-endian coordinates of an Elliptic Curve point.
/// <https://datatracker.ietf.org/doc/html/rfc6979>
pub const SIGNING_ALGORITHM_KEY_LENGTH: usize = 65;
// TODO(#2277): Use OpenSSL signature format (which is 72 bytes).
/// IEEE-P1363 encoded ECDSA-P256 signature length.
/// <https://datatracker.ietf.org/doc/html/rfc6979>
/// <https://standards.ieee.org/standard/1363-2000.html>
pub const SIGNATURE_LENGTH: usize = 64;
/// Algorithm used to verify cryptographic signatures.
static VERIFICATION_ALGORITHM: &EcdsaVerificationAlgorithm =
&ring::signature::ECDSA_P256_SHA256_FIXED;
/// Nonce implementation used by [`AeadEncryptor`].
/// It returns a single nonce once and then only returns errors.
struct OneNonceSequence(Option<aead::Nonce>);
impl OneNonceSequence {
fn new(nonce: [u8; NONCE_LENGTH]) -> Self {
let nonce = aead::Nonce::assume_unique_for_key(nonce);
Self(Some(nonce))
}
}
impl aead::NonceSequence for OneNonceSequence {
fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
self.0.take().ok_or(ring::error::Unspecified)
}
}
/// Convenience struct for passing an encryption key as an argument.
#[derive(PartialEq)]
pub(crate) struct EncryptionKey(pub(crate) [u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]);
/// Convenience struct for passing a decryption key as an argument.
#[derive(PartialEq)]
pub(crate) struct DecryptionKey(pub(crate) [u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]);
/// Implementation of Authenticated Encryption with Associated Data (AEAD).
///
/// <https://datatracker.ietf.org/doc/html/rfc5116>
///
/// This implementation uses separate keys for encrypting data and decrypting peer encrypted data.
/// Which means that this implementation uses the same key for encryption, which peer uses for
/// decryption.
///
/// It is necessary to prevent the Loopback Attack, where malicious network takes an outgoing packet
/// and feeds it back as an incoming packet.
pub struct AeadEncryptor {
/// Key used for encrypting data.
encryption_key: EncryptionKey,
/// Key used for decrypting peer encrypted data.
decryption_key: DecryptionKey,
}
impl AeadEncryptor {
pub(crate) fn new(encryption_key: EncryptionKey, decryption_key: DecryptionKey) -> Self {
Self {
encryption_key,
decryption_key,
}
}
/// Encrypts `data` using `AeadEncryptor::encryption_key`.
pub fn encrypt(&mut self, data: &[u8]) -> anyhow::Result<EncryptedData> {
// Generate a random nonce.
let nonce = Self::generate_nonce().context("Couldn't generate nonce")?;
// Bind [`AeadEncryptor::key`] to a `nonce`.
let unbound_sealing_key = aead::UnboundKey::new(AEAD_ALGORITHM, &self.encryption_key.0)
.map_err(|error| anyhow!("Couldn't create sealing key: {:?}", error))?;
let mut sealing_key =
ring::aead::SealingKey::new(unbound_sealing_key, OneNonceSequence::new(nonce));
let mut encrypted_data = data.to_vec();
sealing_key
// Additional authenticated data is not required for the remotely attested channel,
// since after session key is established client and server exchange messages with a
// single encrypted field.
// And the nonce is authenticated by the AEAD algorithm itself.
// https://datatracker.ietf.org/doc/html/rfc5116#section-2.1
.seal_in_place_append_tag(aead::Aad::empty(), &mut encrypted_data)
.map_err(|error| anyhow!("Couldn't encrypt data: {:?}", error))?;
Ok(EncryptedData::new(nonce, encrypted_data))
}
/// Decrypts and authenticates `data` using `AeadEncryptor::decryption_key`.
/// `data` must contain an encrypted message prefixed with a random nonce of [`NONCE_LENGTH`]
/// length.
pub fn decrypt(&mut self, data: &EncryptedData) -> anyhow::Result<Vec<u8>> {
// Bind `AeadEncryptor::key` to the extracted `nonce`.
let unbound_opening_key =
aead::UnboundKey::new(AEAD_ALGORITHM, &self.decryption_key.0).unwrap();
let mut opening_key =
ring::aead::OpeningKey::new(unbound_opening_key, OneNonceSequence::new(data.nonce));
let mut decrypted_data = data.data.to_vec();
let decrypted_data = opening_key
// Additional authenticated data is not required for the remotely attested channel,
// since after session key is established client and server exchange messages with a
// single encrypted field.
// And the nonce is authenticated by the AEAD algorithm itself.
// https://datatracker.ietf.org/doc/html/rfc5116#section-2.1
.open_in_place(aead::Aad::empty(), &mut decrypted_data)
.map_err(|error| anyhow!("Couldn't decrypt data: {:?}", error))?;
Ok(decrypted_data.to_vec())
}
/// Generate a random nonce.
fn generate_nonce() -> anyhow::Result<[u8; NONCE_LENGTH]> {
get_random()
}
}
/// Implementation of the X25519 Elliptic Curve Diffie-Hellman (ECDH) key negotiation.
///
/// <https://datatracker.ietf.org/doc/html/rfc7748#section-6.1>
pub struct KeyNegotiator {
type_: KeyNegotiatorType,
private_key: agreement::EphemeralPrivateKey,
}
impl KeyNegotiator {
pub fn create(type_: KeyNegotiatorType) -> anyhow::Result<Self> {
let rng = ring::rand::SystemRandom::new();
let private_key = agreement::EphemeralPrivateKey::generate(KEY_AGREEMENT_ALGORITHM, &rng)
.map_err(|error| anyhow!("Couldn't generate private key: {:?}", error))?;
Ok(Self { type_, private_key })
}
pub fn public_key(&self) -> anyhow::Result<[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]> {
let public_key = self
.private_key
.compute_public_key()
.map_err(|error| anyhow!("Couldn't get public key: {:?}", error))?
.as_ref()
.to_vec();
public_key.as_slice().try_into().context(format!(
"Incorrect public key length, expected {}, found {}",
KEY_AGREEMENT_ALGORITHM_KEY_LENGTH,
public_key.len()
))
}
/// Derives session keys from self and peer public keys and creates an [`AeadEncryptor`].
///
/// HKDF is used to derive both server and client session keys. The information string provided
/// to HKDF consists of a purpose string, a server public key and a client public key (in that
/// specific order).
/// Server session key uses the [`SERVER_KEY_PURPOSE`] purpose string and client session key
/// uses [`CLIENT_KEY_PURPOSE`].
///
/// Depending on `encryptor_type` creates a different type of encryptor: either server encryptor
/// or client encryptor.
pub fn create_encryptor(
self,
peer_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<AeadEncryptor> {
let (encryption_key, decryption_key) = self
.derive_session_keys(peer_public_key)
.context("Couldn't derive session keys")?;
let encryptor = AeadEncryptor::new(encryption_key, decryption_key);
Ok(encryptor)
}
/// Implementation of the session keys derivation.
/// Returns a tuple with an encryption key and a decryption key.
pub(crate) fn derive_session_keys(
self,
peer_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<(EncryptionKey, DecryptionKey)> {
let type_ = self.type_.clone();
let self_public_key = self.public_key().context("Couldn't get self public key")?;
let (encryption_key, decryption_key) = agreement::agree_ephemeral(
self.private_key,
&agreement::UnparsedPublicKey::new(KEY_AGREEMENT_ALGORITHM, peer_public_key),
anyhow!("Couldn't derive session keys"),
|key_material| {
let key_material = key_material.try_into().context(format!(
"Incorrect key material length, expected {}, found {}",
KEY_AGREEMENT_ALGORITHM_KEY_LENGTH,
key_material.len()
))?;
let peer_public_key = *peer_public_key;
match type_ {
// On the server side `self_public_key` is the server key.
KeyNegotiatorType::Server => {
let encryption_key = Self::key_derivation_function(
key_material,
SERVER_KEY_PURPOSE,
&self_public_key,
&peer_public_key,
);
let decryption_key = Self::key_derivation_function(
key_material,
CLIENT_KEY_PURPOSE,
&self_public_key,
&peer_public_key,
);
Ok((encryption_key, decryption_key))
}
// On the client side `peer_public_key` is the server key.
KeyNegotiatorType::Client =>
|
}
},
)
.context("Couldn't agree on session keys")?;
Ok((
EncryptionKey(encryption_key.context("Couldn't derive encryption key")?),
DecryptionKey(decryption_key.context("Couldn't derive decryption key")?),
))
}
/// Derives a session key from `key_material` using HKDF.
///
/// <https://datatracker.ietf.org/doc/html/rfc5869>
///
/// <https://datatracker.ietf.org/doc/html/rfc7748#section-6.1>
///
/// In order to derive keys, uses the information string that consists of a purpose string, a
/// server public key and a client public key (in that specific order).
pub(crate) fn key_derivation_function(
key_material: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
key_purpose: &str,
server_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
client_public_key: &[u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH],
) -> anyhow::Result<[u8; AEAD_ALGORITHM_KEY_LENGTH]> {
// Session key is derived from a purpose string and two public keys.
let info = vec![key_purpose.as_bytes(), server_public_key, client_public_key];
// Initialize key derivation function.
let salt = Salt::new(HKDF_SHA256, KEY_DERIVATION_SALT.as_bytes());
let kdf = salt.extract(key_material);
// Derive session key.
let mut session_key: [u8; AEAD_ALGORITHM_KEY_LENGTH] = Default::default();
let output_key_material = kdf
.expand(&info, AEAD_ALGORITHM)
.map_err(|error| anyhow!("Couldn't run HKDF-Expand operation : {:?}", error))?;
output_key_material
.fill(&mut session_key)
.map_err(|error| {
anyhow!(
"Couldn't get the output of the HKDF-Expand operation: {:?}",
error
)
})?;
Ok(session_key)
}
}
/// Defines the type of key negotiator and the set of session keys created by it.
#[derive(Clone)]
pub enum KeyNegotiatorType {
/// Defines a key negotiator which provides server session key for encryption and client
/// session key for decryption.
Server,
/// Defines a key negotiator which provides client session key for encryption and server
/// session key for decryption.
Client,
}
pub struct Signer {
/// Parsed PKCS#8 v2 key pair representation.
key_pair: EcdsaKeyPair,
}
impl Signer {
pub fn create() -> anyhow::Result<Self> {
// TODO(#2557): Ensure SystemRandom work when building for x86_64 UEFI targets.
let rng = ring::rand::SystemRandom::new();
let key_pair_pkcs8 = EcdsaKeyPair::generate_pkcs8(SIGNING_ALGORITHM, &rng)
.map_err(|error| anyhow!("Couldn't generate PKCS#8 key pair: {:?}", error))?;
let key_pair = EcdsaKeyPair::from_pkcs8(SIGNING_ALGORITHM, key_pair_pkcs8.as_ref())
.map_err(|error| anyhow!("Couldn't parse generated key pair: {:?}", error))?;
Ok(Self { key_pair })
}
pub fn public_key(&self) -> anyhow::Result<[u8; SIGNING_ALGORITHM_KEY_LENGTH]> {
let public_key = self.key_pair.public_key().as_ref().to_vec();
public_key.as_slice().try_into().context(format!(
"Incorrect public key length, expected {}, found {}",
SIGNING_ALGORITHM_KEY_LENGTH,
public_key.len()
))
}
pub fn sign(&self, input: &[u8]) -> anyhow::Result<[u8; SIGNATURE_LENGTH]> {
let rng = ring::rand::SystemRandom::new();
let signature = self
.key_pair
.sign(&rng, input)
.map_err(|error| anyhow!("Couldn't sign input: {:?}", error))?
.as_ref()
.to_vec();
signature.as_slice().try_into().context(format!(
"Incorrect signature length, expected {}, found {}",
SIGNATURE_LENGTH,
signature.len()
))
}
}
pub struct SignatureVerifier {
public_key_bytes: [u8; SIGNING_ALGORITHM_KEY_LENGTH],
}
impl SignatureVerifier {
pub fn new(public_key_bytes: &[u8; SIGNING_ALGORITHM_KEY_LENGTH]) -> Self {
Self {
public_key_bytes: *public_key_bytes,
}
}
/// Verifies the signature validity.
pub fn verify(&self, input: &[u8], signature: &[u8; SIGNATURE_LENGTH]) -> anyhow::Result<()> {
let public_key =
ring::signature::UnparsedPublicKey::new(VERIFICATION_ALGORITHM, &self.public_key_bytes);
public_key
.verify(input, signature)
.map_err(|error| anyhow!("Signature verification failed: {:?}", error))?;
Ok(())
}
}
/// Computes a SHA-256 digest of `input` and returns it in a form of raw bytes.
pub fn get_sha256(input: &[u8]) -> [u8; SHA256_HASH_LENGTH] {
digest(&SHA256, input)
.as_ref()
.try_into()
.expect("Incorrect SHA-256 hash length")
}
/// Generates a random vector of `size` bytes.
pub fn get_random<const L: usize>() -> anyhow::Result<[u8; L]> {
let mut result: [u8; L] = [Default::default(); L];
let rng = SystemRandom::new();
rng.fill(&mut result[..])
.map_err(|error| anyhow!("Couldn't create random value: {:?}", error))?;
Ok(result)
}
|
{
let encryption_key = Self::key_derivation_function(
key_material,
CLIENT_KEY_PURPOSE,
&peer_public_key,
&self_public_key,
);
let decryption_key = Self::key_derivation_function(
key_material,
SERVER_KEY_PURPOSE,
&peer_public_key,
&self_public_key,
);
Ok((encryption_key, decryption_key))
}
|
conditional_block
|
u512.rs
|
//! Unsigned 512-bit integer
use std::convert::{From, Into};
use std::ops::{Add, Sub, Mul, Div, Shr, Shl, BitAnd, Rem};
use std::cmp::Ordering;
use std::fmt;
use super::U256;
use super::algorithms::{add2, mac3, from_signed, sub2_sign};
#[repr(C)]
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
/// Represents an unsigned 512-bit integer.
pub struct U512([u32; 16]);
impl U512 {
/// Bits needed to represent this value.
pub fn bits(&self) -> usize {
let &U512(ref arr) = self;
let mut current_bits = 0;
for i in (0..16).rev() {
if arr[i] == 0 {
continue;
}
current_bits = (32 - arr[i].leading_zeros() as usize) + ((15 - i) * 32);
}
current_bits
}
/// Zero value of U512.
pub fn zero() -> U512 {
U512([0u32; 16])
}
}
impl From<U256> for U512 {
fn from(val: U256) -> U512 {
let mut ret = [0u32; 16];
let val: [u32; 8] = val.into();
for i in 0..8 {
ret[8 + i] = val[i];
}
U512(ret)
}
}
impl Into<U256> for U512 {
fn into(self) -> U256 {
assert!(self.0[0..8].iter().all(|s| *s == 0));
let mut ret = [0u32; 8];
for i in 0..8 {
ret[i] = self.0[8 + i];
}
ret.into()
}
}
impl Ord for U512 {
fn cmp(&self, other: &U512) -> Ordering {
let &U512(ref me) = self;
let &U512(ref you) = other;
let mut i = 0;
while i < 16 {
if me[i] < you[i] { return Ordering::Less; }
if me[i] > you[i] { return Ordering::Greater; }
i += 1;
}
Ordering::Equal
}
}
impl PartialOrd for U512 {
fn partial_cmp(&self, other: &U512) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl BitAnd<U512> for U512 {
type Output = U512;
fn bitand(self, other: U512) -> U512 {
let mut r: U512 = self;
for i in 0..16 {
r.0[i] = r.0[i] & other.0[i];
}
r
}
}
impl Shl<usize> for U512 {
type Output = U512;
fn shl(self, shift: usize) -> U512 {
let U512(ref original) = self;
let mut ret = [0u32; 16];
let word_shift = shift / 32;
let bit_shift = shift % 32;
for i in (0..16).rev() {
// Shift
if i >= word_shift {
ret[i - word_shift] += original[i] << bit_shift;
}
// Carry
if bit_shift > 0 && i >= word_shift + 1 {
ret[i - word_shift - 1] += original[i] >> (32 - bit_shift);
}
}
U512(ret)
}
}
impl Shr<usize> for U512 {
type Output = U512;
fn shr(self, shift: usize) -> U512 {
let U512(ref original) = self;
let mut ret = [0u32; 16];
let word_shift = shift / 32;
let bit_shift = shift % 32;
for i in (0..16).rev() {
// Shift
if i + word_shift < 16 {
ret[i + word_shift] += original[i] >> bit_shift;
}
// Carry
if bit_shift > 0 && i > 0 && i + word_shift < 16 {
ret[i + word_shift] += original[i - 1] << (32 - bit_shift);
}
}
U512(ret)
}
}
impl Add for U512 {
type Output = U512;
fn
|
(mut self, other: U512) -> U512 {
let U512(ref mut a) = self;
let U512(ref b) = other;
let carry = add2(a, b);
assert!(carry == 0);
U512(*a)
}
}
impl Sub for U512 {
type Output = U512;
fn sub(mut self, other: U512) -> U512 {
let U512(ref mut a) = self;
let U512(ref b) = other;
let sign = sub2_sign(a, b);
from_signed(sign, a);
U512(*a)
}
}
impl Mul for U512 {
type Output = U512;
fn mul(mut self, other: U512) -> U512 {
let mut ret = [0u32; 16];
let U512(ref mut a) = self;
let U512(ref b) = other;
let mut carry = 0;
for (i, bi) in b.iter().rev().enumerate() {
carry = mac3(&mut ret[0..(16-i)], a, *bi);
}
assert!(carry == 0);
U512(ret)
}
}
impl Div for U512 {
type Output = U512;
fn div(self, other: U512) -> U512 {
let mut sub_copy = self;
let mut shift_copy = other;
let mut ret = [0u32; 16];
let my_bits = self.bits();
let your_bits = other.bits();
// Check for division by 0
assert!(your_bits!= 0);
// Early return in case we are dividing by a larger number than us
if my_bits < your_bits {
return U512(ret);
}
// Bitwise long division
let mut shift = my_bits - your_bits;
shift_copy = shift_copy << shift;
loop {
if sub_copy >= shift_copy {
ret[15 - shift / 32] |= 1 << (shift % 32);
sub_copy = sub_copy - shift_copy;
}
shift_copy = shift_copy >> 1;
if shift == 0 { break; }
shift -= 1;
}
U512(ret)
}
}
impl Rem for U512 {
type Output = U512;
fn rem(self, other: U512) -> U512 {
let d = self / other;
self - (other * d)
}
}
impl fmt::LowerHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..16 {
write!(f, "{:08x}", self.0[i])?;
}
Ok(())
}
}
impl fmt::UpperHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..16 {
write!(f, "{:08X}", self.0[i])?;
}
Ok(())
}
}
|
add
|
identifier_name
|
u512.rs
|
//! Unsigned 512-bit integer
use std::convert::{From, Into};
use std::ops::{Add, Sub, Mul, Div, Shr, Shl, BitAnd, Rem};
use std::cmp::Ordering;
use std::fmt;
use super::U256;
use super::algorithms::{add2, mac3, from_signed, sub2_sign};
#[repr(C)]
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
/// Represents an unsigned 512-bit integer.
pub struct U512([u32; 16]);
impl U512 {
/// Bits needed to represent this value.
pub fn bits(&self) -> usize {
let &U512(ref arr) = self;
let mut current_bits = 0;
for i in (0..16).rev() {
if arr[i] == 0 {
continue;
}
current_bits = (32 - arr[i].leading_zeros() as usize) + ((15 - i) * 32);
}
current_bits
}
/// Zero value of U512.
pub fn zero() -> U512 {
U512([0u32; 16])
}
}
impl From<U256> for U512 {
fn from(val: U256) -> U512 {
let mut ret = [0u32; 16];
let val: [u32; 8] = val.into();
for i in 0..8 {
ret[8 + i] = val[i];
}
U512(ret)
}
}
impl Into<U256> for U512 {
fn into(self) -> U256 {
assert!(self.0[0..8].iter().all(|s| *s == 0));
let mut ret = [0u32; 8];
for i in 0..8 {
ret[i] = self.0[8 + i];
}
ret.into()
}
}
impl Ord for U512 {
fn cmp(&self, other: &U512) -> Ordering {
let &U512(ref me) = self;
let &U512(ref you) = other;
let mut i = 0;
while i < 16 {
if me[i] < you[i] { return Ordering::Less; }
if me[i] > you[i] { return Ordering::Greater; }
i += 1;
}
Ordering::Equal
}
}
impl PartialOrd for U512 {
fn partial_cmp(&self, other: &U512) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl BitAnd<U512> for U512 {
type Output = U512;
fn bitand(self, other: U512) -> U512 {
let mut r: U512 = self;
for i in 0..16 {
r.0[i] = r.0[i] & other.0[i];
}
r
}
}
impl Shl<usize> for U512 {
type Output = U512;
fn shl(self, shift: usize) -> U512 {
let U512(ref original) = self;
let mut ret = [0u32; 16];
let word_shift = shift / 32;
let bit_shift = shift % 32;
for i in (0..16).rev() {
// Shift
if i >= word_shift {
ret[i - word_shift] += original[i] << bit_shift;
}
// Carry
if bit_shift > 0 && i >= word_shift + 1 {
ret[i - word_shift - 1] += original[i] >> (32 - bit_shift);
}
}
U512(ret)
}
}
impl Shr<usize> for U512 {
type Output = U512;
fn shr(self, shift: usize) -> U512 {
let U512(ref original) = self;
let mut ret = [0u32; 16];
let word_shift = shift / 32;
let bit_shift = shift % 32;
for i in (0..16).rev() {
// Shift
if i + word_shift < 16 {
ret[i + word_shift] += original[i] >> bit_shift;
}
// Carry
if bit_shift > 0 && i > 0 && i + word_shift < 16 {
ret[i + word_shift] += original[i - 1] << (32 - bit_shift);
}
}
U512(ret)
}
}
impl Add for U512 {
type Output = U512;
fn add(mut self, other: U512) -> U512 {
let U512(ref mut a) = self;
let U512(ref b) = other;
let carry = add2(a, b);
assert!(carry == 0);
U512(*a)
}
}
impl Sub for U512 {
type Output = U512;
fn sub(mut self, other: U512) -> U512
|
}
impl Mul for U512 {
type Output = U512;
fn mul(mut self, other: U512) -> U512 {
let mut ret = [0u32; 16];
let U512(ref mut a) = self;
let U512(ref b) = other;
let mut carry = 0;
for (i, bi) in b.iter().rev().enumerate() {
carry = mac3(&mut ret[0..(16-i)], a, *bi);
}
assert!(carry == 0);
U512(ret)
}
}
impl Div for U512 {
type Output = U512;
fn div(self, other: U512) -> U512 {
let mut sub_copy = self;
let mut shift_copy = other;
let mut ret = [0u32; 16];
let my_bits = self.bits();
let your_bits = other.bits();
// Check for division by 0
assert!(your_bits!= 0);
// Early return in case we are dividing by a larger number than us
if my_bits < your_bits {
return U512(ret);
}
// Bitwise long division
let mut shift = my_bits - your_bits;
shift_copy = shift_copy << shift;
loop {
if sub_copy >= shift_copy {
ret[15 - shift / 32] |= 1 << (shift % 32);
sub_copy = sub_copy - shift_copy;
}
shift_copy = shift_copy >> 1;
if shift == 0 { break; }
shift -= 1;
}
U512(ret)
}
}
impl Rem for U512 {
type Output = U512;
fn rem(self, other: U512) -> U512 {
let d = self / other;
self - (other * d)
}
}
impl fmt::LowerHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..16 {
write!(f, "{:08x}", self.0[i])?;
}
Ok(())
}
}
impl fmt::UpperHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..16 {
write!(f, "{:08X}", self.0[i])?;
}
Ok(())
}
}
|
{
let U512(ref mut a) = self;
let U512(ref b) = other;
let sign = sub2_sign(a, b);
from_signed(sign, a);
U512(*a)
}
|
identifier_body
|
u512.rs
|
//! Unsigned 512-bit integer
use std::convert::{From, Into};
use std::ops::{Add, Sub, Mul, Div, Shr, Shl, BitAnd, Rem};
use std::cmp::Ordering;
use std::fmt;
use super::U256;
use super::algorithms::{add2, mac3, from_signed, sub2_sign};
#[repr(C)]
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
/// Represents an unsigned 512-bit integer.
pub struct U512([u32; 16]);
impl U512 {
/// Bits needed to represent this value.
pub fn bits(&self) -> usize {
let &U512(ref arr) = self;
let mut current_bits = 0;
for i in (0..16).rev() {
if arr[i] == 0 {
continue;
}
current_bits = (32 - arr[i].leading_zeros() as usize) + ((15 - i) * 32);
}
current_bits
|
U512([0u32; 16])
}
}
impl From<U256> for U512 {
fn from(val: U256) -> U512 {
let mut ret = [0u32; 16];
let val: [u32; 8] = val.into();
for i in 0..8 {
ret[8 + i] = val[i];
}
U512(ret)
}
}
impl Into<U256> for U512 {
fn into(self) -> U256 {
assert!(self.0[0..8].iter().all(|s| *s == 0));
let mut ret = [0u32; 8];
for i in 0..8 {
ret[i] = self.0[8 + i];
}
ret.into()
}
}
impl Ord for U512 {
fn cmp(&self, other: &U512) -> Ordering {
let &U512(ref me) = self;
let &U512(ref you) = other;
let mut i = 0;
while i < 16 {
if me[i] < you[i] { return Ordering::Less; }
if me[i] > you[i] { return Ordering::Greater; }
i += 1;
}
Ordering::Equal
}
}
impl PartialOrd for U512 {
fn partial_cmp(&self, other: &U512) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl BitAnd<U512> for U512 {
type Output = U512;
fn bitand(self, other: U512) -> U512 {
let mut r: U512 = self;
for i in 0..16 {
r.0[i] = r.0[i] & other.0[i];
}
r
}
}
impl Shl<usize> for U512 {
type Output = U512;
fn shl(self, shift: usize) -> U512 {
let U512(ref original) = self;
let mut ret = [0u32; 16];
let word_shift = shift / 32;
let bit_shift = shift % 32;
for i in (0..16).rev() {
// Shift
if i >= word_shift {
ret[i - word_shift] += original[i] << bit_shift;
}
// Carry
if bit_shift > 0 && i >= word_shift + 1 {
ret[i - word_shift - 1] += original[i] >> (32 - bit_shift);
}
}
U512(ret)
}
}
impl Shr<usize> for U512 {
type Output = U512;
fn shr(self, shift: usize) -> U512 {
let U512(ref original) = self;
let mut ret = [0u32; 16];
let word_shift = shift / 32;
let bit_shift = shift % 32;
for i in (0..16).rev() {
// Shift
if i + word_shift < 16 {
ret[i + word_shift] += original[i] >> bit_shift;
}
// Carry
if bit_shift > 0 && i > 0 && i + word_shift < 16 {
ret[i + word_shift] += original[i - 1] << (32 - bit_shift);
}
}
U512(ret)
}
}
impl Add for U512 {
type Output = U512;
fn add(mut self, other: U512) -> U512 {
let U512(ref mut a) = self;
let U512(ref b) = other;
let carry = add2(a, b);
assert!(carry == 0);
U512(*a)
}
}
impl Sub for U512 {
type Output = U512;
fn sub(mut self, other: U512) -> U512 {
let U512(ref mut a) = self;
let U512(ref b) = other;
let sign = sub2_sign(a, b);
from_signed(sign, a);
U512(*a)
}
}
impl Mul for U512 {
type Output = U512;
fn mul(mut self, other: U512) -> U512 {
let mut ret = [0u32; 16];
let U512(ref mut a) = self;
let U512(ref b) = other;
let mut carry = 0;
for (i, bi) in b.iter().rev().enumerate() {
carry = mac3(&mut ret[0..(16-i)], a, *bi);
}
assert!(carry == 0);
U512(ret)
}
}
impl Div for U512 {
type Output = U512;
fn div(self, other: U512) -> U512 {
let mut sub_copy = self;
let mut shift_copy = other;
let mut ret = [0u32; 16];
let my_bits = self.bits();
let your_bits = other.bits();
// Check for division by 0
assert!(your_bits!= 0);
// Early return in case we are dividing by a larger number than us
if my_bits < your_bits {
return U512(ret);
}
// Bitwise long division
let mut shift = my_bits - your_bits;
shift_copy = shift_copy << shift;
loop {
if sub_copy >= shift_copy {
ret[15 - shift / 32] |= 1 << (shift % 32);
sub_copy = sub_copy - shift_copy;
}
shift_copy = shift_copy >> 1;
if shift == 0 { break; }
shift -= 1;
}
U512(ret)
}
}
impl Rem for U512 {
type Output = U512;
fn rem(self, other: U512) -> U512 {
let d = self / other;
self - (other * d)
}
}
impl fmt::LowerHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..16 {
write!(f, "{:08x}", self.0[i])?;
}
Ok(())
}
}
impl fmt::UpperHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..16 {
write!(f, "{:08X}", self.0[i])?;
}
Ok(())
}
}
|
}
/// Zero value of U512.
pub fn zero() -> U512 {
|
random_line_split
|
u512.rs
|
//! Unsigned 512-bit integer
use std::convert::{From, Into};
use std::ops::{Add, Sub, Mul, Div, Shr, Shl, BitAnd, Rem};
use std::cmp::Ordering;
use std::fmt;
use super::U256;
use super::algorithms::{add2, mac3, from_signed, sub2_sign};
#[repr(C)]
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
/// Represents an unsigned 512-bit integer.
pub struct U512([u32; 16]);
impl U512 {
/// Bits needed to represent this value.
pub fn bits(&self) -> usize {
let &U512(ref arr) = self;
let mut current_bits = 0;
for i in (0..16).rev() {
if arr[i] == 0
|
current_bits = (32 - arr[i].leading_zeros() as usize) + ((15 - i) * 32);
}
current_bits
}
/// Zero value of U512.
pub fn zero() -> U512 {
U512([0u32; 16])
}
}
impl From<U256> for U512 {
fn from(val: U256) -> U512 {
let mut ret = [0u32; 16];
let val: [u32; 8] = val.into();
for i in 0..8 {
ret[8 + i] = val[i];
}
U512(ret)
}
}
impl Into<U256> for U512 {
fn into(self) -> U256 {
assert!(self.0[0..8].iter().all(|s| *s == 0));
let mut ret = [0u32; 8];
for i in 0..8 {
ret[i] = self.0[8 + i];
}
ret.into()
}
}
impl Ord for U512 {
fn cmp(&self, other: &U512) -> Ordering {
let &U512(ref me) = self;
let &U512(ref you) = other;
let mut i = 0;
while i < 16 {
if me[i] < you[i] { return Ordering::Less; }
if me[i] > you[i] { return Ordering::Greater; }
i += 1;
}
Ordering::Equal
}
}
impl PartialOrd for U512 {
fn partial_cmp(&self, other: &U512) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl BitAnd<U512> for U512 {
type Output = U512;
fn bitand(self, other: U512) -> U512 {
let mut r: U512 = self;
for i in 0..16 {
r.0[i] = r.0[i] & other.0[i];
}
r
}
}
impl Shl<usize> for U512 {
type Output = U512;
fn shl(self, shift: usize) -> U512 {
let U512(ref original) = self;
let mut ret = [0u32; 16];
let word_shift = shift / 32;
let bit_shift = shift % 32;
for i in (0..16).rev() {
// Shift
if i >= word_shift {
ret[i - word_shift] += original[i] << bit_shift;
}
// Carry
if bit_shift > 0 && i >= word_shift + 1 {
ret[i - word_shift - 1] += original[i] >> (32 - bit_shift);
}
}
U512(ret)
}
}
impl Shr<usize> for U512 {
type Output = U512;
fn shr(self, shift: usize) -> U512 {
let U512(ref original) = self;
let mut ret = [0u32; 16];
let word_shift = shift / 32;
let bit_shift = shift % 32;
for i in (0..16).rev() {
// Shift
if i + word_shift < 16 {
ret[i + word_shift] += original[i] >> bit_shift;
}
// Carry
if bit_shift > 0 && i > 0 && i + word_shift < 16 {
ret[i + word_shift] += original[i - 1] << (32 - bit_shift);
}
}
U512(ret)
}
}
impl Add for U512 {
type Output = U512;
fn add(mut self, other: U512) -> U512 {
let U512(ref mut a) = self;
let U512(ref b) = other;
let carry = add2(a, b);
assert!(carry == 0);
U512(*a)
}
}
impl Sub for U512 {
type Output = U512;
fn sub(mut self, other: U512) -> U512 {
let U512(ref mut a) = self;
let U512(ref b) = other;
let sign = sub2_sign(a, b);
from_signed(sign, a);
U512(*a)
}
}
impl Mul for U512 {
type Output = U512;
fn mul(mut self, other: U512) -> U512 {
let mut ret = [0u32; 16];
let U512(ref mut a) = self;
let U512(ref b) = other;
let mut carry = 0;
for (i, bi) in b.iter().rev().enumerate() {
carry = mac3(&mut ret[0..(16-i)], a, *bi);
}
assert!(carry == 0);
U512(ret)
}
}
impl Div for U512 {
type Output = U512;
fn div(self, other: U512) -> U512 {
let mut sub_copy = self;
let mut shift_copy = other;
let mut ret = [0u32; 16];
let my_bits = self.bits();
let your_bits = other.bits();
// Check for division by 0
assert!(your_bits!= 0);
// Early return in case we are dividing by a larger number than us
if my_bits < your_bits {
return U512(ret);
}
// Bitwise long division
let mut shift = my_bits - your_bits;
shift_copy = shift_copy << shift;
loop {
if sub_copy >= shift_copy {
ret[15 - shift / 32] |= 1 << (shift % 32);
sub_copy = sub_copy - shift_copy;
}
shift_copy = shift_copy >> 1;
if shift == 0 { break; }
shift -= 1;
}
U512(ret)
}
}
impl Rem for U512 {
type Output = U512;
fn rem(self, other: U512) -> U512 {
let d = self / other;
self - (other * d)
}
}
impl fmt::LowerHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..16 {
write!(f, "{:08x}", self.0[i])?;
}
Ok(())
}
}
impl fmt::UpperHex for U512 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..16 {
write!(f, "{:08X}", self.0[i])?;
}
Ok(())
}
}
|
{
continue;
}
|
conditional_block
|
struct-fields-typo.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct BuildData {
foo: isize,
bar: f32
}
fn
|
() {
let foo = BuildData {
foo: 0,
bar: 0.5,
};
let x = foo.baa;//~ ERROR attempted access of field `baa` on type `BuildData`
//~^ HELP did you mean `bar`?
println!("{}", x);
}
|
main
|
identifier_name
|
p_2_1_5_02.rs
|
// P_2_1_5_02
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// 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.
/**
* Place stacked circles of randomised heights at the mouse position
* to create a moire effect drawing
*
* MOUSE
* mouse : place circle
*
* KEYS
* s : save png
*
* CONTRIBUTED BY
* [Niels Poldervaart](http://NielsPoldervaart.nl)
*/
use nannou::prelude::*;
fn main() {
nannou::app(model).run();
}
#[derive(Clone)]
struct Shape {
x: f32,
y: f32,
r: f32,
}
impl Shape {
fn new(x: f32, y: f32, r: f32) -> Self {
Shape { x, y, r }
}
fn display(&self, draw: &Draw, model: &Model) {
for i in (0..self.r as usize).step_by(model.density) {
draw.ellipse()
.x_y(self.x, self.y)
.radius(i as f32 / 2.0)
.resolution(200)
.no_fill()
.stroke_weight(1.25)
.stroke(BLACK);
}
}
}
struct Model {
shapes: Vec<Shape>,
min_radius: f32,
max_radius: f32,
density: usize,
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.size(800, 800)
.view(view)
.mouse_released(mouse_released)
.key_released(key_released)
.build()
.unwrap();
let shapes = vec![Shape::new(0.0, 0.0, app.window_rect().w()); 1];
Model {
shapes,
min_radius: 5.0,
|
max_radius: 250.0,
density: 5,
}
}
fn view(app: &App, model: &Model, frame: Frame) {
// Prepare to draw.
let draw = app.draw();
draw.background().color(WHITE);
model.shapes.iter().for_each(|shape| {
shape.display(&draw, &model);
});
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_released(app: &App, model: &mut Model, _button: MouseButton) {
model.shapes.push(Shape::new(
app.mouse.x,
app.mouse.y,
random_range(model.min_radius, model.max_radius),
));
}
fn key_released(app: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
|
random_line_split
|
|
p_2_1_5_02.rs
|
// P_2_1_5_02
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// 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.
/**
* Place stacked circles of randomised heights at the mouse position
* to create a moire effect drawing
*
* MOUSE
* mouse : place circle
*
* KEYS
* s : save png
*
* CONTRIBUTED BY
* [Niels Poldervaart](http://NielsPoldervaart.nl)
*/
use nannou::prelude::*;
fn main() {
nannou::app(model).run();
}
#[derive(Clone)]
struct Shape {
x: f32,
y: f32,
r: f32,
}
impl Shape {
fn new(x: f32, y: f32, r: f32) -> Self {
Shape { x, y, r }
}
fn display(&self, draw: &Draw, model: &Model) {
for i in (0..self.r as usize).step_by(model.density) {
draw.ellipse()
.x_y(self.x, self.y)
.radius(i as f32 / 2.0)
.resolution(200)
.no_fill()
.stroke_weight(1.25)
.stroke(BLACK);
}
}
}
struct Model {
shapes: Vec<Shape>,
min_radius: f32,
max_radius: f32,
density: usize,
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.size(800, 800)
.view(view)
.mouse_released(mouse_released)
.key_released(key_released)
.build()
.unwrap();
let shapes = vec![Shape::new(0.0, 0.0, app.window_rect().w()); 1];
Model {
shapes,
min_radius: 5.0,
max_radius: 250.0,
density: 5,
}
}
fn view(app: &App, model: &Model, frame: Frame) {
// Prepare to draw.
let draw = app.draw();
draw.background().color(WHITE);
model.shapes.iter().for_each(|shape| {
shape.display(&draw, &model);
});
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_released(app: &App, model: &mut Model, _button: MouseButton) {
model.shapes.push(Shape::new(
app.mouse.x,
app.mouse.y,
random_range(model.min_radius, model.max_radius),
));
}
fn key
|
p: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
|
_released(ap
|
identifier_name
|
p_2_1_5_02.rs
|
// P_2_1_5_02
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// 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.
/**
* Place stacked circles of randomised heights at the mouse position
* to create a moire effect drawing
*
* MOUSE
* mouse : place circle
*
* KEYS
* s : save png
*
* CONTRIBUTED BY
* [Niels Poldervaart](http://NielsPoldervaart.nl)
*/
use nannou::prelude::*;
fn main() {
nannou::app(model).run();
}
#[derive(Clone)]
struct Shape {
x: f32,
y: f32,
r: f32,
}
impl Shape {
fn new(x: f32, y: f32, r: f32) -> Self {
Shape { x, y, r }
}
fn display(&self, draw: &Draw, model: &Model) {
for i in (0..self.r as usize).step_by(model.density) {
draw.ellipse()
.x_y(self.x, self.y)
.radius(i as f32 / 2.0)
.resolution(200)
.no_fill()
.stroke_weight(1.25)
.stroke(BLACK);
}
}
}
struct Model {
shapes: Vec<Shape>,
min_radius: f32,
max_radius: f32,
density: usize,
}
fn model(app: &App) -> Model {
|
n view(app: &App, model: &Model, frame: Frame) {
// Prepare to draw.
let draw = app.draw();
draw.background().color(WHITE);
model.shapes.iter().for_each(|shape| {
shape.display(&draw, &model);
});
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_released(app: &App, model: &mut Model, _button: MouseButton) {
model.shapes.push(Shape::new(
app.mouse.x,
app.mouse.y,
random_range(model.min_radius, model.max_radius),
));
}
fn key_released(app: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
|
let _window = app
.new_window()
.size(800, 800)
.view(view)
.mouse_released(mouse_released)
.key_released(key_released)
.build()
.unwrap();
let shapes = vec![Shape::new(0.0, 0.0, app.window_rect().w()); 1];
Model {
shapes,
min_radius: 5.0,
max_radius: 250.0,
density: 5,
}
}
f
|
identifier_body
|
p_2_1_5_02.rs
|
// P_2_1_5_02
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// 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.
/**
* Place stacked circles of randomised heights at the mouse position
* to create a moire effect drawing
*
* MOUSE
* mouse : place circle
*
* KEYS
* s : save png
*
* CONTRIBUTED BY
* [Niels Poldervaart](http://NielsPoldervaart.nl)
*/
use nannou::prelude::*;
fn main() {
nannou::app(model).run();
}
#[derive(Clone)]
struct Shape {
x: f32,
y: f32,
r: f32,
}
impl Shape {
fn new(x: f32, y: f32, r: f32) -> Self {
Shape { x, y, r }
}
fn display(&self, draw: &Draw, model: &Model) {
for i in (0..self.r as usize).step_by(model.density) {
draw.ellipse()
.x_y(self.x, self.y)
.radius(i as f32 / 2.0)
.resolution(200)
.no_fill()
.stroke_weight(1.25)
.stroke(BLACK);
}
}
}
struct Model {
shapes: Vec<Shape>,
min_radius: f32,
max_radius: f32,
density: usize,
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.size(800, 800)
.view(view)
.mouse_released(mouse_released)
.key_released(key_released)
.build()
.unwrap();
let shapes = vec![Shape::new(0.0, 0.0, app.window_rect().w()); 1];
Model {
shapes,
min_radius: 5.0,
max_radius: 250.0,
density: 5,
}
}
fn view(app: &App, model: &Model, frame: Frame) {
// Prepare to draw.
let draw = app.draw();
draw.background().color(WHITE);
model.shapes.iter().for_each(|shape| {
shape.display(&draw, &model);
});
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_released(app: &App, model: &mut Model, _button: MouseButton) {
model.shapes.push(Shape::new(
app.mouse.x,
app.mouse.y,
random_range(model.min_radius, model.max_radius),
));
}
fn key_released(app: &App, _model: &mut Model, key: Key) {
if key == Key::S {
|
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
|
conditional_block
|
|
mod.rs
|
use crate::context::Context;
use crate::error::RenderError;
use crate::json::value::ScopedJson;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{do_escape, Helper, RenderContext};
pub use self::helper_each::EACH_HELPER;
pub use self::helper_if::{IF_HELPER, UNLESS_HELPER};
pub use self::helper_log::LOG_HELPER;
pub use self::helper_lookup::LOOKUP_HELPER;
pub use self::helper_raw::RAW_HELPER;
pub use self::helper_with::WITH_HELPER;
/// A type alias for `Result<(), RenderError>`
pub type HelperResult = Result<(), RenderError>;
/// Helper Definition
///
/// Implement `HelperDef` to create custom helpers. You can retrieve useful information from these arguments.
///
/// * `&Helper`: current helper template information, contains name, params, hashes and nested template
/// * `&Registry`: the global registry, you can find templates by name from registry
/// * `&Context`: the whole data to render, in most case you can use data from `Helper`
/// * `&mut RenderContext`: you can access data or modify variables (starts with @)/partials in render context, for example, @index of #each. See its document for detail.
/// * `&mut dyn Output`: where you write output to
///
/// By default, you can use a bare function as a helper definition because we have supported unboxed_closure. If you have stateful or configurable helper, you can create a struct to implement `HelperDef`.
///
/// ## Define an inline helper
///
/// ```
/// use handlebars::*;
///
/// fn upper(h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, rc:
/// &mut RenderContext<'_, '_>, out: &mut dyn Output)
/// -> HelperResult {
/// // get parameter from helper or throw an error
/// let param = h.param(0).and_then(|v| v.value().as_str()).unwrap_or("");
/// out.write(param.to_uppercase().as_ref())?;
/// Ok(())
/// }
/// ```
///
/// ## Define block helper
///
/// Block helper is like `#if` or `#each` which has a inner template and an optional *inverse* template (the template in else branch). You can access the inner template by `helper.template()` and `helper.inverse()`. In most cases you will just call `render` on it.
///
/// ```
/// use handlebars::*;
///
/// fn dummy_block<'reg, 'rc>(
/// h: &Helper<'reg, 'rc>,
/// r: &'reg Handlebars<'reg>,
/// ctx: &'rc Context,
/// rc: &mut RenderContext<'reg, 'rc>,
/// out: &mut dyn Output,
/// ) -> HelperResult {
/// h.template()
/// .map(|t| t.render(r, ctx, rc, out))
/// .unwrap_or(Ok(()))
/// }
/// ```
///
/// ## Define helper function using macro
///
/// In most cases you just need some simple function to call from templates. We have a `handlebars_helper!` macro to simplify the job.
///
/// ```
/// use handlebars::*;
///
/// handlebars_helper!(plus: |x: i64, y: i64| x + y);
///
/// let mut hbs = Handlebars::new();
/// hbs.register_helper("plus", Box::new(plus));
/// ```
///
pub trait HelperDef {
/// A simplified api to define helper
///
/// To implement your own `call_inner`, you will return a new `ScopedJson`
/// which has a JSON value computed from current context.
|
/// When calling the helper as a subexpression, the value and its type can
/// be received by upper level helpers.
///
/// Note that the value can be `json!(null)` which is treated as `false` in
/// helpers like `if` and rendered as empty string.
fn call_inner<'reg: 'rc, 'rc>(
&self,
_: &Helper<'reg, 'rc>,
_: &'reg Registry<'reg>,
_: &'rc Context,
_: &mut RenderContext<'reg, 'rc>,
) -> Result<ScopedJson<'reg, 'rc>, RenderError> {
Err(RenderError::unimplemented())
}
/// A complex version of helper interface.
///
/// This function offers `Output`, which you can write custom string into
/// and render child template. Helpers like `if` and `each` are implemented
/// with this. Because the data written into `Output` are typically without
/// type information. So helpers defined by this function are not composable.
///
/// ### Calling from subexpression
///
/// Although helpers defined by this are not composable, when called from
/// subexpression, handlebars tries to parse the string output as JSON to
/// re-build its type. This can be buggy with numrical and other literal values.
/// So it is not recommended to use these helpers in subexpression.
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
match self.call_inner(h, r, ctx, rc) {
Ok(result) => {
if r.strict_mode() && result.is_missing() {
Err(RenderError::strict_error(None))
} else {
// auto escape according to settings
let output = do_escape(r, rc, result.render());
out.write(output.as_ref())?;
Ok(())
}
}
Err(e) => {
if e.is_unimplemented() {
// default implementation, do nothing
Ok(())
} else {
Err(e)
}
}
}
}
}
/// implement HelperDef for bare function so we can use function as helper
impl<
F: for<'reg, 'rc> Fn(
&Helper<'reg, 'rc>,
&'reg Registry<'reg>,
&'rc Context,
&mut RenderContext<'reg, 'rc>,
&mut dyn Output,
) -> HelperResult,
> HelperDef for F
{
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
(*self)(h, r, ctx, rc, out)
}
}
mod block_util;
mod helper_each;
pub(crate) mod helper_extras;
mod helper_if;
mod helper_log;
mod helper_lookup;
mod helper_raw;
mod helper_with;
#[cfg(feature = "script_helper")]
pub(crate) mod scripting;
// pub type HelperDef = for <'a, 'b, 'c> Fn<(&'a Context, &'b Helper, &'b Registry, &'c mut RenderContext), Result<String, RenderError>>;
//
// pub fn helper_dummy (ctx: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result<String, RenderError> {
// h.template().unwrap().render(ctx, r, rc).unwrap()
// }
//
#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use crate::context::Context;
use crate::error::RenderError;
use crate::helpers::HelperDef;
use crate::json::value::JsonRender;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext, Renderable};
#[derive(Clone, Copy)]
struct MetaHelper;
impl HelperDef for MetaHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
let v = h.param(0).unwrap();
if!h.is_block() {
let output = format!("{}:{}", h.name(), v.value().render());
out.write(output.as_ref())?;
} else {
let output = format!("{}:{}", h.name(), v.value().render());
out.write(output.as_ref())?;
out.write("->")?;
h.template().unwrap().render(r, ctx, rc, out)?;
};
Ok(())
}
}
#[test]
fn test_meta_helper() {
let mut handlebars = Registry::new();
assert!(handlebars
.register_template_string("t0", "{{foo this}}")
.is_ok());
assert!(handlebars
.register_template_string("t1", "{{#bar this}}nice{{/bar}}")
.is_ok());
let meta_helper = MetaHelper;
handlebars.register_helper("helperMissing", Box::new(meta_helper));
handlebars.register_helper("blockHelperMissing", Box::new(meta_helper));
let r0 = handlebars.render("t0", &true);
assert_eq!(r0.ok().unwrap(), "foo:true".to_string());
let r1 = handlebars.render("t1", &true);
assert_eq!(r1.ok().unwrap(), "bar:true->nice".to_string());
}
#[test]
fn test_helper_for_subexpression() {
let mut handlebars = Registry::new();
assert!(handlebars
.register_template_string("t2", "{{foo value=(bar 0)}}")
.is_ok());
handlebars.register_helper(
"helperMissing",
Box::new(
|h: &Helper<'_, '_>,
_: &Registry<'_>,
_: &Context,
_: &mut RenderContext<'_, '_>,
out: &mut dyn Output|
-> Result<(), RenderError> {
let output = format!("{}{}", h.name(), h.param(0).unwrap().value());
out.write(output.as_ref())?;
Ok(())
},
),
);
handlebars.register_helper(
"foo",
Box::new(
|h: &Helper<'_, '_>,
_: &Registry<'_>,
_: &Context,
_: &mut RenderContext<'_, '_>,
out: &mut dyn Output|
-> Result<(), RenderError> {
let output = format!("{}", h.hash_get("value").unwrap().value().render());
out.write(output.as_ref())?;
Ok(())
},
),
);
let mut data = BTreeMap::new();
// handlebars should never try to lookup this value because
// subexpressions are now resolved as string literal
data.insert("bar0".to_string(), true);
let r2 = handlebars.render("t2", &data);
assert_eq!(r2.ok().unwrap(), "bar0".to_string());
}
}
|
///
/// ### Calling from subexpression
///
|
random_line_split
|
mod.rs
|
use crate::context::Context;
use crate::error::RenderError;
use crate::json::value::ScopedJson;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{do_escape, Helper, RenderContext};
pub use self::helper_each::EACH_HELPER;
pub use self::helper_if::{IF_HELPER, UNLESS_HELPER};
pub use self::helper_log::LOG_HELPER;
pub use self::helper_lookup::LOOKUP_HELPER;
pub use self::helper_raw::RAW_HELPER;
pub use self::helper_with::WITH_HELPER;
/// A type alias for `Result<(), RenderError>`
pub type HelperResult = Result<(), RenderError>;
/// Helper Definition
///
/// Implement `HelperDef` to create custom helpers. You can retrieve useful information from these arguments.
///
/// * `&Helper`: current helper template information, contains name, params, hashes and nested template
/// * `&Registry`: the global registry, you can find templates by name from registry
/// * `&Context`: the whole data to render, in most case you can use data from `Helper`
/// * `&mut RenderContext`: you can access data or modify variables (starts with @)/partials in render context, for example, @index of #each. See its document for detail.
/// * `&mut dyn Output`: where you write output to
///
/// By default, you can use a bare function as a helper definition because we have supported unboxed_closure. If you have stateful or configurable helper, you can create a struct to implement `HelperDef`.
///
/// ## Define an inline helper
///
/// ```
/// use handlebars::*;
///
/// fn upper(h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, rc:
/// &mut RenderContext<'_, '_>, out: &mut dyn Output)
/// -> HelperResult {
/// // get parameter from helper or throw an error
/// let param = h.param(0).and_then(|v| v.value().as_str()).unwrap_or("");
/// out.write(param.to_uppercase().as_ref())?;
/// Ok(())
/// }
/// ```
///
/// ## Define block helper
///
/// Block helper is like `#if` or `#each` which has a inner template and an optional *inverse* template (the template in else branch). You can access the inner template by `helper.template()` and `helper.inverse()`. In most cases you will just call `render` on it.
///
/// ```
/// use handlebars::*;
///
/// fn dummy_block<'reg, 'rc>(
/// h: &Helper<'reg, 'rc>,
/// r: &'reg Handlebars<'reg>,
/// ctx: &'rc Context,
/// rc: &mut RenderContext<'reg, 'rc>,
/// out: &mut dyn Output,
/// ) -> HelperResult {
/// h.template()
/// .map(|t| t.render(r, ctx, rc, out))
/// .unwrap_or(Ok(()))
/// }
/// ```
///
/// ## Define helper function using macro
///
/// In most cases you just need some simple function to call from templates. We have a `handlebars_helper!` macro to simplify the job.
///
/// ```
/// use handlebars::*;
///
/// handlebars_helper!(plus: |x: i64, y: i64| x + y);
///
/// let mut hbs = Handlebars::new();
/// hbs.register_helper("plus", Box::new(plus));
/// ```
///
pub trait HelperDef {
/// A simplified api to define helper
///
/// To implement your own `call_inner`, you will return a new `ScopedJson`
/// which has a JSON value computed from current context.
///
/// ### Calling from subexpression
///
/// When calling the helper as a subexpression, the value and its type can
/// be received by upper level helpers.
///
/// Note that the value can be `json!(null)` which is treated as `false` in
/// helpers like `if` and rendered as empty string.
fn call_inner<'reg: 'rc, 'rc>(
&self,
_: &Helper<'reg, 'rc>,
_: &'reg Registry<'reg>,
_: &'rc Context,
_: &mut RenderContext<'reg, 'rc>,
) -> Result<ScopedJson<'reg, 'rc>, RenderError>
|
/// A complex version of helper interface.
///
/// This function offers `Output`, which you can write custom string into
/// and render child template. Helpers like `if` and `each` are implemented
/// with this. Because the data written into `Output` are typically without
/// type information. So helpers defined by this function are not composable.
///
/// ### Calling from subexpression
///
/// Although helpers defined by this are not composable, when called from
/// subexpression, handlebars tries to parse the string output as JSON to
/// re-build its type. This can be buggy with numrical and other literal values.
/// So it is not recommended to use these helpers in subexpression.
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
match self.call_inner(h, r, ctx, rc) {
Ok(result) => {
if r.strict_mode() && result.is_missing() {
Err(RenderError::strict_error(None))
} else {
// auto escape according to settings
let output = do_escape(r, rc, result.render());
out.write(output.as_ref())?;
Ok(())
}
}
Err(e) => {
if e.is_unimplemented() {
// default implementation, do nothing
Ok(())
} else {
Err(e)
}
}
}
}
}
/// implement HelperDef for bare function so we can use function as helper
impl<
F: for<'reg, 'rc> Fn(
&Helper<'reg, 'rc>,
&'reg Registry<'reg>,
&'rc Context,
&mut RenderContext<'reg, 'rc>,
&mut dyn Output,
) -> HelperResult,
> HelperDef for F
{
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
(*self)(h, r, ctx, rc, out)
}
}
mod block_util;
mod helper_each;
pub(crate) mod helper_extras;
mod helper_if;
mod helper_log;
mod helper_lookup;
mod helper_raw;
mod helper_with;
#[cfg(feature = "script_helper")]
pub(crate) mod scripting;
// pub type HelperDef = for <'a, 'b, 'c> Fn<(&'a Context, &'b Helper, &'b Registry, &'c mut RenderContext), Result<String, RenderError>>;
//
// pub fn helper_dummy (ctx: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result<String, RenderError> {
// h.template().unwrap().render(ctx, r, rc).unwrap()
// }
//
#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use crate::context::Context;
use crate::error::RenderError;
use crate::helpers::HelperDef;
use crate::json::value::JsonRender;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext, Renderable};
#[derive(Clone, Copy)]
struct MetaHelper;
impl HelperDef for MetaHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
let v = h.param(0).unwrap();
if!h.is_block() {
let output = format!("{}:{}", h.name(), v.value().render());
out.write(output.as_ref())?;
} else {
let output = format!("{}:{}", h.name(), v.value().render());
out.write(output.as_ref())?;
out.write("->")?;
h.template().unwrap().render(r, ctx, rc, out)?;
};
Ok(())
}
}
#[test]
fn test_meta_helper() {
let mut handlebars = Registry::new();
assert!(handlebars
.register_template_string("t0", "{{foo this}}")
.is_ok());
assert!(handlebars
.register_template_string("t1", "{{#bar this}}nice{{/bar}}")
.is_ok());
let meta_helper = MetaHelper;
handlebars.register_helper("helperMissing", Box::new(meta_helper));
handlebars.register_helper("blockHelperMissing", Box::new(meta_helper));
let r0 = handlebars.render("t0", &true);
assert_eq!(r0.ok().unwrap(), "foo:true".to_string());
let r1 = handlebars.render("t1", &true);
assert_eq!(r1.ok().unwrap(), "bar:true->nice".to_string());
}
#[test]
fn test_helper_for_subexpression() {
let mut handlebars = Registry::new();
assert!(handlebars
.register_template_string("t2", "{{foo value=(bar 0)}}")
.is_ok());
handlebars.register_helper(
"helperMissing",
Box::new(
|h: &Helper<'_, '_>,
_: &Registry<'_>,
_: &Context,
_: &mut RenderContext<'_, '_>,
out: &mut dyn Output|
-> Result<(), RenderError> {
let output = format!("{}{}", h.name(), h.param(0).unwrap().value());
out.write(output.as_ref())?;
Ok(())
},
),
);
handlebars.register_helper(
"foo",
Box::new(
|h: &Helper<'_, '_>,
_: &Registry<'_>,
_: &Context,
_: &mut RenderContext<'_, '_>,
out: &mut dyn Output|
-> Result<(), RenderError> {
let output = format!("{}", h.hash_get("value").unwrap().value().render());
out.write(output.as_ref())?;
Ok(())
},
),
);
let mut data = BTreeMap::new();
// handlebars should never try to lookup this value because
// subexpressions are now resolved as string literal
data.insert("bar0".to_string(), true);
let r2 = handlebars.render("t2", &data);
assert_eq!(r2.ok().unwrap(), "bar0".to_string());
}
}
|
{
Err(RenderError::unimplemented())
}
|
identifier_body
|
mod.rs
|
use crate::context::Context;
use crate::error::RenderError;
use crate::json::value::ScopedJson;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{do_escape, Helper, RenderContext};
pub use self::helper_each::EACH_HELPER;
pub use self::helper_if::{IF_HELPER, UNLESS_HELPER};
pub use self::helper_log::LOG_HELPER;
pub use self::helper_lookup::LOOKUP_HELPER;
pub use self::helper_raw::RAW_HELPER;
pub use self::helper_with::WITH_HELPER;
/// A type alias for `Result<(), RenderError>`
pub type HelperResult = Result<(), RenderError>;
/// Helper Definition
///
/// Implement `HelperDef` to create custom helpers. You can retrieve useful information from these arguments.
///
/// * `&Helper`: current helper template information, contains name, params, hashes and nested template
/// * `&Registry`: the global registry, you can find templates by name from registry
/// * `&Context`: the whole data to render, in most case you can use data from `Helper`
/// * `&mut RenderContext`: you can access data or modify variables (starts with @)/partials in render context, for example, @index of #each. See its document for detail.
/// * `&mut dyn Output`: where you write output to
///
/// By default, you can use a bare function as a helper definition because we have supported unboxed_closure. If you have stateful or configurable helper, you can create a struct to implement `HelperDef`.
///
/// ## Define an inline helper
///
/// ```
/// use handlebars::*;
///
/// fn upper(h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, rc:
/// &mut RenderContext<'_, '_>, out: &mut dyn Output)
/// -> HelperResult {
/// // get parameter from helper or throw an error
/// let param = h.param(0).and_then(|v| v.value().as_str()).unwrap_or("");
/// out.write(param.to_uppercase().as_ref())?;
/// Ok(())
/// }
/// ```
///
/// ## Define block helper
///
/// Block helper is like `#if` or `#each` which has a inner template and an optional *inverse* template (the template in else branch). You can access the inner template by `helper.template()` and `helper.inverse()`. In most cases you will just call `render` on it.
///
/// ```
/// use handlebars::*;
///
/// fn dummy_block<'reg, 'rc>(
/// h: &Helper<'reg, 'rc>,
/// r: &'reg Handlebars<'reg>,
/// ctx: &'rc Context,
/// rc: &mut RenderContext<'reg, 'rc>,
/// out: &mut dyn Output,
/// ) -> HelperResult {
/// h.template()
/// .map(|t| t.render(r, ctx, rc, out))
/// .unwrap_or(Ok(()))
/// }
/// ```
///
/// ## Define helper function using macro
///
/// In most cases you just need some simple function to call from templates. We have a `handlebars_helper!` macro to simplify the job.
///
/// ```
/// use handlebars::*;
///
/// handlebars_helper!(plus: |x: i64, y: i64| x + y);
///
/// let mut hbs = Handlebars::new();
/// hbs.register_helper("plus", Box::new(plus));
/// ```
///
pub trait HelperDef {
/// A simplified api to define helper
///
/// To implement your own `call_inner`, you will return a new `ScopedJson`
/// which has a JSON value computed from current context.
///
/// ### Calling from subexpression
///
/// When calling the helper as a subexpression, the value and its type can
/// be received by upper level helpers.
///
/// Note that the value can be `json!(null)` which is treated as `false` in
/// helpers like `if` and rendered as empty string.
fn call_inner<'reg: 'rc, 'rc>(
&self,
_: &Helper<'reg, 'rc>,
_: &'reg Registry<'reg>,
_: &'rc Context,
_: &mut RenderContext<'reg, 'rc>,
) -> Result<ScopedJson<'reg, 'rc>, RenderError> {
Err(RenderError::unimplemented())
}
/// A complex version of helper interface.
///
/// This function offers `Output`, which you can write custom string into
/// and render child template. Helpers like `if` and `each` are implemented
/// with this. Because the data written into `Output` are typically without
/// type information. So helpers defined by this function are not composable.
///
/// ### Calling from subexpression
///
/// Although helpers defined by this are not composable, when called from
/// subexpression, handlebars tries to parse the string output as JSON to
/// re-build its type. This can be buggy with numrical and other literal values.
/// So it is not recommended to use these helpers in subexpression.
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
match self.call_inner(h, r, ctx, rc) {
Ok(result) => {
if r.strict_mode() && result.is_missing() {
Err(RenderError::strict_error(None))
} else {
// auto escape according to settings
let output = do_escape(r, rc, result.render());
out.write(output.as_ref())?;
Ok(())
}
}
Err(e) => {
if e.is_unimplemented()
|
else {
Err(e)
}
}
}
}
}
/// implement HelperDef for bare function so we can use function as helper
impl<
F: for<'reg, 'rc> Fn(
&Helper<'reg, 'rc>,
&'reg Registry<'reg>,
&'rc Context,
&mut RenderContext<'reg, 'rc>,
&mut dyn Output,
) -> HelperResult,
> HelperDef for F
{
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
(*self)(h, r, ctx, rc, out)
}
}
mod block_util;
mod helper_each;
pub(crate) mod helper_extras;
mod helper_if;
mod helper_log;
mod helper_lookup;
mod helper_raw;
mod helper_with;
#[cfg(feature = "script_helper")]
pub(crate) mod scripting;
// pub type HelperDef = for <'a, 'b, 'c> Fn<(&'a Context, &'b Helper, &'b Registry, &'c mut RenderContext), Result<String, RenderError>>;
//
// pub fn helper_dummy (ctx: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result<String, RenderError> {
// h.template().unwrap().render(ctx, r, rc).unwrap()
// }
//
#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use crate::context::Context;
use crate::error::RenderError;
use crate::helpers::HelperDef;
use crate::json::value::JsonRender;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext, Renderable};
#[derive(Clone, Copy)]
struct MetaHelper;
impl HelperDef for MetaHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
let v = h.param(0).unwrap();
if!h.is_block() {
let output = format!("{}:{}", h.name(), v.value().render());
out.write(output.as_ref())?;
} else {
let output = format!("{}:{}", h.name(), v.value().render());
out.write(output.as_ref())?;
out.write("->")?;
h.template().unwrap().render(r, ctx, rc, out)?;
};
Ok(())
}
}
#[test]
fn test_meta_helper() {
let mut handlebars = Registry::new();
assert!(handlebars
.register_template_string("t0", "{{foo this}}")
.is_ok());
assert!(handlebars
.register_template_string("t1", "{{#bar this}}nice{{/bar}}")
.is_ok());
let meta_helper = MetaHelper;
handlebars.register_helper("helperMissing", Box::new(meta_helper));
handlebars.register_helper("blockHelperMissing", Box::new(meta_helper));
let r0 = handlebars.render("t0", &true);
assert_eq!(r0.ok().unwrap(), "foo:true".to_string());
let r1 = handlebars.render("t1", &true);
assert_eq!(r1.ok().unwrap(), "bar:true->nice".to_string());
}
#[test]
fn test_helper_for_subexpression() {
let mut handlebars = Registry::new();
assert!(handlebars
.register_template_string("t2", "{{foo value=(bar 0)}}")
.is_ok());
handlebars.register_helper(
"helperMissing",
Box::new(
|h: &Helper<'_, '_>,
_: &Registry<'_>,
_: &Context,
_: &mut RenderContext<'_, '_>,
out: &mut dyn Output|
-> Result<(), RenderError> {
let output = format!("{}{}", h.name(), h.param(0).unwrap().value());
out.write(output.as_ref())?;
Ok(())
},
),
);
handlebars.register_helper(
"foo",
Box::new(
|h: &Helper<'_, '_>,
_: &Registry<'_>,
_: &Context,
_: &mut RenderContext<'_, '_>,
out: &mut dyn Output|
-> Result<(), RenderError> {
let output = format!("{}", h.hash_get("value").unwrap().value().render());
out.write(output.as_ref())?;
Ok(())
},
),
);
let mut data = BTreeMap::new();
// handlebars should never try to lookup this value because
// subexpressions are now resolved as string literal
data.insert("bar0".to_string(), true);
let r2 = handlebars.render("t2", &data);
assert_eq!(r2.ok().unwrap(), "bar0".to_string());
}
}
|
{
// default implementation, do nothing
Ok(())
}
|
conditional_block
|
mod.rs
|
use crate::context::Context;
use crate::error::RenderError;
use crate::json::value::ScopedJson;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{do_escape, Helper, RenderContext};
pub use self::helper_each::EACH_HELPER;
pub use self::helper_if::{IF_HELPER, UNLESS_HELPER};
pub use self::helper_log::LOG_HELPER;
pub use self::helper_lookup::LOOKUP_HELPER;
pub use self::helper_raw::RAW_HELPER;
pub use self::helper_with::WITH_HELPER;
/// A type alias for `Result<(), RenderError>`
pub type HelperResult = Result<(), RenderError>;
/// Helper Definition
///
/// Implement `HelperDef` to create custom helpers. You can retrieve useful information from these arguments.
///
/// * `&Helper`: current helper template information, contains name, params, hashes and nested template
/// * `&Registry`: the global registry, you can find templates by name from registry
/// * `&Context`: the whole data to render, in most case you can use data from `Helper`
/// * `&mut RenderContext`: you can access data or modify variables (starts with @)/partials in render context, for example, @index of #each. See its document for detail.
/// * `&mut dyn Output`: where you write output to
///
/// By default, you can use a bare function as a helper definition because we have supported unboxed_closure. If you have stateful or configurable helper, you can create a struct to implement `HelperDef`.
///
/// ## Define an inline helper
///
/// ```
/// use handlebars::*;
///
/// fn upper(h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, rc:
/// &mut RenderContext<'_, '_>, out: &mut dyn Output)
/// -> HelperResult {
/// // get parameter from helper or throw an error
/// let param = h.param(0).and_then(|v| v.value().as_str()).unwrap_or("");
/// out.write(param.to_uppercase().as_ref())?;
/// Ok(())
/// }
/// ```
///
/// ## Define block helper
///
/// Block helper is like `#if` or `#each` which has a inner template and an optional *inverse* template (the template in else branch). You can access the inner template by `helper.template()` and `helper.inverse()`. In most cases you will just call `render` on it.
///
/// ```
/// use handlebars::*;
///
/// fn dummy_block<'reg, 'rc>(
/// h: &Helper<'reg, 'rc>,
/// r: &'reg Handlebars<'reg>,
/// ctx: &'rc Context,
/// rc: &mut RenderContext<'reg, 'rc>,
/// out: &mut dyn Output,
/// ) -> HelperResult {
/// h.template()
/// .map(|t| t.render(r, ctx, rc, out))
/// .unwrap_or(Ok(()))
/// }
/// ```
///
/// ## Define helper function using macro
///
/// In most cases you just need some simple function to call from templates. We have a `handlebars_helper!` macro to simplify the job.
///
/// ```
/// use handlebars::*;
///
/// handlebars_helper!(plus: |x: i64, y: i64| x + y);
///
/// let mut hbs = Handlebars::new();
/// hbs.register_helper("plus", Box::new(plus));
/// ```
///
pub trait HelperDef {
/// A simplified api to define helper
///
/// To implement your own `call_inner`, you will return a new `ScopedJson`
/// which has a JSON value computed from current context.
///
/// ### Calling from subexpression
///
/// When calling the helper as a subexpression, the value and its type can
/// be received by upper level helpers.
///
/// Note that the value can be `json!(null)` which is treated as `false` in
/// helpers like `if` and rendered as empty string.
fn
|
<'reg: 'rc, 'rc>(
&self,
_: &Helper<'reg, 'rc>,
_: &'reg Registry<'reg>,
_: &'rc Context,
_: &mut RenderContext<'reg, 'rc>,
) -> Result<ScopedJson<'reg, 'rc>, RenderError> {
Err(RenderError::unimplemented())
}
/// A complex version of helper interface.
///
/// This function offers `Output`, which you can write custom string into
/// and render child template. Helpers like `if` and `each` are implemented
/// with this. Because the data written into `Output` are typically without
/// type information. So helpers defined by this function are not composable.
///
/// ### Calling from subexpression
///
/// Although helpers defined by this are not composable, when called from
/// subexpression, handlebars tries to parse the string output as JSON to
/// re-build its type. This can be buggy with numrical and other literal values.
/// So it is not recommended to use these helpers in subexpression.
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
match self.call_inner(h, r, ctx, rc) {
Ok(result) => {
if r.strict_mode() && result.is_missing() {
Err(RenderError::strict_error(None))
} else {
// auto escape according to settings
let output = do_escape(r, rc, result.render());
out.write(output.as_ref())?;
Ok(())
}
}
Err(e) => {
if e.is_unimplemented() {
// default implementation, do nothing
Ok(())
} else {
Err(e)
}
}
}
}
}
/// implement HelperDef for bare function so we can use function as helper
impl<
F: for<'reg, 'rc> Fn(
&Helper<'reg, 'rc>,
&'reg Registry<'reg>,
&'rc Context,
&mut RenderContext<'reg, 'rc>,
&mut dyn Output,
) -> HelperResult,
> HelperDef for F
{
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
(*self)(h, r, ctx, rc, out)
}
}
mod block_util;
mod helper_each;
pub(crate) mod helper_extras;
mod helper_if;
mod helper_log;
mod helper_lookup;
mod helper_raw;
mod helper_with;
#[cfg(feature = "script_helper")]
pub(crate) mod scripting;
// pub type HelperDef = for <'a, 'b, 'c> Fn<(&'a Context, &'b Helper, &'b Registry, &'c mut RenderContext), Result<String, RenderError>>;
//
// pub fn helper_dummy (ctx: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result<String, RenderError> {
// h.template().unwrap().render(ctx, r, rc).unwrap()
// }
//
#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use crate::context::Context;
use crate::error::RenderError;
use crate::helpers::HelperDef;
use crate::json::value::JsonRender;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext, Renderable};
#[derive(Clone, Copy)]
struct MetaHelper;
impl HelperDef for MetaHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> Result<(), RenderError> {
let v = h.param(0).unwrap();
if!h.is_block() {
let output = format!("{}:{}", h.name(), v.value().render());
out.write(output.as_ref())?;
} else {
let output = format!("{}:{}", h.name(), v.value().render());
out.write(output.as_ref())?;
out.write("->")?;
h.template().unwrap().render(r, ctx, rc, out)?;
};
Ok(())
}
}
#[test]
fn test_meta_helper() {
let mut handlebars = Registry::new();
assert!(handlebars
.register_template_string("t0", "{{foo this}}")
.is_ok());
assert!(handlebars
.register_template_string("t1", "{{#bar this}}nice{{/bar}}")
.is_ok());
let meta_helper = MetaHelper;
handlebars.register_helper("helperMissing", Box::new(meta_helper));
handlebars.register_helper("blockHelperMissing", Box::new(meta_helper));
let r0 = handlebars.render("t0", &true);
assert_eq!(r0.ok().unwrap(), "foo:true".to_string());
let r1 = handlebars.render("t1", &true);
assert_eq!(r1.ok().unwrap(), "bar:true->nice".to_string());
}
#[test]
fn test_helper_for_subexpression() {
let mut handlebars = Registry::new();
assert!(handlebars
.register_template_string("t2", "{{foo value=(bar 0)}}")
.is_ok());
handlebars.register_helper(
"helperMissing",
Box::new(
|h: &Helper<'_, '_>,
_: &Registry<'_>,
_: &Context,
_: &mut RenderContext<'_, '_>,
out: &mut dyn Output|
-> Result<(), RenderError> {
let output = format!("{}{}", h.name(), h.param(0).unwrap().value());
out.write(output.as_ref())?;
Ok(())
},
),
);
handlebars.register_helper(
"foo",
Box::new(
|h: &Helper<'_, '_>,
_: &Registry<'_>,
_: &Context,
_: &mut RenderContext<'_, '_>,
out: &mut dyn Output|
-> Result<(), RenderError> {
let output = format!("{}", h.hash_get("value").unwrap().value().render());
out.write(output.as_ref())?;
Ok(())
},
),
);
let mut data = BTreeMap::new();
// handlebars should never try to lookup this value because
// subexpressions are now resolved as string literal
data.insert("bar0".to_string(), true);
let r2 = handlebars.render("t2", &data);
assert_eq!(r2.ok().unwrap(), "bar0".to_string());
}
}
|
call_inner
|
identifier_name
|
manual.rs
|
extern crate ralloc;
use std::ptr;
fn main()
|
for i in 0..300 {
*ptr1.offset(i) = i as u8;
}
assert_eq!(*ptr1, 0);
assert_eq!(*ptr1.offset(200), 200);
ralloc::free(ptr1, 30);
ralloc::free(ptr2, 500);
}
}
|
{
let ptr1 = ralloc::alloc(30, 3);
let ptr2 = ralloc::alloc(500, 20);
assert_eq!(0, ptr1 as usize % 3);
assert_eq!(0, ptr2 as usize % 20);
unsafe {
ptr::write_bytes(ptr1, 0x22, 30);
for i in 0..500 {
*ptr2.offset(i) = i as u8;
}
assert_eq!(*ptr1, 0x22);
assert_eq!(*ptr1.offset(5), 0x22);
assert_eq!(*ptr2, 0);
assert_eq!(*ptr2.offset(15), 15);
let ptr1 = ralloc::realloc(ptr1, 30, 300, 3);
|
identifier_body
|
manual.rs
|
extern crate ralloc;
use std::ptr;
fn main() {
let ptr1 = ralloc::alloc(30, 3);
let ptr2 = ralloc::alloc(500, 20);
assert_eq!(0, ptr1 as usize % 3);
assert_eq!(0, ptr2 as usize % 20);
unsafe {
ptr::write_bytes(ptr1, 0x22, 30);
for i in 0..500 {
*ptr2.offset(i) = i as u8;
}
|
assert_eq!(*ptr2, 0);
assert_eq!(*ptr2.offset(15), 15);
let ptr1 = ralloc::realloc(ptr1, 30, 300, 3);
for i in 0..300 {
*ptr1.offset(i) = i as u8;
}
assert_eq!(*ptr1, 0);
assert_eq!(*ptr1.offset(200), 200);
ralloc::free(ptr1, 30);
ralloc::free(ptr2, 500);
}
}
|
assert_eq!(*ptr1, 0x22);
assert_eq!(*ptr1.offset(5), 0x22);
|
random_line_split
|
manual.rs
|
extern crate ralloc;
use std::ptr;
fn
|
() {
let ptr1 = ralloc::alloc(30, 3);
let ptr2 = ralloc::alloc(500, 20);
assert_eq!(0, ptr1 as usize % 3);
assert_eq!(0, ptr2 as usize % 20);
unsafe {
ptr::write_bytes(ptr1, 0x22, 30);
for i in 0..500 {
*ptr2.offset(i) = i as u8;
}
assert_eq!(*ptr1, 0x22);
assert_eq!(*ptr1.offset(5), 0x22);
assert_eq!(*ptr2, 0);
assert_eq!(*ptr2.offset(15), 15);
let ptr1 = ralloc::realloc(ptr1, 30, 300, 3);
for i in 0..300 {
*ptr1.offset(i) = i as u8;
}
assert_eq!(*ptr1, 0);
assert_eq!(*ptr1.offset(200), 200);
ralloc::free(ptr1, 30);
ralloc::free(ptr2, 500);
}
}
|
main
|
identifier_name
|
build.rs
|
// Copyright 2012-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.
//! Used by `rustc` when compiling a plugin crate.
use syntax::ast;
use syntax::attr;
use syntax::codemap::Span;
use syntax::diagnostic;
use syntax::visit;
use syntax::visit::Visitor;
struct RegistrarFinder {
registrars: Vec<(ast::NodeId, Span)>,
}
impl Visitor<()> for RegistrarFinder {
fn visit_item(&mut self, item: &ast::Item, _: ()) {
match item.node {
ast::ItemFn(..) => {
if attr::contains_name(item.attrs.as_slice(),
"plugin_registrar") {
self.registrars.push((item.id, item.span));
}
}
_ => {}
}
visit::walk_item(self, item, ());
}
}
/// Find the function marked with `#[plugin_registrar]`, if any.
pub fn find_plugin_registrar(diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::NodeId> {
let mut finder = RegistrarFinder { registrars: Vec::new() };
visit::walk_crate(&mut finder, krate, ());
match finder.registrars.len() {
0 => None,
1 =>
|
,
_ => {
diagnostic.handler().err("multiple plugin registration functions found");
for &(_, span) in finder.registrars.iter() {
diagnostic.span_note(span, "one is here");
}
diagnostic.handler().abort_if_errors();
unreachable!();
}
}
}
|
{
let (node_id, _) = finder.registrars.pop().unwrap();
Some(node_id)
}
|
conditional_block
|
build.rs
|
// Copyright 2012-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.
//! Used by `rustc` when compiling a plugin crate.
use syntax::ast;
use syntax::attr;
use syntax::codemap::Span;
use syntax::diagnostic;
use syntax::visit;
use syntax::visit::Visitor;
struct RegistrarFinder {
registrars: Vec<(ast::NodeId, Span)>,
}
impl Visitor<()> for RegistrarFinder {
fn visit_item(&mut self, item: &ast::Item, _: ()) {
match item.node {
ast::ItemFn(..) => {
if attr::contains_name(item.attrs.as_slice(),
"plugin_registrar") {
self.registrars.push((item.id, item.span));
}
}
_ => {}
}
visit::walk_item(self, item, ());
}
}
/// Find the function marked with `#[plugin_registrar]`, if any.
pub fn find_plugin_registrar(diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::NodeId>
|
{
let mut finder = RegistrarFinder { registrars: Vec::new() };
visit::walk_crate(&mut finder, krate, ());
match finder.registrars.len() {
0 => None,
1 => {
let (node_id, _) = finder.registrars.pop().unwrap();
Some(node_id)
},
_ => {
diagnostic.handler().err("multiple plugin registration functions found");
for &(_, span) in finder.registrars.iter() {
diagnostic.span_note(span, "one is here");
}
diagnostic.handler().abort_if_errors();
unreachable!();
}
}
}
|
identifier_body
|
|
build.rs
|
// Copyright 2012-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.
//! Used by `rustc` when compiling a plugin crate.
use syntax::ast;
use syntax::attr;
use syntax::codemap::Span;
use syntax::diagnostic;
use syntax::visit;
use syntax::visit::Visitor;
struct
|
{
registrars: Vec<(ast::NodeId, Span)>,
}
impl Visitor<()> for RegistrarFinder {
fn visit_item(&mut self, item: &ast::Item, _: ()) {
match item.node {
ast::ItemFn(..) => {
if attr::contains_name(item.attrs.as_slice(),
"plugin_registrar") {
self.registrars.push((item.id, item.span));
}
}
_ => {}
}
visit::walk_item(self, item, ());
}
}
/// Find the function marked with `#[plugin_registrar]`, if any.
pub fn find_plugin_registrar(diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::NodeId> {
let mut finder = RegistrarFinder { registrars: Vec::new() };
visit::walk_crate(&mut finder, krate, ());
match finder.registrars.len() {
0 => None,
1 => {
let (node_id, _) = finder.registrars.pop().unwrap();
Some(node_id)
},
_ => {
diagnostic.handler().err("multiple plugin registration functions found");
for &(_, span) in finder.registrars.iter() {
diagnostic.span_note(span, "one is here");
}
diagnostic.handler().abort_if_errors();
unreachable!();
}
}
}
|
RegistrarFinder
|
identifier_name
|
build.rs
|
// Copyright 2012-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.
//! Used by `rustc` when compiling a plugin crate.
use syntax::ast;
use syntax::attr;
use syntax::codemap::Span;
|
use syntax::visit;
use syntax::visit::Visitor;
struct RegistrarFinder {
registrars: Vec<(ast::NodeId, Span)>,
}
impl Visitor<()> for RegistrarFinder {
fn visit_item(&mut self, item: &ast::Item, _: ()) {
match item.node {
ast::ItemFn(..) => {
if attr::contains_name(item.attrs.as_slice(),
"plugin_registrar") {
self.registrars.push((item.id, item.span));
}
}
_ => {}
}
visit::walk_item(self, item, ());
}
}
/// Find the function marked with `#[plugin_registrar]`, if any.
pub fn find_plugin_registrar(diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::NodeId> {
let mut finder = RegistrarFinder { registrars: Vec::new() };
visit::walk_crate(&mut finder, krate, ());
match finder.registrars.len() {
0 => None,
1 => {
let (node_id, _) = finder.registrars.pop().unwrap();
Some(node_id)
},
_ => {
diagnostic.handler().err("multiple plugin registration functions found");
for &(_, span) in finder.registrars.iter() {
diagnostic.span_note(span, "one is here");
}
diagnostic.handler().abort_if_errors();
unreachable!();
}
}
}
|
use syntax::diagnostic;
|
random_line_split
|
lib.rs
|
//! ### TODO
//!
//! * offer GC interface and example GCs
//! * rust currently doesn't allow generic static values - when it does, make this library
//! truely generic: Add `read_pool`, `write_pool`. Keep `[Byte]Symbol`, `[Byte]SymbolPool` as
//! useful aliases.
//!
#![feature(hashmap_hasher)]
#![feature(set_recovery)]
extern crate fnv;
extern crate rustc_serialize;
use std::borrow::Borrow;
use std::collections::HashSet;
use std::collections::hash_state;
use std::fmt::{self, Debug, Display};
use std::hash::Hash;
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::marker::PhantomData;
use std::ops::Deref;
use rustc_serialize::{Encodable, Decodable};
// ++++++++++++++++++++ Interned ++++++++++++++++++++
#[derive(Hash, PartialOrd, Ord)]
pub struct Interned<B:?Sized, O>{
inner: Arc<O>,
_phantom: PhantomData<B>,
}
impl<B:?Sized, O> Interned<B, O> {
fn new(inner: Arc<O>) -> Self { Interned{ inner: inner, _phantom: PhantomData } }
}
impl<B:?Sized, O> Clone for Interned<B, O> {
fn clone(&self) -> Self {
Self::new(self.inner.clone())
}
}
impl<B:?Sized, O> PartialEq for Interned<B, O> {
fn eq(&self, rhs: &Self) -> bool {
(&*self.inner) as *const _ as usize == (&*rhs.inner) as *const _ as usize
}
}
impl<B:?Sized, O> Eq for Interned<B, O> {}
impl<B:?Sized, O> Borrow<B> for Interned<B, O>
where O: Borrow<B>
{
fn borrow(&self) -> &B { (*self.inner).borrow() }
}
//FIXME
/*impl<B:?Sized, O> Into<O> for Interned<B, O>
where O: Clone
{
fn into(self) -> O { self.inner.clone() }
}*/
impl<B:?Sized, O> Debug for Interned<B, O>
where O: Debug
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
(*self.inner).fmt(formatter)
}
}
impl<B:?Sized, O> Display for Interned<B, O>
where O: Display
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
(*self.inner).fmt(formatter)
}
}
impl<B:?Sized, O> Deref for Interned<B, O>
where O: Borrow<B>
{
type Target = B;
fn deref(&self) -> &Self::Target { (*self.inner).borrow() }
}
impl<B:?Sized, O> Encodable for Interned<B, O>
where O: Encodable
{
fn encode<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
(*self.inner).encode(s)
}
}
impl<B:?Sized, O> Decodable for Interned<B, O>
where O: Decodable, Interned<B, O>: From<O>
{
fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
Ok(Self::from(try!{O::decode(d)}))
}
}
// ++++++++++++++++++++ InternPool ++++++++++++++++++++
pub struct InternPool<B:?Sized, O> {
data: HashSet<Interned<B, O>, hash_state::DefaultState<fnv::FnvHasher>>,
}
impl<B:?Sized, O> InternPool<B, O>
where B: Hash + Eq, O: Borrow<B> + Hash + Eq
{
fn new() -> Self {
InternPool{ data: HashSet::default() }
}
pub fn get(&self, obj: &B) -> Option<&Interned<B, O>> {
self.data.get(obj)
}
pub fn intern<X>(&mut self, obj: X) -> Interned<B, O>
where X: Borrow<B>, X: Into<O>
{
match self.get(obj.borrow()) {
Some(ret) => { return (*ret).clone(); }
None => {}
}
let ret: Interned<B, O> = Interned::new(Arc::new(obj.into()));
self.data.insert(ret.clone());
ret
}
}
// ++++++++++++++++++++ Symbol, SymbolPool ++++++++++++++++++++
pub type Symbol = Interned<str, String>;
pub type SymbolPool = InternPool<str, String>;
fn symbol_pool_instance() -> &'static RwLock<SymbolPool> {
static POOL: Option<RwLock<SymbolPool>> = None;
match &POOL {
&Some(ref r) => r,
// beware of racey hack!
pool => unsafe {
let init = Some(RwLock::new(SymbolPool::new()));
::std::ptr::write(pool as *const _ as *mut Option<RwLock<SymbolPool>>, init);
POOL.as_ref().unwrap()
}
}
}
pub fn read_symbol_pool() -> RwLockReadGuard<'static, SymbolPool> {
symbol_pool_instance().read().unwrap()
}
pub fn write_symbol_pool() -> RwLockWriteGuard<'static, SymbolPool> {
symbol_pool_instance().write().unwrap()
}
impl<'a> From<&'a str> for Symbol {
fn from(s: &'a str) -> Symbol {
write_symbol_pool().intern(s)
}
}
impl<'a> From<String> for Symbol {
fn from(s: String) -> Symbol {
write_symbol_pool().intern(s)
}
}
// ++++++++++++++++++++ ByteSymbol, ByteSymbolPool ++++++++++++++++++++
pub type ByteSymbol = Interned<[u8], Vec<u8>>;
pub type ByteSymbolPool = InternPool<[u8], Vec<u8>>;
fn byte_symbol_pool_instance() -> &'static RwLock<ByteSymbolPool> {
static POOL: Option<RwLock<ByteSymbolPool>> = None;
match &POOL {
&Some(ref r) => r,
// beware of racey hack!
pool => unsafe {
let init = Some(RwLock::new(ByteSymbolPool::new()));
::std::ptr::write(pool as *const _ as *mut Option<RwLock<ByteSymbolPool>>, init);
POOL.as_ref().unwrap()
|
pub fn read_byte_symbol_pool() -> RwLockReadGuard<'static, ByteSymbolPool> {
byte_symbol_pool_instance().read().unwrap()
}
pub fn write_byte_symbol_pool() -> RwLockWriteGuard<'static, ByteSymbolPool> {
byte_symbol_pool_instance().write().unwrap()
}
impl<'a> From<&'a [u8]> for ByteSymbol {
fn from(s: &'a [u8]) -> ByteSymbol {
write_byte_symbol_pool().intern(s)
}
}
impl<'a> From<Vec<u8>> for ByteSymbol {
fn from(s: Vec<u8>) -> ByteSymbol {
write_byte_symbol_pool().intern(s)
}
}
|
}
}
}
|
random_line_split
|
lib.rs
|
//! ### TODO
//!
//! * offer GC interface and example GCs
//! * rust currently doesn't allow generic static values - when it does, make this library
//! truely generic: Add `read_pool`, `write_pool`. Keep `[Byte]Symbol`, `[Byte]SymbolPool` as
//! useful aliases.
//!
#![feature(hashmap_hasher)]
#![feature(set_recovery)]
extern crate fnv;
extern crate rustc_serialize;
use std::borrow::Borrow;
use std::collections::HashSet;
use std::collections::hash_state;
use std::fmt::{self, Debug, Display};
use std::hash::Hash;
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::marker::PhantomData;
use std::ops::Deref;
use rustc_serialize::{Encodable, Decodable};
// ++++++++++++++++++++ Interned ++++++++++++++++++++
#[derive(Hash, PartialOrd, Ord)]
pub struct Interned<B:?Sized, O>{
inner: Arc<O>,
_phantom: PhantomData<B>,
}
impl<B:?Sized, O> Interned<B, O> {
fn new(inner: Arc<O>) -> Self { Interned{ inner: inner, _phantom: PhantomData } }
}
impl<B:?Sized, O> Clone for Interned<B, O> {
fn clone(&self) -> Self {
Self::new(self.inner.clone())
}
}
impl<B:?Sized, O> PartialEq for Interned<B, O> {
fn eq(&self, rhs: &Self) -> bool {
(&*self.inner) as *const _ as usize == (&*rhs.inner) as *const _ as usize
}
}
impl<B:?Sized, O> Eq for Interned<B, O> {}
impl<B:?Sized, O> Borrow<B> for Interned<B, O>
where O: Borrow<B>
{
fn borrow(&self) -> &B { (*self.inner).borrow() }
}
//FIXME
/*impl<B:?Sized, O> Into<O> for Interned<B, O>
where O: Clone
{
fn into(self) -> O { self.inner.clone() }
}*/
impl<B:?Sized, O> Debug for Interned<B, O>
where O: Debug
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
(*self.inner).fmt(formatter)
}
}
impl<B:?Sized, O> Display for Interned<B, O>
where O: Display
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
(*self.inner).fmt(formatter)
}
}
impl<B:?Sized, O> Deref for Interned<B, O>
where O: Borrow<B>
{
type Target = B;
fn deref(&self) -> &Self::Target { (*self.inner).borrow() }
}
impl<B:?Sized, O> Encodable for Interned<B, O>
where O: Encodable
{
fn encode<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
(*self.inner).encode(s)
}
}
impl<B:?Sized, O> Decodable for Interned<B, O>
where O: Decodable, Interned<B, O>: From<O>
{
fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
Ok(Self::from(try!{O::decode(d)}))
}
}
// ++++++++++++++++++++ InternPool ++++++++++++++++++++
pub struct InternPool<B:?Sized, O> {
data: HashSet<Interned<B, O>, hash_state::DefaultState<fnv::FnvHasher>>,
}
impl<B:?Sized, O> InternPool<B, O>
where B: Hash + Eq, O: Borrow<B> + Hash + Eq
{
fn new() -> Self {
InternPool{ data: HashSet::default() }
}
pub fn get(&self, obj: &B) -> Option<&Interned<B, O>> {
self.data.get(obj)
}
pub fn intern<X>(&mut self, obj: X) -> Interned<B, O>
where X: Borrow<B>, X: Into<O>
{
match self.get(obj.borrow()) {
Some(ret) => { return (*ret).clone(); }
None => {}
}
let ret: Interned<B, O> = Interned::new(Arc::new(obj.into()));
self.data.insert(ret.clone());
ret
}
}
// ++++++++++++++++++++ Symbol, SymbolPool ++++++++++++++++++++
pub type Symbol = Interned<str, String>;
pub type SymbolPool = InternPool<str, String>;
fn symbol_pool_instance() -> &'static RwLock<SymbolPool> {
static POOL: Option<RwLock<SymbolPool>> = None;
match &POOL {
&Some(ref r) => r,
// beware of racey hack!
pool => unsafe {
let init = Some(RwLock::new(SymbolPool::new()));
::std::ptr::write(pool as *const _ as *mut Option<RwLock<SymbolPool>>, init);
POOL.as_ref().unwrap()
}
}
}
pub fn read_symbol_pool() -> RwLockReadGuard<'static, SymbolPool> {
symbol_pool_instance().read().unwrap()
}
pub fn write_symbol_pool() -> RwLockWriteGuard<'static, SymbolPool> {
symbol_pool_instance().write().unwrap()
}
impl<'a> From<&'a str> for Symbol {
fn from(s: &'a str) -> Symbol {
write_symbol_pool().intern(s)
}
}
impl<'a> From<String> for Symbol {
fn from(s: String) -> Symbol {
write_symbol_pool().intern(s)
}
}
// ++++++++++++++++++++ ByteSymbol, ByteSymbolPool ++++++++++++++++++++
pub type ByteSymbol = Interned<[u8], Vec<u8>>;
pub type ByteSymbolPool = InternPool<[u8], Vec<u8>>;
fn byte_symbol_pool_instance() -> &'static RwLock<ByteSymbolPool>
|
pub fn read_byte_symbol_pool() -> RwLockReadGuard<'static, ByteSymbolPool> {
byte_symbol_pool_instance().read().unwrap()
}
pub fn write_byte_symbol_pool() -> RwLockWriteGuard<'static, ByteSymbolPool> {
byte_symbol_pool_instance().write().unwrap()
}
impl<'a> From<&'a [u8]> for ByteSymbol {
fn from(s: &'a [u8]) -> ByteSymbol {
write_byte_symbol_pool().intern(s)
}
}
impl<'a> From<Vec<u8>> for ByteSymbol {
fn from(s: Vec<u8>) -> ByteSymbol {
write_byte_symbol_pool().intern(s)
}
}
|
{
static POOL: Option<RwLock<ByteSymbolPool>> = None;
match &POOL {
&Some(ref r) => r,
// beware of racey hack!
pool => unsafe {
let init = Some(RwLock::new(ByteSymbolPool::new()));
::std::ptr::write(pool as *const _ as *mut Option<RwLock<ByteSymbolPool>>, init);
POOL.as_ref().unwrap()
}
}
}
|
identifier_body
|
lib.rs
|
//! ### TODO
//!
//! * offer GC interface and example GCs
//! * rust currently doesn't allow generic static values - when it does, make this library
//! truely generic: Add `read_pool`, `write_pool`. Keep `[Byte]Symbol`, `[Byte]SymbolPool` as
//! useful aliases.
//!
#![feature(hashmap_hasher)]
#![feature(set_recovery)]
extern crate fnv;
extern crate rustc_serialize;
use std::borrow::Borrow;
use std::collections::HashSet;
use std::collections::hash_state;
use std::fmt::{self, Debug, Display};
use std::hash::Hash;
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::marker::PhantomData;
use std::ops::Deref;
use rustc_serialize::{Encodable, Decodable};
// ++++++++++++++++++++ Interned ++++++++++++++++++++
#[derive(Hash, PartialOrd, Ord)]
pub struct Interned<B:?Sized, O>{
inner: Arc<O>,
_phantom: PhantomData<B>,
}
impl<B:?Sized, O> Interned<B, O> {
fn new(inner: Arc<O>) -> Self { Interned{ inner: inner, _phantom: PhantomData } }
}
impl<B:?Sized, O> Clone for Interned<B, O> {
fn clone(&self) -> Self {
Self::new(self.inner.clone())
}
}
impl<B:?Sized, O> PartialEq for Interned<B, O> {
fn eq(&self, rhs: &Self) -> bool {
(&*self.inner) as *const _ as usize == (&*rhs.inner) as *const _ as usize
}
}
impl<B:?Sized, O> Eq for Interned<B, O> {}
impl<B:?Sized, O> Borrow<B> for Interned<B, O>
where O: Borrow<B>
{
fn borrow(&self) -> &B { (*self.inner).borrow() }
}
//FIXME
/*impl<B:?Sized, O> Into<O> for Interned<B, O>
where O: Clone
{
fn into(self) -> O { self.inner.clone() }
}*/
impl<B:?Sized, O> Debug for Interned<B, O>
where O: Debug
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
(*self.inner).fmt(formatter)
}
}
impl<B:?Sized, O> Display for Interned<B, O>
where O: Display
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
(*self.inner).fmt(formatter)
}
}
impl<B:?Sized, O> Deref for Interned<B, O>
where O: Borrow<B>
{
type Target = B;
fn deref(&self) -> &Self::Target { (*self.inner).borrow() }
}
impl<B:?Sized, O> Encodable for Interned<B, O>
where O: Encodable
{
fn
|
<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
(*self.inner).encode(s)
}
}
impl<B:?Sized, O> Decodable for Interned<B, O>
where O: Decodable, Interned<B, O>: From<O>
{
fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
Ok(Self::from(try!{O::decode(d)}))
}
}
// ++++++++++++++++++++ InternPool ++++++++++++++++++++
pub struct InternPool<B:?Sized, O> {
data: HashSet<Interned<B, O>, hash_state::DefaultState<fnv::FnvHasher>>,
}
impl<B:?Sized, O> InternPool<B, O>
where B: Hash + Eq, O: Borrow<B> + Hash + Eq
{
fn new() -> Self {
InternPool{ data: HashSet::default() }
}
pub fn get(&self, obj: &B) -> Option<&Interned<B, O>> {
self.data.get(obj)
}
pub fn intern<X>(&mut self, obj: X) -> Interned<B, O>
where X: Borrow<B>, X: Into<O>
{
match self.get(obj.borrow()) {
Some(ret) => { return (*ret).clone(); }
None => {}
}
let ret: Interned<B, O> = Interned::new(Arc::new(obj.into()));
self.data.insert(ret.clone());
ret
}
}
// ++++++++++++++++++++ Symbol, SymbolPool ++++++++++++++++++++
pub type Symbol = Interned<str, String>;
pub type SymbolPool = InternPool<str, String>;
fn symbol_pool_instance() -> &'static RwLock<SymbolPool> {
static POOL: Option<RwLock<SymbolPool>> = None;
match &POOL {
&Some(ref r) => r,
// beware of racey hack!
pool => unsafe {
let init = Some(RwLock::new(SymbolPool::new()));
::std::ptr::write(pool as *const _ as *mut Option<RwLock<SymbolPool>>, init);
POOL.as_ref().unwrap()
}
}
}
pub fn read_symbol_pool() -> RwLockReadGuard<'static, SymbolPool> {
symbol_pool_instance().read().unwrap()
}
pub fn write_symbol_pool() -> RwLockWriteGuard<'static, SymbolPool> {
symbol_pool_instance().write().unwrap()
}
impl<'a> From<&'a str> for Symbol {
fn from(s: &'a str) -> Symbol {
write_symbol_pool().intern(s)
}
}
impl<'a> From<String> for Symbol {
fn from(s: String) -> Symbol {
write_symbol_pool().intern(s)
}
}
// ++++++++++++++++++++ ByteSymbol, ByteSymbolPool ++++++++++++++++++++
pub type ByteSymbol = Interned<[u8], Vec<u8>>;
pub type ByteSymbolPool = InternPool<[u8], Vec<u8>>;
fn byte_symbol_pool_instance() -> &'static RwLock<ByteSymbolPool> {
static POOL: Option<RwLock<ByteSymbolPool>> = None;
match &POOL {
&Some(ref r) => r,
// beware of racey hack!
pool => unsafe {
let init = Some(RwLock::new(ByteSymbolPool::new()));
::std::ptr::write(pool as *const _ as *mut Option<RwLock<ByteSymbolPool>>, init);
POOL.as_ref().unwrap()
}
}
}
pub fn read_byte_symbol_pool() -> RwLockReadGuard<'static, ByteSymbolPool> {
byte_symbol_pool_instance().read().unwrap()
}
pub fn write_byte_symbol_pool() -> RwLockWriteGuard<'static, ByteSymbolPool> {
byte_symbol_pool_instance().write().unwrap()
}
impl<'a> From<&'a [u8]> for ByteSymbol {
fn from(s: &'a [u8]) -> ByteSymbol {
write_byte_symbol_pool().intern(s)
}
}
impl<'a> From<Vec<u8>> for ByteSymbol {
fn from(s: Vec<u8>) -> ByteSymbol {
write_byte_symbol_pool().intern(s)
}
}
|
encode
|
identifier_name
|
p1.rs
|
use serialize::base64::{self, ToBase64};
use serialize::hex::FromHex;
#[test]
fn run() {
let hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f697 \
36f6e6f7573206d757368726f6f6d";
let b64_exp = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
|
}
|
let b64_act = hex.from_hex().unwrap().to_base64(base64::STANDARD);
assert_eq!(b64_exp, b64_act);
|
random_line_split
|
p1.rs
|
use serialize::base64::{self, ToBase64};
use serialize::hex::FromHex;
#[test]
fn run()
|
{
let hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f697 \
36f6e6f7573206d757368726f6f6d";
let b64_exp = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
let b64_act = hex.from_hex().unwrap().to_base64(base64::STANDARD);
assert_eq!(b64_exp, b64_act);
}
|
identifier_body
|
|
p1.rs
|
use serialize::base64::{self, ToBase64};
use serialize::hex::FromHex;
#[test]
fn
|
() {
let hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f697 \
36f6e6f7573206d757368726f6f6d";
let b64_exp = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
let b64_act = hex.from_hex().unwrap().to_base64(base64::STANDARD);
assert_eq!(b64_exp, b64_act);
}
|
run
|
identifier_name
|
04_using_matches.rs
|
extern crate clap;
use clap::{App, Arg};
fn
|
() {
// Once all App settings (including all arguments) have been set, you call get_matches() which
// parses the string provided by the user, and returns all the valid matches to the ones you
// specified.
//
// You can then query the matches struct to get information about how the user ran the program
// at startup.
//
// For this example, let's assume you created an App which accepts three arguments (plus two
// generated by clap), a flag to display debugging information triggered with "-d" or
// "--debug" as well as an option argument which specifies a custom configuration file to use
// triggered with "-c file" or "--config file" or "--config=file" and finally a positional
// argument which is the input file we want to work with, this will be the only required
// argument.
let matches = App::new("MyApp")
.about("Parses an input file to do awesome things")
.version("1.0")
.author("Kevin K. <[email protected]>")
.arg(Arg::with_name("debug")
.help("turn on debugging information")
.short("d")
.long("debug"))
.arg(Arg::with_name("config")
.help("sets the config file to use")
.short("c")
.long("config"))
.arg(Arg::with_name("input")
.help("the input file to use")
.index(1)
.required(true))
.get_matches();
// We can find out whether or not debugging was turned on
if matches.is_present("debug") {
println!("Debugging is turned on");
}
// If we wanted to do some custom initialization based off some configuration file
// provided by the user, we could get the file (A string of the file)
if let Some(file) = matches.value_of("config") {
println!("Using config file: {}", file);
}
// Because "input" is required we can safely call unwrap() because had the user NOT
// specified a value, clap would have explained the error the user, and exited.
println!("Doing real work with file: {}", matches.value_of("input").unwrap() );
// Continued program logic goes here...
}
|
main
|
identifier_name
|
04_using_matches.rs
|
extern crate clap;
use clap::{App, Arg};
fn main() {
// Once all App settings (including all arguments) have been set, you call get_matches() which
// parses the string provided by the user, and returns all the valid matches to the ones you
// specified.
//
// You can then query the matches struct to get information about how the user ran the program
// at startup.
//
// For this example, let's assume you created an App which accepts three arguments (plus two
// generated by clap), a flag to display debugging information triggered with "-d" or
// "--debug" as well as an option argument which specifies a custom configuration file to use
// triggered with "-c file" or "--config file" or "--config=file" and finally a positional
// argument which is the input file we want to work with, this will be the only required
// argument.
let matches = App::new("MyApp")
.about("Parses an input file to do awesome things")
.version("1.0")
|
.arg(Arg::with_name("config")
.help("sets the config file to use")
.short("c")
.long("config"))
.arg(Arg::with_name("input")
.help("the input file to use")
.index(1)
.required(true))
.get_matches();
// We can find out whether or not debugging was turned on
if matches.is_present("debug") {
println!("Debugging is turned on");
}
// If we wanted to do some custom initialization based off some configuration file
// provided by the user, we could get the file (A string of the file)
if let Some(file) = matches.value_of("config") {
println!("Using config file: {}", file);
}
// Because "input" is required we can safely call unwrap() because had the user NOT
// specified a value, clap would have explained the error the user, and exited.
println!("Doing real work with file: {}", matches.value_of("input").unwrap() );
// Continued program logic goes here...
}
|
.author("Kevin K. <[email protected]>")
.arg(Arg::with_name("debug")
.help("turn on debugging information")
.short("d")
.long("debug"))
|
random_line_split
|
04_using_matches.rs
|
extern crate clap;
use clap::{App, Arg};
fn main() {
// Once all App settings (including all arguments) have been set, you call get_matches() which
// parses the string provided by the user, and returns all the valid matches to the ones you
// specified.
//
// You can then query the matches struct to get information about how the user ran the program
// at startup.
//
// For this example, let's assume you created an App which accepts three arguments (plus two
// generated by clap), a flag to display debugging information triggered with "-d" or
// "--debug" as well as an option argument which specifies a custom configuration file to use
// triggered with "-c file" or "--config file" or "--config=file" and finally a positional
// argument which is the input file we want to work with, this will be the only required
// argument.
let matches = App::new("MyApp")
.about("Parses an input file to do awesome things")
.version("1.0")
.author("Kevin K. <[email protected]>")
.arg(Arg::with_name("debug")
.help("turn on debugging information")
.short("d")
.long("debug"))
.arg(Arg::with_name("config")
.help("sets the config file to use")
.short("c")
.long("config"))
.arg(Arg::with_name("input")
.help("the input file to use")
.index(1)
.required(true))
.get_matches();
// We can find out whether or not debugging was turned on
if matches.is_present("debug") {
println!("Debugging is turned on");
}
// If we wanted to do some custom initialization based off some configuration file
// provided by the user, we could get the file (A string of the file)
if let Some(file) = matches.value_of("config")
|
// Because "input" is required we can safely call unwrap() because had the user NOT
// specified a value, clap would have explained the error the user, and exited.
println!("Doing real work with file: {}", matches.value_of("input").unwrap() );
// Continued program logic goes here...
}
|
{
println!("Using config file: {}", file);
}
|
conditional_block
|
04_using_matches.rs
|
extern crate clap;
use clap::{App, Arg};
fn main()
|
.help("turn on debugging information")
.short("d")
.long("debug"))
.arg(Arg::with_name("config")
.help("sets the config file to use")
.short("c")
.long("config"))
.arg(Arg::with_name("input")
.help("the input file to use")
.index(1)
.required(true))
.get_matches();
// We can find out whether or not debugging was turned on
if matches.is_present("debug") {
println!("Debugging is turned on");
}
// If we wanted to do some custom initialization based off some configuration file
// provided by the user, we could get the file (A string of the file)
if let Some(file) = matches.value_of("config") {
println!("Using config file: {}", file);
}
// Because "input" is required we can safely call unwrap() because had the user NOT
// specified a value, clap would have explained the error the user, and exited.
println!("Doing real work with file: {}", matches.value_of("input").unwrap() );
// Continued program logic goes here...
}
|
{
// Once all App settings (including all arguments) have been set, you call get_matches() which
// parses the string provided by the user, and returns all the valid matches to the ones you
// specified.
//
// You can then query the matches struct to get information about how the user ran the program
// at startup.
//
// For this example, let's assume you created an App which accepts three arguments (plus two
// generated by clap), a flag to display debugging information triggered with "-d" or
// "--debug" as well as an option argument which specifies a custom configuration file to use
// triggered with "-c file" or "--config file" or "--config=file" and finally a positional
// argument which is the input file we want to work with, this will be the only required
// argument.
let matches = App::new("MyApp")
.about("Parses an input file to do awesome things")
.version("1.0")
.author("Kevin K. <[email protected]>")
.arg(Arg::with_name("debug")
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.