text stringlengths 8 4.13M |
|---|
iter range(a: int, b: int) -> int {
assert (a < b);
let i: int = a;
while i < b { put i; i += 1; }
}
fn main() {
let sum: int = 0;
for each x: int in range(0, 100) { sum += x; }
log sum;
}
|
extern crate regex;
use aoc2019::io::slurp_stdin;
use std::iter::FromIterator;
fn get_input() -> (Vec<i64>, Vec<i64>, Vec<i64>) {
let re = regex::Regex::new(r"<x=(-?\d+), y=(-?\d+), z=(-?\d+)>").unwrap();
let mut xs = Vec::new();
let mut ys = Vec::new();
let mut zs = Vec::new();
for m in re.captures_iter(&slurp_stdin()) {
let get = |i| -> i64 {
m.get(i).unwrap().as_str().parse().unwrap()
};
xs.push(get(1));
ys.push(get(2));
zs.push(get(3));
}
(xs,ys,zs)
}
fn step_coord(pos: &mut [i64], vel: &mut [i64]) {
for i in 0..pos.len() {
for j in i+1..pos.len() {
if pos[i] > pos[j] {
vel[i] -= 1;
vel[j] += 1;
} else if pos[i] < pos[j] {
vel[i] += 1;
vel[j] -= 1;
}
}
}
for i in 0..pos.len() {
pos[i] += vel[i];
}
}
fn step(
pos_x: &mut [i64],
pos_y: &mut [i64],
pos_z: &mut [i64],
vel_x: &mut [i64],
vel_y: &mut [i64],
vel_z: &mut [i64])
{
step_coord(pos_x, vel_x);
step_coord(pos_y, vel_y);
step_coord(pos_z, vel_z);
}
fn energy(
pos_x: &[i64],
pos_y: &[i64],
pos_z: &[i64],
vel_x: &[i64],
vel_y: &[i64],
vel_z: &[i64]) -> i64
{
let mut e = 0;
fn sum_abs(x: i64, y: i64, z: i64) -> i64 {
x.abs() + y.abs() + z.abs()
}
for i in 0..pos_x.len() {
e += sum_abs(pos_x[i], pos_y[i], pos_z[i]) * sum_abs(vel_x[i], vel_y[i], vel_z[i]);
}
e
}
fn loop_length(start_pos: &[i64], start_vel: &[i64]) -> usize {
let mut iters = 0;
let mut pos = Vec::from_iter(start_pos.iter().cloned());
let mut vel = Vec::from_iter(start_vel.iter().cloned());
loop {
step_coord(&mut pos, &mut vel);
iters += 1;
if pos == start_pos && vel == start_vel {
return iters;
}
}
}
fn gcd(x: usize, y: usize) -> usize {
if x == 0 {
y
} else {
gcd(y%x, x)
}
}
fn lcm(x: usize, y: usize) -> usize {
x * y / gcd(x, y)
}
fn main() {
let (start_pos_x, start_pos_y, start_pos_z) = get_input();
let zeros = {
let mut v = Vec::new();
v.resize(start_pos_x.len(), 0i64);
v
};
{
let mut pos_x = start_pos_x.clone();
let mut pos_y = start_pos_y.clone();
let mut pos_z = start_pos_z.clone();
let mut vel_x = zeros.clone();
let mut vel_y = zeros.clone();
let mut vel_z = zeros.clone();
for _ in 0..1000 {
step(&mut pos_x, &mut pos_y, &mut pos_z, &mut vel_x, &mut vel_y, &mut vel_z);
}
println!("{}", energy(&pos_x, &pos_y, &pos_z, &vel_x, &vel_y, &vel_z));
}
{
let loop_x = loop_length(&start_pos_x, &zeros);
let loop_y = loop_length(&start_pos_y, &zeros);
let loop_z = loop_length(&start_pos_z, &zeros);
println!("{}", lcm(lcm(loop_x, loop_y), loop_z))
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_gpout0_ctrl: CLK_GPOUT0_CTRL,
#[doc = "0x04 - Clock divisor, can be changed on-the-fly"]
pub clk_gpout0_div: CLK_GPOUT0_DIV,
#[doc = "0x08 - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub clk_gpout0_selected: CLK_GPOUT0_SELECTED,
#[doc = "0x0c - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_gpout1_ctrl: CLK_GPOUT1_CTRL,
#[doc = "0x10 - Clock divisor, can be changed on-the-fly"]
pub clk_gpout1_div: CLK_GPOUT1_DIV,
#[doc = "0x14 - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub clk_gpout1_selected: CLK_GPOUT1_SELECTED,
#[doc = "0x18 - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_gpout2_ctrl: CLK_GPOUT2_CTRL,
#[doc = "0x1c - Clock divisor, can be changed on-the-fly"]
pub clk_gpout2_div: CLK_GPOUT2_DIV,
#[doc = "0x20 - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub clk_gpout2_selected: CLK_GPOUT2_SELECTED,
#[doc = "0x24 - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_gpout3_ctrl: CLK_GPOUT3_CTRL,
#[doc = "0x28 - Clock divisor, can be changed on-the-fly"]
pub clk_gpout3_div: CLK_GPOUT3_DIV,
#[doc = "0x2c - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub clk_gpout3_selected: CLK_GPOUT3_SELECTED,
#[doc = "0x30 - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_ref_ctrl: CLK_REF_CTRL,
#[doc = "0x34 - Clock divisor, can be changed on-the-fly"]
pub clk_ref_div: CLK_REF_DIV,
#[doc = "0x38 - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n The glitchless multiplexer does not switch instantaneously (to avoid glitches), so software should poll this register to wait for the switch to complete. This register contains one decoded bit for each of the clock sources enumerated in the CTRL SRC field. At most one of these bits will be set at any time, indicating that clock is currently present at the output of the glitchless mux. Whilst switching is in progress, this register may briefly show all-0s."]
pub clk_ref_selected: CLK_REF_SELECTED,
#[doc = "0x3c - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_sys_ctrl: CLK_SYS_CTRL,
#[doc = "0x40 - Clock divisor, can be changed on-the-fly"]
pub clk_sys_div: CLK_SYS_DIV,
#[doc = "0x44 - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n The glitchless multiplexer does not switch instantaneously (to avoid glitches), so software should poll this register to wait for the switch to complete. This register contains one decoded bit for each of the clock sources enumerated in the CTRL SRC field. At most one of these bits will be set at any time, indicating that clock is currently present at the output of the glitchless mux. Whilst switching is in progress, this register may briefly show all-0s."]
pub clk_sys_selected: CLK_SYS_SELECTED,
#[doc = "0x48 - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_peri_ctrl: CLK_PERI_CTRL,
_reserved19: [u8; 4usize],
#[doc = "0x50 - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub clk_peri_selected: CLK_PERI_SELECTED,
#[doc = "0x54 - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_usb_ctrl: CLK_USB_CTRL,
#[doc = "0x58 - Clock divisor, can be changed on-the-fly"]
pub clk_usb_div: CLK_USB_DIV,
#[doc = "0x5c - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub clk_usb_selected: CLK_USB_SELECTED,
#[doc = "0x60 - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_adc_ctrl: CLK_ADC_CTRL,
#[doc = "0x64 - Clock divisor, can be changed on-the-fly"]
pub clk_adc_div: CLK_ADC_DIV,
#[doc = "0x68 - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub clk_adc_selected: CLK_ADC_SELECTED,
#[doc = "0x6c - Clock control, can be changed on-the-fly (except for auxsrc)"]
pub clk_rtc_ctrl: CLK_RTC_CTRL,
#[doc = "0x70 - Clock divisor, can be changed on-the-fly"]
pub clk_rtc_div: CLK_RTC_DIV,
#[doc = "0x74 - Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub clk_rtc_selected: CLK_RTC_SELECTED,
#[doc = "0x78 - "]
pub clk_sys_resus_ctrl: CLK_SYS_RESUS_CTRL,
#[doc = "0x7c - "]
pub clk_sys_resus_status: CLK_SYS_RESUS_STATUS,
#[doc = "0x80 - Reference clock frequency in kHz"]
pub fc0_ref_khz: FC0_REF_KHZ,
#[doc = "0x84 - Minimum pass frequency in kHz. This is optional. Set to 0 if you are not using the pass/fail flags"]
pub fc0_min_khz: FC0_MIN_KHZ,
#[doc = "0x88 - Maximum pass frequency in kHz. This is optional. Set to 0x1ffffff if you are not using the pass/fail flags"]
pub fc0_max_khz: FC0_MAX_KHZ,
#[doc = "0x8c - Delays the start of frequency counting to allow the mux to settle\\n Delay is measured in multiples of the reference clock period"]
pub fc0_delay: FC0_DELAY,
#[doc = "0x90 - The test interval is 0.98us * 2**interval, but let's call it 1us * 2**interval\\n The default gives a test interval of 250us"]
pub fc0_interval: FC0_INTERVAL,
#[doc = "0x94 - Clock sent to frequency counter, set to 0 when not required\\n Writing to this register initiates the frequency count"]
pub fc0_src: FC0_SRC,
#[doc = "0x98 - Frequency counter status"]
pub fc0_status: FC0_STATUS,
#[doc = "0x9c - Result of frequency measurement, only valid when status_done=1"]
pub fc0_result: FC0_RESULT,
#[doc = "0xa0 - enable clock in wake mode"]
pub wake_en0: WAKE_EN0,
#[doc = "0xa4 - enable clock in wake mode"]
pub wake_en1: WAKE_EN1,
#[doc = "0xa8 - enable clock in sleep mode"]
pub sleep_en0: SLEEP_EN0,
#[doc = "0xac - enable clock in sleep mode"]
pub sleep_en1: SLEEP_EN1,
#[doc = "0xb0 - indicates the state of the clock enable"]
pub enabled0: ENABLED0,
#[doc = "0xb4 - indicates the state of the clock enable"]
pub enabled1: ENABLED1,
#[doc = "0xb8 - Raw Interrupts"]
pub intr: INTR,
#[doc = "0xbc - Interrupt Enable"]
pub inte: INTE,
#[doc = "0xc0 - Interrupt Force"]
pub intf: INTF,
#[doc = "0xc4 - Interrupt status after masking & forcing"]
pub ints: INTS,
}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout0_ctrl](clk_gpout0_ctrl) module"]
pub type CLK_GPOUT0_CTRL = crate::Reg<u32, _CLK_GPOUT0_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT0_CTRL;
#[doc = "`read()` method returns [clk_gpout0_ctrl::R](clk_gpout0_ctrl::R) reader structure"]
impl crate::Readable for CLK_GPOUT0_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_gpout0_ctrl::W](clk_gpout0_ctrl::W) writer structure"]
impl crate::Writable for CLK_GPOUT0_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_gpout0_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout0_div](clk_gpout0_div) module"]
pub type CLK_GPOUT0_DIV = crate::Reg<u32, _CLK_GPOUT0_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT0_DIV;
#[doc = "`read()` method returns [clk_gpout0_div::R](clk_gpout0_div::R) reader structure"]
impl crate::Readable for CLK_GPOUT0_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_gpout0_div::W](clk_gpout0_div::W) writer structure"]
impl crate::Writable for CLK_GPOUT0_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_gpout0_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout0_selected](clk_gpout0_selected) module"]
pub type CLK_GPOUT0_SELECTED = crate::Reg<u32, _CLK_GPOUT0_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT0_SELECTED;
#[doc = "`read()` method returns [clk_gpout0_selected::R](clk_gpout0_selected::R) reader structure"]
impl crate::Readable for CLK_GPOUT0_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub mod clk_gpout0_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout1_ctrl](clk_gpout1_ctrl) module"]
pub type CLK_GPOUT1_CTRL = crate::Reg<u32, _CLK_GPOUT1_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT1_CTRL;
#[doc = "`read()` method returns [clk_gpout1_ctrl::R](clk_gpout1_ctrl::R) reader structure"]
impl crate::Readable for CLK_GPOUT1_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_gpout1_ctrl::W](clk_gpout1_ctrl::W) writer structure"]
impl crate::Writable for CLK_GPOUT1_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_gpout1_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout1_div](clk_gpout1_div) module"]
pub type CLK_GPOUT1_DIV = crate::Reg<u32, _CLK_GPOUT1_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT1_DIV;
#[doc = "`read()` method returns [clk_gpout1_div::R](clk_gpout1_div::R) reader structure"]
impl crate::Readable for CLK_GPOUT1_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_gpout1_div::W](clk_gpout1_div::W) writer structure"]
impl crate::Writable for CLK_GPOUT1_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_gpout1_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout1_selected](clk_gpout1_selected) module"]
pub type CLK_GPOUT1_SELECTED = crate::Reg<u32, _CLK_GPOUT1_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT1_SELECTED;
#[doc = "`read()` method returns [clk_gpout1_selected::R](clk_gpout1_selected::R) reader structure"]
impl crate::Readable for CLK_GPOUT1_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub mod clk_gpout1_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout2_ctrl](clk_gpout2_ctrl) module"]
pub type CLK_GPOUT2_CTRL = crate::Reg<u32, _CLK_GPOUT2_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT2_CTRL;
#[doc = "`read()` method returns [clk_gpout2_ctrl::R](clk_gpout2_ctrl::R) reader structure"]
impl crate::Readable for CLK_GPOUT2_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_gpout2_ctrl::W](clk_gpout2_ctrl::W) writer structure"]
impl crate::Writable for CLK_GPOUT2_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_gpout2_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout2_div](clk_gpout2_div) module"]
pub type CLK_GPOUT2_DIV = crate::Reg<u32, _CLK_GPOUT2_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT2_DIV;
#[doc = "`read()` method returns [clk_gpout2_div::R](clk_gpout2_div::R) reader structure"]
impl crate::Readable for CLK_GPOUT2_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_gpout2_div::W](clk_gpout2_div::W) writer structure"]
impl crate::Writable for CLK_GPOUT2_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_gpout2_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout2_selected](clk_gpout2_selected) module"]
pub type CLK_GPOUT2_SELECTED = crate::Reg<u32, _CLK_GPOUT2_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT2_SELECTED;
#[doc = "`read()` method returns [clk_gpout2_selected::R](clk_gpout2_selected::R) reader structure"]
impl crate::Readable for CLK_GPOUT2_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub mod clk_gpout2_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout3_ctrl](clk_gpout3_ctrl) module"]
pub type CLK_GPOUT3_CTRL = crate::Reg<u32, _CLK_GPOUT3_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT3_CTRL;
#[doc = "`read()` method returns [clk_gpout3_ctrl::R](clk_gpout3_ctrl::R) reader structure"]
impl crate::Readable for CLK_GPOUT3_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_gpout3_ctrl::W](clk_gpout3_ctrl::W) writer structure"]
impl crate::Writable for CLK_GPOUT3_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_gpout3_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout3_div](clk_gpout3_div) module"]
pub type CLK_GPOUT3_DIV = crate::Reg<u32, _CLK_GPOUT3_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT3_DIV;
#[doc = "`read()` method returns [clk_gpout3_div::R](clk_gpout3_div::R) reader structure"]
impl crate::Readable for CLK_GPOUT3_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_gpout3_div::W](clk_gpout3_div::W) writer structure"]
impl crate::Writable for CLK_GPOUT3_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_gpout3_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_gpout3_selected](clk_gpout3_selected) module"]
pub type CLK_GPOUT3_SELECTED = crate::Reg<u32, _CLK_GPOUT3_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_GPOUT3_SELECTED;
#[doc = "`read()` method returns [clk_gpout3_selected::R](clk_gpout3_selected::R) reader structure"]
impl crate::Readable for CLK_GPOUT3_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub mod clk_gpout3_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_ref_ctrl](clk_ref_ctrl) module"]
pub type CLK_REF_CTRL = crate::Reg<u32, _CLK_REF_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_REF_CTRL;
#[doc = "`read()` method returns [clk_ref_ctrl::R](clk_ref_ctrl::R) reader structure"]
impl crate::Readable for CLK_REF_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_ref_ctrl::W](clk_ref_ctrl::W) writer structure"]
impl crate::Writable for CLK_REF_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_ref_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_ref_div](clk_ref_div) module"]
pub type CLK_REF_DIV = crate::Reg<u32, _CLK_REF_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_REF_DIV;
#[doc = "`read()` method returns [clk_ref_div::R](clk_ref_div::R) reader structure"]
impl crate::Readable for CLK_REF_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_ref_div::W](clk_ref_div::W) writer structure"]
impl crate::Writable for CLK_REF_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_ref_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n The glitchless multiplexer does not switch instantaneously (to avoid glitches), so software should poll this register to wait for the switch to complete. This register contains one decoded bit for each of the clock sources enumerated in the CTRL SRC field. At most one of these bits will be set at any time, indicating that clock is currently present at the output of the glitchless mux. Whilst switching is in progress, this register may briefly show all-0s.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_ref_selected](clk_ref_selected) module"]
pub type CLK_REF_SELECTED = crate::Reg<u32, _CLK_REF_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_REF_SELECTED;
#[doc = "`read()` method returns [clk_ref_selected::R](clk_ref_selected::R) reader structure"]
impl crate::Readable for CLK_REF_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n The glitchless multiplexer does not switch instantaneously (to avoid glitches), so software should poll this register to wait for the switch to complete. This register contains one decoded bit for each of the clock sources enumerated in the CTRL SRC field. At most one of these bits will be set at any time, indicating that clock is currently present at the output of the glitchless mux. Whilst switching is in progress, this register may briefly show all-0s."]
pub mod clk_ref_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_sys_ctrl](clk_sys_ctrl) module"]
pub type CLK_SYS_CTRL = crate::Reg<u32, _CLK_SYS_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_SYS_CTRL;
#[doc = "`read()` method returns [clk_sys_ctrl::R](clk_sys_ctrl::R) reader structure"]
impl crate::Readable for CLK_SYS_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_sys_ctrl::W](clk_sys_ctrl::W) writer structure"]
impl crate::Writable for CLK_SYS_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_sys_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_sys_div](clk_sys_div) module"]
pub type CLK_SYS_DIV = crate::Reg<u32, _CLK_SYS_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_SYS_DIV;
#[doc = "`read()` method returns [clk_sys_div::R](clk_sys_div::R) reader structure"]
impl crate::Readable for CLK_SYS_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_sys_div::W](clk_sys_div::W) writer structure"]
impl crate::Writable for CLK_SYS_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_sys_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n The glitchless multiplexer does not switch instantaneously (to avoid glitches), so software should poll this register to wait for the switch to complete. This register contains one decoded bit for each of the clock sources enumerated in the CTRL SRC field. At most one of these bits will be set at any time, indicating that clock is currently present at the output of the glitchless mux. Whilst switching is in progress, this register may briefly show all-0s.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_sys_selected](clk_sys_selected) module"]
pub type CLK_SYS_SELECTED = crate::Reg<u32, _CLK_SYS_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_SYS_SELECTED;
#[doc = "`read()` method returns [clk_sys_selected::R](clk_sys_selected::R) reader structure"]
impl crate::Readable for CLK_SYS_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n The glitchless multiplexer does not switch instantaneously (to avoid glitches), so software should poll this register to wait for the switch to complete. This register contains one decoded bit for each of the clock sources enumerated in the CTRL SRC field. At most one of these bits will be set at any time, indicating that clock is currently present at the output of the glitchless mux. Whilst switching is in progress, this register may briefly show all-0s."]
pub mod clk_sys_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_peri_ctrl](clk_peri_ctrl) module"]
pub type CLK_PERI_CTRL = crate::Reg<u32, _CLK_PERI_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_PERI_CTRL;
#[doc = "`read()` method returns [clk_peri_ctrl::R](clk_peri_ctrl::R) reader structure"]
impl crate::Readable for CLK_PERI_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_peri_ctrl::W](clk_peri_ctrl::W) writer structure"]
impl crate::Writable for CLK_PERI_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_peri_ctrl;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_peri_selected](clk_peri_selected) module"]
pub type CLK_PERI_SELECTED = crate::Reg<u32, _CLK_PERI_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_PERI_SELECTED;
#[doc = "`read()` method returns [clk_peri_selected::R](clk_peri_selected::R) reader structure"]
impl crate::Readable for CLK_PERI_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub mod clk_peri_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_usb_ctrl](clk_usb_ctrl) module"]
pub type CLK_USB_CTRL = crate::Reg<u32, _CLK_USB_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_USB_CTRL;
#[doc = "`read()` method returns [clk_usb_ctrl::R](clk_usb_ctrl::R) reader structure"]
impl crate::Readable for CLK_USB_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_usb_ctrl::W](clk_usb_ctrl::W) writer structure"]
impl crate::Writable for CLK_USB_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_usb_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_usb_div](clk_usb_div) module"]
pub type CLK_USB_DIV = crate::Reg<u32, _CLK_USB_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_USB_DIV;
#[doc = "`read()` method returns [clk_usb_div::R](clk_usb_div::R) reader structure"]
impl crate::Readable for CLK_USB_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_usb_div::W](clk_usb_div::W) writer structure"]
impl crate::Writable for CLK_USB_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_usb_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_usb_selected](clk_usb_selected) module"]
pub type CLK_USB_SELECTED = crate::Reg<u32, _CLK_USB_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_USB_SELECTED;
#[doc = "`read()` method returns [clk_usb_selected::R](clk_usb_selected::R) reader structure"]
impl crate::Readable for CLK_USB_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub mod clk_usb_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_adc_ctrl](clk_adc_ctrl) module"]
pub type CLK_ADC_CTRL = crate::Reg<u32, _CLK_ADC_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_ADC_CTRL;
#[doc = "`read()` method returns [clk_adc_ctrl::R](clk_adc_ctrl::R) reader structure"]
impl crate::Readable for CLK_ADC_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_adc_ctrl::W](clk_adc_ctrl::W) writer structure"]
impl crate::Writable for CLK_ADC_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_adc_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_adc_div](clk_adc_div) module"]
pub type CLK_ADC_DIV = crate::Reg<u32, _CLK_ADC_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_ADC_DIV;
#[doc = "`read()` method returns [clk_adc_div::R](clk_adc_div::R) reader structure"]
impl crate::Readable for CLK_ADC_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_adc_div::W](clk_adc_div::W) writer structure"]
impl crate::Writable for CLK_ADC_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_adc_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_adc_selected](clk_adc_selected) module"]
pub type CLK_ADC_SELECTED = crate::Reg<u32, _CLK_ADC_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_ADC_SELECTED;
#[doc = "`read()` method returns [clk_adc_selected::R](clk_adc_selected::R) reader structure"]
impl crate::Readable for CLK_ADC_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub mod clk_adc_selected;
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_rtc_ctrl](clk_rtc_ctrl) module"]
pub type CLK_RTC_CTRL = crate::Reg<u32, _CLK_RTC_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_RTC_CTRL;
#[doc = "`read()` method returns [clk_rtc_ctrl::R](clk_rtc_ctrl::R) reader structure"]
impl crate::Readable for CLK_RTC_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_rtc_ctrl::W](clk_rtc_ctrl::W) writer structure"]
impl crate::Writable for CLK_RTC_CTRL {}
#[doc = "Clock control, can be changed on-the-fly (except for auxsrc)"]
pub mod clk_rtc_ctrl;
#[doc = "Clock divisor, can be changed on-the-fly\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_rtc_div](clk_rtc_div) module"]
pub type CLK_RTC_DIV = crate::Reg<u32, _CLK_RTC_DIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_RTC_DIV;
#[doc = "`read()` method returns [clk_rtc_div::R](clk_rtc_div::R) reader structure"]
impl crate::Readable for CLK_RTC_DIV {}
#[doc = "`write(|w| ..)` method takes [clk_rtc_div::W](clk_rtc_div::W) writer structure"]
impl crate::Writable for CLK_RTC_DIV {}
#[doc = "Clock divisor, can be changed on-the-fly"]
pub mod clk_rtc_div;
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_rtc_selected](clk_rtc_selected) module"]
pub type CLK_RTC_SELECTED = crate::Reg<u32, _CLK_RTC_SELECTED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_RTC_SELECTED;
#[doc = "`read()` method returns [clk_rtc_selected::R](clk_rtc_selected::R) reader structure"]
impl crate::Readable for CLK_RTC_SELECTED {}
#[doc = "Indicates which SRC is currently selected by the glitchless mux (one-hot).\\n This slice does not have a glitchless mux (only the AUX_SRC field is present, not SRC) so this register is hardwired to 0x1."]
pub mod clk_rtc_selected;
#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_sys_resus_ctrl](clk_sys_resus_ctrl) module"]
pub type CLK_SYS_RESUS_CTRL = crate::Reg<u32, _CLK_SYS_RESUS_CTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_SYS_RESUS_CTRL;
#[doc = "`read()` method returns [clk_sys_resus_ctrl::R](clk_sys_resus_ctrl::R) reader structure"]
impl crate::Readable for CLK_SYS_RESUS_CTRL {}
#[doc = "`write(|w| ..)` method takes [clk_sys_resus_ctrl::W](clk_sys_resus_ctrl::W) writer structure"]
impl crate::Writable for CLK_SYS_RESUS_CTRL {}
#[doc = ""]
pub mod clk_sys_resus_ctrl;
#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clk_sys_resus_status](clk_sys_resus_status) module"]
pub type CLK_SYS_RESUS_STATUS = crate::Reg<u32, _CLK_SYS_RESUS_STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CLK_SYS_RESUS_STATUS;
#[doc = "`read()` method returns [clk_sys_resus_status::R](clk_sys_resus_status::R) reader structure"]
impl crate::Readable for CLK_SYS_RESUS_STATUS {}
#[doc = ""]
pub mod clk_sys_resus_status;
#[doc = "Reference clock frequency in kHz\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fc0_ref_khz](fc0_ref_khz) module"]
pub type FC0_REF_KHZ = crate::Reg<u32, _FC0_REF_KHZ>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FC0_REF_KHZ;
#[doc = "`read()` method returns [fc0_ref_khz::R](fc0_ref_khz::R) reader structure"]
impl crate::Readable for FC0_REF_KHZ {}
#[doc = "`write(|w| ..)` method takes [fc0_ref_khz::W](fc0_ref_khz::W) writer structure"]
impl crate::Writable for FC0_REF_KHZ {}
#[doc = "Reference clock frequency in kHz"]
pub mod fc0_ref_khz;
#[doc = "Minimum pass frequency in kHz. This is optional. Set to 0 if you are not using the pass/fail flags\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fc0_min_khz](fc0_min_khz) module"]
pub type FC0_MIN_KHZ = crate::Reg<u32, _FC0_MIN_KHZ>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FC0_MIN_KHZ;
#[doc = "`read()` method returns [fc0_min_khz::R](fc0_min_khz::R) reader structure"]
impl crate::Readable for FC0_MIN_KHZ {}
#[doc = "`write(|w| ..)` method takes [fc0_min_khz::W](fc0_min_khz::W) writer structure"]
impl crate::Writable for FC0_MIN_KHZ {}
#[doc = "Minimum pass frequency in kHz. This is optional. Set to 0 if you are not using the pass/fail flags"]
pub mod fc0_min_khz;
#[doc = "Maximum pass frequency in kHz. This is optional. Set to 0x1ffffff if you are not using the pass/fail flags\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fc0_max_khz](fc0_max_khz) module"]
pub type FC0_MAX_KHZ = crate::Reg<u32, _FC0_MAX_KHZ>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FC0_MAX_KHZ;
#[doc = "`read()` method returns [fc0_max_khz::R](fc0_max_khz::R) reader structure"]
impl crate::Readable for FC0_MAX_KHZ {}
#[doc = "`write(|w| ..)` method takes [fc0_max_khz::W](fc0_max_khz::W) writer structure"]
impl crate::Writable for FC0_MAX_KHZ {}
#[doc = "Maximum pass frequency in kHz. This is optional. Set to 0x1ffffff if you are not using the pass/fail flags"]
pub mod fc0_max_khz;
#[doc = "Delays the start of frequency counting to allow the mux to settle\\n Delay is measured in multiples of the reference clock period\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fc0_delay](fc0_delay) module"]
pub type FC0_DELAY = crate::Reg<u32, _FC0_DELAY>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FC0_DELAY;
#[doc = "`read()` method returns [fc0_delay::R](fc0_delay::R) reader structure"]
impl crate::Readable for FC0_DELAY {}
#[doc = "`write(|w| ..)` method takes [fc0_delay::W](fc0_delay::W) writer structure"]
impl crate::Writable for FC0_DELAY {}
#[doc = "Delays the start of frequency counting to allow the mux to settle\\n Delay is measured in multiples of the reference clock period"]
pub mod fc0_delay;
#[doc = "The test interval is 0.98us * 2**interval, but let's call it 1us * 2**interval\\n The default gives a test interval of 250us\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fc0_interval](fc0_interval) module"]
pub type FC0_INTERVAL = crate::Reg<u32, _FC0_INTERVAL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FC0_INTERVAL;
#[doc = "`read()` method returns [fc0_interval::R](fc0_interval::R) reader structure"]
impl crate::Readable for FC0_INTERVAL {}
#[doc = "`write(|w| ..)` method takes [fc0_interval::W](fc0_interval::W) writer structure"]
impl crate::Writable for FC0_INTERVAL {}
#[doc = "The test interval is 0.98us * 2**interval, but let's call it 1us * 2**interval\\n The default gives a test interval of 250us"]
pub mod fc0_interval;
#[doc = "Clock sent to frequency counter, set to 0 when not required\\n Writing to this register initiates the frequency count\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fc0_src](fc0_src) module"]
pub type FC0_SRC = crate::Reg<u32, _FC0_SRC>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FC0_SRC;
#[doc = "`read()` method returns [fc0_src::R](fc0_src::R) reader structure"]
impl crate::Readable for FC0_SRC {}
#[doc = "`write(|w| ..)` method takes [fc0_src::W](fc0_src::W) writer structure"]
impl crate::Writable for FC0_SRC {}
#[doc = "Clock sent to frequency counter, set to 0 when not required\\n Writing to this register initiates the frequency count"]
pub mod fc0_src;
#[doc = "Frequency counter status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fc0_status](fc0_status) module"]
pub type FC0_STATUS = crate::Reg<u32, _FC0_STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FC0_STATUS;
#[doc = "`read()` method returns [fc0_status::R](fc0_status::R) reader structure"]
impl crate::Readable for FC0_STATUS {}
#[doc = "Frequency counter status"]
pub mod fc0_status;
#[doc = "Result of frequency measurement, only valid when status_done=1\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fc0_result](fc0_result) module"]
pub type FC0_RESULT = crate::Reg<u32, _FC0_RESULT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FC0_RESULT;
#[doc = "`read()` method returns [fc0_result::R](fc0_result::R) reader structure"]
impl crate::Readable for FC0_RESULT {}
#[doc = "Result of frequency measurement, only valid when status_done=1"]
pub mod fc0_result;
#[doc = "enable clock in wake mode\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wake_en0](wake_en0) module"]
pub type WAKE_EN0 = crate::Reg<u32, _WAKE_EN0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WAKE_EN0;
#[doc = "`read()` method returns [wake_en0::R](wake_en0::R) reader structure"]
impl crate::Readable for WAKE_EN0 {}
#[doc = "`write(|w| ..)` method takes [wake_en0::W](wake_en0::W) writer structure"]
impl crate::Writable for WAKE_EN0 {}
#[doc = "enable clock in wake mode"]
pub mod wake_en0;
#[doc = "enable clock in wake mode\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wake_en1](wake_en1) module"]
pub type WAKE_EN1 = crate::Reg<u32, _WAKE_EN1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WAKE_EN1;
#[doc = "`read()` method returns [wake_en1::R](wake_en1::R) reader structure"]
impl crate::Readable for WAKE_EN1 {}
#[doc = "`write(|w| ..)` method takes [wake_en1::W](wake_en1::W) writer structure"]
impl crate::Writable for WAKE_EN1 {}
#[doc = "enable clock in wake mode"]
pub mod wake_en1;
#[doc = "enable clock in sleep mode\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sleep_en0](sleep_en0) module"]
pub type SLEEP_EN0 = crate::Reg<u32, _SLEEP_EN0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SLEEP_EN0;
#[doc = "`read()` method returns [sleep_en0::R](sleep_en0::R) reader structure"]
impl crate::Readable for SLEEP_EN0 {}
#[doc = "`write(|w| ..)` method takes [sleep_en0::W](sleep_en0::W) writer structure"]
impl crate::Writable for SLEEP_EN0 {}
#[doc = "enable clock in sleep mode"]
pub mod sleep_en0;
#[doc = "enable clock in sleep mode\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sleep_en1](sleep_en1) module"]
pub type SLEEP_EN1 = crate::Reg<u32, _SLEEP_EN1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SLEEP_EN1;
#[doc = "`read()` method returns [sleep_en1::R](sleep_en1::R) reader structure"]
impl crate::Readable for SLEEP_EN1 {}
#[doc = "`write(|w| ..)` method takes [sleep_en1::W](sleep_en1::W) writer structure"]
impl crate::Writable for SLEEP_EN1 {}
#[doc = "enable clock in sleep mode"]
pub mod sleep_en1;
#[doc = "indicates the state of the clock enable\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [enabled0](enabled0) module"]
pub type ENABLED0 = crate::Reg<u32, _ENABLED0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ENABLED0;
#[doc = "`read()` method returns [enabled0::R](enabled0::R) reader structure"]
impl crate::Readable for ENABLED0 {}
#[doc = "indicates the state of the clock enable"]
pub mod enabled0;
#[doc = "indicates the state of the clock enable\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [enabled1](enabled1) module"]
pub type ENABLED1 = crate::Reg<u32, _ENABLED1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ENABLED1;
#[doc = "`read()` method returns [enabled1::R](enabled1::R) reader structure"]
impl crate::Readable for ENABLED1 {}
#[doc = "indicates the state of the clock enable"]
pub mod enabled1;
#[doc = "Raw Interrupts\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [intr](intr) module"]
pub type INTR = crate::Reg<u32, _INTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR;
#[doc = "`read()` method returns [intr::R](intr::R) reader structure"]
impl crate::Readable for INTR {}
#[doc = "Raw Interrupts"]
pub mod intr;
#[doc = "Interrupt Enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [inte](inte) module"]
pub type INTE = crate::Reg<u32, _INTE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTE;
#[doc = "`read()` method returns [inte::R](inte::R) reader structure"]
impl crate::Readable for INTE {}
#[doc = "`write(|w| ..)` method takes [inte::W](inte::W) writer structure"]
impl crate::Writable for INTE {}
#[doc = "Interrupt Enable"]
pub mod inte;
#[doc = "Interrupt Force\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [intf](intf) module"]
pub type INTF = crate::Reg<u32, _INTF>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTF;
#[doc = "`read()` method returns [intf::R](intf::R) reader structure"]
impl crate::Readable for INTF {}
#[doc = "`write(|w| ..)` method takes [intf::W](intf::W) writer structure"]
impl crate::Writable for INTF {}
#[doc = "Interrupt Force"]
pub mod intf;
#[doc = "Interrupt status after masking & forcing\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ints](ints) module"]
pub type INTS = crate::Reg<u32, _INTS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTS;
#[doc = "`read()` method returns [ints::R](ints::R) reader structure"]
impl crate::Readable for INTS {}
#[doc = "Interrupt status after masking & forcing"]
pub mod ints;
|
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub struct HandleCreationError {
pub code: i32
}
impl Error for HandleCreationError {
fn description(&self) -> &str {
match self.code {
-1 => "Generic failure",
-2 => "Out of memory",
-3 => "Hardware revision is not supported",
-4 => "Memory lock failed",
-5 => "mmap() failed",
-6 => "Unable to map registers into userspace",
-7 => "Unable to initialize GPIO",
-8 => "Unable to initialize PWM",
-9 => "Failed to create mailbox device",
-10 => "DMA error",
-11 => "Selected GPIO not possible",
-12 => "Unable to initialize PCM",
-13 => "Unable to initialize SPI",
-14 => "SPI transfer error",
_ => "unrecognised error"
}
}
}
impl fmt::Display for HandleCreationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Handle creation failed, error code: {}. {}", self.code, self.description())
}
}
|
use serde_json::json;
use sqlx::{Pool, Row, Sqlite};
use std::sync::Arc;
use super::model::{CompactPost, DBPost, Post};
use crate::_utils::{database::DBOrderDirection, error::DataAccessError};
pub struct PostRepository {
main_sql_db: Arc<Pool<Sqlite>>,
}
impl PostRepository {
pub fn new(main_sql_db: Arc<Pool<Sqlite>>) -> Self {
Self { main_sql_db }
}
pub async fn get_many_published_compact_posts(
&self,
order_by: &str,
order_direction: DBOrderDirection,
limit: u32,
start: u32,
) -> Result<Vec<CompactPost>, DataAccessError> {
let conn = self.main_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection: {:?}", conn);
return Err(DataAccessError::InternalError);
}
let mut conn = conn.unwrap();
// @TODO-ZM: figure out how query $ replacement work, there is some unneeded "magic" here
let db_result = sqlx::query(
format!(
r#"
SELECT id, slug, title, poster_id, short_description, tag_ids, published_at
FROM post
WHERE is_published = 1
ORDER BY {} {}
LIMIT $1
OFFSET $2
"#,
order_by, order_direction,
)
.as_str(),
)
.bind(limit)
.bind(start)
.fetch_all(&mut *conn)
.await;
if db_result.is_err() {
tracing::error!(
"Error while getting many published compact posts: {:?}",
db_result.err()
);
return Err(DataAccessError::InternalError);
}
let db_result = db_result.unwrap();
let mut compact_posts = vec![];
for row in db_result {
let tag_ids = row.get::<String, _>("tag_ids");
let tag_ids = tag_ids
.split(",")
.filter(|id| !id.is_empty())
.map(|id| id.parse::<u32>())
.collect::<Vec<Result<u32, _>>>();
if tag_ids.iter().any(|id| id.is_err()) {
tracing::error!(
"Error while getting one post by id, on parsing tag_ids, error: {:?}",
tag_ids
);
return Err(DataAccessError::InternalError);
}
let tag_ids = tag_ids
.iter()
.map(|id| id.clone().unwrap())
.collect::<Vec<u32>>();
let json_compact_post = json!({
"id": row.get::<u32, _>("id"),
"slug": row.get::<String, _>("slug"),
"title": row.get::<String, _>("title"),
"poster_id": row.get::<u32, _>("poster_id"),
"short_description": row.get::<String, _>("short_description"),
"tag_ids": tag_ids,
"published_at": row.get::<String, _>("published_at"),
});
let compact_compact_post = serde_json::from_value::<CompactPost>(json_compact_post);
if compact_compact_post.is_err() {
tracing::error!(
"Error while getting many published compact posts, on parsing compact_compact_post, error: {:?}",
compact_compact_post.err()
);
return Err(DataAccessError::InternalError);
}
let compact_post = compact_compact_post.unwrap();
compact_posts.push(compact_post);
}
Ok(compact_posts)
}
pub async fn get_many_compact_posts_by_ids(
&self,
ids: Vec<u32>,
) -> Result<Vec<CompactPost>, DataAccessError> {
let conn = self.main_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection: {:?}", conn);
return Err(DataAccessError::InternalError);
}
let mut conn = conn.unwrap();
let db_result = sqlx::query(
format!(
r#"
SELECT id, slug, title, poster_id, short_description, tag_ids, published_at
FROM post
WHERE id IN ({})
"#,
ids
.iter()
.map(|id| id.to_string())
.collect::<Vec<String>>()
.join(",")
)
.as_str(),
)
.fetch_all(&mut *conn)
.await;
if db_result.is_err() {
tracing::error!(
"Error while getting many compact posts by ids: {:?}",
db_result.err()
);
return Err(DataAccessError::InternalError);
}
let db_result = db_result.unwrap();
let mut compact_posts = vec![];
for row in db_result {
let tag_ids = row.get::<String, _>("tag_ids");
let tag_ids = tag_ids
.split(",")
.filter(|id| !id.is_empty())
.map(|id| id.parse::<u32>())
.collect::<Vec<Result<u32, _>>>();
if tag_ids.iter().any(|id| id.is_err()) {
tracing::error!(
"Error while getting one post by id, on parsing tag_ids, error: {:?}",
tag_ids
);
return Err(DataAccessError::InternalError);
}
let tag_ids = tag_ids
.iter()
.map(|id| id.clone().unwrap())
.collect::<Vec<u32>>();
let json_compact_post = json!({
"id": row.get::<u32, _>("id"),
"slug": row.get::<String, _>("slug"),
"title": row.get::<String, _>("title"),
"poster_id": row.get::<u32, _>("poster_id"),
"short_description": row.get::<String, _>("short_description"),
"tag_ids": tag_ids,
"published_at": row.get::<String, _>("published_at"),
});
let compact_compact_post = serde_json::from_value::<CompactPost>(json_compact_post);
if compact_compact_post.is_err() {
tracing::error!(
"Error while getting many compact posts by ids, on parsing compact_compact_post, error: {:?}",
compact_compact_post.err()
);
return Err(DataAccessError::InternalError);
}
let compact_post = compact_compact_post.unwrap();
compact_posts.push(compact_post);
}
Ok(compact_posts)
}
pub async fn get_many_posts_by_ids(&self, ids: Vec<u32>) -> Result<Vec<Post>, DataAccessError> {
let conn = self.main_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection: {:?}", conn);
return Err(DataAccessError::InternalError);
}
let mut conn = conn.unwrap();
let db_result = sqlx::query(
format!(
r#"
SELECT id, slug, title, poster_id, short_description, description, tag_ids, published_at, is_published
FROM post
WHERE id IN ({})
"#,
ids.iter().map(|id| id.to_string()).collect::<Vec<String>>().join(",")
).as_str(),
)
.fetch_all(&mut *conn)
.await;
if db_result.is_err() {
tracing::error!(
"Error while getting many posts by ids: {:?}",
db_result.err()
);
return Err(DataAccessError::InternalError);
}
let db_result = db_result.unwrap();
let mut posts = vec![];
for row in db_result {
let tag_ids = row.get::<String, _>("tag_ids");
let tag_ids = tag_ids
.split(",")
.filter(|id| !id.is_empty())
.map(|id| id.parse::<u32>())
.collect::<Vec<Result<u32, _>>>();
if tag_ids.iter().any(|id| id.is_err()) {
tracing::error!(
"Error while getting one post by id, on parsing tag_ids, error: {:?}",
tag_ids
);
return Err(DataAccessError::InternalError);
}
let tag_ids = tag_ids
.iter()
.map(|id| id.clone().unwrap())
.collect::<Vec<u32>>();
let json_post = json!({
"id": row.get::<u32, _>("id"),
"slug": row.get::<String, _>("slug"),
"title": row.get::<String, _>("title"),
"poster_id": row.get::<u32, _>("poster_id"),
"short_description": row.get::<String, _>("short_description"),
"description": row.get::<String, _>("description"),
"tag_ids": tag_ids,
"published_at": row.get::<String, _>("published_at"),
"is_published": row.get::<bool, _>("is_published"),
});
let post = serde_json::from_value::<Post>(json_post);
if post.is_err() {
tracing::error!("Error while getting many posts by ids: {:?}", post.err());
return Err(DataAccessError::InternalError);
}
let post = post.unwrap();
posts.push(post);
}
Ok(posts)
}
pub async fn get_one_post_by_id(&self, id: u32) -> Result<Post, DataAccessError> {
let conn = self.main_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection: {:?}", conn);
return Err(DataAccessError::InternalError);
}
let mut conn = conn.unwrap();
// @TODO-ZM: use * instead of listing all the fields?
let db_result = sqlx::query(
r#"
SELECT id, slug, title, poster_id, short_description, description, tag_ids, published_at, is_published
FROM post
WHERE id = $1
"#,
)
.bind(id)
.fetch_one(&mut *conn)
.await;
if db_result.is_err() {
match db_result.err().unwrap() {
sqlx::Error::RowNotFound => {
return Err(DataAccessError::NotFound);
}
err => {
tracing::error!("Error while getting one post by id: {:?}", err);
return Err(DataAccessError::InternalError);
}
}
}
let db_result = db_result.unwrap();
let tag_ids = db_result.get::<String, _>("tag_ids");
let tag_ids = tag_ids
.split(",")
.filter(|id| !id.is_empty())
.map(|id| id.parse::<u32>())
.collect::<Vec<Result<u32, _>>>();
if tag_ids.iter().any(|id| id.is_err()) {
tracing::error!(
"Error while getting one post by id, on parsing tag_ids, error: {:?}",
tag_ids
);
return Err(DataAccessError::InternalError);
}
let tag_ids = tag_ids
.iter()
.map(|id| id.clone().unwrap())
.collect::<Vec<u32>>();
let json_post = json!({
"id": db_result.get::<u32, _>("id"),
"slug": db_result.get::<String, _>("slug"),
"title": db_result.get::<String, _>("title"),
"poster_id": db_result.get::<u32, _>("poster_id"),
"short_description": db_result.get::<String, _>("short_description"),
"description": db_result.get::<String, _>("description"),
"tag_ids": tag_ids,
"published_at": db_result.get::<String, _>("published_at"),
"is_published": db_result.get::<bool, _>("is_published"),
});
tracing::info!("zako");
let post = serde_json::from_value::<Post>(json_post);
if post.is_err() {
tracing::error!("Error while getting one post by id: {:?}", post.err());
return Err(DataAccessError::InternalError);
}
let post = post.unwrap();
Ok(post)
}
pub async fn create_one_post(&self, post: &DBPost) -> Result<u32, DataAccessError> {
let conn = self.main_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection: {:?}", conn);
return Err(DataAccessError::InternalError);
}
let mut conn = conn.unwrap();
let db_result = sqlx::query(
r#"
INSERT INTO post (slug, title, poster_id, short_description, description, tag_ids, published_at, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, strftime('%Y-%m-%dT%H:%M:%S.%fZ', 'now'))
"#,
)
.bind(&post.slug)
.bind(&post.title)
.bind(&post.poster_id)
.bind(&post.short_description)
.bind(&post.description)
.bind(&post.tag_ids.iter().map(|id| id.to_string()).collect::<Vec<String>>().join(","))
.bind(&post.published_at)
.execute(&mut *conn)
.await;
if db_result.is_err() {
tracing::error!("Error while creating one post: {:?}", db_result);
return Err(DataAccessError::InternalError);
}
let id = db_result.unwrap().last_insert_rowid() as u32;
Ok(id)
}
pub async fn get_published_post_count(&self) -> Result<u32, DataAccessError> {
let conn = self.main_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection: {:?}", conn);
return Err(DataAccessError::InternalError);
}
let mut conn = conn.unwrap();
let db_result = sqlx::query(
r#"
SELECT COUNT(*) as count
FROM post
WHERE is_published = 1
"#,
)
.fetch_one(&mut *conn)
.await;
if db_result.is_err() {
tracing::error!(
"Error while getting published post count: {:?}",
db_result.err()
);
return Err(DataAccessError::InternalError);
}
let db_result = db_result.unwrap();
let count = db_result.get::<i64, _>("count") as u32;
Ok(count)
}
pub async fn publish_one_post_by_id(&self, id: u32) -> Result<(), DataAccessError> {
let conn = self.main_sql_db.acquire().await;
if conn.is_err() {
tracing::error!("Error while getting sql connection: {:?}", conn);
return Err(DataAccessError::InternalError);
}
let mut conn = conn.unwrap();
let db_result = sqlx::query(
r#"
UPDATE post
SET published_at = strftime('%Y-%m-%dT%H:%M:%S.%fZ', 'now')
WHERE id = $1
"#,
)
.bind(id)
.execute(&mut *conn)
.await;
if db_result.is_err() {
tracing::error!("Error while publishing one post: {:?}", db_result);
return Err(DataAccessError::InternalError);
}
Ok(())
}
}
|
use tproto::BindClient;
use tcore::reactor::{Core, Handle, Remote};
use tio::{AsyncRead, AsyncWrite};
use tio::codec::Framed;
use tproto::pipeline::{ClientService, ClientProto};
use tserv::{Service, NewService};
use bytes::Bytes;
use std::io;
use codec::AMQPCodec;
pub struct AMQPProto;
// impl<T: AsyncRead + AsyncWrite + 'static> ClientProto<T> for AMQPProto {
// type Request = Bytes;
// type Response = Bytes;
// type Transport = Framed<T, AMQPCodec>;
// type BindTransport = Result<Self::Transport, io::Error>;
// fn bind_transport(&self, io: T) -> Self::BindTransport {
// Ok(io.framed(AMQPCodec))
// }
// }
|
#![feature(allocator_api)]
mod error;
mod rule;
use libip6tc_sys as sys;
use std::ffi::{CStr, CString};
use error::IptcError;
struct Table4 {
// TODO:
}
struct Table6 {
handle: *mut sys::xtc_handle,
table_name: CString,
}
impl Table6 {
pub fn new(table_name: &str) -> Result<Self, IptcError> {
let table_name = CString::new(table_name).unwrap();
// Takes a snapshot of the rules
// https://www.tldp.org/HOWTO/Querying-libiptc-HOWTO/qfunction.html
let handle = unsafe { sys::ip6tc_init(table_name.as_ptr()) };
if handle.is_null() {
Err(IptcError::from_errno())
} else {
Ok(Self { handle, table_name })
}
}
}
struct Chain4 {}
struct Chain6 {}
trait Chain: Sized {
fn new(table_name: &str, chain_name: &str) -> Result<Self, IptcError>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let _t = Table6::new("mangle");
}
}
|
use cloverleaf_core::sdp::parse_candidate;
use cloverleaf_core::sdp::Sdp;
use cloverleaf_core::CandidateType;
#[test]
fn test_sdp_parsing() {
let text = "a=ice-pwd:99ad05513f44705637769b05c7e86c0b\r\na=ice-ufrag:ae11196c\r\n";
let sdp = Sdp::from(text);
assert!(sdp.ufrag.as_str() == "ae11196c");
assert!(sdp.pwd.as_str() == "99ad05513f44705637769b05c7e86c0b");
}
#[test]
fn test_candidate_parsing() {
let text =
"candidate:0 1 UDP 2122187007 9971baf2-00e6-4bb3-b954-7a61b4eb8daf.local 48155 typ host";
let candidate = parse_candidate(text);
assert!(candidate.is_ok());
let text = "candidate:4 1 TCP 2105458943 9971baf2-00e6-4bb3-b954-7a61b4eb8daf.local 9 typ host tcptype active";
let candidate = parse_candidate(text);
assert!(candidate.is_ok());
let candidate = candidate.unwrap();
assert_eq!(
candidate.typ,
CandidateType::HostTcp("9971baf2-00e6-4bb3-b954-7a61b4eb8daf.local".into())
);
let text = "candidate:1 1 UDP 1685987327 103.208.69.28 19828 typ srflx raddr 0.0.0.0 rport 0";
let candidate = parse_candidate(text);
assert!(candidate.is_ok());
let candidate = candidate.unwrap();
assert_eq!(
candidate.typ,
CandidateType::ServerReflexive("0.0.0.0".into(), "0".parse().unwrap())
);
}
|
use std::{collections::HashMap, net::SocketAddr};
use {
crate::{atom::Atom, config, document::Document, range::Range},
bincode::{deserialize, serialize},
serde::{Deserialize, Serialize},
serde_json::ser::to_vec,
std::io,
tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream},
},
tracing::{error, info, instrument},
};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum Event {
RemoteInsert { id: i64, lines: Vec<Atom> },
RemoteDelete { id: i64, lines: Vec<Atom> },
Insert { lines: Vec<char>, range: Range },
Delete { range: Range },
}
#[derive(Debug)]
pub struct Peer {
id: i64,
addr: SocketAddr,
conn: TcpStream,
}
impl Peer {
#[instrument(level = "info")]
pub fn new(id: i64, addr: SocketAddr, conn: TcpStream) -> Self {
Self { id, addr, conn }
}
/// Send the event to the peer.
#[instrument(level = "info")]
pub async fn send(&mut self, event: &Event) -> io::Result<()> {
let buf = serialize(event).unwrap();
self.conn.write_all(&buf).await
}
}
#[derive(Debug)]
pub struct Client {
addr: SocketAddr,
conn: TcpStream,
}
impl Client {
// Sends the event as a JSON payload to the frontend.
#[instrument(level = "info")]
pub fn send(&self, range: &Range, event: &Event) {
let buf = to_vec(event).expect("Unable to serialize event.");
self.conn.write_all(&buf);
}
#[instrument(level = "info")]
pub async fn connect(config: config::Client) -> Self {
if let Ok(conn) = TcpStream::connect((config.host, config.port)).await {
Self {
addr: conn.local_addr().unwrap(),
conn,
}
} else {
panic!("Unable to connect to client editor.");
}
}
}
/// A node will handle propagation of changes in its respective document.
/// Changes will be applied in a FIFO manner. Each local change will be accompanied by sending a request to each connected client to
/// apply the same change in order to keep each node's document consistent.
/// For efficiency, client connections are established at the start of the program so that connections can be re-used.
#[derive(Debug)]
pub struct Node {
host: String,
port: u16,
id: i64,
socket: TcpListener,
client: Client,
peers: HashMap<i64, Peer>,
document: Document,
}
impl Node {
/// Creates the node, creating client connections as necessary.
/// Any errors connecting will immediately terminate the initalization process.
#[instrument(level = "info")]
pub async fn init(addr: config::Client, client_addr: config::Client) -> Self {
match TcpListener::bind((addr.host.clone(), addr.port)).await {
Ok(socket) => {
info!(
"Started TCP listener on {}:{}.",
addr.host.clone(),
addr.port
);
Self {
host: addr.host,
port: addr.port,
id: -1,
socket,
client: Client::connect(client_addr).await,
peers: HashMap::new(),
document: Document::new(-1),
}
}
Err(e) => panic!(format!(
"Error connecting to local address: {}:{}",
addr.host, addr.port
)),
}
}
/// An event can come from one of two sources:
/// - The client (editor frontend); or
/// - connected peers (foreign replicated documents)
/// # Client
/// Message from client -> Update local document state -> Propagate change(s) to connected peers
/// # Peers
/// Message from peer -> Send character operation to messaging service -> Renders the new document state
#[instrument(level = "info")]
pub async fn run(&mut self) -> io::Result<()> {
info!("[{}:{}] Running node...", self.host, self.port);
loop {
let (mut conn, addr) = self.socket.accept().await?;
let mut buf = Vec::new();
conn.read_to_end(&mut buf).await?;
match deserialize::<Event>(&buf) {
Ok(event) => match event {
Event::Insert {
ref lines,
ref range,
} => {
if let Some(lines) = self.document.local_insert(range, lines) {
let event = Event::RemoteInsert { id: self.id, lines };
self.propagate(event).await;
}
}
Event::Delete { ref range } => {
if let Some(lines) = self.document.local_delete(range) {
let event = Event::RemoteDelete { id: self.id, lines };
self.propagate(event).await;
}
}
Event::RemoteInsert { id, ref lines } => {
self.add_peer(id, addr, conn);
if let Some(ref range) = self.document.remote_insert(lines) {
// send range and line contents
self.client.send(range, lines);
}
}
Event::RemoteDelete { id, ref lines } => {
self.add_peer(id, addr, conn);
if let Some(range) = self.document.remote_delete(lines) {
self.client.send(range, lines);
}
}
},
Err(e) => error!("Error parsing message from peer: {}", e),
};
}
}
/// Add a peer to the network.
/// Peers are identified by their GUID.
/// If a peer is unidentified (i.e. their GUID is either -1 (unitialized) or unknown), then it will be added to the network.
/// Otherwise, it is ignored.
#[instrument(level = "info")]
fn add_peer(&mut self, id: i64, addr: SocketAddr, conn: TcpStream) {
if !self.peers.contains_key(&id) {
self.peers.insert(id, Peer::new(id, addr, conn));
}
}
/// Send the change to each client's respective thread.
#[instrument(level = "info")]
async fn propagate(&mut self, event: Event) {
let tasks: Vec<_> = self
.peers
.iter_mut()
.map(|(_, peer)| peer.send(&event))
.collect();
for task in tasks {
if let Err(e) = task.await {
error!("Error sending change to peer: {}.", e);
}
}
}
}
#[cfg(test)]
mod tests {
use super::config::Client;
use super::Node;
#[tokio::test]
async fn test_add_node() -> Result<(), Box<dyn std::error::Error>> {
let addr = Client::new("localhost".to_string(), 2000);
let client = Client::new("localhost".to_string(), 2001);
let mut n1 = Node::init(addr, client).await;
n1.run().await?;
Ok(())
}
}
|
// Copyright (c) The diem-devtools Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
use chrono::DateTime;
use goldenfile::Mint;
use quick_junit::{
NonSuccessKind, Property, Report, TestRerun, Testcase, TestcaseStatus, Testsuite,
};
use std::time::Duration;
#[test]
fn fixtures() {
let mut mint = Mint::new("tests/fixtures");
let f = mint
.new_goldenfile("basic_report.xml")
.expect("creating new goldenfile succeeds");
let basic_report = basic_report();
basic_report
.serialize(f)
.expect("serializing basic_report succeeds");
}
fn basic_report() -> Report {
let mut report = Report::new("my-test-run");
report.set_timestamp(
DateTime::parse_from_rfc2822("Thu, 1 Apr 2021 10:52:37 -0800")
.expect("valid RFC2822 datetime"),
);
report.set_time(Duration::new(42, 234_567_890));
let mut testsuite = Testsuite::new("testsuite0");
testsuite.set_timestamp(
DateTime::parse_from_rfc2822("Thu, 1 Apr 2021 10:52:39 -0800")
.expect("valid RFC2822 datetime"),
);
// ---
let testcase_status = TestcaseStatus::success();
let mut testcase = Testcase::new("testcase0", testcase_status);
testcase.set_system_out("testcase0-output");
testsuite.add_testcase(testcase);
// ---
let mut testcase_status = TestcaseStatus::non_success(NonSuccessKind::Failure);
testcase_status
.set_description("this is the failure description")
.set_message("testcase1-message");
let mut testcase = Testcase::new("testcase1", testcase_status);
testcase
.set_system_err("some sort of failure output")
.set_time(Duration::from_millis(4242));
testsuite.add_testcase(testcase);
// ---
let mut testcase_status = TestcaseStatus::non_success(NonSuccessKind::Error);
testcase_status
.set_description("testcase2 error description")
.set_type("error type");
let mut testcase = Testcase::new("testcase2", testcase_status);
testcase.set_time(Duration::from_nanos(421580));
testsuite.add_testcase(testcase);
// ---
let mut testcase_status = TestcaseStatus::skipped();
testcase_status
.set_type("skipped type")
.set_message("skipped message");
// no description to test that.
let mut testcase = Testcase::new("testcase3", testcase_status);
testcase
.set_timestamp(
DateTime::parse_from_rfc2822("Thu, 1 Apr 2021 11:52:41 -0700")
.expect("valid RFC2822 datetime"),
)
.set_assertions(20)
.set_system_out("testcase3 output")
.set_system_err("testcase3 error");
testsuite.add_testcase(testcase);
// ---
let mut testcase_status = TestcaseStatus::success();
let mut test_rerun = TestRerun::new(NonSuccessKind::Failure);
test_rerun
.set_type("flaky failure type")
.set_description("this is a flaky failure description");
testcase_status.add_rerun(test_rerun);
let mut test_rerun = TestRerun::new(NonSuccessKind::Error);
test_rerun
.set_type("flaky error type")
.set_system_out("flaky system output")
.set_system_err("flaky system error")
.set_stack_trace("flaky stack trace")
.set_description("flaky error description");
testcase_status.add_rerun(test_rerun);
let mut testcase = Testcase::new("testcase4", testcase_status);
testcase.set_time(Duration::from_millis(661661));
testsuite.add_testcase(testcase);
// ---
let mut testcase_status = TestcaseStatus::non_success(NonSuccessKind::Failure);
testcase_status.set_description("main test failure description");
let mut test_rerun = TestRerun::new(NonSuccessKind::Failure);
test_rerun.set_type("retry failure type");
testcase_status.add_rerun(test_rerun);
let mut test_rerun = TestRerun::new(NonSuccessKind::Error);
test_rerun
.set_type("retry error type")
.set_system_out("retry error system output")
.set_stack_trace("retry error stack trace");
testcase_status.add_rerun(test_rerun);
let mut testcase = Testcase::new("testcase5", testcase_status);
testcase.set_time(Duration::from_millis(156));
testsuite.add_testcase(testcase);
testsuite.add_property(Property::new("env", "FOOBAR"));
report.add_testsuite(testsuite);
report
}
|
// client (p2p) packets
use serde::{Deserialize, Serialize};
// the version constant. increased by 100 every minor client version, and by 10000 every major
// version. eg. 200 is 0.2.0, 10000 is 1.0.0, 10203 is 1.2.3.
// if two versions' hundreds places differ, the versions are incompatible.
pub const PROTOCOL_VERSION: u32 = 200;
pub fn versions_compatible(v1: u32, v2: u32) -> bool {
v1 / 100 == v2 / 100
}
pub fn compatible_with(v: u32) -> bool {
versions_compatible(PROTOCOL_VERSION, v)
}
// stroke packet information
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct StrokePoint {
// 29.3 fixed-point coordinates of the point
pub x: i32,
pub y: i32,
// hex-encoded color
// a value of 0 is special and means eraser mode
pub color: u32,
// 15.1 fixed-point brush size
pub brush_size: i16,
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum Packet {
// ---
// VERSION 0.1.0 (no version packet)
// ---
//
// introduction protocol
//
// introduction to other clients. the string contains the nickname
Hello(String),
// response from the other clients with their nicknames
HiThere(String),
// image data sent to a client by the host when it first joins
#[deprecated(since = "0.2.0", note = "use Chunks instead; will be removed in 0.3.0")]
CanvasData((i32, i32), Vec<u8>),
//
// painting
// --------
// these packets are sent 20 times per second
//
// cursor packet containing fixed-point 29.3 coordinates and a fixed-point 31.1 brush size
Cursor(i32, i32, i16),
// a paint stroke
Stroke(Vec<StrokePoint>),
// ---
// VERSION 0.2.0 (protocol 200)
// ---
// version packet. this is sent as part of a response to Hello
Version(u32),
// sent by the host to a client upon connection
ChunkPositions(Vec<(i32, i32)>),
// request from the client to download chunks
GetChunks(Vec<(i32, i32)>),
// response from the other peer with the chunks encoded as PNG images.
Chunks(Vec<((i32, i32), Vec<u8>)>),
}
/// converts a float to a fixed-point 29.3
pub fn to_fixed29p3(x: f32) -> i32 {
(x * 8.0).round() as i32
}
/// converts a float to a fixed-point 15.1
pub fn to_fixed15p1(x: f32) -> i16 {
(x * 2.0).round() as i16
}
/// converts a fixed-point 29.3 to a float
pub fn from_fixed29p3(x: i32) -> f32 {
x as f32 / 8.0
}
/// converts a fixed-point 15.1 to a float
pub fn from_fixed15p1(x: i16) -> f32 {
x as f32 / 2.0
}
|
pub mod database_initialization;
pub mod role_permissions;
use std::env;
use tokio_postgres::NoTls;
pub struct DatabaseConnection {
pub client: tokio_postgres::Client,
}
static mut CONNECTION: Option<DatabaseConnection> = None;
pub async fn get_connection<'a>() -> &'a DatabaseConnection {
unsafe {
if CONNECTION.is_none() {
CONNECTION = Some(DatabaseConnection::create().await);
}
if CONNECTION.as_ref().unwrap().client.is_closed() {
CONNECTION = Some(DatabaseConnection::create().await);
}
CONNECTION.as_ref().unwrap()
}
}
impl DatabaseConnection {
async fn create() -> DatabaseConnection {
info!("Connecting to database");
let (client, conn) = tokio_postgres::connect(
env::var("DB_CONNECTION_STRING")
.expect("DB Connection String was not set!")
.as_str(),
NoTls,
)
.await
.expect("Failed to connect to database");
tokio::spawn(async move {
if let Err(e) = conn.await {
error!("Database connection error: {}", e);
}
});
DatabaseConnection { client }
}
}
|
use super::expression::Expression;
use crate::types;
#[derive(Clone, Debug, PartialEq)]
pub struct Record {
type_: types::Record,
elements: Vec<Expression>,
}
impl Record {
pub fn new(type_: types::Record, elements: Vec<Expression>) -> Self {
Self { type_, elements }
}
pub fn type_(&self) -> &types::Record {
&self.type_
}
pub fn elements(&self) -> &[Expression] {
&self.elements
}
}
|
#[derive(PrimitiveEnum_u8)]
#[derive(Debug, Copy, Clone, PartialEq)]
#[allow(non_camel_case_types)]
/// MSP command values, used for command encapsulation
pub enum MspCommandCode {
MSP_API_VERSION = 1,
MSP_FC_VARIANT = 2,
MSP_FC_VERSION = 3,
MSP_BOARD_INFO = 4,
MSP_BUILD_INFO = 5,
// MSP commands for Cleanflight original features
MSP_BATTERY_CONFIG = 32,
MSP_SET_BATTERY_CONFIG = 33,
MSP_MODE_RANGES = 34,
MSP_SET_MODE_RANGE = 35,
MSP_FEATURE = 36,
MSP_SET_FEATURE = 37,
MSP_BOARD_ALIGNMENT = 38,
MSP_SET_BOARD_ALIGNMENT = 39,
MSP_AMPERAGE_METER_CONFIG = 40,
MSP_SET_AMPERAGE_METER_CONFIG =41,
MSP_MIXER = 42,
MSP_SET_MIXER = 43,
MSP_RX_CONFIG = 44,
MSP_SET_RX_CONFIG = 45,
MSP_LED_COLORS = 46,
MSP_SET_LED_COLORS = 47,
MSP_LED_STRIP_CONFIG = 48,
MSP_SET_LED_STRIP_CONFIG = 49,
MSP_RSSI_CONFIG = 50,
MSP_SET_RSSI_CONFIG = 51,
MSP_ADJUSTMENT_RANGES = 52,
MSP_SET_ADJUSTMENT_RANGE = 53,
MSP_CF_SERIAL_CONFIG = 54,
MSP_SET_CF_SERIAL_CONFIG = 55,
MSP_VOLTAGE_METER_CONFIG = 56,
MSP_SET_VOLTAGE_METER_CONFIG =57,
MSP_SONAR = 58,
MSP_PID_CONTROLLER = 59,
MSP_SET_PID_CONTROLLER = 60,
MSP_ARMING_CONFIG = 61,
MSP_SET_ARMING_CONFIG = 62,
MSP_DATAFLASH_SUMMARY = 70,
MSP_DATAFLASH_READ = 71,
MSP_DATAFLASH_ERASE = 72,
MSP_LOOP_TIME = 73,
MSP_SET_LOOP_TIME = 74,
MSP_FAILSAFE_CONFIG = 75,
MSP_SET_FAILSAFE_CONFIG = 76,
MSP_RXFAIL_CONFIG = 77,
MSP_SET_RXFAIL_CONFIG = 78,
MSP_SDCARD_SUMMARY = 79,
MSP_BLACKBOX_CONFIG = 80,
MSP_SET_BLACKBOX_CONFIG = 81,
MSP_TRANSPONDER_CONFIG = 82,
MSP_SET_TRANSPONDER_CONFIG = 83,
MSP_LED_STRIP_MODECOLOR = 127,
MSP_SET_LED_STRIP_MODECOLOR = 221,
MSP_VOLTAGE_METERS = 128,
MSP_AMPERAGE_METERS = 129,
MSP_BATTERY_STATE = 130,
MSP_MOTOR_CONFIG = 131,
// OSD commands
MSP_OSD_VIDEO_CONFIG = 180,
MSP_SET_OSD_VIDEO_CONFIG = 181,
MSP_OSD_VIDEO_STATUS = 182,
MSP_OSD_ELEMENT_SUMMARY = 183,
MSP_OSD_LAYOUT_CONFIG = 184,
MSP_SET_OSD_LAYOUT_CONFIG = 185,
// Multiwii MSP commands
MSP_IDENT = 100,
MSP_STATUS = 101,
MSP_RAW_IMU = 102,
MSP_SERVO = 103,
MSP_MOTOR = 104,
MSP_RC = 105,
MSP_RAW_GPS = 106,
MSP_COMP_GPS = 107,
MSP_ATTITUDE = 108,
MSP_ALTITUDE = 109,
MSP_ANALOG = 110,
MSP_RC_TUNING = 111,
MSP_PID = 112,
MSP_BOX = 113,
MSP_MISC = 114,
MSP_MOTOR_PINS = 115,
MSP_BOXNAMES = 116,
MSP_PIDNAMES = 117,
MSP_WP = 118,
MSP_BOXIDS = 119,
MSP_SERVO_CONFIGURATIONS = 120,
MSP_MOTOR_3D_CONFIG = 124,
MSP_RC_DEADBAND = 125,
MSP_SENSOR_ALIGNMENT = 126,
MSP_SET_RAW_RC = 200,
MSP_SET_RAW_GPS = 201,
MSP_SET_PID = 202,
MSP_SET_BOX = 203,
MSP_SET_RC_TUNING = 204,
MSP_ACC_CALIBRATION = 205,
MSP_MAG_CALIBRATION = 206,
MSP_SET_MISC = 207,
MSP_RESET_CONF = 208,
MSP_SET_WP = 209,
MSP_SELECT_SETTING = 210,
MSP_SET_HEAD = 211,
MSP_SET_SERVO_CONFIGURATION = 212,
MSP_SET_MOTOR = 214,
MSP_SET_3D = 217,
MSP_SET_RC_DEADBAND = 218,
MSP_SET_RESET_CURR_PID = 219,
MSP_SET_SENSOR_ALIGNMENT = 220,
// MSP_BIND = 240,
MSP_SERVO_MIX_RULES = 241,
MSP_SET_SERVO_MIX_RULE = 242,
MSP_EEPROM_WRITE = 250,
MSP_DEBUGMSG = 253,
MSP_DEBUG = 254,
MSP_BF_CONFIG = 66,
// Additional baseflight commands that are not compatible with MultiWii
MSP_UID = 160, // Unique device ID
MSP_STATUS_EX = 150, // cycletime, errors_count, CPU load, sensor present etc
MSP_ACC_TRIM = 240, // get acc angle trim values
MSP_SET_ACC_TRIM = 239, // set acc angle trim values
MSP_GPS_SV_INFO = 164, // get Signal Strength
// Additional private MSP for baseflight configurator
MSP_RX_MAP = 64, // get channel map (also returns number of channels total)
MSP_SET_RX_MAP = 65, // set rc map, numchannels to set comes from MSP_RX_MAP
MSP_SET_REBOOT = 68, // reboot settings
MSP_BF_BUILD_INFO = 69, // build date as well as some space for future expansion,
// Betaflight
MSP_ADVANCED_CONFIG = 90,
MSP_SET_ADVANCED_CONFIG = 91,
MSP_FILTER_CONFIG = 92,
MSP_SET_FILTER_CONFIG = 93,
MSP_PID_ADVANCED = 94,
MSP_SET_PID_ADVANCED = 95,
MSP_SENSOR_CONFIG = 96,
MSP_SET_SENSOR_CONFIG = 97
}
|
#![no_main]
extern crate abxml;
#[macro_use]
extern crate libfuzzer_sys;
use abxml::chunks::XmlNamespaceStartWrapper;
use abxml::model::NamespaceStart;
fuzz_target!(|data: &[u8]| {
let xnsw = XmlNamespaceStartWrapper::new(data);
xnsw.get_prefix_index();
xnsw.get_namespace_index();
xnsw.get_line();
});
|
use friday_error::FridayError;
use std::fmt;
pub enum Symbol {
Own
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Symbol::Own => f.write_str("**")
}
}
}
#[derive(Clone)]
pub struct Path {
components: Vec<String>
}
impl Path {
pub fn new<S: AsRef<str>>(path: S) -> Result<Path, FridayError> {
// TODO: Maybe do some path validation?
Ok(Path {
components: path.as_ref()
.split("/")
.filter(|s| s.len() > 0)
.map(|s| s.to_owned())
.collect()
})
}
pub fn safe_new<S: AsRef<str>>(path: S) -> Path {
// Here we trust the input to be correct..
// TODO: is there some better way to get compile-time guarantees
// and retain nice UX for coding Web vendors?
Path {
components: path.as_ref()
.split("/")
.filter(|s| s.len() > 0)
.map(|s| s.to_owned())
.collect()
}
}
fn is_own(s: Option<&String>) -> bool {
if s.is_none() {
return false;
}
return s.unwrap().eq(&Symbol::Own.to_string());
}
fn is_equal(a: Option<&String>, b: Option<&String>) -> bool {
// Wish we could lift option values
match a.map(|x| b.map(|y| x == y)) {
None => false,
Some(v) => match v {
None => false,
Some(v) => v
}
}
}
/// Checks if two paths point to the same resource
pub fn overlap(a: &Path, b: &Path) -> bool {
// This functions check if two paths overlap
// if paths use no special syntax this is the same as equivalence
let mut a_it = a.components.iter();
let mut b_it = b.components.iter();
loop {
let a_next = a_it.next();
let b_next = b_it.next();
// If both are None they match
if a_next.is_none() && b_next.is_none() {
return true;
}
// If one is own we have a match
if Path::is_own(a_next) || Path::is_own(b_next) {
return true;
}
// If they are not equal we don't have a match
if !Path::is_equal(a_next, b_next) {
return false;
}
}
}
}
/// Return a path relative to some base e.g
/// "/static/some_path/some_file.ext" with base "static" returns
/// "/some_path/some_file.ext"
pub fn rel_from<S: AsRef<str>>(path: S, base: S) -> Option<String> {
return Path::new(path).map_or_else(
|_| None,
|path| {
let mut it = path.components.iter();
loop {
match it.next() {
None => return None,
Some(comp) => {
if comp == base.as_ref() {
return Some(it.fold(String::new(), |acc, v| acc + "/" + v))
}
}
}
}
});
}
impl fmt::Debug for Path {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("\n").unwrap();
for (i, entry) in self.components.iter().enumerate() {
f.write_str(&i.to_string()).unwrap();
f.write_str(" ").unwrap();
f.write_str(&entry).unwrap();
f.write_str("\n").unwrap();
}
f.write_str("\n").unwrap();
return Ok(())
}
}
impl fmt::Display for Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(
self.components.iter()
.fold(String::new(), |acc, v| acc + "/" + v)
.as_str()
).unwrap();
return Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn make_path() {
let mut path = Path::new("/hello/world").expect("Failed to make path");
assert_eq!(path.components, vec!["hello", "world"]);
path = Path::new("/").expect("Failed to make path");
assert_eq!(path.components, Vec::<String>::new());
path = Path::new("").expect("Failed to make path");
assert_eq!(path.components, Vec::<String>::new());
path = Path::new("/hello/world/").expect("Failed to make path");
assert_eq!(path.components, vec!["hello", "world"]);
}
#[test]
fn check_overlap() {
let mut a = Path::new("/hello/world").expect("Failed to make path");
let mut b = Path::new("/hello/world").expect("Failed to make path");
assert!(Path::overlap(&a, &b));
a = Path::new("/").expect("Failed to make path");
b = Path::new("").expect("Failed to make path");
assert!(Path::overlap(&a, &b));
a = Path::new("/hello").expect("Failed to make path");
b = Path::new("/hello/world").expect("Failed to make path");
assert!(!Path::overlap(&a, &b));
a = Path::new("hello").expect("Failed to make path");
b = Path::new("/hello").expect("Failed to make path");
// TODO: Is this a problem yay or nay?
assert!(Path::overlap(&a, &b));
a = Path::new(format!("/{}", Symbol::Own)).expect("");
b = Path::new("/").expect("Failed to make path");
assert!(Path::overlap(&a, &b));
a = Path::new(format!("/static/{}", Symbol::Own)).expect("");
b = Path::new("/static/hello.js").expect("Failed to make path");
assert!(Path::overlap(&a, &b));
a = Path::new(format!("/static/{}", Symbol::Own)).expect("");
b = Path::new("/hue/").expect("");
assert!(!Path::overlap(&a, &b));
}
}
|
#[doc = "Register `PKGR` reader"]
pub type R = crate::R<PKGR_SPEC>;
#[doc = "Field `PKG` reader - Package"]
pub type PKG_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:3 - Package"]
#[inline(always)]
pub fn pkg(&self) -> PKG_R {
PKG_R::new((self.bits & 0x0f) as u8)
}
}
#[doc = "SYSCFG package register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pkgr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PKGR_SPEC;
impl crate::RegisterSpec for PKGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pkgr::R`](R) reader structure"]
impl crate::Readable for PKGR_SPEC {}
#[doc = "`reset()` method sets PKGR to value 0"]
impl crate::Resettable for PKGR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::{
collections::HashMap,
convert::TryFrom,
fmt,
fs::File,
io::{Read, Write},
path::PathBuf,
process::{self, Command},
rc::Rc,
};
use cargo_lock::{Dependency, Lockfile};
use cargo_metadata::MetadataCommand;
use cargo_toml::{Edition, Manifest};
use petgraph::visit::Bfs;
macro_rules! log {
($msg:expr) => {
println!("==> {}", $msg)
};
($fmt:expr, $($args:expr),+) => {
println!(concat!("==> ", $fmt), $($args),+)
};
}
macro_rules! vlog {
($verb:expr, $msg:expr) => {
if $verb {
log!($msg)
}
};
($verb:expr, $fmt:expr, $($args:expr),+) => {
if $verb {
log!($fmt, $($args),+);
}
};
}
const PREAMBLE: &str = "# Rules generated by bygge. DO NOT MODIFY BY HAND!";
const DEFAULT_RULES: &str = r#"
rule cargo-fetch
command = cargo fetch --manifest-path $in && touch $out
description = CARGO $in
rule rustc
command = CARGO_PKG_VERSION="$version" CARGO_PKG_NAME="$name" rustc --crate-name $name $in --emit=$emit --out-dir $outdir $extraargs $args && sed -i.bak '/\.d:/g' $depfile
description = RUSTC $out
depfile = $depfile
deps = gcc
build Cargo.lock: cargo-fetch Cargo.toml
"#;
struct Error(String);
impl Error {
fn new<S: Into<String>>(msg: S) -> Error {
Error(msg.into())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Error: {}", self.0)
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for Error {}
enum Task {
Build,
Create,
}
impl TryFrom<&str> for Task {
type Error = Error;
fn try_from(cmd: &str) -> Result<Task, Error> {
match cmd {
"build" => Ok(Task::Build),
"create" => Ok(Task::Create),
_ => Err(Error::new(format!("invalid command: {:?}", cmd))),
}
}
}
#[derive(Debug)]
struct Args {
help: bool,
version: bool,
verbose: bool,
release: bool,
manifest_path: String,
lockfile: String,
ninja_file: String,
command: String,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = pico_args::Arguments::from_env();
// Arguments can be parsed in any order.
let args = Args {
help: args.contains(["-h", "--help"]),
version: args.contains(["-V", "--version"]),
verbose: args.contains(["-v", "--verbose"]),
release: args.contains(["-r", "--release"]),
manifest_path: args
.opt_value_from_str(["-p", "--manifest-path"])?
.unwrap_or_else(|| "Cargo.toml".into()),
lockfile: args
.opt_value_from_str(["-l", "--lockfile"])?
.unwrap_or_else(|| "Cargo.lock".into()),
ninja_file: args
.opt_value_from_str(["-n", "--ninjafile"])?
.unwrap_or_else(|| "build.ninja".into()),
command: args.subcommand()?.unwrap_or_else(|| "".into()),
};
if args.version {
println!("bygge v{}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
if args.help {
usage();
return Ok(());
}
match Task::try_from(&*args.command) {
Ok(Task::Create) => create(args)?,
Ok(Task::Build) => build(args)?,
Err(e) => {
println!("{}\n", e);
usage();
process::exit(1);
}
}
Ok(())
}
fn registry_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
const REGISTRY_PATH: &str = ".cargo/registry/src/github.com-1ecc6299db9ec823";
match dirs::home_dir() {
Some(home) => Ok(home.join(REGISTRY_PATH)),
None => Err(Error::new("Can't get home directory").into()),
}
}
fn create(args: Args) -> Result<(), Box<dyn std::error::Error>> {
log!("Creating build file: {}", args.ninja_file);
command(
args.verbose,
&["cargo", "fetch", "--manifest-path", &args.manifest_path],
)?;
let mut rules = File::create(&args.ninja_file)?;
writeln!(rules, "{}", PREAMBLE)?;
writeln!(rules, "builddir = build")?;
write!(rules, r#"extraargs = --cap-lints allow -C debuginfo=2 "#)?;
if args.release {
vlog!(args.verbose, "Enabling optimizations for build artifacts");
write!(rules, " -C opt-level=3")?;
} else {
vlog!(args.verbose, "No optimizations for build artifacts");
}
writeln!(rules, "\n{}", DEFAULT_RULES)?;
let lockfile = Lockfile::load(&args.lockfile)?;
let manifest = Manifest::from_path(&args.manifest_path)?;
let package = manifest.package.unwrap();
let pkg_name = package.name;
log!("Package: {}", pkg_name);
let mut crates = Vec::new();
let mut crate_cache = HashMap::new();
let mut crate_features_cache = HashMap::new();
let mut cmd = MetadataCommand::new();
cmd.manifest_path(&args.manifest_path);
let metadata = cmd.exec()?;
let resolve = metadata.resolve.unwrap();
let packages = metadata.packages;
for node in resolve.nodes {
let id = node.id.clone();
let package = match packages.iter().find(|p| p.id == id) {
Some(package) => package,
None => continue,
};
let features: Vec<_> = node.features.iter().map(|f| f.to_string()).collect();
crate_features_cache.insert(
format!(
"{}:{}",
normalize_crate_name(&package.name),
package.version
),
features,
);
}
let root_package = lockfile
.packages
.iter()
.find(|pkg| pkg.name.as_str() == pkg_name)
.unwrap();
if args.verbose {
log!("Detected {} dependencies.", lockfile.packages.len());
}
let tree = lockfile.dependency_tree()?;
let nodes = tree.nodes();
let graph = tree.graph();
let (_, &root_idx) = nodes
.iter()
.find(|(dep, _)| dep.matches(root_package))
.unwrap();
// First pass: collect all information about all crates.
let mut bfs = Bfs::new(&graph, root_idx);
while let Some(nx) = bfs.next(&graph) {
let node = &graph[nx];
let pkg_name = node.name.as_str();
let version = format!("{}", node.version);
let dependencies = node.dependencies.clone();
let c = if nx == root_idx {
Crate {
name: pkg_name.into(),
normalized_name: normalize_crate_name(pkg_name),
version: format!("{}", node.version),
crate_type: CrateType::Bin,
entry_path: "src/main.rs".into(),
edition: Edition::E2018,
implicit_deps: vec![args.lockfile.clone()],
dependencies,
enabled_features: vec![],
}
} else {
if skip_dep(pkg_name) {
continue;
}
let crate_path = registry_path()?.join(&format!(
"{pkg}-{version}",
pkg = pkg_name,
version = version,
));
let toml_path = crate_path.join("Cargo.toml");
let mut f = File::open(&toml_path)?;
let mut buffer = Vec::new();
f.read_to_end(&mut buffer)?;
let manifest = Manifest::from_slice(&buffer)?;
let (entry, proc_macro) = manifest
.lib
.map(|lib| {
(
lib.path.unwrap_or_else(|| "src/lib.rs".into()),
lib.proc_macro,
)
})
.unwrap_or_else(|| ("src/lib.rs".into(), false));
let entry_path = crate_path.join(entry);
let entry_path = entry_path.display().to_string();
let crate_type = if proc_macro {
CrateType::ProcMacro
} else {
CrateType::Lib
};
let edition = manifest.package.unwrap().edition;
let normalized_name = normalize_crate_name(pkg_name);
let version = format!("{}", node.version);
let enabled_features = crate_features_cache
.get(&format!("{}:{}", normalized_name, version))
.cloned()
.unwrap_or_default();
Crate {
name: pkg_name.into(),
normalized_name,
version,
crate_type,
entry_path,
edition,
implicit_deps: vec![],
dependencies,
enabled_features,
}
};
let c = Rc::new(c);
crates.push(c.clone());
crate_cache.insert(format!("{}:{}", c.name, c.version), c);
}
// Second pass: Write out the rules.
for pkg in crates {
build_rule(&crate_cache, &rules, &pkg)?;
if let CrateType::Bin = pkg.crate_type {
writeln!(rules, "default $builddir/{}\n", &pkg.normalized_name)?;
}
}
Ok(())
}
fn build(args: Args) -> Result<(), Box<dyn std::error::Error>> {
let mut cmd = vec!["ninja", "-f", &args.ninja_file];
if args.verbose {
cmd.push("--verbose");
}
command(args.verbose, &cmd)?;
Ok(())
}
fn command(verbose: bool, cmdline: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
vlog!(verbose, "Running: {}", cmdline.join(" "));
Command::new(cmdline[0])
.args(&cmdline[1..])
.status()
.map_err(|_| Error::new(format!("failed to run `{}`", cmdline[0])))
.and_then(|status| {
if status.success() {
Ok(())
} else {
Err(Error::new(format!("`{}` failed.", cmdline[0])))
}
})?;
Ok(())
}
fn build_rule<W: Write>(
crate_cache: &HashMap<String, Rc<Crate>>,
mut out: W,
pkg: &Crate,
) -> Result<(), Box<dyn std::error::Error>> {
write!(
out,
"build {}: rustc {} | {} ",
pkg.target(),
pkg.entry_path,
pkg.implicit_deps.join(" ")
)?;
for dep in &pkg.dependencies {
if skip_dep(dep.name.as_str()) {
continue;
}
let dep_type = crate_cache
.get(&format!("{}:{}", dep.name.as_str(), dep.version))
.expect(&format!(
"No crate-type known for {}:{}",
dep.name.as_str(),
dep.version
))
.crate_type;
write!(
out,
"$builddir/deps/lib{}.{} ",
normalize_crate_name(dep.name.as_str()),
dep_type.suffix()
)?;
}
writeln!(out)?;
writeln!(out, " name = {}", pkg.normalized_name)?;
writeln!(out, " version = {}", pkg.version)?;
write!(
out,
" args = --crate-type {} --edition {} -L dependency=$builddir/deps ",
pkg.crate_type,
edition_str(pkg.edition),
)?;
for feature in &pkg.enabled_features {
write!(out, "--cfg 'feature=\"{}\"' ", feature)?;
}
// We don't handle build.rs yet,
// so let's hackily add some cfgs to make libc and others compile correctly.
if pkg.normalized_name == "libc" {
write!(
out,
r#"--cfg libc_priv_mod_use --cfg libc_union --cfg libc_const_size_of --cfg libc_align --cfg libc_core_cvoid --cfg libc_packedN "#
)?;
}
if pkg.normalized_name == "indexmap" {
write!(out, "--cfg has_std ")?;
}
if pkg.normalized_name == "proc_macro2" {
write!(out, "--cfg use_proc_macro --cfg wrap_proc_macro ")?;
}
if pkg.normalized_name == "serde" {
write!(
out,
r#"--cfg ops_bound --cfg core_reverse --cfg de_boxed_c_str --cfg de_boxed_path --cfg de_rc_dst --cfg core_duration --cfg integer128 --cfg range_inclusive --cfg num_nonzero --cfg core_try_from --cfg num_nonzero_signed --cfg std_atomic64 --cfg std_atomic "#
)?;
}
for dep in &pkg.dependencies {
if skip_dep(dep.name.as_str()) {
continue;
}
let dep_type = crate_cache
.get(&format!("{}:{}", dep.name.as_str(), dep.version))
.expect(&format!(
"No crate-type known for {}:{}",
dep.name.as_str(),
dep.version
))
.crate_type;
write!(
out,
"--extern {}=$builddir/deps/lib{}.{} ",
normalize_crate_name(dep.name.as_str()),
normalize_crate_name(dep.name.as_str()),
dep_type.suffix(),
)?;
}
writeln!(out)?;
writeln!(out, " outdir = {}", pkg.outdir())?;
writeln!(out, " emit = {}", pkg.crate_type.emit())?;
writeln!(
out,
" depfile = {}/{}.d",
pkg.outdir(),
pkg.normalized_name
)?;
writeln!(out)?;
Ok(())
}
fn normalize_crate_name(crate_name: &str) -> String {
crate_name.replace('-', "_")
}
fn edition_str(ed: Edition) -> &'static str {
use Edition::*;
match ed {
E2018 => "2018",
_ => "2015",
}
}
#[derive(Clone, Copy, Debug)]
enum CrateType {
Bin,
Lib,
ProcMacro,
}
impl CrateType {
fn suffix(&self) -> &'static str {
match self {
Self::Bin => "",
Self::ProcMacro => {
if cfg!(target_os = "macos") {
"dylib"
} else if cfg!(target_os = "windows") {
"dll"
} else {
// Fallback (and default for Unix)
"so"
}
}
_ => "rlib",
}
}
fn emit(&self) -> &'static str {
match self {
Self::Bin => "dep-info,link",
_ => "dep-info,metadata,link",
}
}
}
impl fmt::Display for CrateType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use CrateType::*;
let v = match self {
Bin => "bin",
Lib => "lib",
ProcMacro => "proc-macro",
};
write!(f, "{}", v)
}
}
struct Crate {
name: String,
normalized_name: String,
version: String,
crate_type: CrateType,
entry_path: String,
edition: Edition,
implicit_deps: Vec<String>,
dependencies: Vec<Dependency>,
enabled_features: Vec<String>,
}
impl Crate {
fn target(&self) -> String {
match self.crate_type {
CrateType::Bin => format!("$builddir/{}", self.normalized_name),
_ => format!(
"$builddir/deps/lib{pkg}.{suffix} $builddir/deps/lib{pkg}.rmeta",
pkg = self.normalized_name,
suffix = self.crate_type.suffix(),
),
}
}
fn outdir(&self) -> &'static str {
match self.crate_type {
CrateType::Bin => "$builddir",
_ => "$builddir/deps",
}
}
}
fn skip_dep(name: &str) -> bool {
// Skipping some crates we know we can't build
name.contains("redox")
}
fn usage() {
const USAGE: &str = r#"
USAGE:
bygge [OPTIONS] [SUBCOMMAND]
OPTIONS:
-p, --manifest-path Path to Cargo.toml [default: Cargo.toml]
-l, --lockfile Path to Cargo.lock [default: Cargo.lock]
-n, --ninjafile Path to build file [default: build.ninja]
-r, --release Build artifacts in release mode, with optimizations
-v, --verbose Enable verbose output
-h, --help Print this help and exit
-V, --version Print version info and exit
Available subcommands:
build Run the ninja build.
create Create the ninja configuration.
"#;
println!("{} v{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
print!("{}", USAGE);
}
|
extern crate rss;
use rss::Channel;
use rss::extension::dublincore::DublinCoreExtension;
use rss::extension::get_extension_values;
#[test]
fn read_channel() {
let input = include_str!("data/channel.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
assert_eq!(channel.title, "Title");
assert_eq!(channel.link, "http://example.com/");
assert_eq!(channel.description, "Description");
assert_eq!(channel.language.as_ref().map(|s| s.as_str()), Some("en-US"));
assert_eq!(channel.managing_editor.as_ref().map(|s| s.as_str()),
Some("editor@example.com"));
assert_eq!(channel.webmaster.as_ref().map(|s| s.as_str()),
Some("webmaster@example.com"));
assert_eq!(channel.pub_date.as_ref().map(|s| s.as_str()),
Some("Sat, 27 Aug 2016 00:00:00 GMT"));
assert_eq!(channel.last_build_date.as_ref().map(|s| s.as_str()),
Some("Sat, 27 Aug 2016 09:00:00 GMT"));
assert_eq!(channel.generator.as_ref().map(|s| s.as_str()),
Some("Generator"));
assert_eq!(channel.docs.as_ref().map(|s| s.as_str()),
Some("http://blogs.law.harvard.edu/tech/rss"));
assert_eq!(channel.ttl.as_ref().map(|s| s.as_str()), Some("60"));
assert_eq!(channel.skip_hours[0].as_str(), "6");
assert_eq!(channel.skip_hours[1].as_str(), "8");
assert_eq!(channel.skip_days[0].as_str(), "Tuesday");
assert_eq!(channel.skip_days[1].as_str(), "Thursday");
}
#[test]
fn read_item() {
let input = include_str!("data/item.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
let item = &channel.items[0];
assert_eq!(item.title.as_ref().map(|s| s.as_str()), Some("Title"));
assert_eq!(item.link.as_ref().map(|s| s.as_str()),
Some("http://example.com/"));
assert_eq!(item.description.as_ref().map(|s| s.as_str()),
Some("Description"));
assert_eq!(item.author.as_ref().map(|s| s.as_str()),
Some("author@example.com"));
assert_eq!(item.comments.as_ref().map(|s| s.as_str()), Some("Comments"));
assert_eq!(item.pub_date.as_ref().map(|s| s.as_str()),
Some("Sat, 27 Aug 2016 00:00:00 GMT"));
}
#[test]
fn read_content() {
let input = include_str!("data/content.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
assert_eq!(channel.items[0].content.as_ref().map(|s| s.as_str()),
Some("An example <a href=\"http://example.com/\">link</a>."));
}
#[test]
fn read_source() {
let input = include_str!("data/source.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
assert_eq!(channel.items[0].source.as_ref().map(|v| v.url.as_str()),
Some("http://example.com/feed/"));
assert_eq!(channel.items[0].source.as_ref().and_then(|v| v.title.as_ref().map(|s| s.as_str())),
Some("Feed"));
}
#[test]
fn read_guid() {
let input = include_str!("data/guid.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
assert_eq!(channel.items[0].guid.as_ref().map(|v| v.is_permalink),
Some(false));
assert_eq!(channel.items[0].guid.as_ref().map(|v| v.value.as_str()),
Some("abc"));
assert_eq!(channel.items[1].guid.as_ref().map(|v| v.is_permalink),
Some(true));
assert_eq!(channel.items[1].guid.as_ref().map(|v| v.value.as_str()),
Some("def"));
}
#[test]
fn read_enclosure() {
let input = include_str!("data/enclosure.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
assert_eq!(channel.items[0].enclosure.as_ref().map(|v| v.url.as_str()),
Some("http://example.com/media.mp3"));
assert_eq!(channel.items[0].enclosure.as_ref().map(|v| v.length.as_str()),
Some("4992349"));
assert_eq!(channel.items[0].enclosure.as_ref().map(|v| v.mime_type.as_str()),
Some("audio/mpeg"));
}
#[test]
fn read_category() {
let input = include_str!("data/category.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
assert_eq!(channel.categories[0].domain, None);
assert_eq!(channel.categories[0].name, "Category 1");
assert_eq!(channel.categories[1].domain.as_ref().map(|s| s.as_str()),
Some("http://example.com/"));
assert_eq!(channel.categories[1].name, "Category 2");
assert_eq!(channel.items[0].categories[0].domain, None);
assert_eq!(channel.items[0].categories[0].name, "Category 1");
assert_eq!(channel.items[0].categories[1].domain.as_ref().map(|s| s.as_str()),
Some("http://example.com/"));
assert_eq!(channel.items[0].categories[1].name, "Category 2");
}
#[test]
fn read_image() {
let input = include_str!("data/image.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
let image = channel.image.as_ref().expect("image missing");
assert_eq!(image.title, "Title");
assert_eq!(image.url, "http://example.org/url");
assert_eq!(image.link, "http://example.org/link");
assert_eq!(image.width.as_ref().map(|s| s.as_str()), Some("100"));
assert_eq!(image.height.as_ref().map(|s| s.as_str()), Some("200"));
assert_eq!(image.description.as_ref().map(|s| s.as_str()),
Some("Description"));
}
#[test]
fn read_mixed_content() {
let input = include_str!("data/mixed_content.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
assert_eq!(channel.title, "Title");
}
#[test]
fn read_cloud() {
let input = include_str!("data/cloud.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
let cloud = channel.cloud.expect("cloud missing");
assert_eq!(cloud.domain, "example.com");
assert_eq!(cloud.port, "80");
assert_eq!(cloud.path, "/rpc");
assert_eq!(cloud.register_procedure, "notify");
assert_eq!(cloud.protocol, "xml-rpc");
}
#[test]
fn read_textinput() {
let input = include_str!("data/textinput.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
let text_input = channel.text_input.expect("textinput missing");
assert_eq!(text_input.title, "Title");
assert_eq!(text_input.name, "Name");
assert_eq!(text_input.link, "http://example.com/");
assert_eq!(text_input.description, "Description");
}
#[test]
fn read_extension() {
let input = include_str!("data/extension.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
let ns = channel.namespaces.get("ext").expect("failed to find namespace");
assert_eq!(ns, "http://example.com/");
assert_eq!(channel.namespaces.len(), 1);
let ext = channel.items[0].extensions.get("ext").expect("failed to find extension");
assert_eq!(get_extension_values(&ext, "creator"),
Some(vec!["Creator Name"]));
assert_eq!(get_extension_values(&ext, "contributor"),
Some(vec!["Contributor 1", "Contributor 2"]));
assert_eq!(ext.get("parent")
.map(|v| {
v.iter()
.find(|v| v.children.contains_key("child"))
.expect("failed to find child elements")
.children
.get("child")
.unwrap()
.iter()
.map(|v| v.value.as_ref().map(|s| s.as_str()))
.collect::<Vec<_>>()
}),
Some(vec![Some("Child 1"), Some("Child 2")]));
}
#[test]
fn read_itunes() {
let input = include_str!("data/itunes.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
let itunes = channel.itunes_ext.as_ref().expect("itunes extension missing");
assert_eq!(itunes.author.as_ref().map(|s| s.as_str()), Some("Author"));
assert_eq!(itunes.block.as_ref().map(|s| s.as_str()), Some("yes"));
assert_eq!(itunes.categories.len(), 2);
assert_eq!(itunes.categories[0].text.as_str(), "Category 1");
assert_eq!(itunes.categories[0]
.subcategory
.as_ref()
.map(|v| v.text.as_str()),
Some("Subcategory"));
assert_eq!(itunes.categories[1].text.as_str(), "Category 2");
assert_eq!(itunes.categories[1].subcategory, None);
assert_eq!(itunes.image.as_ref().map(|s| s.as_str()),
Some("http://example.com/image.jpg"));
assert_eq!(itunes.explicit.as_ref().map(|s| s.as_str()), Some("no"));
assert_eq!(itunes.complete.as_ref().map(|s| s.as_str()), Some("yes"));
assert_eq!(itunes.new_feed_url.as_ref().map(|s| s.as_str()),
Some("http://example.com/feed/"));
assert_eq!(itunes.owner.as_ref().and_then(|v| v.name.as_ref()).map(|s| s.as_str()),
Some("Name"));
assert_eq!(itunes.owner.as_ref().and_then(|v| v.email.as_ref()).map(|s| s.as_str()),
Some("example@example.com"));
assert_eq!(itunes.subtitle.as_ref().map(|s| s.as_str()),
Some("Subtitle"));
assert_eq!(itunes.summary.as_ref().map(|s| s.as_str()), Some("Summary"));
assert_eq!(itunes.keywords.as_ref().map(|s| s.as_str()),
Some("key1,key2,key3"));
let itunes = &channel.items[0].itunes_ext.as_ref().expect("itunes extension missing");
assert_eq!(itunes.author.as_ref().map(|s| s.as_str()), Some("Author"));
assert_eq!(itunes.block.as_ref().map(|s| s.as_str()), Some("yes"));
assert_eq!(itunes.image.as_ref().map(|s| s.as_str()),
Some("http://example.com/image.jpg"));
assert_eq!(itunes.duration.as_ref().map(|s| s.as_str()),
Some("01:22:33"));
assert_eq!(itunes.explicit.as_ref().map(|s| s.as_str()), Some("yes"));
assert_eq!(itunes.closed_captioned.as_ref().map(|s| s.as_str()),
Some("no"));
assert_eq!(itunes.order.as_ref().map(|s| s.as_str()), Some("1"));
assert_eq!(itunes.subtitle.as_ref().map(|s| s.as_str()),
Some("Subtitle"));
assert_eq!(itunes.summary.as_ref().map(|s| s.as_str()), Some("Summary"));
assert_eq!(itunes.keywords.as_ref().map(|s| s.as_str()),
Some("key1,key2,key3"));
}
#[test]
fn read_dublincore() {
let input = include_str!("data/dublincore.xml");
let channel = input.parse::<Channel>().expect("failed to parse xml");
fn test_ext(dc: &DublinCoreExtension) {
assert_eq!(dc.contributor.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Contributor 1", "Contributor 2"]);
assert_eq!(dc.coverage.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Coverage"]);
assert_eq!(dc.creator.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Creator"]);
assert_eq!(dc.date.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["2016-08-27"]);
assert_eq!(dc.description.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Description"]);
assert_eq!(dc.format.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["text/plain"]);
assert_eq!(dc.identifier.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Identifier"]);
assert_eq!(dc.language.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["en-US"]);
assert_eq!(dc.publisher.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Publisher"]);
assert_eq!(dc.relation.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Relation"]);
assert_eq!(dc.rights.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Company"]);
assert_eq!(dc.source.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Source"]);
assert_eq!(dc.subject.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Subject"]);
assert_eq!(dc.title.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Title"]);
assert_eq!(dc.resource_type.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
vec!["Type"]);
}
test_ext(&channel.dublin_core_ext.as_ref().expect("dc extension missing"));
test_ext(&channel.items[0].dublin_core_ext.as_ref().expect("ds extension missing"));
}
|
use ssh2::{Session, Channel};
use std::error::Error;
use std::net::TcpStream;
use std::path::Path;
use std::io::Write;
use yaml_rust::{YamlLoader, Yaml};
use std::fs;
use regex::Regex;
use clap::ArgMatches;
fn create_session(host: &str) -> Result<Session, Box<dyn Error>> {
match (TcpStream::connect(host), Session::new()) {
(Ok(tcp), Ok(mut sess)) => {
sess.set_tcp_stream(tcp);
return Ok(sess);
},
(Err(_), _) => Err("Could not initialize TcpStream.".into()),
(_, Err(_)) => Err("Could not create ssh Session.".into()),
}
}
fn handshake(mut sess: Session) -> Result<Session, Box<dyn Error>> {
match sess.handshake() {
Ok(_) => Ok(sess),
Err(_) => Err("Unable to successfully handshake.".into())
}
}
fn authenticate(sess: Session, username: &str, password: &str) -> Result<Session, Box<dyn Error>> {
match sess.userauth_password(username, password) {
Ok(_) => Ok(sess),
Err(_) => Err("Incorrect login credentials.".into())
}
}
fn add_file(sess: Session, filename: &str, data_len: u64) -> Result<Channel, Box<dyn Error>> {
match sess.scp_send(Path::new(filename), 0o666, data_len, None) {
Ok(remote_file) => Ok(remote_file),
Err(_) => Err("Could not create remote file.".into())
}
}
fn write_file(mut remote_file: Channel, data: &str) -> Result<usize, Box<dyn Error>> {
match remote_file.write(data.as_bytes()) {
Ok(written) => Ok(written),
Err(_) => Err("Could not write to remote file.".into())
}
}
pub fn send_remote_file(host: &str, user: &str, pass: &str, filename: &str, data: &str) -> Result<usize, Box<dyn Error>> {
create_session(host)
.and_then(handshake)
.and_then(|sess| authenticate(sess, user, pass))
.and_then(|sess| add_file(sess, filename, data.len() as u64))
.and_then(|remote_file| write_file(remote_file, data))
}
pub struct FileInfo {
pub name: String,
pub data: String }
pub struct Arguments {
pub link: String,
pub host: String,
pub user: String,
pub pass: String,
pub dir: String }
fn to_file_info(path: &str, hash: &str, magnet: &str) -> FileInfo {
FileInfo {
name: format!("{}/meta-{}.torrent", path, hash),
data: format!("d10:magnet-uri{}:{}e", magnet.len().to_string(), magnet)}
}
pub fn convert_magnet(path: &str, magnet: &str) -> Result<FileInfo, Box<dyn Error>> {
match Regex::new(r"^magnet:\?xt=urn:btih:([a-z,0-9]+)").unwrap().captures(magnet) {
Some(hash) => Ok(to_file_info(path, &hash[1], magnet)),
None => Err("Input must match '^magnet:\\?xt=urn:btih:[a-z,0-9]+.*'".into()),
}
}
fn file_to_string(file: &str) -> Result<Yaml, Box<dyn Error>> {
match fs::read_to_string(file) {
Ok(contents) => match YamlLoader::load_from_str(&*contents) {
Ok(a) => Ok(a[0].to_owned()),
Err(_) => Err("Could not load yaml from file.".into()),
},
Err(_) => Err("Could not read file to string.".into()),
}
}
fn to_argument(link: &str, host: &str, user: &str, pass: &str, dir: &str) -> Arguments {
Arguments {
link: link.to_string(),
host: host.to_string(),
user: user.to_string(),
pass: pass.to_string(),
dir: dir.to_string()
}
}
fn argument_from_config(arg_matches: ArgMatches, doc: Yaml) -> Result<Arguments, Box<dyn Error>> {
if let (Some(link), Some(host), Some(user), Some(pass), Some(dir)) = (
arg_matches.value_of("magnet_link"),
doc["host"].as_str(),
doc["user"].as_str(),
doc["pass"].as_str(),
doc["dir"].as_str()) {
Ok(to_argument(link, host, user, pass, dir))
} else {
Err("Could not read config from file. Needs host, user, pass, and path.".into())
}
}
fn arguments_from_explicit(arg_matches: ArgMatches) -> Result<Arguments, Box<dyn Error>> {
if let (Some(link), Some(host), Some(user), Some(pass), Some(dir)) = (
arg_matches.value_of("magnet_link"),
arg_matches.value_of("host"),
arg_matches.value_of("user"),
arg_matches.value_of("pass"),
arg_matches.value_of("dir")) {
Ok(to_argument(link, host, user, pass, dir))
} else {
Err("Could not read arguments.".into())
}
}
pub fn get_host_info(arg_matches: ArgMatches) -> Result<Arguments, Box<dyn Error>> {
if arg_matches.is_present("config") || !arg_matches.is_present("host") {
file_to_string(arg_matches.value_of("config").unwrap_or("config.yaml"))
.and_then(|doc| argument_from_config(arg_matches, doc))
} else {
arguments_from_explicit(arg_matches)
}
} |
use crate::prelude::*;
use azure_core::prelude::*;
use http::StatusCode;
use std::convert::TryInto;
#[derive(Debug, Clone)]
pub struct DeleteAttachmentBuilder<'a, 'b> {
attachment_client: &'a AttachmentClient,
if_match_condition: Option<IfMatchCondition<'b>>,
user_agent: Option<UserAgent<'b>>,
activity_id: Option<ActivityId<'b>>,
consistency_level: Option<ConsistencyLevel>,
}
impl<'a, 'b> DeleteAttachmentBuilder<'a, 'b> {
pub(crate) fn new(attachment_client: &'a AttachmentClient) -> Self {
Self {
attachment_client,
if_match_condition: None,
user_agent: None,
activity_id: None,
consistency_level: None,
}
}
setters! {
user_agent: &'b str => Some(UserAgent::new(user_agent)),
activity_id: &'b str => Some(ActivityId::new(activity_id)),
consistency_level: ConsistencyLevel => Some(consistency_level),
if_match_condition: IfMatchCondition<'b> => Some(if_match_condition),
}
pub async fn execute(&self) -> crate::Result<crate::responses::DeleteAttachmentResponse> {
let mut req = self
.attachment_client
.prepare_request_with_attachment_name(http::Method::DELETE);
// add trait headers
req = azure_core::headers::add_optional_header(&self.if_match_condition, req);
req = azure_core::headers::add_optional_header(&self.user_agent, req);
req = azure_core::headers::add_optional_header(&self.activity_id, req);
req = azure_core::headers::add_optional_header(&self.consistency_level, req);
req = crate::cosmos_entity::add_as_partition_key_header_serialized(
self.attachment_client
.document_client()
.partition_key_serialized(),
req,
);
let req = req.body(bytes::Bytes::from_static(EMPTY_BODY))?;
debug!("req == {:#?}", req);
Ok(self
.attachment_client
.http_client()
.execute_request_check_status(req, StatusCode::NO_CONTENT)
.await?
.try_into()?)
}
}
|
use tantivy::tokenizer::RawTokenizer;
#[derive(Clone)]
pub struct RawTokenizerFactory {}
impl RawTokenizerFactory {
pub fn new() -> Self {
RawTokenizerFactory {}
}
pub fn create(self) -> RawTokenizer {
RawTokenizer {}
}
}
#[cfg(test)]
mod tests {
use tantivy::tokenizer::Tokenizer;
use crate::tokenizer::raw_tokenizer_factory::RawTokenizerFactory;
#[test]
fn test_raw_tokenizer() {
let factory = RawTokenizerFactory::new();
let tokenizer = factory.create();
let mut stream = tokenizer.token_stream("hello");
{
let token = stream.next().unwrap();
assert_eq!(token.text, "hello");
assert_eq!(token.offset_from, 0);
assert_eq!(token.offset_to, 5);
}
assert!(stream.next().is_none());
}
}
|
//! Rust binding for the Cuba integrator.
//!
//! Cuba (http://www.feynarts.de/cuba/) is written by Thomas Hahn.
//!
//! # Usage
//! Create a `CubaIntegrator` and supply it with a function of the form
//!
//! ```
//! type UserData = ();
//!
//! fn integrand(
//! x: &[f64],
//! f: &mut [f64],
//! user_data: &mut UserData,
//! nvec: usize,
//! core: i32,
//! weight: &[f64],
//! iter: usize,
//! ) -> Result<(), &'static str> {
//! 0
//! }
//! ```
//! where `UserData` can be any type. If you don't want to provide user data,
//! simply make `UserData` a `usize` and provide any number.
//!
//! # Example
//!
//! ```
//! extern crate cuba;
//! use cuba::{CubaIntegrator, CubaVerbosity};
//!
//! #[derive(Debug)]
//! struct UserData {
//! f1: f64,
//! f2: f64,
//! }
//!
//! #[inline(always)]
//! fn integrand(
//! x: &[f64],
//! f: &mut [f64],
//! user_data: &mut UserData,
//! nvec: usize,
//! _core: i32,
//! _weight: &[f64],
//! _iter: usize,
//! ) -> Result<(), &'static str> {
//! for i in 0..nvec {
//! f[i * 2] = (x[i * 2] * x[i * 2]).sin() * user_data.f1;
//! f[i * 2 + 1] = (x[i * 2 + 1] * x[i * 2 + 1]).cos() * user_data.f2;
//! }
//!
//! Ok(())
//! }
//!
//! fn main() {
//! let mut ci = CubaIntegrator::new();
//! ci.set_mineval(10)
//! .set_maxeval(10000000)
//! .set_epsrel(0.0001)
//! .set_seed(0) // use quasi-random numbers
//! .set_cores(2, 1000);
//!
//! let data = UserData { f1: 5., f2: 7. };
//! let r = ci.vegas(2, 2, 4, CubaVerbosity::Progress, 0, integrand, data);
//!
//! println!("{:#?}", r);
//! }
//! ```
extern crate libc;
use libc::{c_char, c_double, c_int, c_longlong, c_void};
use std::ffi::CString;
use std::ptr;
use std::slice;
/// Logging level.
///
/// `Silent` does not print any output, `Progress` prints 'reasonable' information on the
/// progress of the integration, `Input` also echoes the input parameters,
/// and `Subregions` further prints the subregion results.
pub enum CubaVerbosity {
Silent = 0,
Progress = 1,
Input = 2,
Subregions = 3,
}
macro_rules! gen_setter {
($setr:ident, $r:ident, $t: ty) => {
pub fn $setr(&mut self, $r: $t) -> &mut Self {
self.$r = $r;
self
}
};
}
#[link(name = "cuba")]
extern "C" {
fn cubacores(n: *const c_int, p: *const c_int);
fn llVegas(
ndim: c_int,
ncomp: c_int,
integrand: Option<VegasIntegrandC>,
userdata: *mut c_void,
nvec: c_longlong,
epsrel: c_double,
epsabs: c_double,
flags: c_int,
seed: c_int,
mineval: c_longlong,
maxeval: c_longlong,
nstart: c_longlong,
nincrease: c_longlong,
nbatch: c_longlong,
gridno: c_int,
statefile: *const c_char,
spin: *mut c_void,
neval: *mut c_longlong,
fail: *mut c_int,
integral: *mut c_double,
error: *mut c_double,
prob: *mut c_double,
);
fn llSuave(
ndim: c_int,
ncomp: c_int,
integrand: Option<SuaveIntegrandC>,
userdata: *mut c_void,
nvec: c_longlong,
epsrel: c_double,
epsabs: c_double,
flags: c_int,
seed: c_int,
mineval: c_longlong,
maxeval: c_longlong,
nnew: c_longlong,
nmin: c_longlong,
flatness: c_double,
statefile: *const c_char,
spin: *mut c_void,
nregions: *mut c_int,
neval: *mut c_longlong,
fail: *mut c_int,
integral: *mut c_double,
error: *mut c_double,
prob: *mut c_double,
);
fn llDivonne(
ndim: c_int,
ncomp: c_int,
integrand: Option<DivonneIntegrandC>,
userdata: *mut c_void,
nvec: c_longlong,
epsrel: c_double,
epsabs: c_double,
flags: c_int,
seed: c_int,
mineval: c_longlong,
maxeval: c_longlong,
key1: c_int,
key2: c_int,
key3: c_int,
maxpass: c_int,
border: c_double,
maxchisq: c_double,
mindeviation: c_double,
ngiven: c_longlong,
lxdgiven: c_int,
xgiven: *const c_double,
nextra: c_longlong,
peakfinder: Option<PeakfinderC>,
statefile: *const c_char,
spin: *mut c_void,
nregions: *mut c_int,
neval: *mut c_longlong,
fail: *mut c_int,
integral: *mut c_double,
error: *mut c_double,
prob: *mut c_double,
);
fn llCuhre(
ndim: c_int,
ncomp: c_int,
integrand: Option<CuhreIntegrandC>,
userdata: *mut c_void,
nvec: c_longlong,
epsrel: c_double,
epsabs: c_double,
flags: c_int,
mineval: c_longlong,
maxeval: c_longlong,
key: c_int,
statefile: *const c_char,
spin: *mut c_void,
nregions: *mut c_int,
neval: *mut c_longlong,
fail: *mut c_int,
integral: *mut c_double,
error: *mut c_double,
prob: *mut c_double,
);
}
type VegasIntegrandC = extern "C" fn(
ndim: *const c_int,
x: *const c_double,
ncomp: *const c_int,
f: *mut c_double,
userdata: *mut c_void,
nvec: *const c_int,
core: *const c_int,
weight: *const c_double,
iter: *const c_int,
) -> c_int;
type SuaveIntegrandC = extern "C" fn(
ndim: *const c_int,
x: *const c_double,
ncomp: *const c_int,
f: *mut c_double,
userdata: *mut c_void,
nvec: *const c_int,
core: *const c_int,
weight: *const c_double,
iter: *const c_int,
) -> c_int;
type CuhreIntegrandC = extern "C" fn(
ndim: *const c_int,
x: *const c_double,
ncomp: *const c_int,
f: *mut c_double,
userdata: *mut c_void,
nvec: *const c_int,
core: *const c_int,
) -> c_int;
type DivonneIntegrandC = extern "C" fn(
ndim: *const c_int,
x: *const c_double,
ncomp: *const c_int,
f: *mut c_double,
userdata: *mut c_void,
nvec: *const c_int,
core: *const c_int,
phase: *const c_int,
) -> c_int;
type PeakfinderC = extern "C" fn(
ndim: *const c_int,
b: *const c_double,
n: *mut c_int,
x: *mut c_double,
userdata: *mut c_void,
);
/// Vegas integrand evaluation function.
///
/// The dimensions of random input variables `x` and output `f`
/// are provided to the integration routine as dimension and components respectively.
/// `T` can be any type. If you don't want to provide user data,
/// simply make `T` a `usize` and provide any number.
///
/// `core` specifies the current core that is being used. This can be used to write to
/// the user data in a thread-safe way.
///
/// On returning an error, the integration will be aborted.
pub type VegasIntegrand<T> = fn(
x: &[f64],
f: &mut [f64],
user_data: &mut T,
nvec: usize,
core: i32,
weight: &[f64],
iter: usize,
) -> Result<(), &'static str>;
/// Suave integrand evaluation function.
///
/// The dimensions of random input variables `x` and output `f`
/// are provided to the integration routine as dimension and components respectively.
/// `T` can be any type. If you don't want to provide user data,
/// simply make `T` a `usize` and provide any number.
///
/// `core` specifies the current core that is being used. This can be used to write to
/// the user data in a thread-safe way.
///
/// On returning an error, the integration will be aborted.
pub type SuaveIntegrand<T> = fn(
x: &[f64],
f: &mut [f64],
user_data: &mut T,
nvec: usize,
core: i32,
weight: &[f64],
iter: usize,
) -> Result<(), &'static str>;
/// Cuhre integrand evaluation function.
///
/// The dimensions of random input variables `x` and output `f`
/// are provided to the integration routine as dimension and components respectively.
/// `T` can be any type. If you don't want to provide user data,
/// simply make `T` a `usize` and provide any number.
///
/// `core` specifies the current core that is being used. This can be used to write to
/// the user data in a thread-safe way.
///
/// On returning an error, the integration will be aborted.
pub type CuhreIntegrand<T> = fn(
x: &[f64],
f: &mut [f64],
user_data: &mut T,
nvec: usize,
core: i32,
) -> Result<(), &'static str>;
/// Divonne integrand evaluation function.
///
/// The dimensions of random input variables `x` and output `f`
/// are provided to the integration routine as dimension and components respectively.
/// `T` can be any type. If you don't want to provide user data,
/// simply make `T` a `usize` and provide any number.
///
/// `core` specifies the current core that is being used. This can be used to write to
/// the user data in a thread-safe way.
///
/// On returning an error, the integration will be aborted.
pub type DivonneIntegrand<T> = fn(
x: &[f64],
f: &mut [f64],
user_data: &mut T,
nvec: usize,
core: i32,
phase: usize,
) -> Result<(), &'static str>;
#[repr(C)]
struct VegasUserData<T> {
integrand: VegasIntegrand<T>,
user_data: T,
}
#[repr(C)]
struct CuhreUserData<T> {
integrand: CuhreIntegrand<T>,
user_data: T,
}
#[repr(C)]
struct SuaveUserData<T> {
integrand: SuaveIntegrand<T>,
user_data: T,
}
#[repr(C)]
struct DivonneUserData<T> {
integrand: DivonneIntegrand<T>,
user_data: T,
}
/// The result of an integration with Cuba.
#[derive(Debug)]
pub struct CubaResult {
pub neval: i64,
pub fail: i32,
pub result: Vec<f64>,
pub error: Vec<f64>,
pub prob: Vec<f64>,
}
/// A Cuba integrator. It should be created with an integrand function.
pub struct CubaIntegrator {
mineval: i64,
maxeval: i64,
nstart: i64,
nincrease: i64,
epsrel: f64,
epsabs: f64,
batch: i64,
cores: usize,
max_points_per_core: usize,
seed: i32,
use_only_last_sample: bool,
save_state_file: String,
keep_state_file: bool,
reset_vegas_integrator: bool,
// Cuhre
key: i32,
// Divonne
key1: i32,
key2: i32,
key3: i32,
maxpass: i32,
border: f64,
maxchisq: f64,
mindeviation: f64,
}
impl CubaIntegrator {
/// Create a new Cuba integrator. Use the `set_` functions
/// to set integration parameters.
pub fn new() -> CubaIntegrator {
CubaIntegrator {
mineval: 0,
maxeval: 50000,
nstart: 1000,
nincrease: 500,
epsrel: 0.001,
epsabs: 1e-12,
batch: 1000,
cores: 1,
max_points_per_core: 1000,
seed: 0,
use_only_last_sample: false,
save_state_file: String::new(),
keep_state_file: false,
reset_vegas_integrator: false,
key: 0,
key1: 47,
key2: 1,
key3: 1,
maxpass: 5,
border: 0.,
maxchisq: 10.,
mindeviation: 0.25,
}
}
/// Set the number of cores and the maximum number of points per core.
/// The default is the number of idle cores for `cores` and
/// 1000 for `max_points_per_core`.
pub fn set_cores(&mut self, cores: usize, max_points_per_core: usize) -> &mut Self {
self.cores = cores;
self.max_points_per_core = max_points_per_core;
unsafe {
cubacores(&(cores as c_int), &(max_points_per_core as c_int));
}
self
}
gen_setter!(set_mineval, mineval, i64);
gen_setter!(set_maxeval, maxeval, i64);
gen_setter!(set_nstart, nstart, i64);
gen_setter!(set_nincrease, nincrease, i64);
gen_setter!(set_epsrel, epsrel, f64);
gen_setter!(set_epsabs, epsabs, f64);
gen_setter!(set_batch, batch, i64);
gen_setter!(set_seed, seed, i32);
gen_setter!(set_use_only_last_sample, use_only_last_sample, bool);
gen_setter!(set_save_state_file, save_state_file, String);
gen_setter!(set_keep_state_file, keep_state_file, bool);
gen_setter!(set_reset_vegas_integrator, reset_vegas_integrator, bool);
gen_setter!(set_key, key, i32);
gen_setter!(set_key1, key1, i32);
gen_setter!(set_key2, key2, i32);
gen_setter!(set_key3, key3, i32);
gen_setter!(set_maxpass, maxpass, i32);
gen_setter!(set_border, border, f64);
gen_setter!(set_maxchisq, maxchisq, f64);
gen_setter!(set_mindeviation, mindeviation, f64);
extern "C" fn c_vegas_integrand<T>(
ndim: *const c_int,
x: *const c_double,
ncomp: *const c_int,
f: *mut c_double,
userdata: *mut c_void,
nvec: *const c_int,
core: *const c_int,
weight: *const c_double,
iter: *const c_int,
) -> c_int {
unsafe {
let k: &mut VegasUserData<T> = &mut *(userdata as *mut _);
// call the safe integrand
match (k.integrand)(
&slice::from_raw_parts(x, *ndim as usize * *nvec as usize),
&mut slice::from_raw_parts_mut(f, *ncomp as usize * *nvec as usize),
&mut k.user_data,
*nvec as usize,
*core as i32,
&slice::from_raw_parts(weight, *nvec as usize),
*iter as usize,
) {
Ok(_) => 0,
Err(e) => {
println!("Error during integration: {}. Aborting.", e);
-999
}
}
}
}
extern "C" fn c_suave_integrand<T>(
ndim: *const c_int,
x: *const c_double,
ncomp: *const c_int,
f: *mut c_double,
userdata: *mut c_void,
nvec: *const c_int,
core: *const c_int,
weight: *const c_double,
iter: *const c_int,
) -> c_int {
unsafe {
let k: &mut SuaveUserData<T> = &mut *(userdata as *mut _);
// call the safe integrand
match (k.integrand)(
&slice::from_raw_parts(x, *ndim as usize * *nvec as usize),
&mut slice::from_raw_parts_mut(f, *ncomp as usize * *nvec as usize),
&mut k.user_data,
*nvec as usize,
*core as i32,
&slice::from_raw_parts(weight, *ndim as usize * *nvec as usize),
*iter as usize,
) {
Ok(_) => 0,
Err(e) => {
println!("Error during integration: {}. Aborting.", e);
-999
}
}
}
}
extern "C" fn c_cuhre_integrand<T>(
ndim: *const c_int,
x: *const c_double,
ncomp: *const c_int,
f: *mut c_double,
userdata: *mut c_void,
nvec: *const c_int,
core: *const c_int,
) -> c_int {
unsafe {
let k: &mut CuhreUserData<T> = &mut *(userdata as *mut _);
// call the safe integrand
match (k.integrand)(
&slice::from_raw_parts(x, *ndim as usize * *nvec as usize),
&mut slice::from_raw_parts_mut(f, *ncomp as usize * *nvec as usize),
&mut k.user_data,
*nvec as usize,
*core as i32,
) {
Ok(_) => 0,
Err(e) => {
println!("Error during integration: {}. Aborting.", e);
-999
}
}
}
}
extern "C" fn c_divonne_integrand<T>(
ndim: *const c_int,
x: *const c_double,
ncomp: *const c_int,
f: *mut c_double,
userdata: *mut c_void,
nvec: *const c_int,
core: *const c_int,
phase: *const c_int,
) -> c_int {
unsafe {
let k: &mut DivonneUserData<T> = &mut *(userdata as *mut _);
// call the safe integrand
match (k.integrand)(
&slice::from_raw_parts(x, *ndim as usize * *nvec as usize),
&mut slice::from_raw_parts_mut(f, *ncomp as usize * *nvec as usize),
&mut k.user_data,
*nvec as usize,
*core as i32,
*phase as usize,
) {
Ok(_) => 0,
Err(e) => {
println!("Error during integration: {}. Aborting.", e);
-999
}
}
}
}
extern "C" fn c_peakfinder(
ndim: *const c_int,
b: *const c_double,
n: *mut c_int,
x: *mut c_double,
userdata: *mut c_void,
) {
// TODO: call a safe peakfinder routine
}
/// Integrate using the Vegas integrator.
///
/// * `ndim` - Dimension of the input
/// * `ncomp` - Dimension (components) of the output
/// * `nvec` - Number of input points given to the integrand function
/// * `verbosity` - Verbosity level
/// * `gridno` - Grid number between -10 and 10. If 0, no grid is stored.
/// If it is positive, the grid is storedin the `gridno`th slot.
/// With a negative number the grid is cleared.
/// * `user_data` - User data used by the integrand function
pub fn vegas<T>(
&mut self,
ndim: usize,
ncomp: usize,
nvec: usize,
verbosity: CubaVerbosity,
gridno: i32,
integrand: VegasIntegrand<T>,
user_data: T,
) -> CubaResult {
let mut out = CubaResult {
neval: 0,
fail: 0,
result: vec![0.; ncomp],
error: vec![0.; ncomp],
prob: vec![0.; ncomp],
};
assert!(
gridno >= -10 && gridno <= 10,
"Grid number needs to be between -10 and 10."
);
assert!(
nvec <= self.batch as usize && nvec <= self.max_points_per_core,
"nvec needs to be at most the vegas batch size or the max points per core"
);
// pass the safe integrand and the user data
let mut x = VegasUserData {
integrand: integrand,
user_data: user_data,
};
let user_data_ptr = &mut x as *mut _ as *mut c_void;
// Bits 0 and 1 set the CubaVerbosity
let mut cubaflags = verbosity as i32;
// Bit 2 sets whether only last sample should be used
if self.use_only_last_sample {
cubaflags |= 0b100;
}
// Bit 4 specifies whether the state file should be retained after integration
if self.keep_state_file {
cubaflags |= 0b10000;
}
// Bit 5 specifies whether the integrator state (except the grid) should be reset
// after having loaded a state file (Vegas only)
if self.reset_vegas_integrator {
cubaflags |= 0b100000;
}
let c_str = CString::new(self.save_state_file.as_str()).expect("CString::new failed");
unsafe {
llVegas(
ndim as c_int, // ndim
ncomp as c_int, // ncomp
Some(CubaIntegrator::c_vegas_integrand::<T>), // integrand
user_data_ptr, // user data
nvec as c_longlong, // nvec
self.epsrel, // epsrel
self.epsabs, // epsabs
cubaflags as c_int, // flags
self.seed, // seed
self.mineval, // mineval
self.maxeval, // maxeval
self.nstart, // nstart
self.nincrease, // nincrease
self.batch, // batch
gridno, // grid no
c_str.as_ptr(), // statefile
ptr::null_mut(), // spin
&mut out.neval,
&mut out.fail,
&mut out.result[0],
&mut out.error[0],
&mut out.prob[0],
);
}
out
}
/// Integrate using the Suave integrator.
///
/// * `ndim` - Dimension of the input
/// * `ncomp` - Dimension (components) of the output
/// * `nvec` - Number of input points given to the integrand function
/// * `nnew` - Number of new integrand evaluations in each subdivision
/// * `nmin` - Minimum number of samples a former pass must contribute to a
/// subregion to be considered in that region’s compound integral value
/// * `flatness` - This determines how prominently individual samples with a large fluctuation
/// figure in the total fluctuation
/// * `verbosity` - Verbosity level
/// * `user_data` - User data used by the integrand function
pub fn suave<T>(
&mut self,
ndim: usize,
ncomp: usize,
nvec: usize,
nnew: usize,
nmin: usize,
flatness: f64,
verbosity: CubaVerbosity,
integrand: SuaveIntegrand<T>,
user_data: T,
) -> CubaResult {
let mut out = CubaResult {
neval: 0,
fail: 0,
result: vec![0.; ncomp],
error: vec![0.; ncomp],
prob: vec![0.; ncomp],
};
assert!(
nvec <= self.max_points_per_core && nvec <= nnew,
"nvec needs to be at most the max points per core and nnew"
);
// pass the safe integrand and the user data
let mut x = SuaveUserData {
integrand: integrand,
user_data: user_data,
};
let user_data_ptr = &mut x as *mut _ as *mut c_void;
// Bits 0 and 1 set the CubaVerbosity
let mut cubaflags = verbosity as i32;
// Bit 2 sets whether only last sample should be used
if self.use_only_last_sample {
cubaflags |= 0b100;
}
// Bit 4 specifies whether the state file should be retained after integration
if self.keep_state_file {
cubaflags |= 0b10000;
}
// Bit 5 specifies whether the integrator state (except the grid) should be reset
// after having loaded a state file (Vegas only)
if self.reset_vegas_integrator {
cubaflags |= 0b100000;
}
let mut nregions = 0;
let c_str = CString::new(self.save_state_file.as_str()).expect("CString::new failed");
unsafe {
llSuave(
ndim as c_int, // ndim
ncomp as c_int, // ncomp
Some(CubaIntegrator::c_suave_integrand::<T>), // integrand
user_data_ptr, // user data
nvec as c_longlong, // nvec
self.epsrel, // epsrel
self.epsabs, // epsabs
cubaflags as c_int, // flags
self.seed, // seed
self.mineval, // mineval
self.maxeval, // maxeval
nnew as c_longlong,
nmin as c_longlong,
flatness,
c_str.as_ptr(),
ptr::null_mut(),
&mut nregions,
&mut out.neval,
&mut out.fail,
&mut out.result[0],
&mut out.error[0],
&mut out.prob[0],
);
}
out
}
/// Integrate using the Divonne integrator.
///
/// * `ndim` - Dimension of the input
/// * `ncomp` - Dimension (components) of the output
/// * `nvec` - Number of input points given to the integrand function
/// * `xgiven` - A list of input points which lie close to peaks
/// * `verbosity` - Verbosity level
/// * `user_data` - User data used by the integrand function
pub fn divonne<T>(
&mut self,
ndim: usize,
ncomp: usize,
nvec: usize,
xgiven: &[f64],
verbosity: CubaVerbosity,
integrand: DivonneIntegrand<T>,
user_data: T,
) -> CubaResult {
let mut out = CubaResult {
neval: 0,
fail: 0,
result: vec![0.; ncomp],
error: vec![0.; ncomp],
prob: vec![0.; ncomp],
};
assert!(
nvec <= self.max_points_per_core,
"nvec needs to be at most the max points per core"
);
// pass the safe integrand and the user data
let mut x = DivonneUserData {
integrand: integrand,
user_data: user_data,
};
let user_data_ptr = &mut x as *mut _ as *mut c_void;
// Bits 0 and 1 set the CubaVerbosity
let mut cubaflags = verbosity as i32;
// Bit 2 sets whether only last sample should be used
if self.use_only_last_sample {
cubaflags |= 0b100;
}
// Bit 4 specifies whether the state file should be retained after integration
if self.keep_state_file {
cubaflags |= 0b10000;
}
// Bit 5 specifies whether the integrator state (except the grid) should be reset
// after having loaded a state file (Vegas only)
if self.reset_vegas_integrator {
cubaflags |= 0b100000;
}
let mut nregions = 0;
let c_str = CString::new(self.save_state_file.as_str()).expect("CString::new failed");
unsafe {
llDivonne(
ndim as c_int, // ndim
ncomp as c_int, // ncomp
Some(CubaIntegrator::c_divonne_integrand::<T>), // integrand
user_data_ptr, // user data
nvec as c_longlong, // nvec
self.epsrel, // epsrel
self.epsabs, // epsabs
cubaflags as c_int, // flags
self.seed, // seed
self.mineval, // mineval
self.maxeval, // maxeval
self.key1,
self.key2,
self.key3,
self.maxpass,
self.border,
self.maxchisq,
self.mindeviation,
(xgiven.len() / ndim) as c_longlong,
ndim as c_int,
if xgiven.len() == 0 {
ptr::null_mut()
} else {
&xgiven[0]
},
0,
None,
c_str.as_ptr(),
ptr::null_mut(),
&mut nregions,
&mut out.neval,
&mut out.fail,
&mut out.result[0],
&mut out.error[0],
&mut out.prob[0],
);
}
out
}
/// Integrate using the Cuhre integrator.
///
/// * `ndim` - Dimension of the input
/// * `ncomp` - Dimension (components) of the output
/// * `nvec` - Number of input points given to the integrand function
/// * `verbosity` - Verbosity level
/// * `user_data` - User data used by the integrand function
pub fn cuhre<T>(
&mut self,
ndim: usize,
ncomp: usize,
nvec: usize,
verbosity: CubaVerbosity,
integrand: CuhreIntegrand<T>,
user_data: T,
) -> CubaResult {
let mut out = CubaResult {
neval: 0,
fail: 0,
result: vec![0.; ncomp],
error: vec![0.; ncomp],
prob: vec![0.; ncomp],
};
assert!(nvec <= 32, "nvec needs to be at most 32");
// pass the safe integrand and the user data
let mut x = CuhreUserData {
integrand: integrand,
user_data: user_data,
};
let user_data_ptr = &mut x as *mut _ as *mut c_void;
// Bits 0 and 1 set the CubaVerbosity
let mut cubaflags = verbosity as i32;
// Bit 2 sets whether only last sample should be used
if self.use_only_last_sample {
cubaflags |= 0b100;
}
// Bit 4 specifies whether the state file should be retained after integration
if self.keep_state_file {
cubaflags |= 0b10000;
}
let mut nregions = 0;
let c_str = CString::new(self.save_state_file.as_str()).expect("CString::new failed");
unsafe {
llCuhre(
ndim as c_int, // ndim
ncomp as c_int, // ncomp
Some(CubaIntegrator::c_cuhre_integrand::<T>), // integrand
user_data_ptr, // user data
nvec as c_longlong, // nvec
self.epsrel, // epsrel
self.epsabs, // epsabs
cubaflags as c_int, // flags
self.mineval, // mineval
self.maxeval, // maxeval
self.key, // key
c_str.as_ptr(), // statefile
ptr::null_mut(), // spin
&mut nregions,
&mut out.neval,
&mut out.fail,
&mut out.result[0],
&mut out.error[0],
&mut out.prob[0],
);
}
out
}
}
|
use hymns::runner::timed_run;
const INPUT: &str = include_str!("../input.txt");
fn part1() -> u64 {
let mut score = 0;
for line in INPUT.lines() {
let mut stack = vec![];
for c in line.chars() {
match c {
'(' | '[' | '{' | '<' => stack.push(c),
closing => match (stack.pop().unwrap(), closing) {
('(', ')') | ('[', ']') | ('{', '}') | ('<', '>') => (),
(_, ')') => score += 3,
(_, ']') => score += 57,
(_, '}') => score += 1197,
(_, '>') => score += 25137,
_ => unreachable!(),
},
}
}
}
score
}
fn build_stack(line: &str) -> Option<Vec<char>> {
let mut stack = vec![];
for c in line.chars() {
match c {
'(' | '[' | '{' | '<' => stack.push(c),
closing => match (stack.last().unwrap(), closing) {
('(', ')') | ('[', ']') | ('{', '}') | ('<', '>') => {
stack.pop();
}
_ => return None,
},
}
}
Some(stack)
}
fn part2() -> u64 {
// TODO: use running median instead of sorting
let mut scores = vec![];
for stack in INPUT.lines().filter_map(build_stack) {
let score = stack.into_iter().rev().fold(0, |mut score, c| {
score *= 5;
match c {
'(' => score += 1,
'[' => score += 2,
'{' => score += 3,
'<' => score += 4,
_ => unreachable!(),
}
score
});
scores.push(score);
}
scores.sort_unstable();
scores[scores.len() / 2]
}
fn main() {
timed_run(1, part1);
timed_run(2, part2);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
assert_eq!(part1(), 392367);
}
#[test]
fn test_part2() {
assert_eq!(part2(), 2192104158);
}
}
|
pub mod test;
pub mod jsonserver;
|
use std::{str, thread};
use std::net::{TcpListener, TcpStream, SocketAddrV4, Ipv4Addr};
use std::io::{Read, Write, BufReader};
pub use request::{Request};
pub use response::{Response};
mod request;
mod response;
macro_rules! formatted_out {
($head:expr, $body:expr) => {
{
println!("----- {} -----", $head);
println!("{}", $body);
println!("");
}
};
}
fn stringify_request(buffer: &[u8]) -> String {
let str_request = str::from_utf8(buffer).unwrap_or("");
str_request.replace("\u{0}", "")
}
fn handle_client(mut stream: TcpStream) {
let local_addr = stream.local_addr().unwrap();
let peer_addr = stream.peer_addr().unwrap();
println!("--- connection info ---");
println!("Server ip: {}, port: {}", local_addr.ip(), local_addr.port());
println!("Peer ip: {}, port: {}", peer_addr.ip(), peer_addr.port());
println!("");
let mut buffer: [u8; 1024*16] = [0; 1024*16]; //16 kB
let _no_of_bytes_read = stream.read(&mut buffer);
let stringified_request = stringify_request(&buffer);
let request = request::new_request(&stringified_request);
formatted_out!("request", request);
let mut response = Response::new();
let _no_of_bytes_written = stream.write(response.stringify_response().as_bytes());
}
fn main() {
let host: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
let port: u16 = 3000;
let socket_addr = SocketAddrV4::new(host, port);
let listener = TcpListener::bind(socket_addr).unwrap();
println!("Started Sopot server on {}", socket_addr);
println!("");
// TODO: what's difference between #incoming and #accept?
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || {
handle_client(stream);
});
},
Err(_) => {
println!("Connection failed!");
},
}
}
}
|
#[doc = "Reader of register DLYB_CFGR"]
pub type R = crate::R<u32, super::DLYB_CFGR>;
#[doc = "Writer for register DLYB_CFGR"]
pub type W = crate::W<u32, super::DLYB_CFGR>;
#[doc = "Register DLYB_CFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::DLYB_CFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SEL`"]
pub type SEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SEL`"]
pub struct SEL_W<'a> {
w: &'a mut W,
}
impl<'a> SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `UNIT`"]
pub type UNIT_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `UNIT`"]
pub struct UNIT_W<'a> {
w: &'a mut W,
}
impl<'a> UNIT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 8)) | (((value as u32) & 0x7f) << 8);
self.w
}
}
#[doc = "Reader of field `LNG`"]
pub type LNG_R = crate::R<u16, u16>;
#[doc = "Reader of field `LNGF`"]
pub type LNGF_R = crate::R<bool, bool>;
impl R {
#[doc = "Bits 0:3 - SEL"]
#[inline(always)]
pub fn sel(&self) -> SEL_R {
SEL_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 8:14 - UNIT"]
#[inline(always)]
pub fn unit(&self) -> UNIT_R {
UNIT_R::new(((self.bits >> 8) & 0x7f) as u8)
}
#[doc = "Bits 16:27 - LNG"]
#[inline(always)]
pub fn lng(&self) -> LNG_R {
LNG_R::new(((self.bits >> 16) & 0x0fff) as u16)
}
#[doc = "Bit 31 - LNGF"]
#[inline(always)]
pub fn lngf(&self) -> LNGF_R {
LNGF_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:3 - SEL"]
#[inline(always)]
pub fn sel(&mut self) -> SEL_W {
SEL_W { w: self }
}
#[doc = "Bits 8:14 - UNIT"]
#[inline(always)]
pub fn unit(&mut self) -> UNIT_W {
UNIT_W { w: self }
}
}
|
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use address::Address;
use clock::ChainEpoch;
use encoding::Cbor;
use num_bigint::{
bigint_ser::{BigIntDe, BigIntSer},
biguint_ser::{BigUintDe, BigUintSer},
BigInt,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use vm::TokenAmount;
/// A given payment channel actor is established by `from`
/// to enable off-chain microtransactions to `to` address
/// to be reconciled and tallied on chain.
#[derive(Default, Debug)]
pub struct State {
/// Channel owner, who has funded the actor.
pub from: Address,
/// Recipient of payouts from channel.
pub to: Address,
/// Amount successfully redeemed through the payment channel, paid out on `Collect`.
pub to_send: TokenAmount,
/// Height at which the channel can be collected.
pub settling_at: ChainEpoch,
/// Height before which the channel `ToSend` cannot be collected.
pub min_settle_height: ChainEpoch,
/// Collections of lane states for the channel, maintained in ID order.
pub lane_states: Vec<LaneState>,
}
impl State {
pub fn new(from: Address, to: Address) -> Self {
Self {
from,
to,
to_send: Default::default(),
settling_at: 0,
min_settle_height: 0,
lane_states: Vec::new(),
}
}
}
/// The Lane state tracks the latest (highest) voucher nonce used to merge the lane
/// as well as the amount it has already redeemed.
#[derive(Default, Debug)]
pub struct LaneState {
/// Identifier unique to this channel
pub id: u64,
// TODO this could possibly be a BigUint, but won't affect serialization
pub redeemed: BigInt,
pub nonce: u64,
}
/// Specifies which `lane`s to be merged with what `nonce` on `channel_update`
#[derive(Default, Debug, PartialEq)]
pub struct Merge {
pub lane: u64,
pub nonce: u64,
}
impl Cbor for State {}
impl Serialize for State {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(
&self.from,
&self.to,
BigUintSer(&self.to_send),
&self.settling_at,
&self.min_settle_height,
&self.lane_states,
)
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for State {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (from, to, BigUintDe(to_send), settling_at, min_settle_height, lane_states) =
Deserialize::deserialize(deserializer)?;
Ok(Self {
from,
to,
to_send,
settling_at,
min_settle_height,
lane_states,
})
}
}
impl Cbor for LaneState {}
impl Serialize for LaneState {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(&self.id, BigIntSer(&self.redeemed), &self.nonce).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for LaneState {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (id, BigIntDe(redeemed), nonce) = Deserialize::deserialize(deserializer)?;
Ok(Self {
id,
redeemed,
nonce,
})
}
}
impl Cbor for Merge {}
impl Serialize for Merge {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(&self.lane, &self.nonce).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Merge {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (lane, nonce) = Deserialize::deserialize(deserializer)?;
Ok(Self { lane, nonce })
}
}
|
extern crate utils;
use std::env;
use std::io::{self, BufReader};
use std::io::prelude::*;
use std::fs::File;
use utils::*;
type Input = Vec<i32>;
fn solve(input: &Input) -> (i32, i32) {
let mut p1 = 0;
let mut p2 = 0;
for i in 0..input.len() {
for j in 0..input.len() {
if i == j {
continue;
}
if input[i] + input[j] == 2020 {
p1 = input[i] * input[j];
}
for k in 0..input.len() {
if j == k {
continue;
}
if input[i] + input[j] + input[k] == 2020 {
p2 = input[i] * input[j] * input[k];
}
}
}
}
(p1, p2)
}
fn main() {
measure(|| {
let input = input().expect("Input failed");
let (part1, part2) = solve(&input);
println!("Part1: {}", part1);
println!("Part2: {}", part2);
});
}
fn read_input<R: Read>(reader: BufReader<R>) -> io::Result<Input> {
Ok(reader.lines().map(|l| l.unwrap().parse::<i32>().unwrap()).collect())
}
fn input() -> io::Result<Input> {
let f = File::open(env::args().skip(1).next().expect("No input file given"))?;
read_input(BufReader::new(f))
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &'static str =
"1000
1020
1000
20";
fn as_input(s: &str) -> Input {
read_input(BufReader::new(s.split('\n').map(|s| s.trim()).collect::<Vec<_>>().join("\n").as_bytes())).unwrap()
}
#[test]
fn test_part1() {
assert_eq!(solve(&as_input(INPUT)).0, 1000 * 1020);
}
#[test]
fn test_part2() {
assert_eq!(solve(&as_input(INPUT)).1, 1000 * 1000 * 20);
}
}
|
use crate::types::linalg::dimension::Dimension;
use crate::types::linalg::matrix::Matrix;
use crate::types::shader::shader::Shader;
use crate::types::shader::uniform::Uniform;
use gl::types::*;
use std::ffi::CString;
pub struct ShaderProgram {
pub id: GLuint,
}
impl ShaderProgram {
pub fn link(shaders: &[&Shader]) -> Result<Self, String> {
unsafe {
let id = gl::CreateProgram();
for shader in shaders.iter() {
shader.attach(id);
}
gl::LinkProgram(id);
for shader in shaders.iter() {
shader.detach(id);
}
let mut success = 1;
gl::GetProgramiv(id, gl::LINK_STATUS, &mut success);
if success == 0 {
let mut len = 0;
gl::GetProgramiv(id, gl::INFO_LOG_LENGTH, &mut len);
let buffer = vec![0u8; len as usize];
gl::GetProgramInfoLog(id, len, std::ptr::null_mut(), buffer.as_ptr() as *mut i8);
Err(CString::from_vec_unchecked(buffer).into_string().unwrap())
} else {
Ok(ShaderProgram { id })
}
}
}
pub fn gl_use(&self) {
unsafe { gl::UseProgram(self.id) }
}
pub fn delete(self) {
unsafe { gl::DeleteProgram(self.id) }
}
pub fn uniform_from_str(&self, s: &str) -> Result<Uniform, String> {
let cstr = CString::new(s).unwrap();
let id = unsafe { gl::GetUniformLocation(self.id, cstr.as_ptr()) };
if id == -1 {
Err("Uniform not found!".to_owned())
} else {
Ok(Uniform { id })
}
}
pub fn uniform1i(&self, uniform: &Uniform, i1: i32) {
//TODO Design decision: Make sure shader program is active? Requires internal "active" field and mutability
unsafe { gl::Uniform1i(uniform.id, i1) }
}
pub fn uniform1f(&self, uniform: &Uniform, f1: f32) {
//TODO Design decision: Make sure shader program is active? Requires internal "active" field and mutability.
unsafe { gl::Uniform1f(uniform.id, f1) }
}
pub fn uniform4f(&self, uniform: &Uniform, f1: f32, f2: f32, f3: f32, f4: f32) {
//TODO Design decision: Make sure shader program is active? Requires internal "active" field and mutability.
unsafe { gl::Uniform4f(uniform.id, f1, f2, f3, f4) }
}
pub fn uniform_matrix4fv(&self, uniform: &Uniform, mat: &Matrix<f32>) {
//TODO Design decision: Make sure shader program is active? Requires internal "active" field and mutability.
debug_assert!(mat.dimension == Dimension::new(4, 4));
unsafe { gl::UniformMatrix4fv(uniform.id, 1, gl::TRUE, mat.as_ptr()) }
}
}
impl Drop for ShaderProgram {
fn drop(&mut self) {
unsafe { gl::DeleteProgram(self.id) }
}
}
|
use std::comm::{channel, Receiver};
use token::*;
use ast::*;
use std::from_str::from_str;
use scanner;
use std::collections::hashmap::HashMap;
///Scan and Parse a file in parallel producing an AST
pub fn parse_file_async(path : &str) -> Vec<Box<Stmt>> {
let tokens = scanner::stream_from_file(path);
AsyncParser::new(tokens).parse_sync()
}
///Scan and then Parse a file producing an AST
pub fn parse_file_sync(path : &str) -> Vec<Box<Stmt>> {
let tokens = scanner::tokenize_file(path);
SyncParser::new(tokens).parse_sync()
}
///Scan and Parse a string in parallel producing an AST
pub fn parse_str_async(code : &str) -> Vec<Box<Stmt>> {
let tokens = scanner::stream_from_str(code);
AsyncParser::new(tokens).parse_sync()
}
///Scan and then Parse a string producing an AST
pub fn parse_str_sync(code : &str) -> Vec<Box<Stmt>> {
let tokens = scanner::tokenize_str(code);
SyncParser::new(tokens).parse_sync()
}
///Scan and Parse a file in parallel producing a stream of top level AST nodes
pub fn parse_and_stream_file_async(path : &str) -> Receiver<Box<Stmt>> {
let (sendr, recvr) = channel();
let path = path.to_string();
spawn(proc(){
let tokens = scanner::stream_from_file(path.as_slice());
AsyncParser::new(tokens).parse_async(sendr);
});
recvr
}
///Scan and then Parse a file producing a stream of top level AST nodes
pub fn parse_and_stream_file_sync(path : &str) -> Receiver<Box<Stmt>> {
let (sendr, recvr) = channel();
let path = path.to_string();
spawn(proc(){
let tokens = scanner::tokenize_file(path.as_slice());
SyncParser::new(tokens).parse_async(sendr);
});
recvr
}
///Scan and Parse a string in parallel producing a stream of top level AST nodes
pub fn parse_and_stream_str_async(path : &str) -> Receiver<Box<Stmt>> {
let (sendr, recvr) = channel();
let path = path.to_string();
spawn(proc(){
let tokens = scanner::stream_from_str(path.as_slice());
AsyncParser::new(tokens).parse_async(sendr);
});
recvr
}
///Scan and then Parse a string producing a stream of top level AST nodes
pub fn parse_and_stream_str_sync(path : &str) -> Receiver<Box<Stmt>> {
let (sendr, recvr) = channel();
let path = path.to_string();
spawn(proc(){
let tokens = scanner::tokenize_str(path.as_slice());
SyncParser::new(tokens).parse_async(sendr);
});
recvr
}
pub struct AsyncParser {
tokens : Receiver<Token>,
presidences : HashMap<Ident, int>,
peek_tok : Option<Token>,
tok : Option<Token>,
parsing_gen : bool
}
pub struct SyncParser {
tokens : Vec<Token>,
presidences : HashMap<Ident, int>,
tok_idx : int,
parsing_gen : bool
}
pub trait HydraParser : HydraBaseParser {
fn parse_sync(&mut self) -> Vec<Box<Stmt>> {
let mut stmts = Vec::new();
self.for_each_stmt(|stmt : Box<Stmt>|{
stmts.push(stmt);
});
stmts
}
fn parse_async(&mut self, sendr : Sender<Box<Stmt>>) {
self.for_each_stmt(|stmt : Box<Stmt>|{
sendr.send(stmt);
});
}
}
///abc or abc.def or a.b.c, d.e.f
///TODO: merge prop_path and prop_paths to return one of these so
///prefix...and eventually postfix...unary operators can be parsed
enum IdentPrefix {
SingleIdent(Ident),
SingleIdentList(Vec<Ident>),
MultiIdentList(Vec<Vec<Ident>>)
}
trait HydraBaseParser {
///Returns the current token
fn tok(&mut self) -> Token;
///Returns the next token or None if at EOF
fn peek(&mut self) -> Option<Token>;
///Consumes the next token and returns true if
///possible, otherwise returns false if at EOF
fn next_opt(&mut self) -> bool;
///Returns a tokens presidence
fn get_presidence(&mut self, &Token) -> int;
///Sets the presidence for a token
fn set_presidence(&mut self, &Token, int);
///Returns whether or not parser is currently parsing a generator
///definition
fn parsing_generator(&self) -> bool;
///Let Parser know it is parsing a generator definition
fn start_gen_parsing(&mut self);
///Let Parser know it is no longer parsing a generator definition
fn end_gen_parsing(&mut self);
///Advance to next token or fail! if at EOF
fn next(&mut self) {
if !self.next_opt() {
fail!("Unexpected end of input")
};
}
///If the next token is the passed token type, then consume it and return
///true, otherwise false
fn next_is(&mut self, typ : TokenType) -> bool {
match self.peek() {
Some(tok) => {
if tok.typ == typ {
self.next();
true
} else {
false
}
},
None => false
}
}
///Consume the next token if it is of the expected token type, otherwise fail!
fn expect(&mut self, typ : TokenType){
if !self.next_is(typ) {
let tok = self.tok();
fail!(
"\n\nExpected {:?} at '{}' => {}:{}\n\n",
typ,
tok.text,
tok.line,
tok.col
);
}
}
fn for_each_stmt(&mut self, cb : |Box<Stmt>|) {
loop {
let stmt = match self.program_stmt() {
Some(s) => s,
None => return
};
cb(stmt);
}
}
fn program_stmt(&mut self) -> Option<Box<Stmt>> {
match self.peek() {
Some(tok) => {
let stmt = match tok.typ {
For => {
self.next();
self.for_in_loop()
},
While => {
self.next();
self.while_loop()
},
Var => {
self.next();
self.var_decl()
},
Identifier => {
self.func_call_or_assignment_stmt()
},
If => {
self.next();
self.if_else_stmt()
},
Function => {
self.next();
self.function_def()
},
Operator => {
self.next();
self.operator_def()
},
Generator => {
self.next();
self.expect(Function);
self.start_gen_parsing();
self.function_def()
},
NewLine => {
self.next();
match self.program_stmt() {
Some(stmt) => stmt,
None => return None
}
},
_ => fail!(
"Statement at {}:{} not allowed at top level",
self.tok().line,
self.tok().col
)
};
Some(stmt)
},
None => {
None
}
}
}
fn function_def(&mut self) -> Box<Stmt> {
self.expect(Identifier);
let func_name = self.tok().text.to_string();
self.expect(Lparen);
//TODO: this should be opt_idents();
let params = self.idents();
self.expect(Rparen);
let stmts = self.block(); //TODO: this should also be optional
if self.parsing_generator() {
self.end_gen_parsing();
GeneratorDef::new(func_name, params, stmts)
} else {
FunctionDef::new(func_name, params, stmts)
}
}
fn operator_def(&mut self) -> Box<Stmt> {
self.expect(Lbracket);
if !self.next_is(Int_Literal) {
fail!("Expected Int for operator presidence");
}
let pres = from_str::<int>(self.tok().text.as_slice()).unwrap();
self.expect(Rbracket);
match self.peek() {
Some(tok) => {
if tok.typ != Identifier {
fail!("Expected Identifier at {}:{}", tok.line, tok.col);
}
self.set_presidence(&tok, pres);
},
None => fail!("Unexpected end of input")
};
self.function_def()
}
fn var_decl(&mut self) -> Box<Stmt> {
let vars = self.idents();
if self.next_is(Assign) {
let vals = self.exprs();
self.expect(Semicolon);
VarAssign::new(vars, vals)
} else {
self.expect(Semicolon);
VarDecl::new(vars)
}
}
fn while_loop(&mut self) -> Box<Stmt> {
let cond = self.expr();
let stmts = self.do_block();
WhileLoop::new(cond, stmts)
}
fn for_in_loop(&mut self) -> Box<Stmt> {
let start = self.tok();//use to make span
let bound_vars = self.idents();
self.expect(In);
let generator = self.expr();
let stmts = self.do_block();
ForInLoop::new(bound_vars, generator, stmts)
}
fn if_else_stmt(&mut self) -> Box<Stmt> {
let mut branches = Vec::new();
let if_cond = self.expr();
self.expect(Then);
let if_stmts = self.stmts();
branches.push(IfElseBranch::new(Some(if_cond), if_stmts));
loop {
if self.next_is(End){
break;
}
self.expect(Else);
if self.next_is(If) {
let else_if_cond = self.expr();
self.expect(Then);
let else_if_stmts = self.stmts();
branches.push(IfElseBranch::new(Some(else_if_cond), else_if_stmts));
} else {
let else_stmts = self.stmts();
branches.push(IfElseBranch::new(None, else_stmts));
}
}
IfElseStmt::new(branches)
}
fn ident_prefix(&mut self) -> Vec<Ident> {
let mut idents = Vec::new();
idents.push(self.ident());
loop {
if !self.next_is(Period) {
break;
}
idents.push(self.ident());
}
idents
}
fn stmt_ident_prefixs(&mut self) -> IdentPrefix {
let first = self.ident_prefix();
if self.next_is(Comma) {
let mut prop_paths = Vec::new();
prop_paths.push(first);
prop_paths.push(self.ident_prefix());
loop {
if !self.next_is(Comma) {
break;
}
prop_paths.push(self.ident_prefix());
}
MultiIdentList(prop_paths)
} else {
if first.len() == 1 {
SingleIdent(first[0].to_string())
} else {
SingleIdentList(first)
}
}
}
fn expr_ident_prefixs(&mut self) -> IdentPrefix {
let prefix = self.ident_prefix();
if prefix.len() == 1 {
SingleIdent(prefix[0].to_string())
} else {
SingleIdentList(prefix)
}
}
fn func_call(&mut self, prop_path : Vec<Ident>) -> Box<Expr> {
self.expect(Lparen);
let params = self.exprs();
self.expect(Rparen);
FuncCall::new(prop_path, params)
}
fn func_call_stmt(&mut self, prop_paths : Vec<Ident>) -> Box<Stmt> {
self.expect(Lparen);
let params = self.exprs();
self.expect(Rparen);
self.expect(Semicolon);
let expr = FuncCall::new(prop_paths, params);
ExprStmt::new(expr)
}
fn assignment_stmt(&mut self, prop_paths : Vec<Vec<Ident>>) -> Box<Stmt> {
self.expect(Assign);
let rhs = self.exprs();
self.expect(Semicolon);
AssignStmt::new(prop_paths, rhs)
}
fn func_call_or_assignment_stmt(&mut self) -> Box<Stmt> {
let prop_paths = self.stmt_ident_prefixs();
match self.peek() {
Some(tok) => {
match tok.typ {
Assign => {
match prop_paths {
SingleIdentList(path) => {
self.assignment_stmt(vec!(path))
},
MultiIdentList(paths) => {
self.assignment_stmt(paths)
},
SingleIdent(prefix) => {
self.assignment_stmt(vec!(vec!(prefix)))
}
}
},
Lparen => {
match prop_paths {
SingleIdentList(path) => {
self.func_call_stmt(path)
},
MultiIdentList(paths) => {
fail!("Function calls need to be their own statement")
},
SingleIdent(prefix) => {
self.func_call_stmt(vec!(prefix))
}
}
},
_ => fail!("Useless stmt at {}:{}", tok.line, tok.col)
}
},
None => {
let tok = self.tok();
fail!("Useless stmt at {}:{}", tok.line, tok.col)
}
}
}
fn stmt_opt(&mut self) -> Option<Box<Stmt>> {
match self.peek() {
Some(tok) => {
match tok.typ {
Identifier => {
Some(self.func_call_or_assignment_stmt())
},
For => {
self.next();
Some(self.for_in_loop())
},
While => {
self.next();
Some(self.while_loop())
},
Var => {
self.next();
Some(self.var_decl())
},
Break => {
self.next();
let stmt = LoopControlStmt::new(Break);
self.expect(Semicolon);
Some(stmt)
},
Continue => {
self.next();
let stmt = LoopControlStmt::new(Continue);
self.expect(Semicolon);
Some(stmt)
},
If => {
self.next();
Some(self.if_else_stmt())
},
Return => {
if self.parsing_generator() {
fail!("Return statements are not allowed in generator defninitions");
}
self.next();
//TODO: this should be optional...you should be able to return early
let ret_val = self.expr();
self.next_is(Semicolon);
Some(ReturnStmt::new(ret_val))
},
Yield => {
if !self.parsing_generator() {
fail!("Yield statements are only allowed in generator defninitions");
}
self.next();
let yield_vals = self.exprs();
self.expect(Semicolon);
Some(YieldStmt::new(yield_vals))
},
NewLine => {
self.next();
self.stmt_opt()
}
_ => None
}
},
None => None
}
}
fn stmt(&mut self) -> Box<Stmt> {
match self.stmt_opt() {
Some(stmt) => stmt,
None => fail!("Expected statement at {}:{}", self.tok().line, self.tok().col)
}
}
fn incl_range(&mut self, start : Box<Expr>) -> Box<Expr> {
let end = self.expr();
InclusiveRange::new(start, end)
}
fn excl_range(&mut self, start : Box<Expr>) -> Box<Expr> {
let end = self.expr();
ExclusiveRange::new(start, end)
}
fn is_binary_op(&self, typ : TokenType) -> bool {
match typ {
Add_Op | Min_Op | Mult_Op | Div_Op | Mod_Op | Power_Op |
Less_Than | Greater_Than | Less_Than_Eq | Greater_Than_Eq | Equal | Bang_Eq => true,
Identifier => true, //binary operators that are words
_ => false
}
}
fn resolve_bin_expr(&mut self, expr1 : Box<Expr>) -> Box<Expr> {
let op1 = self.tok();
let expr2 = match self.basic_expr_opt(){
Some(e) => e,
None => fail!(
"Trailing {:?} at {}:{}",
op1.typ,
op1.line,
op1.col
)
};
let op2 = self.peek();
match op2 {
Some(ref op) => {
if !self.is_binary_op(op.typ) {
return BinaryExpr::new(expr1, op1.text, expr2);
}
},
None => {
return BinaryExpr::new(expr1, op1.text, expr2);
}
};
let op2 = op2.unwrap();
self.next();
let op1_pres = self.get_presidence(&op1);
let op2_pres = self.get_presidence(&op2);
if op1_pres >= op2_pres {
let expr_tmp = BinaryExpr::new(expr1, op1.text, expr2);
self.resolve_bin_expr(expr_tmp)
} else {
let expr_tmp = self.resolve_bin_expr(expr2);
BinaryExpr::new(expr1, op1.text, expr_tmp)
}
}
fn basic_expr_opt(&mut self) -> Option<Box<Expr>> {
match self.peek() {
Some(tok) => {
match tok.typ {
Int_Literal => {
self.next();
let num = from_str::<int>(self.tok().text.as_slice()).unwrap();
Some(Int::new(num))
},
Identifier => {
Some(self.ident_or_func_call())
}
_ => None
}
},
None => None
}
}
fn ident_or_func_call(&mut self) -> Box<Expr> {
let prop_paths = self.expr_ident_prefixs();
match prop_paths {
SingleIdentList(path) => {
match self.peek() {
Some(tok) => {
if tok.typ == Lparen {
self.func_call(path)
} else {
//TODO this will change when objects get support
//this will actually never get called until i have things like
//myobj.prop.name as valid expressions
IdentExpr::new(path[0].to_string())
}
},
None => {
//TODO: removing this and returning another identexpr will
//remove the need for a semicolon...hmmm unless the semicolon
//is checked by the caller
let tok = self.tok();
fail!("Expected Expression at {}:{}", tok.line, tok.col);
}
}
},
SingleIdent(ident) => {
match self.peek() {
Some(tok) => {
if tok.typ == Lparen {
self.func_call(vec!(ident))
} else {
match self.expr_opt() {
Some(expr) => {
PrefixUnaryExpr::new(ident, expr)
},
None => IdentExpr::new(ident)
}
}
},
None => {
IdentExpr::new(ident)
}
}
},
MultiIdentList(paths) => {
//this should never happen as this function should be returning basic
//expressions not lists of them
fail!("PARSER ERROR: THIS SHOULD BE UNREACHABLE");
}
}
}
fn expr_opt(&mut self) -> Option<Box<Expr>> {
//integers and binary exp
let expr_opt = self.basic_expr_opt();
if expr_opt.is_none() {
return None
}
match self.peek() {
Some(tok) => {
match tok.typ {
//'start()...end()' or '0 + 2 - 1 through end'
Incl_Range | Through => {
self.next();
Some(self.incl_range(expr_opt.unwrap()))
},
//'start()..end()' or '0 + 2 - 1 upto end'
Excl_Range | Upto => {
self.next();
Some(self.excl_range(expr_opt.unwrap()))
},
// 2 * 2 + 4 = 8 ------- 2 + 2 * 4 = 10
// TODO:change this call to take a full token and tell you if it could be a binary op including identifiers
_ if self.is_binary_op(tok.typ) => {
self.next();
Some(self.resolve_bin_expr(expr_opt.unwrap()))
},
_ => expr_opt
}
},
None => expr_opt
}
}
fn expr(&mut self) -> Box<Expr> {
match self.expr_opt() {
Some(expr) => expr,
None => fail!("Expected expr at {}:{}", self.tok().line, self.tok().col)
}
}
fn ident_opt(&mut self) -> Option<Ident> {
if self.next_is(Identifier) {
Some(self.tok().text)
} else {
None
}
}
fn ident(&mut self) -> Ident {
self.expect(Identifier);
self.tok().text
}
//always optional
fn stmts(&mut self) -> Vec<Box<Stmt>> {
let mut stmts = Vec::new();
loop {
match self.stmt_opt() {
Some(stmt) => {
stmts.push(stmt);
},
None => break
}
};
stmts
}
fn exprs(&mut self) -> Vec<Box<Expr>> {
let mut exprs = Vec::new();
match self.expr_opt() {
Some(e) => {
exprs.push(e);
loop {
if !self.next_is(Comma) {
break;
}
exprs.push(self.expr());
};
},
None => {}
};
return exprs
}
fn idents(&mut self) -> Vec<Ident> {
let mut idents = Vec::new();
idents.push(self.ident());
loop {
if !self.next_is(Comma) {
break;
}
idents.push(self.ident());
}
return idents
}
fn block(&mut self) -> Vec<Box<Stmt>> {
self.expect(Lcurly);
let stmts = self.stmts();
self.expect(Rcurly);
stmts
}
fn do_block(&mut self) -> Vec<Box<Stmt>> {
self.expect(Do);
let stmts = self.stmts();
self.expect(End);
stmts
}
}
impl AsyncParser {
pub fn new(toks : Receiver<Token>) -> AsyncParser {
let first = match toks.recv_opt() {
Ok(t) => Some(t),
Err(_) => fail!("Created parser with empty input")
};
AsyncParser {
tokens : toks,
presidences : new_presidence_map(),
peek_tok : first,
tok : None,
parsing_gen : false
}
}
}
impl HydraParser for AsyncParser {}
impl HydraBaseParser for AsyncParser {
fn next_opt(&mut self) -> bool {
match self.peek() {
Some(tok) => {
self.peek_tok = match self.tokens.recv_opt() {
Ok(peek) => Some(peek),
Err(_) => None
};
self.tok = Some(tok);
true
},
None => false
}
}
fn peek(&mut self) -> Option<Token> {
self.peek_tok.clone()
}
fn tok(&mut self) -> Token {
match self.tok {
Some(ref t) => t.clone(),
None => fail!("Tried to get token before advancing")
}
}
fn get_presidence(&mut self, tok : &Token) -> int {
match self.presidences.find(&tok.text) {
Some(pres) => *pres,
None => fail!("Must define {} operator before it can be used", tok.text)
}
}
fn set_presidence(&mut self, tok : &Token, pres : int) {
self.presidences.insert(tok.text.to_string(), pres);
}
fn parsing_generator(&self) -> bool {
self.parsing_gen
}
fn start_gen_parsing(&mut self) {
self.parsing_gen = true;
}
fn end_gen_parsing(&mut self) {
self.parsing_gen = false;
}
}
impl SyncParser {
pub fn new(toks : Vec<Token>) -> SyncParser {
if toks.is_empty() {
fail!("Created parser with empty input");
}
SyncParser {
tokens : toks,
presidences : new_presidence_map(),
tok_idx : -1,
parsing_gen : false
}
}
}
impl HydraParser for SyncParser {}
impl HydraBaseParser for SyncParser {
fn next_opt(&mut self) -> bool {
match self.peek() {
Some(tok) => {
self.tok_idx += 1;
true
},
None => false
}
}
fn peek(&mut self) -> Option<Token> {
if self.tok_idx >= ((self.tokens.len() as int) - 1) {
None
} else {
let peek_idx = (self.tok_idx + 1) as uint;
Some(self.tokens[peek_idx].clone())
}
}
fn tok(&mut self) -> Token {
let idx = self.tok_idx;
if idx < 0 {
fail!("Tried to get token before advancing");
}
self.tokens[idx as uint].clone()
}
fn get_presidence(&mut self, tok : &Token) -> int {
match self.presidences.find(&tok.text) {
Some(pres) => *pres,
None => fail!("Must define {} operator before it can be used", tok.text)
}
}
fn set_presidence(&mut self, tok : &Token, pres : int) {
self.presidences.insert(tok.text.to_string(), pres);
}
fn parsing_generator(&self) -> bool {
self.parsing_gen
}
fn start_gen_parsing(&mut self) {
self.parsing_gen = true;
}
fn end_gen_parsing(&mut self) {
self.parsing_gen = false;
}
}
fn new_presidence_map() -> HashMap<Ident, int> {
let mut map = HashMap::new();
map.insert("%".to_string(), 1);
map.insert("+".to_string(), 2);
map.insert("-".to_string(), 2);
map.insert("*".to_string(), 3);
map.insert("/".to_string(), 3);
map.insert("^".to_string(), 4);
map
}
////////////////////////////////////////////////////////////////////////////////
// Tests //
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////
// Expressions //
///////////////////////////////////////
macro_rules! check_expr(
($code:expr -> $expr_lit:expr) => ({
let tokens = scanner::stream_from_str($code);
let expr = AsyncParser::new(tokens).expr();
assert!(expr == $expr_lit);
});
)
#[test]
fn int_expr(){
check_expr!("123" -> Int::new(123));
}
#[test]
fn ident_expr(){
check_expr!("abc" -> IdentExpr::new("abc".to_string()));
}
#[test]
fn basic_func_call_expr(){
check_expr!("abc()" -> FuncCall::new(vec!("abc".to_string()), vec!()));
}
#[test]
fn func_call_expr_with_params(){
check_expr!("abc(1, def)" -> FuncCall::new(
vec!("abc".to_string()),
vec!(Int::new(1), IdentExpr::new("def".to_string()))
));
}
#[test]
fn inclusive_range_expr(){
check_expr!("0 through 10" -> InclusiveRange::new(Int::new(0), Int::new(10)));
}
#[test]
fn dotted_inclusive_range_expr(){
check_expr!("0...10" -> InclusiveRange::new(Int::new(0), Int::new(10)));
}
#[test]
fn exclusive_range_expr(){
check_expr!("0 upto 10" -> ExclusiveRange::new(Int::new(0), Int::new(10)));
}
#[test]
fn dotted_exclusive_range_expr(){
check_expr!("0..10" -> ExclusiveRange::new(Int::new(0), Int::new(10)));
}
#[test]
fn basic_bin_expr(){
check_expr!("1 + ten" -> BinaryExpr::new(
Int::new(1),
"+".to_string(),
IdentExpr::new("ten".to_string())
));
}
#[test]
fn complex_bin_expr(){
check_expr!("1 + 2 * 3 - 4 / 5" ->
BinaryExpr::new(
Int::new(1),
"+".to_string(),
BinaryExpr::new(
BinaryExpr::new(
Int::new(2),
"*".to_string(),
Int::new(3)
),
"-".to_string(),
BinaryExpr::new(
Int::new(4),
"/".to_string(),
Int::new(5)
),
)
)
);
}
#[test]
fn prefix_unary_expr(){
check_expr!("double 1 + 1" -> PrefixUnaryExpr::new(
"double".to_string(),
BinaryExpr::new(
Int::new(1),
"+".to_string(),
Int::new(1)
)
));
}
///////////////////////////////////////
// Statements //
///////////////////////////////////////
macro_rules! check_stmt(
($code:expr -> $stmt_lit:expr) => ({
let tokens = scanner::stream_from_str($code);
let stmts = AsyncParser::new(tokens).parse_sync();
assert!(stmts.get(0) == &$stmt_lit);
});
)
#[test]
fn expr_stmt(){
check_stmt!("abc(1, def);" -> ExprStmt::new(
FuncCall::new(
vec!("abc".to_string()),
vec!(
Int::new(1),
IdentExpr::new("def".to_string())
)
)
));
}
#[test]
fn single_var_decl(){
check_stmt!("var a;" -> VarDecl::new(
vec!(
"a".to_string()
)
));
}
#[test]
fn multi_var_decl(){
check_stmt!("var a, b, c;" -> VarDecl::new(
vec!(
"a".to_string(),
"b".to_string(),
"c".to_string()
)
));
}
#[test]
fn single_var_assign(){
check_stmt!("var a = 1;" -> VarAssign::new(
vec!(
"a".to_string()
),
vec!(
Int::new(1)
)
));
}
#[test]
fn multi_var_assign(){
check_stmt!("var a, b, c = 1, hy, dra();" -> VarAssign::new(
vec!(
"a".to_string(),
"b".to_string(),
"c".to_string()
),
vec!(
Int::new(1),
IdentExpr::new("hy".to_string()),
FuncCall::new(
vec!("dra".to_string()),
vec!()
)
)
));
}
#[test]
fn uneven_var_assign(){
check_stmt!("var a, b, c = 1;" -> VarAssign::new(
vec!(
"a".to_string(),
"b".to_string(),
"c".to_string()
),
vec!(
Int::new(1)
)
));
}
#[test]
fn single_assign(){
check_stmt!("a = 1;" -> AssignStmt::new(
vec!(vec!("a".to_string())),
vec!(Int::new(1))
));
}
#[test]
fn multiple_assign(){
check_stmt!("a, b = 1, 2;" -> AssignStmt::new(
vec!(
vec!("a".to_string()),
vec!("b".to_string())
),
vec!(
Int::new(1),
Int::new(2)
)
));
}
#[test]
fn if_branch(){
check_stmt!("if cond then something(); end" -> IfElseStmt::new(
vec!(
IfElseBranch::new(
Some(IdentExpr::new("cond".to_string())),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("something".to_string()),
vec!()
)
)
)
)
)
));
}
#[test]
fn if_else_branch(){
check_stmt!("if cond then something(); else something_else(); end" -> IfElseStmt::new(
vec!(
IfElseBranch::new(
Some(IdentExpr::new("cond".to_string())),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("something".to_string()),
vec!()
)
)
)
),
IfElseBranch::new(
None,
vec!(
ExprStmt::new(
FuncCall::new(
vec!("something_else".to_string()),
vec!()
)
)
)
)
)
));
}
#[test]
fn if_elseif_branch(){
check_stmt!("if cond then something(); else if cond2 then something_else(); end" -> IfElseStmt::new(
vec!(
IfElseBranch::new(
Some(IdentExpr::new("cond".to_string())),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("something".to_string()),
vec!()
)
)
)
),
IfElseBranch::new(
Some(IdentExpr::new("cond2".to_string())),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("something_else".to_string()),
vec!()
)
)
)
)
)
));
}
#[test]
fn if_elseif_else_branch(){
check_stmt!("if cond then something(); else if cond2 then something_else(); else nothing(); end" -> IfElseStmt::new(
vec!(
IfElseBranch::new(
Some(IdentExpr::new("cond".to_string())),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("something".to_string()),
vec!()
)
)
)
),
IfElseBranch::new(
Some(IdentExpr::new("cond2".to_string())),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("something_else".to_string()),
vec!()
)
)
)
),
IfElseBranch::new(
None,
vec!(
ExprStmt::new(
FuncCall::new(
vec!("nothing".to_string()),
vec!()
)
)
)
)
)
));
}
#[test]
fn for_in_loop_single_var(){
check_stmt!("for i in 0..10 do break; end" -> ForInLoop::new(
vec!(
"i".to_string()
),
ExclusiveRange::new(
Int::new(0),
Int::new(10)
),
vec!(
LoopControlStmt::new(Break)
)
));
}
#[test]
fn for_in_loop_multi_var(){
check_stmt!("for i, j in positions do continue; end" -> ForInLoop::new(
vec!(
"i".to_string(),
"j".to_string()
),
IdentExpr::new("positions".to_string()),
vec!(
LoopControlStmt::new(Continue)
)
));
}
#[test]
fn while_loop(){
check_stmt!("while cond do break; continue; end" -> WhileLoop::new(
IdentExpr::new("cond".to_string()),
vec!(
LoopControlStmt::new(Break),
LoopControlStmt::new(Continue)
)
));
}
#[test]
fn func_def_no_params(){
//CURRENTLY FAILS AS PARAMS AREN'T OPTIONAL
check_stmt!("function abc(){ stuff(); }" -> FunctionDef::new(
"abc".to_string(),
vec!(),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("stuff".to_string()),
vec!()
)
)
)
)
);
}
#[test]
fn func_def_single_param(){
check_stmt!("function abc(a){ stuff(); }" -> FunctionDef::new(
"abc".to_string(),
vec!(
"a".to_string()
),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("stuff".to_string()),
vec!()
)
)
)
)
);
}
#[test]
fn func_def_multi_param(){
check_stmt!("function abc(a, b, c){ return a; }" -> FunctionDef::new(
"abc".to_string(),
vec!(
"a".to_string(),
"b".to_string(),
"c".to_string()
),
vec!(
ReturnStmt::new(
IdentExpr::new("a".to_string())
)
)
)
);
}
#[test]
fn gen_func_def_no_params(){
//CURRENTLY FAILS AS PARAMS AREN'T OPTIONAL
check_stmt!("gen function abc(){ stuff(); }" -> GeneratorDef::new(
"abc".to_string(),
vec!(),
vec!(
ExprStmt::new(
FuncCall::new(
vec!("stuff".to_string()),
vec!()
)
)
)
)
);
}
#[test]
fn gen_func_def_single_param(){
check_stmt!("gen function abc(a){ yield a; }" -> GeneratorDef::new(
"abc".to_string(),
vec!(
"a".to_string()
),
vec!(
YieldStmt::new(
vec!(
IdentExpr::new("a".to_string())
)
)
)
)
);
}
#[test]
fn gen_func_def_multi_param(){
check_stmt!("gen function abc(a, b, c){ yield a, b, c; }" -> GeneratorDef::new(
"abc".to_string(),
vec!(
"a".to_string(),
"b".to_string(),
"c".to_string()
),
vec!(
YieldStmt::new(
vec!(
IdentExpr::new("a".to_string()),
IdentExpr::new("b".to_string()),
IdentExpr::new("c".to_string())
)
)
)
)
);
}
#[test]
#[should_fail]
fn func_def_yield_fail() {
let tokens = scanner::stream_from_str("function abc(a, b, c){ yield a; }");
AsyncParser::new(tokens).parse_sync();
}
#[test]
#[should_fail]
fn gen_func_def_yield_fail() {
let tokens = scanner::stream_from_str("gen function abc(a, b, c){ return a; }");
AsyncParser::new(tokens).parse_sync();
}
#[test]
#[should_fail]
fn break_top_level_fail() {
let tokens = scanner::stream_from_str("break");
AsyncParser::new(tokens).parse_sync();
}
#[test]
#[should_fail]
fn continue_top_level_fail() {
let tokens = scanner::stream_from_str("continue");
AsyncParser::new(tokens).parse_sync();
}
#[test]
#[should_fail]
fn return_top_level_fail() {
let tokens = scanner::stream_from_str("return");
AsyncParser::new(tokens).parse_sync();
}
#[test]
#[should_fail]
fn yield_top_level_fail() {
let tokens = scanner::stream_from_str("yield");
AsyncParser::new(tokens).parse_sync();
} |
use quote::Tokens;
use syn::{Ident, Path};
use glib_utils::*;
use hir::{FnArg, Signal, Slot, Ty};
use super::class::ClassContext;
use super::cstringident::CStringIdent;
impl<'ast> ClassContext<'ast> {
pub fn signal_trampolines(&self) -> Vec<Tokens> {
self.signals()
.map(|signal| {
let signalname_trampoline = signal_trampoline_name(signal);
let InstanceName = self.InstanceName;
let InstanceNameFfi = self.InstanceNameFfi;
let callback_guard = glib_callback_guard();
let sig = &signal.sig;
let c_inputs = sig.input_args_with_glib_types();
let input_types = signal.sig.input_arg_types();
let arg_names = sig.input_args_from_glib_types();
let output = &sig.output;
let ret = quote_cs! {
f(&#InstanceName::from_glib_borrow(this).downcast_unchecked(), #arg_names)
};
let ret = sig.ret_to_glib(ret);
quote_cs! {
unsafe extern "C" fn #signalname_trampoline<P>(
this: *mut imp::#InstanceNameFfi,
#c_inputs
f: glib_ffi::gpointer,
) -> #output
where
P: IsA<#InstanceName>,
{
#callback_guard
let f: &&(Fn(&P, #input_types) -> #output + 'static) = mem::transmute(f);
#ret
}
}
})
.collect()
}
pub fn signal_declarations(&self) -> Vec<Tokens> {
self.signals()
.map(|signal| {
// FIXME: we are not passing signal flags
//
// FIXME: We are not passing a class_closure, marshaller, etc.
let get_type_fn_name = self.instance_get_type_fn_name();
let signal_id_name = signal_id_name(&signal);
let signal_name = CStringIdent(signal.sig.name);
assert!(signal.sig.inputs.len() > 0);
let n_params = (signal.sig.inputs.len() - 1) as u32;
let param_gtypes: Vec<Path> = signal.sig.inputs.iter()
.skip(1) // skip &self
.map(|arg| {
if let FnArg::Arg { ref ty, .. } = arg {
ty.to_gtype_path()
} else {
unreachable!();
}
})
.collect();
let return_gtype = signal.sig.output.to_gtype_path();
quote_cs! {
let param_gtypes = [#(#param_gtypes),*];
// FIXME: we are using G_SIGNAL_RUN_LAST all the time so that signals
// with return values will work. We should do this automatically only
// for signals with return values, or let the user specify the flags and
// check that they match gobject's requirements.
PRIV.#signal_id_name =
gobject_sys::g_signal_newv (#signal_name as *const u8 as *const i8,
#get_type_fn_name(),
gobject_sys::G_SIGNAL_RUN_LAST, // flags
ptr::null_mut(), // class_closure,
None, // accumulator
ptr::null_mut(), // accu_data
None, // c_marshaller,
#return_gtype, // return_type
#n_params, // n_params,
mut_override(param_gtypes.as_ptr())
);
}
})
.collect()
}
pub fn signal_emit_methods(&self) -> Vec<Tokens> {
self.signals()
.map(|signal| {
let emit_name = emit_signalname(signal);
let signal_id_name = signal_id_name(&signal);
let rust_params = &signal.sig.inputs;
let rust_return_ty = &signal.sig.output;
let signal_params = signal.sig.input_args_to_glib_values();
let return_gtype = signal.sig.output.to_gtype_path();
let (initialize_return_value, convert_return_value_to_rust) = match rust_return_ty {
Ty::Unit => (quote_cs!{}, quote_cs! { () }),
_ => (
quote_cs! {
gobject_sys::g_value_init(ret.to_glib_none_mut().0, #return_gtype);
},
quote_cs! {
if ret.type_() == glib::Type::Invalid {
unreachable!();
} else {
ret.get().unwrap()
}
},
),
};
quote_cs! {
#[allow(unused)]
fn #emit_name(#(#rust_params),*) -> #rust_return_ty {
// foo/imp.rs: increment()
let params: &[glib::Value] = &[
#signal_params
];
unsafe {
let mut ret = glib::Value::uninitialized();
#initialize_return_value
gobject_sys::g_signal_emitv(
mut_override(params.as_ptr()) as *mut gobject_sys::GValue,
PRIV.#signal_id_name,
0, // detail
ret.to_glib_none_mut().0,
);
#convert_return_value_to_rust
}
}
}
})
.collect()
}
pub fn signal_id_names(&self) -> Vec<Ident> {
self.signals()
.map(|signal| signal_id_name(signal))
.collect()
}
pub fn signals(&'ast self) -> impl Iterator<Item = &'ast Signal> {
self.class.slots.iter().filter_map(|slot| match *slot {
Slot::Signal(ref s) => Some(s),
_ => None,
})
}
}
/// From a signal called `foo`, generate `foo_signal_id`. This is used to
/// store the signal ids from g_signal_newv() in the Class structure.
fn signal_id_name<'ast>(signal: &'ast Signal) -> Ident {
Ident::from(format!("{}_signal_id", signal.sig.name.as_ref()))
}
/// From a signal called `foo` generate a `foo_trampoline` identifier. This is used
/// for the functions that get passed to g_signal_connect().
pub fn signal_trampoline_name(signal: &Signal) -> Ident {
Ident::from(format!(
"{}_signal_handler_trampoline",
signal.sig.name.as_ref()
))
}
/// From a signal called `foo` generate a `connect_foo` identifier. This is used
/// for the public methods in the InstanceExt trait.
pub fn connect_signalname(signal: &Signal) -> Ident {
Ident::from(format!("connect_{}", signal.sig.name.as_ref()))
}
/// From a signal called `foo` generate a `emit_foo` identifier. This is used
/// for the user's implementations of methods.
fn emit_signalname(signal: &Signal) -> Ident {
Ident::from(format!("emit_{}", signal.sig.name.as_ref()))
}
|
use crate::{
rendering::*,
};
pub trait Canvas<'f> {
fn drawing_data(&mut self) -> &mut DrawingData;
fn rect(&mut self) -> Rect {
let masks = self.masks();
Rect::new(self.drawing_data(), masks)
}
fn line(&mut self) -> Line {
let masks = self.masks();
Line::new(self.drawing_data(), masks)
}
fn ellipse(&mut self) -> Ellipse {
let masks = self.masks();
Ellipse::new(self.drawing_data(), masks)
}
fn image<P>(&mut self, image: P) -> Image
where P: Into<String>
{
let masks = self.masks();
Image::new(self.drawing_data(), image.into(), masks)
}
fn text<P>(&mut self, font: P) -> Text
where P: Into<String>
{
let masks = self.masks();
Text::new(self.drawing_data(), font.into(), masks)
}
fn masks(&self) -> (i32, i32);
fn rect_mask(&mut self) -> RectMask {
RectMask::new(self.drawing_data())
}
}
pub struct Frame<'f> {
pub(crate) drawing_data: &'f mut DrawingData,
}
impl<'f> Canvas<'f> for Frame<'f> {
fn drawing_data(&mut self) -> &mut DrawingData {
self.drawing_data
}
fn masks(&self) -> (i32, i32) {
(0, 0)
}
}
|
use std::env;
use std::time::Instant;
#[macro_use]
extern crate microprofile;
trait Test {
fn fibonacci(&self, n: u32) -> u32;
fn run(&self, n: u32);
}
struct Optick {}
impl Test for Optick {
#[optick_attr::profile]
fn fibonacci(&self, n: u32) -> u32 {
match n {
0 => 1,
1 => 1,
_ => self.fibonacci(n - 1) + self.fibonacci(n - 2),
}
}
fn run(&self, n: u32) {
optick::start_capture();
let mut time = Instant::now();
self.fibonacci(n);
let run_duration = time.elapsed();
time = Instant::now();
optick::stop_capture("optick_capture");
let save_duration = time.elapsed();
println!("Optick time: {:.2?}", run_duration);
println!("Optick save: {:.2?}", save_duration);
}
// #[optick_attr::capture("optick_capture_mt.opt")]
// fn run_mt(&self, n: u32) {
// let mut handles = Vec::new();
// for _ in 0..num_cpus::get()/2-1 {
// handles.push(thread::spawn(move|| {
// optick::register_thread("Worker");
// Optick{}.fibonacci(n);
// }));
// }
// Optick{}.fibonacci(n);
// for handle in handles {
// handle.join().unwrap();
// }
// }
}
struct Superluminal {}
impl Test for Superluminal {
fn fibonacci(&self, n: u32) -> u32 {
superluminal_perf::begin_event("fibonacci");
let res = match n {
0 => 1,
1 => 1,
_ => self.fibonacci(n - 1) + self.fibonacci(n - 2),
};
superluminal_perf::end_event();
return res;
}
fn run(&self, n: u32) {
let start = Instant::now();
self.fibonacci(n);
println!("Superluminal time: {:.2?}", start.elapsed());
}
}
struct Microprofile {}
impl Test for Microprofile {
fn fibonacci(&self, n: u32) -> u32 {
microprofile::scope!("foo", "fibonacci");
match n {
0 => 1,
1 => 1,
_ => self.fibonacci(n - 1) + self.fibonacci(n - 2),
}
}
fn run(&self, n: u32) {
microprofile::init();
microprofile::set_enable_all_groups(true);
microprofile::start_auto_flip(20);
let mut time = Instant::now();
self.fibonacci(n);
let run_duration = time.elapsed();
microprofile::stop_auto_flip();
time = Instant::now();
microprofile::dump_file_immediately("microprofile.html", "");
let save_duration = time.elapsed();
println!("Microprofile time: {:.2?}", run_duration);
println!("Microprofile save: {:.2?}", save_duration);
microprofile::shutdown();
}
}
struct Tracy {}
impl Test for Tracy {
fn fibonacci(&self, n: u32) -> u32 {
match n {
0 => 1,
1 => 1,
_ => self.fibonacci(n - 1) + self.fibonacci(n - 2),
}
}
fn run(&self, n: u32) {
loop {
tracy_rs::tracy_begin_frame!("MainThread");
let time = Instant::now();
self.fibonacci(n);
let run_duration = time.elapsed();
tracy_rs::tracy_end_frame!("MainThread");
println!("Tracy time: {:.2?}", run_duration);
}
}
}
struct Puffin {}
impl Test for Puffin {
fn fibonacci(&self, n: u32) -> u32 {
puffin::profile_function!();
let res = match n {
0 => 1,
1 => 1,
_ => self.fibonacci(n - 1) + self.fibonacci(n - 2),
};
return res;
}
fn run(&self, n: u32) {
puffin::set_scopes_on(true);
let start = Instant::now();
self.fibonacci(n);
println!("Puffin time: {:.2?}", start.elapsed());
}
}
/// Usage: profiler-bench-rs optick 30
pub fn main() {
let args: Vec<String> = env::args().collect();
let mut profiler = "optick";
if args.len() > 1 {
profiler = &args[1];
}
let mut number: u32 = 23;
if args.len() > 2 {
number = (&args[2]).parse().unwrap();
}
println!("Running benchmark: {} (N={})", profiler, number);
match &profiler[..] {
"optick" => Optick {}.run(number),
"superluminal" => Superluminal {}.run(number),
"microprofile" => Microprofile {}.run(number),
"tracy" => Tracy {}.run(number),
"puffin" => Puffin {}.run(number),
_ => println!("Can't find a test for {}!", profiler),
}
} |
#[macro_use]
extern crate neon;
extern crate base64;
extern crate holochain_agent;
extern crate holochain_core;
extern crate holochain_core_api;
extern crate holochain_dna;
extern crate holochain_cas_implementations;
extern crate serde_json;
extern crate tempfile;
pub mod app;
|
use crate::*;
use std::rc::Rc;
use std::cell::RefCell;
use shoji::*;
// HBox
// HBox lays out its children in a single horizontal row from left to right.
// HBox will resize children to their desired widths but constrain the height to the parent container height.
pub struct HBox {
children: Vec<Box<dyn Element>>,
layout: Option<UILayout>
}
impl HBox {
pub fn new() -> Self {
HBox {
children: Vec::new(),
layout: None
}
}
pub fn add_child(&mut self, mut c:impl Element+'static) {
match &mut self.layout {
Some(lm) => c.attach_layout(Some(lm.layout_manager.clone()),Some(lm.layout_node)),
None => c.attach_layout(None,None)
};
self.children.push(Box::new(c));
}
}
impl Element for HBox {
fn render(&self, renderer: &mut dyn Renderer){
if let Some(layout) = &self.layout {
renderer.draw_rectangle(&layout.as_rect());
// render the children
for child in &self.children {
child.render(renderer);
}
}
}
fn attach_layout(&mut self,layout_manager:Option<Rc<RefCell<Shoji>>>, parent_node:Option<NodeIndex>) {
if layout_manager.is_some() {
self.layout = Some(UILayout::new(layout_manager, parent_node, LayoutStyle::default(),&mut self.children));
}
}
fn on_keyboard(&self, key: u32, scancode: u32, action: u32, modifiers: u32) {
panic!("this should be implemented")
}
fn on_character(&self, codepoint: u32) {
panic!("this should be implemented")
}
fn on_mouse_move(&self, xpos: f64, ypos: f64) {
panic!("this should be implemented")
}
fn on_mouse_enter_exit(&self, entered: bool) {
panic!("this should be implemented")
}
fn on_mouse_button(&self, button: i32, action: i32, mods: i32) {
panic!("this should be implemented")
}
fn on_mouse_wheel(&self, xoffset: f64, yoffset: f64) {
panic!("this should be implemented")
}
}
|
#[doc = "Reader of register RCC_APB3DIVR"]
pub type R = crate::R<u32, super::RCC_APB3DIVR>;
#[doc = "Writer for register RCC_APB3DIVR"]
pub type W = crate::W<u32, super::RCC_APB3DIVR>;
#[doc = "Register RCC_APB3DIVR `reset()`'s with value 0x8000_0000"]
impl crate::ResetValue for super::RCC_APB3DIVR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x8000_0000
}
}
#[doc = "APB3DIV\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum APB3DIV_A {
#[doc = "0: hclk (default after\r\n reset)"]
B_0X0 = 0,
#[doc = "1: hclk / 2"]
B_0X1 = 1,
#[doc = "2: hclk / 4"]
B_0X2 = 2,
#[doc = "3: hclk / 8"]
B_0X3 = 3,
}
impl From<APB3DIV_A> for u8 {
#[inline(always)]
fn from(variant: APB3DIV_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `APB3DIV`"]
pub type APB3DIV_R = crate::R<u8, APB3DIV_A>;
impl APB3DIV_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, APB3DIV_A> {
use crate::Variant::*;
match self.bits {
0 => Val(APB3DIV_A::B_0X0),
1 => Val(APB3DIV_A::B_0X1),
2 => Val(APB3DIV_A::B_0X2),
3 => Val(APB3DIV_A::B_0X3),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == APB3DIV_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == APB3DIV_A::B_0X1
}
#[doc = "Checks if the value of the field is `B_0X2`"]
#[inline(always)]
pub fn is_b_0x2(&self) -> bool {
*self == APB3DIV_A::B_0X2
}
#[doc = "Checks if the value of the field is `B_0X3`"]
#[inline(always)]
pub fn is_b_0x3(&self) -> bool {
*self == APB3DIV_A::B_0X3
}
}
#[doc = "Write proxy for field `APB3DIV`"]
pub struct APB3DIV_W<'a> {
w: &'a mut W,
}
impl<'a> APB3DIV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: APB3DIV_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "hclk (default after reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(APB3DIV_A::B_0X0)
}
#[doc = "hclk / 2"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(APB3DIV_A::B_0X1)
}
#[doc = "hclk / 4"]
#[inline(always)]
pub fn b_0x2(self) -> &'a mut W {
self.variant(APB3DIV_A::B_0X2)
}
#[doc = "hclk / 8"]
#[inline(always)]
pub fn b_0x3(self) -> &'a mut W {
self.variant(APB3DIV_A::B_0X3)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "APB3DIVRDY\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum APB3DIVRDY_A {
#[doc = "0: The new division factor is not yet\r\n taken into account."]
B_0X0 = 0,
#[doc = "1: The new division factor is taken\r\n into account. (default after reset)"]
B_0X1 = 1,
}
impl From<APB3DIVRDY_A> for bool {
#[inline(always)]
fn from(variant: APB3DIVRDY_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `APB3DIVRDY`"]
pub type APB3DIVRDY_R = crate::R<bool, APB3DIVRDY_A>;
impl APB3DIVRDY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> APB3DIVRDY_A {
match self.bits {
false => APB3DIVRDY_A::B_0X0,
true => APB3DIVRDY_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == APB3DIVRDY_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == APB3DIVRDY_A::B_0X1
}
}
impl R {
#[doc = "Bits 0:2 - APB3DIV"]
#[inline(always)]
pub fn apb3div(&self) -> APB3DIV_R {
APB3DIV_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bit 31 - APB3DIVRDY"]
#[inline(always)]
pub fn apb3divrdy(&self) -> APB3DIVRDY_R {
APB3DIVRDY_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - APB3DIV"]
#[inline(always)]
pub fn apb3div(&mut self) -> APB3DIV_W {
APB3DIV_W { w: self }
}
}
|
use std::time::SystemTime;
use crate::{Money, Debt};
pub fn get_users() -> Vec<String> {
vec!["alice".into(),"bob".into(), "ben".into(), "mitchell".into()]
}
pub fn get_all_debts() -> Vec<Debt> {
vec![]
}
pub fn get_debts_involving(user: &str) -> Vec<Debt> {
vec![
Debt{ debtor: "asdf".into(), creditor: "asdf".into(), time: SystemTime::now(), amount: Money::from_dollars(1) },
Debt{ debtor: "asdf".into(), creditor: "asdf".into(), time: SystemTime::now(), amount: Money::from_dollars(1) },
Debt{ debtor: "asdf".into(), creditor: "asdf".into(), time: SystemTime::now(), amount: Money::from_dollars(1) },
Debt{ debtor: "asdf".into(), creditor: "asdf".into(), time: SystemTime::now(), amount: Money::from_dollars(1) }]
}
|
extern crate whitespace_text_steganography;
use std::fs;
pub fn hide(payload_path: &str, carrier_path: &str, output_path: &str) {
let result = whitespace_text_steganography::hide(payload_path, carrier_path);
fs::write(output_path, result).expect("Unable to write package file");
}
pub fn reveal(carrier_path: &str, output_path: &str) {
let result = whitespace_text_steganography::reveal(carrier_path);
// todo (sdv) this does not create the file if the directory does not exist
fs::write(output_path, result).expect("Unable to write hidden text file");
}
|
//! Structs and methods for working with `Hittable` spheres.
use crate::aabb::AABB;
use crate::hittable::{get_sphere_uv, HitRecord, Hittable};
use crate::material::Material;
use crate::onb::ONB;
use crate::pdf::random_to_sphere;
use crate::ray::Ray;
use crate::vec3;
use crate::vec3::Vec3;
use rand::prelude::*;
use std::sync::Arc;
/// A sphere. Can be hit with rays.
#[derive(Debug, Clone)]
pub struct Sphere {
pub center: Vec3,
pub radius: f32,
pub material: Arc<Material>,
}
impl Sphere {
/// Create a new sphere.
pub fn new(center: Vec3, radius: f32, material: Material) -> Sphere {
Sphere {
center,
radius,
material: Arc::new(material),
}
}
}
impl Hittable for Sphere {
fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
// See the raytracing in one weekend book, chapter 6, for this formula.
// We found a (modified) quadratic formula for hit-testing a sphere.
let oc = ray.origin - self.center;
let a = ray.direction.length_squared();
let half_b = oc.dot(&ray.direction);
let c = oc.length_squared() - (self.radius * self.radius);
let discriminant = (half_b * half_b) - (a * c);
// The sphere is hit if the discriminant is greater than 0.
if discriminant > 0.0 {
let root = discriminant.sqrt();
let solution_1 = (-half_b - root) / a;
let solution_2 = (-half_b + root) / a;
let t = if solution_1 < t_max && solution_1 > t_min {
Some(solution_1)
} else if solution_2 < t_max && solution_2 > t_min {
Some(solution_2)
} else {
None
};
if let Some(t) = t {
let hit_point = ray.at(t);
Some(HitRecord::new(
ray,
t,
hit_point,
(hit_point - self.center) / self.radius,
self.material.clone(),
get_sphere_uv((hit_point - self.center) / self.radius),
))
} else {
None
}
} else {
None
}
}
fn bounding_box(&self, _t0: f32, _t1: f32) -> Option<AABB> {
Some(AABB::new(
self.center - vec3!(self.radius, self.radius, self.radius),
self.center + vec3!(self.radius, self.radius, self.radius),
))
}
fn pdf_value(&self, origin: &Vec3, v: &Vec3) -> f32 {
if self
.hit(&Ray::new(*origin, *v, 0.0), 0.001, std::f32::MAX)
.is_some()
{
let cos_theta_max =
(1.0 - self.radius * self.radius / (self.center - *origin).length_squared()).sqrt();
let solid_angle = 2.0 * std::f32::consts::PI * (1.0 - cos_theta_max);
1.0 / solid_angle
} else {
0.0
}
}
fn random(&self, origin: &Vec3) -> Vec3 {
// Not ideal, but eh...
let mut rng = thread_rng();
let direction = self.center - *origin;
let distance_squared = direction.length_squared();
let uvw = ONB::build_from_w(direction);
uvw.local(&random_to_sphere(&mut rng, self.radius, distance_squared))
}
fn box_clone(&self) -> Box<dyn Hittable> {
Box::new(self.clone())
}
}
|
mod eddington;
mod polar_eddington;
pub trait Properties {
fn mass() -> f64;
fn ang_momentum() -> f64;
}
pub use self::eddington::EddingtonFinkelstein;
pub use self::polar_eddington::{NearPole0EF, NearPolePiEF};
|
use crate::{Result, SUDOERS_ALL_ALL_NOPASSWD, USERNAME};
use sudo_test::{Command, Env, TextFile};
#[test]
fn cwd_not_set_cannot_change_dir() -> Result<()> {
let env = Env(TextFile(SUDOERS_ALL_ALL_NOPASSWD)).build()?;
let output = Command::new("sudo")
.args(["--chdir", "/root", "pwd"])
.output(&env)?;
assert_eq!(Some(1), output.status().code());
assert!(!output.status().success());
let diagnostic = if sudo_test::is_original_sudo() {
"you are not permitted to use the -D option with /usr/bin/pwd"
} else {
"you are not allowed to use '--chdir /root' with '/usr/bin/pwd'"
};
assert_contains!(output.stderr(), diagnostic);
Ok(())
}
#[test]
fn cwd_set_to_glob_change_dir() -> Result<()> {
let env = Env(TextFile("ALL ALL=(ALL:ALL) CWD=* NOPASSWD: ALL")).build()?;
let output = Command::new("sh")
.args(["-c", "cd /; sudo --chdir /root pwd"])
.output(&env)?;
assert_eq!(Some(0), output.status().code());
assert!(output.status().success());
assert_contains!(output.stdout()?, "/root");
Ok(())
}
#[test]
fn cwd_fails_for_non_existent_dirs() -> Result<()> {
let env = Env(TextFile("ALL ALL=(ALL:ALL) CWD=* NOPASSWD: ALL")).build()?;
let output = Command::new("sudo")
.args([
"--chdir",
"/path/to/nowhere",
"sh",
"-c",
"echo >&2 'avocado'",
])
.output(&env)?;
assert_eq!(Some(1), output.status().code());
assert!(!output.status().success());
let stderr = output.stderr();
assert_contains!(
stderr,
"unable to change directory to /path/to/nowhere: No such file or directory"
);
assert_not_contains!(stderr, "avocado");
Ok(())
}
#[test]
fn cwd_with_login_fails_for_non_existent_dirs() -> Result<()> {
let env = Env(TextFile("ALL ALL=(ALL:ALL) CWD=* NOPASSWD: ALL"))
.user(USERNAME)
.build()?;
let output = Command::new("sudo")
.args([
"-u",
USERNAME,
"-i",
"--chdir",
"/path/to/nowhere",
"sh",
"-c",
"echo >&2 'avocado'",
])
.output(&env)?;
assert_eq!(Some(1), output.status().code());
assert!(!output.status().success());
let stderr = output.stderr();
assert_contains!(
stderr,
"unable to change directory to /path/to/nowhere: No such file or directory"
);
assert_not_contains!(stderr, "avocado");
Ok(())
}
#[test]
fn cwd_set_to_non_glob_value_then_cannot_use_chdir_flag() -> Result<()> {
let env = Env(TextFile("ALL ALL=(ALL:ALL) CWD=/root NOPASSWD: ALL")).build()?;
let output = Command::new("sh")
.args(["-c", "cd /; sudo --chdir /tmp pwd"])
.output(&env)?;
assert!(!output.status().success());
assert_eq!(Some(1), output.status().code());
let diagnostic = if sudo_test::is_original_sudo() {
"you are not permitted to use the -D option with /usr/bin/pwd"
} else {
"you are not allowed to use '--chdir /tmp' with '/usr/bin/pwd'"
};
assert_contains!(output.stderr(), diagnostic);
Ok(())
}
#[test]
fn cwd_set_to_non_glob_value_then_cannot_use_that_path_with_chdir_flag() -> Result<()> {
let path = "/root";
let env = Env(format!("ALL ALL=(ALL:ALL) CWD={path} NOPASSWD: ALL")).build()?;
let output = Command::new("sh")
.arg("-c")
.arg(format!("cd /; sudo --chdir {path} pwd"))
.output(&env)?;
assert!(!output.status().success());
assert_eq!(Some(1), output.status().code());
let diagnostic = if sudo_test::is_original_sudo() {
"you are not permitted to use the -D option with /usr/bin/pwd".to_owned()
} else {
format!("you are not allowed to use '--chdir {path}' with '/usr/bin/pwd'")
};
assert_contains!(output.stderr(), diagnostic);
Ok(())
}
#[test]
#[ignore = "wontfix"]
fn any_chdir_value_is_accepted_if_it_matches_pwd_cwd_unset() -> Result<()> {
let path = "/root";
let env = Env("ALL ALL=(ALL:ALL) NOPASSWD: ALL").build()?;
let stdout = Command::new("sh")
.arg("-c")
.arg(format!("cd {path}; sudo --chdir {path} pwd"))
.output(&env)?
.stdout()?;
assert_eq!(path, stdout);
Ok(())
}
// NOTE unclear if we want to adopt this behavior
#[test]
#[ignore = "wontfix"]
fn any_chdir_value_is_accepted_if_it_matches_pwd_cwd_set() -> Result<()> {
let cwd_path = "/root";
let another_path = "/tmp";
let env = Env(format!("ALL ALL=(ALL:ALL) CWD={cwd_path} NOPASSWD: ALL")).build()?;
let stdout = Command::new("sh")
.arg("-c")
.arg(format!(
"cd {another_path}; sudo --chdir {another_path} pwd"
))
.output(&env)?
.stdout()?;
assert_eq!(cwd_path, stdout);
Ok(())
}
#[test]
fn target_user_has_insufficient_perms() -> Result<()> {
let path = "/root";
let env = Env("ALL ALL=(ALL:ALL) CWD=* NOPASSWD: ALL")
.user(USERNAME)
.build()?;
let output = Command::new("sh")
.arg("-c")
.arg(format!("cd /; sudo -u {USERNAME} --chdir {path} pwd"))
.output(&env)?;
assert!(!output.status().success());
assert_eq!(Some(1), output.status().code());
let diagnostic = if sudo_test::is_original_sudo() {
"sudo: unable to change directory to /root: Permission denied"
} else {
"Permission denied"
};
assert_contains!(output.stderr(), diagnostic);
Ok(())
}
|
use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer};
#[derive(Debug, Clone)]
pub struct GitHubError {
pub details: String,
}
#[derive(Debug, Clone)]
pub struct PearsError {
pub details: String,
}
#[derive(Deserialize, Debug, Clone)]
pub struct ConfigRepo {
pub owner: String,
pub name: String,
}
#[derive(Deserialize, Debug, Clone)]
pub struct Config {
pub me: String,
pub token: String,
pub groups: Option<Vec<Group>>,
}
#[derive(Deserialize, Debug, Clone)]
pub struct Group {
pub name: String,
pub repos: Vec<ConfigRepo>,
}
#[derive(Deserialize, Debug)]
pub struct GraphqlResponse {
pub data: RepoResponse,
}
#[derive(Deserialize, Debug)]
pub struct RepoResponse {
pub repository: Repo,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Repo {
pub name: String,
#[serde(deserialize_with = "deserialize_pagination")]
pub pull_requests: Vec<PullRequest>,
}
#[derive(Deserialize, Debug)]
pub struct User {
pub login: String,
}
#[derive(Deserialize, Debug)]
pub struct Commit {
pub sha: String,
pub user: User,
pub repo: Repo,
}
#[derive(Deserialize, Debug)]
pub struct Label {
pub name: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PullRequest {
pub id: String,
pub state: String,
pub title: String,
pub body: Option<String>,
pub number: i32,
pub url: String,
pub mergeable: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub closed_at: Option<DateTime<Utc>>,
pub merged_at: Option<DateTime<Utc>>,
pub author: User,
#[serde(deserialize_with = "deserialize_pagination")]
pub labels: Vec<Label>,
#[serde(deserialize_with = "deserialize_pagination")]
pub comments: Vec<Comment>,
#[serde(deserialize_with = "deserialize_pagination")]
pub reviews: Vec<Review>,
}
impl PullRequest {
pub fn is_approved(&self) -> bool {
self.reviews.iter().any(|e| e.state == "APPROVED")
}
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Review {
pub author: User,
pub body_text: String,
pub state: String,
#[serde(deserialize_with = "deserialize_pagination")]
pub comments: Vec<Comment>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Comment {
pub author: User,
pub body_text: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
pub fn deserialize_pagination<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
#[derive(Deserialize, Debug)]
pub struct GraphqlPagination<T> {
pub edges: Vec<GraphqlPaginationNode<T>>,
}
#[derive(Deserialize, Debug)]
pub struct GraphqlPaginationNode<T> {
pub node: T,
}
GraphqlPagination::deserialize(deserializer)
.map(|p| p.edges.into_iter().map(|e| e.node).collect())
}
|
use std::collections::btree_set;
use std::borrow::Borrow;
/// A one-to-many index datastructure built around the standard library b-tree.
#[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
pub struct BTreeIndex<K, V> {
set: btree_set::BTreeSet<(K, V)>,
}
/// An iterator over the entries of a [`BTreeIndex`].
///
/// This `struct` is created by the [`iter'] method on [`BTreeIndex`]. See its
/// documentation for more.
///
/// [`iter`]: struct.BTreeIndex.html#method.iter
/// [`BTreeIndex`]: struct.BTreeIndex.html
pub struct Iter<'a, K: 'a, V: 'a> {
iter: btree_set::Iter<'a, (K, V)>,
}
/// An owning iterator over the entries of a [`BTreeIndex`].
///
/// [`BTreeIndex`]: struct.BTreeIndex.html
pub struct IntoIter<K, V> {
iter: btree_set::IntoIter<(K, V)>,
}
/// An iterator over the keys of a [`BTreeIndex`].
///
/// [`BTreeIndex`]: struct.BTreeIndex.html
pub struct Keys<'a, K: 'a, V: 'a> {
iter: btree_set::Iter<'a, (K, V)>,
}
/// An iterator over the values of a [`BTreeIndex`].
///
/// [`BTreeIndex`]: struct.BTreeIndex.html
pub struct Values<'a, K: 'a, V: 'a> {
iter: btree_set::Iter<'a, (K, V)>,
}
/// A view on the values for a particular key in a [`BTreeIndex`]a.
///
/// [`BTreeIndex`]: struct.BTreeIndex.html
pub struct ValueSet<'a, K: 'a, V: 'a> {
values: btree_set::Range<'a, (K, V)>,
}
impl<K: Ord, V: Ord> BTreeIndex<K, V> {
pub fn new() -> BTreeIndex<K, V> {
return BTreeIndex {
set: btree_set::BTreeSet::new(),
}
}
pub fn clear(&mut self) {
self.set.clear();
}
pub fn get<'a>(&'a self, key: K) -> ValueSet<'a, K, V> {
unimplemented!();
}
pub fn insert(&mut self, key: K, value: V) -> bool {
return self.set.insert((key, value));
}
pub fn remove<Q: ?Sized, R: ?Sized>(&mut self, key: K, value: V) -> bool
where K: Borrow<Q>, V: Borrow<R>, Q: Ord, R: Ord {
return self.set.remove(&(key, value));
}
pub fn iter(&self) -> Iter<K, V> {
return Iter {
iter: self.set.iter(),
};
}
pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
return Keys {
iter: self.set.iter(),
};
}
pub fn values<'a>(&'a self) -> Values<'a, K, V> {
return Values {
iter: self.set.iter(),
};
}
pub fn len(&self) -> usize {
return self.set.len();
}
pub fn is_empty(&self) -> bool {
return self.set.is_empty();
}
}
impl<K: Ord, V: Ord> Default for BTreeIndex<K, V> {
fn default() -> BTreeIndex<K, V> {
return BTreeIndex::new();
}
}
impl<K: Ord, V: Ord> Extend<(K, V)> for BTreeIndex<K, V> {
fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = (K, V)> {
self.set.extend(iter);
}
}
impl<'a, K, V> Extend<(&'a K, &'a V)> for BTreeIndex<K, V>
where K: Copy + Ord, V: Copy {
fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = (&'a K, &'a V)> {
unimplemented!();
}
}
impl<'a, K: 'a + Ord, V: 'a + Ord> IntoIterator for &'a BTreeIndex<K, V> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Iter<'a, K, V> {
return self.iter();
}
}
impl<K, V> IntoIterator for BTreeIndex<K, V> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> IntoIter<K, V> {
return IntoIter {
iter: self.set.into_iter(),
};
}
}
impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<(&'a K, &'a V)> {
unimplemented!();
}
fn size_hint(&self) -> (usize, Option<usize>) {
unimplemented!();
}
}
impl<K, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
unimplemented!();
}
fn size_hint(&self) -> (usize, Option<usize>) {
unimplemented!();
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
|
use yew::prelude::*;
use yewtil::future::LinkFuture;
mod state;
pub use state::SelectState;
mod selection;
pub use selection::Selection;
mod wrappers;
pub use wrappers::{SelectDisplay, SelectFilter};
/// Bulma-based selection box
/// TODO: document
pub struct Select<T: 'static> {
link: ComponentLink<Self>,
props: SelectProps<T>,
focused: bool,
selection_index: usize,
search_text: String,
}
#[derive(Properties)]
pub struct SelectProps<T> {
/// Omit selected items from the dropdown list (if false, selected will be
/// highlighted).
#[prop_or_default]
pub omit_selected: bool,
/// Control whether to show the selected items as tags in the input field
/// (if in multiple mode). Useful to turn off if you want to control display
/// of the selected items outside of the field.
///
/// This does nothing in single selection mode.
#[prop_or(true)]
pub display_selected: bool,
pub state: SelectState<T>,
pub display: SelectDisplay<T>,
#[prop_or_default]
pub onselected: Option<Callback<usize>>,
#[prop_or_default]
pub onremoved: Option<Callback<usize>>,
#[prop_or_else(|| String::from("Type to search"))]
pub placeholder: String,
#[prop_or_default]
pub readonly: bool,
#[prop_or_default]
pub disabled: bool,
#[prop_or_default]
pub loading: bool,
}
// This SHOULD be the auto impl, but for some reason that thinks that T needs to be Clone
impl<T> Clone for SelectProps<T> {
fn clone(&self) -> Self {
Self {
omit_selected: self.omit_selected,
display_selected: self.display_selected,
state: self.state.clone(),
display: self.display.clone(),
onselected: self.onselected.clone(),
onremoved: self.onremoved.clone(),
placeholder: self.placeholder.clone(),
readonly: self.readonly,
disabled: self.disabled,
loading: self.loading,
}
}
}
impl<T> PartialEq for SelectProps<T> {
fn eq(&self, other: &Self) -> bool {
self.readonly == other.readonly && self.disabled == other.disabled && self.loading == other.loading &&
self.state == other.state
// && Arc::ptr_eq(&self.filter, &other.filter) // TODO: don't ignore filter changes?
&& self.omit_selected == other.omit_selected
&& self.placeholder == other.placeholder
&& self.onselected == other.onselected
&& self.onremoved == other.onremoved
}
}
pub enum Msg {
Noop,
Input(String),
ClearSearch,
Filtered,
Selected(usize),
Removed(usize),
Hover(usize),
Focus,
Blur,
KeyPress(KeyboardEvent),
}
impl<T: 'static> Component for Select<T> {
type Properties = SelectProps<T>;
type Message = Msg;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
focused: false,
selection_index: 0,
search_text: String::new(),
props,
}
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props != props {
if props.disabled {
self.focused = false;
self.selection_index = 0;
self.search_text.clear();
}
self.props = props;
true
} else {
false
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Noop => false,
Msg::Filtered => true,
Msg::Input(input) => {
if self.props.disabled || self.props.readonly {
return false;
}
self.focused = true;
self.search_text = input.clone();
let state = self.props.state.clone();
self.link.send_future(async move {
if input.is_empty() {
state.unfilter().await;
} else {
state.filter(&input).await;
}
Msg::Filtered
});
true
}
Msg::ClearSearch => {
let options = self.props.state.clone();
self.link.send_future(async move {
options.unfilter().await;
Msg::Filtered
});
self.search_text.clear();
true
}
Msg::Selected(idx) => {
if let Some(ref onselected) = self.props.onselected {
onselected.emit(idx);
}
self.link
.send_message_batch(vec![Msg::ClearSearch, Msg::Blur]);
false
}
Msg::Removed(idx) => {
if let Some(ref onremoved) = self.props.onremoved {
onremoved.emit(idx);
}
false
}
Msg::Hover(idx) => {
self.selection_index = idx;
true
}
Msg::Focus => {
if self.props.disabled || self.props.readonly {
return false;
}
self.focused = true;
true
}
Msg::Blur => {
self.focused = false;
self.selection_index = 0;
self.search_text.clear();
true
}
Msg::KeyPress(event) => {
if self.props.disabled || self.props.readonly {
return false;
}
match event.code().as_ref() {
"Enter" => {
if let Some((index, _)) =
self.props.state.get_filtered(self.selection_index)
{
self.link.send_message(Msg::Selected(index));
}
false
}
"Escape" => {
self.focused = false;
self.selection_index = 0;
self.search_text.clear();
true
}
"ArrowUp" => {
self.focused = true;
let event: &Event = &event;
event.prevent_default();
self.selection_index = self.selection_index.saturating_sub(1);
true
}
"ArrowDown" => {
self.focused = true;
let event: &Event = &event;
event.prevent_default();
self.selection_index += 1;
true
}
_ => false,
}
}
}
}
fn view(&self) -> Html {
let options = if self.props.omit_selected {
self.props
.state
.filtered_items()
.into_iter()
.filter(|(_, selected, _)| !selected)
.collect::<Vec<_>>()
} else {
self.props.state.filtered_items()
};
let options = if options.is_empty() {
html! {
<div class="has-text-centered">
<p>
<span class="icon">
<i class="fas fa-inbox" />
</span>
</p>
<p>{"No Data"}</p>
</div>
}
} else {
options
.into_iter()
.enumerate()
.map(|(i, (idx, selected, item))| {
html! {
<a
class=classes!(
"dropdown-item",
if self.selection_index == i {"is-active"}
else if selected {"has-background-primary-light"}
else {""}
)
>
<p
onmouseenter=self.link.callback(move |_| Msg::Hover(i))
onmousedown=self.link.callback(move |event: MouseEvent| {
let event: &Event = &event;
event.prevent_default();
Msg::Selected(idx)
})
>
{ self.props.display.call(&item) }
</p>
</a>
}
})
.collect::<Html>()
};
html! {
<div class=classes!("dropdown", if self.focused {"is-active"} else {""})>
<div class="dropdown-trigger">
{
if self.props.state.is_multiple() {
self.view_multiple()
} else {
self.view_single()
}
}
</div>
<div class="dropdown-menu">
<div class="dropdown-content">
{ options }
</div>
</div>
</div>
}
}
}
impl<T> Select<T> {
fn view_single(&self) -> Html {
if self.focused {
html! {
<div class="control has-icons-right">
<input
class=classes!("input", if self.props.loading {"is-loading"} else {""})
type="text"
value=&self.search_text
placeholder=self.props.state.selected_items().first().map(|(_, x)| self.props.display.call(x)).unwrap_or_else(|| self.props.placeholder.clone())
oninput=self.link.callback(|event: InputData| Msg::Input(event.value))
onfocus=self.link.callback(|_| Msg::Focus)
onblur=self.link.callback(|_| Msg::Blur)
onkeydown=self.link.callback(Msg::KeyPress)
disabled=self.props.disabled
readonly=self.props.readonly
/>
<span class="icon is-small is-right">
{
if self.search_text.is_empty() {
html! { <i class="fas fa-search" /> }
} else {
html! {<button class="delete" onclick=self.link.callback(|_| Msg::ClearSearch) /> }
}
}
</span>
</div>
}
} else {
html! {
<div class="control has-icons-right">
<input
class=classes!("input", if self.props.loading {"is-loading"} else {""})
type="text"
value=self.props.state.selected_items().first().map(|(_, x)| self.props.display.call(x)).unwrap_or_default()
oninput=self.link.callback(|data: InputData| {
// Don't allow input when not focused
let event: &Event = &data.event;
event.prevent_default();
Msg::Focus
})
onfocus=self.link.callback(|_| Msg::Focus)
onblur=self.link.callback(|_| Msg::Blur)
onclick=self.link.callback(|_| Msg::Focus)
onkeydown=self.link.callback(Msg::KeyPress)
disabled=self.props.disabled
readonly=self.props.readonly
/>
<span class="icon is-small is-right">
<i class="fas fa-angle-down" />
</span>
</div>
}
}
}
fn view_multiple(&self) -> Html {
html! {
<div class=classes!("input", "ybss-multiple-input-wrapper", if self.focused {"is-active"} else {""})>
{
if self.props.display_selected {
self.props.state.selected_items().into_iter().map(|(i, item)| html! {
<span class="tag">
{ self.props.display.call(&item) }
<div class="delete is-small" onclick=self.link.callback(move |_| Msg::Removed(i)) />
</span>
}).collect::<Html>()
} else {
html! {}
}
}
<input
class=classes!("input", if self.props.loading {"is-loading"} else {""})
type="text"
placeholder="Type to search"
value=&self.search_text
oninput=self.link.callback(|event: InputData| Msg::Input(event.value))
onfocus=self.link.callback(|_| Msg::Focus)
onblur=self.link.callback(|_| Msg::Blur)
onkeydown=self.link.callback(Msg::KeyPress)
disabled=self.props.disabled
readonly=self.props.readonly
/>
</div>
}
}
}
|
#[doc = "Reader of register PENDING0"]
pub type R = crate::R<u32, super::PENDING0>;
#[doc = "Reader of field `SOURCE`"]
pub type SOURCE_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - This field specifies the following sources: Bit 0: CM0 MPU. Bit 1: CRYPTO MPU. Bit 2: DW 0 MPU. Bit 3: DW 1 MPU. ... Bit 14: CM4 code bus MPU. Bit 15: DAP MPU. Bit 16: CM4 s+G92ystem bus MPU. Bit 28: Peripheral master interface 0 PPU. Bit 29: Peripheral master interface 1 PPU. Bit 30: Peripheral master interface 2 PPU. Bit 31: Peripheral master interface 3 PPU."]
#[inline(always)]
pub fn source(&self) -> SOURCE_R {
SOURCE_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
// #![deny(warnings)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate prometheus;
extern crate pretty_env_logger;
#[macro_use]
extern crate log;
use broadcast::{Receiver, Sender};
use futures::{Stream, StreamExt};
use jsonwebtoken::{dangerous_insecure_decode_with_validation, Algorithm, Validation};
use prometheus::{Gauge, Registry};
use std::env;
use std::result::Result;
use std::time::Duration;
use tokio::sync::broadcast;
use warp::{sse::ServerSentEvent, Filter};
use warp::{Rejection, Reply};
use prom_docker_limit_exporter::docker::{Claims, DockerHub, Token};
lazy_static! {
static ref DOCKER_GAUGE_REMAINING: Gauge = register_gauge!(opts!(
"dockerhub_limit_remaining_requests_total",
"Docker Hub Rate Limit Remaining Requests",
labels! {"docker" => "remaining"}
))
.unwrap();
static ref DOCKER_GAUGE_LIMIT: Gauge = register_gauge!(opts!(
"dockerhub_limit_requests_total",
"Docker Hub Rate Limit Requests",
labels! {"docker" => "limit"}
))
.unwrap();
pub static ref REGISTRY: Registry = Registry::new();
}
#[tokio::main]
async fn main() {
env::set_var("RUST_LOG", "info");
pretty_env_logger::init();
register_custom_metrics();
let metrics_route = warp::path!("metrics").and_then(metrics_handler);
let (tx, mut rx) = broadcast::channel(15);
let tx1 = tx.clone();
let username = env::var("DOCKERHUB_USERNAME").unwrap_or_default();
let password = env::var("DOCKERHUB_PASSWORD").unwrap_or_default();
let docker_client = DockerHub::new(username, password);
tokio::spawn(metrics_collector(docker_client.clone(), tx));
tokio::spawn(async move {
loop {
let received = rx.recv().await;
match received {
Ok((limit, remain)) => {
info!("{}, {}", limit, remain);
set_metrics(limit, remain);
}
Err(e) => {
error!("Error: {:?}", e);
std::process::exit(1);
}
}
}
});
// TODO: Expose API for limit information. It's incomplete now.
let tick_route = warp::path("ticks").and(warp::get()).map(move || {
let rx1 = tx1.subscribe();
let event_stream = metrics_stream(rx1);
warp::sse::reply(warp::sse::keep_alive().stream(event_stream))
});
let routes = metrics_route.or(tick_route);
warp::serve(routes).run(([0, 0, 0, 0], 8080)).await;
}
// TODO: Expose API for limit information. It's incomplete now.
fn metrics_stream(
rx: Receiver<(f64, f64)>,
) -> impl Stream<Item = Result<impl ServerSentEvent + Send + 'static, warp::Error>> + Send + 'static
{
rx.map(|s| match s {
Ok((c, _)) => Ok(warp::sse::data(c)),
Err(e) => {
error!("Error in receiving: {}", e);
std::process::exit(1);
}
})
}
fn register_custom_metrics() {
REGISTRY
.register(Box::new(DOCKER_GAUGE_REMAINING.clone()))
.expect("collector can be registered");
REGISTRY
.register(Box::new(DOCKER_GAUGE_LIMIT.clone()))
.expect("collector can be registered");
}
async fn metrics_handler() -> Result<impl Reply, Rejection> {
use prometheus::Encoder;
let encoder = prometheus::TextEncoder::new();
let mut buffer = Vec::new();
if let Err(e) = encoder.encode(®ISTRY.gather(), &mut buffer) {
eprintln!("could not encode custom metrics: {}", e);
};
let res = match String::from_utf8(buffer.clone()) {
Ok(v) => v,
Err(e) => {
eprintln!("custom metrics could not be from_utf8'd: {}", e);
String::default()
}
};
buffer.clear();
Ok(res)
}
async fn metrics_collector(docker_client: DockerHub, tx: Sender<(f64, f64)>) {
let mut collect_interval = tokio::time::interval(Duration::from_secs(10));
let mut token = extract_token(&docker_client).await;
loop {
collect_interval.tick().await;
if is_valid_token(&token) {
let (limit, remain) = extract_limit_remain(&token, &docker_client).await;
if let Some((l, r)) = cleanup_metrics(limit, remain) {
tx.send((l, r)).unwrap();
}
} else {
error!("Invalid Token, Renewing");
token = extract_token(&docker_client).await;
continue;
}
}
}
fn cleanup_metrics(limit: String, remain: String) -> Option<(f64, f64)> {
if limit.is_empty() && remain.is_empty() {
warn!("Limit and Remain is Empty.");
return None;
}
let limit_split: Vec<&str> = limit.as_str().split(';').collect();
let remain_split: Vec<&str> = remain.as_str().split(';').collect();
if !limit_split.is_empty() && !remain_split.is_empty() {
let final_limit = limit_split[0].to_string().parse().unwrap();
let final_remain = remain_split[0].to_string().parse().unwrap();
Some((final_limit, final_remain))
} else {
warn!("Limit Vector and Remain Vector is Empty");
None
}
}
fn set_metrics(limit: f64, remain: f64) {
DOCKER_GAUGE_LIMIT.set(limit);
DOCKER_GAUGE_REMAINING.set(remain);
}
async fn extract_token(dc: &DockerHub) -> Token {
let token = match dc.get_token().await {
Ok(t) => t,
Err(e) => {
if let Some(err) = e.downcast_ref::<reqwest::Error>() {
error!("Request Error: {}", err);
std::process::exit(1);
}
if let Some(err) = e.downcast_ref::<config::ConfigError>() {
error!("Config Error: {}", err);
std::process::exit(1);
}
error!("Unknown Error: {}", e);
std::process::exit(1);
}
};
token
}
async fn extract_limit_remain(token: &Token, dc: &DockerHub) -> (String, String) {
let limit_remain = match dc.get_docker_limits(token.clone()).await {
Ok(lr) => lr,
Err(e) => {
if let Some(err) = e.downcast_ref::<reqwest::Error>() {
error!("Request Error: {}", err);
std::process::exit(1);
}
if let Some(err) = e.downcast_ref::<config::ConfigError>() {
error!("Config Error: {}", err);
std::process::exit(1);
}
error!("Unknown Error: {}", e);
std::process::exit(1);
}
};
limit_remain
}
fn is_valid_token(token: &Token) -> bool {
let token_validate = dangerous_insecure_decode_with_validation::<Claims>(
&token.token,
&Validation::new(Algorithm::RS256),
);
if let Err(e) = token_validate {
match e.kind() {
jsonwebtoken::errors::ErrorKind::ExpiredSignature => return false,
_ => {
error!("Unknown Error: {:?}", e);
std::process::exit(1);
}
}
}
true
}
|
use super::schema::migration_statistics;
#[derive(Insertable)]
#[table_name = "migration_statistics"]
pub struct MigrationStatistics<'a> {
pub id: Option<i64>,
pub unused_count: i64,
pub migrated_from_id: i64,
pub migrated_to_id: i64,
pub migration_step: &'a str,
}
|
#[doc = "Reader of register RTC_CFGR"]
pub type R = crate::R<u32, super::RTC_CFGR>;
#[doc = "Writer for register RTC_CFGR"]
pub type W = crate::W<u32, super::RTC_CFGR>;
#[doc = "Register RTC_CFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::RTC_CFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `OUT2_RMP`"]
pub type OUT2_RMP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OUT2_RMP`"]
pub struct OUT2_RMP_W<'a> {
w: &'a mut W,
}
impl<'a> OUT2_RMP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `LSCOEN`"]
pub type LSCOEN_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `LSCOEN`"]
pub struct LSCOEN_W<'a> {
w: &'a mut W,
}
impl<'a> LSCOEN_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 1)) | (((value as u32) & 0x03) << 1);
self.w
}
}
impl R {
#[doc = "Bit 0 - OUT2_RMP"]
#[inline(always)]
pub fn out2_rmp(&self) -> OUT2_RMP_R {
OUT2_RMP_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 1:2 - LSCOEN"]
#[inline(always)]
pub fn lscoen(&self) -> LSCOEN_R {
LSCOEN_R::new(((self.bits >> 1) & 0x03) as u8)
}
}
impl W {
#[doc = "Bit 0 - OUT2_RMP"]
#[inline(always)]
pub fn out2_rmp(&mut self) -> OUT2_RMP_W {
OUT2_RMP_W { w: self }
}
#[doc = "Bits 1:2 - LSCOEN"]
#[inline(always)]
pub fn lscoen(&mut self) -> LSCOEN_W {
LSCOEN_W { w: self }
}
}
|
//! Board file for STM32F407G-DISC1 development board
//!
//! - <https://www.st.com/en/evaluation-tools/stm32f4discovery.html>
#![no_std]
// Disable this attribute when documenting, as a workaround for
// https://github.com/rust-lang/rust/issues/62184.
#![cfg_attr(not(doc), no_main)]
#![feature(const_in_array_repeat_expressions)]
#![deny(missing_docs)]
use capsules::virtual_alarm::VirtualMuxAlarm;
use kernel::capabilities;
use kernel::common::dynamic_deferred_call::{DynamicDeferredCall, DynamicDeferredCallClientState};
use kernel::component::Component;
use kernel::hil::gpio::Configure;
use kernel::hil::gpio::Output;
use kernel::Platform;
use kernel::{create_capability, debug, static_init};
/// Support routines for debugging I/O.
pub mod io;
// Unit Tests for drivers.
#[allow(dead_code)]
mod virtual_uart_rx_test;
// Number of concurrent processes this platform supports.
const NUM_PROCS: usize = 4;
// Actual memory for holding the active process structures.
static mut PROCESSES: [Option<&'static dyn kernel::procs::ProcessType>; NUM_PROCS] =
[None, None, None, None];
// Static reference to chip for panic dumps.
static mut CHIP: Option<&'static stm32f407vg::chip::Stm32f407> = None;
// How should the kernel respond when a process faults.
const FAULT_RESPONSE: kernel::procs::FaultResponse = kernel::procs::FaultResponse::Panic;
/// Dummy buffer that causes the linker to reserve enough space for the stack.
#[no_mangle]
#[link_section = ".stack_buffer"]
pub static mut STACK_MEMORY: [u8; 0x1000] = [0; 0x1000];
/// A structure representing this platform that holds references to all
/// capsules for this platform.
struct STM32F407GDISC1 {
console: &'static capsules::console::Console<'static>,
ipc: kernel::ipc::IPC,
led: &'static capsules::led::LED<'static, stm32f407vg::gpio::Pin<'static>>,
button: &'static capsules::button::Button<'static, stm32f407vg::gpio::Pin<'static>>,
ninedof: &'static capsules::ninedof::NineDof<'static>,
lis3dsh: &'static my_capsules::lis3dsh::Lis3dshSpi<'static>,
temp: &'static capsules::temperature::TemperatureSensor<'static>,
alarm: &'static capsules::alarm::AlarmDriver<
'static,
VirtualMuxAlarm<'static, stm32f407vg::tim2::Tim2<'static>>,
>,
}
/// Mapping of integer syscalls to objects that implement syscalls.
impl Platform for STM32F407GDISC1 {
fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
where
F: FnOnce(Option<&dyn kernel::Driver>) -> R,
{
match driver_num {
capsules::console::DRIVER_NUM => f(Some(self.console)),
capsules::led::DRIVER_NUM => f(Some(self.led)),
capsules::button::DRIVER_NUM => f(Some(self.button)),
capsules::alarm::DRIVER_NUM => f(Some(self.alarm)),
my_capsules::lis3dsh::DRIVER_NUM => f(Some(self.lis3dsh)),
capsules::ninedof::DRIVER_NUM => f(Some(self.ninedof)),
capsules::temperature::DRIVER_NUM => f(Some(self.temp)),
kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
_ => f(None),
}
}
}
/// Helper function called during bring-up that configures DMA.
unsafe fn setup_dma() {
use stm32f407vg::dma1::{Dma1Peripheral, DMA1};
use stm32f407vg::usart;
use stm32f407vg::usart::USART2;
// setup dma for USART2
DMA1.enable_clock();
let usart2_tx_stream = Dma1Peripheral::USART2_TX.get_stream();
let usart2_rx_stream = Dma1Peripheral::USART2_RX.get_stream();
USART2.set_dma(
usart::TxDMA(usart2_tx_stream),
usart::RxDMA(usart2_rx_stream),
);
usart2_tx_stream.set_client(&USART2);
usart2_rx_stream.set_client(&USART2);
usart2_tx_stream.setup(Dma1Peripheral::USART2_TX);
usart2_rx_stream.setup(Dma1Peripheral::USART2_RX);
cortexm4::nvic::Nvic::new(Dma1Peripheral::USART2_TX.get_stream_irqn()).enable();
cortexm4::nvic::Nvic::new(Dma1Peripheral::USART2_RX.get_stream_irqn()).enable();
}
/// Helper function called during bring-up that configures multiplexed I/O.
unsafe fn set_pin_primary_functions() {
use stm32f407vg::exti::{LineId, EXTI};
use stm32f407vg::gpio::{AlternateFunction, Mode, PinId, PortId, PORT};
use stm32f407vg::syscfg::SYSCFG;
SYSCFG.enable_clock();
PORT[PortId::A as usize].enable_clock();
PORT[PortId::D as usize].enable_clock();
PORT[PortId::E as usize].enable_clock();
// User LD5 (RED) is connected to PD14. Configure PD14 as `debug_gpio!(0, ...)`
PinId::PD14.get_pin().as_ref().map(|pin| {
pin.make_output();
// Configure kernel debug gpios as early as possible
kernel::debug::assign_gpios(Some(pin), None, None);
});
// pd05 and pd06 (USART2): STM32F407G_Disc1 has ST-LINK VCP but not connect pin
// so requires a serial_usb convert equipment
PinId::PD05.get_pin().as_ref().map(|pin| {
pin.set_mode(Mode::AlternateFunctionMode);
// AF7 is USART2_TX
pin.set_alternate_function(AlternateFunction::AF7);
});
PinId::PD06.get_pin().as_ref().map(|pin| {
pin.set_mode(Mode::AlternateFunctionMode);
// AF7 is USART2_RX
pin.set_alternate_function(AlternateFunction::AF7);
});
// user button is connected on pa0
PinId::PA00.get_pin().as_ref().map(|pin| {
// By default, upon reset, the pin is in input mode, with no internal
// pull-up, no internal pull-down (i.e., floating).
//
// Only set the mapping between EXTI line and the Pin and let capsule do
// the rest.
EXTI.associate_line_gpiopin(LineId::Exti0, pin);
});
cortexm4::nvic::Nvic::new(stm32f407vg::nvic::EXTI0).enable();
// SPI1 has the lis3dsh sensor connected
// PA05: SPI1 SCK
PinId::PA05.get_pin().as_ref().map(|pin| {
pin.make_output();
pin.set_floating_state(kernel::hil::gpio::FloatingState::PullNone);
pin.set_mode(Mode::AlternateFunctionMode);
// AF5 is SPI1/SPI2
pin.set_alternate_function(AlternateFunction::AF5);
});
// PA06: SPI1 MISO
PinId::PA06.get_pin().as_ref().map(|pin| {
pin.set_mode(Mode::AlternateFunctionMode);
pin.set_floating_state(kernel::hil::gpio::FloatingState::PullNone);
// AF5 is SPI1/SPI2
pin.set_alternate_function(AlternateFunction::AF5);
});
// PA07: SPI1 MOSI
PinId::PA07.get_pin().as_ref().map(|pin| {
pin.make_output();
pin.set_floating_state(kernel::hil::gpio::FloatingState::PullNone);
pin.set_mode(Mode::AlternateFunctionMode);
// AF5 is SPI1/SPI2
pin.set_alternate_function(AlternateFunction::AF5);
});
// PE03: SPI1 CS
PinId::PE03.get_pin().as_ref().map(|pin| {
pin.make_output();
pin.set_floating_state(kernel::hil::gpio::FloatingState::PullNone);
pin.set();
});
stm32f407vg::spi::SPI1.enable_clock();
}
/// Helper function for miscellaneous peripheral functions
unsafe fn setup_peripherals() {
use stm32f407vg::tim2::TIM2;
// USART2 IRQn is 38
cortexm4::nvic::Nvic::new(stm32f407vg::nvic::USART2).enable();
// TIM2 IRQn is 28
TIM2.enable_clock();
TIM2.start();
cortexm4::nvic::Nvic::new(stm32f407vg::nvic::TIM2).enable();
}
/// Reset Handler.
///
/// This symbol is loaded into vector table by the STM32F446RE chip crate.
/// When the chip first powers on or later does a hard reset, after the core
/// initializes all the hardware, the address of this function is loaded and
/// execution begins here.
#[no_mangle]
pub unsafe fn reset_handler() {
stm32f407vg::init();
// We use the default HSI 16Mhz clock
set_pin_primary_functions();
setup_dma();
setup_peripherals();
let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&PROCESSES));
let dynamic_deferred_call_clients =
static_init!([DynamicDeferredCallClientState; 2], Default::default());
let dynamic_deferred_caller = static_init!(
DynamicDeferredCall,
DynamicDeferredCall::new(dynamic_deferred_call_clients)
);
DynamicDeferredCall::set_global_instance(dynamic_deferred_caller);
let chip = static_init!(
stm32f407vg::chip::Stm32f407,
stm32f407vg::chip::Stm32f407::new()
);
CHIP = Some(chip);
// UART
// Create a shared UART channel for kernel debug.
stm32f407vg::usart::USART2.enable_clock();
let uart_mux = components::console::UartMuxComponent::new(
&stm32f407vg::usart::USART2,
115200,
dynamic_deferred_caller,
)
.finalize(());
// `finalize()` configures the underlying USART, so we need to
// tell `send_byte()` not to configure the USART again.
io::WRITER.set_initialized();
// Create capabilities that the board needs to call certain protected kernel
// functions.
let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
let process_management_capability =
create_capability!(capabilities::ProcessManagementCapability);
// Setup the console.
let console = components::console::ConsoleComponent::new(board_kernel, uart_mux).finalize(());
// Create the debugger object that handles calls to `debug!()`.
components::debug_writer::DebugWriterComponent::new(uart_mux).finalize(());
// // Setup the process inspection console
// let process_console_uart = static_init!(UartDevice, UartDevice::new(mux_uart, true));
// process_console_uart.setup();
// pub struct ProcessConsoleCapability;
// unsafe impl capabilities::ProcessManagementCapability for ProcessConsoleCapability {}
// let process_console = static_init!(
// capsules::process_console::ProcessConsole<'static, ProcessConsoleCapability>,
// capsules::process_console::ProcessConsole::new(
// process_console_uart,
// &mut capsules::process_console::WRITE_BUF,
// &mut capsules::process_console::READ_BUF,
// &mut capsules::process_console::COMMAND_BUF,
// board_kernel,
// ProcessConsoleCapability,
// )
// );
// hil::uart::Transmit::set_transmit_client(process_console_uart, process_console);
// hil::uart::Receive::set_receive_client(process_console_uart, process_console);
// process_console.start();
// LEDs
// Clock to Port D is enabled in `set_pin_primary_functions()`
let led = components::led::LedsComponent::new(components::led_component_helper!(
stm32f407vg::gpio::Pin,
(
stm32f407vg::gpio::PinId::PD12.get_pin().as_ref().unwrap(),
kernel::hil::gpio::ActivationMode::ActiveHigh
),
(
stm32f407vg::gpio::PinId::PD13.get_pin().as_ref().unwrap(),
kernel::hil::gpio::ActivationMode::ActiveHigh
),
(
stm32f407vg::gpio::PinId::PD14.get_pin().as_ref().unwrap(),
kernel::hil::gpio::ActivationMode::ActiveHigh
),
(
stm32f407vg::gpio::PinId::PD15.get_pin().as_ref().unwrap(),
kernel::hil::gpio::ActivationMode::ActiveHigh
)
))
.finalize(components::led_component_buf!(stm32f407vg::gpio::Pin));
// BUTTONs
let button = components::button::ButtonComponent::new(
board_kernel,
components::button_component_helper!(
stm32f407vg::gpio::Pin,
(
stm32f407vg::gpio::PinId::PA00.get_pin().as_ref().unwrap(),
kernel::hil::gpio::ActivationMode::ActiveLow,
kernel::hil::gpio::FloatingState::PullNone
)
),
)
.finalize(components::button_component_buf!(stm32f407vg::gpio::Pin));
// ALARM
let tim2 = &stm32f407vg::tim2::TIM2;
let mux_alarm = components::alarm::AlarmMuxComponent::new(tim2).finalize(
components::alarm_mux_component_helper!(stm32f407vg::tim2::Tim2),
);
let alarm = components::alarm::AlarmDriverComponent::new(board_kernel, mux_alarm)
.finalize(components::alarm_component_helper!(stm32f407vg::tim2::Tim2));
// LIS3DSH sensor
let mux_spi = components::spi::SpiMuxComponent::new(&stm32f407vg::spi::SPI1)
.finalize(components::spi_mux_component_helper!(stm32f407vg::spi::Spi));
let lis3dsh = my_components::lis3dsh::Lis3dshSpiComponent::new()
.finalize(my_components::lis3dsh_spi_component_helper!(
// spi type
stm32f407vg::spi::Spi,
// chip select
stm32f407vg::gpio::PinId::PE03,
// spi mux
mux_spi
),
);
lis3dsh.configure(
my_capsules::lis3dsh::Lis3dshDataRate::DataRate100Hz,
my_capsules::lis3dsh::Lis3dshScale::Scale2G,
my_capsules::lis3dsh::Lis3dshFilter::Filter800Hz,
);
let grant_cap = create_capability!(capabilities::MemoryAllocationCapability);
let grant_temperature = board_kernel.create_grant(&grant_cap);
let temp = static_init!(
capsules::temperature::TemperatureSensor<'static>,
capsules::temperature::TemperatureSensor::new(lis3dsh, grant_temperature)
);
kernel::hil::sensors::TemperatureDriver::set_client(lis3dsh, temp);
let ninedof = components::ninedof::NineDofComponent::new(board_kernel)
.finalize(components::ninedof_component_helper!(lis3dsh));
let stm32f407g_disc1 = STM32F407GDISC1 {
console: console,
ipc: kernel::ipc::IPC::new(board_kernel, &memory_allocation_capability),
led: led,
button: button,
ninedof: ninedof,
lis3dsh: lis3dsh,
temp: temp,
alarm: alarm,
};
// // Optional kernel tests
// //
// // See comment in `boards/imix/src/main.rs`
// virtual_uart_rx_test::run_virtual_uart_receive(mux_uart);
debug!("Initialization complete. Entering main loop");
/// These symbols are defined in the linker script.
extern "C" {
/// Beginning of the ROM region containing app images.
static _sapps: u8;
/// End of the ROM region containing app images.
static _eapps: u8;
/// Beginning of the RAM region for app memory.
static mut _sappmem: u8;
/// End of the RAM region for app memory.
static _eappmem: u8;
}
kernel::procs::load_processes(
board_kernel,
chip,
core::slice::from_raw_parts(
&_sapps as *const u8,
&_eapps as *const u8 as usize - &_sapps as *const u8 as usize,
),
core::slice::from_raw_parts_mut(
&mut _sappmem as *mut u8,
&_eappmem as *const u8 as usize - &_sappmem as *const u8 as usize,
),
&mut PROCESSES,
FAULT_RESPONSE,
&process_management_capability,
)
.unwrap_or_else(|err| {
debug!("Error loading processes!");
debug!("{:?}", err);
});
let scheduler = components::sched::round_robin::RoundRobinComponent::new(&PROCESSES)
.finalize(components::rr_component_helper!(NUM_PROCS));
board_kernel.kernel_loop(
&stm32f407g_disc1,
chip,
Some(&stm32f407g_disc1.ipc),
scheduler,
&main_loop_capability,
);
}
|
mod block;
mod r#break;
mod class;
mod r#continue;
mod debugger;
mod empty;
mod expr;
mod r#for;
mod func;
mod if_stmt;
mod labelled;
mod r#return;
mod switch;
mod throw;
mod r#try;
mod var_decl;
mod r#while;
mod with;
|
mod handler;
mod healthz;
mod metrics;
mod statusz;
pub use {handler::handler as handler};
pub use {healthz::handler as healthz};
pub use {metrics::handler as metrics};
pub use {statusz::handler as statusz};
|
use bls12_381::Scalar;
mod vm;
mod vm_load;
use vm_load::load_zkvm;
fn main() {
let mut vm = load_zkvm();
vm.setup();
let params = vec![
(
0,
Scalar::from_raw([
0xb981_9dc8_2d90_607e,
0xa361_ee3f_d48f_df77,
0x52a3_5a8c_1908_dd87,
0x15a3_6d1f_0f39_0d88,
]),
),
(
1,
Scalar::from_raw([
0x7b0d_c53c_4ebf_1891,
0x1f3a_beeb_98fa_d3e8,
0xf789_1142_c001_d925,
0x015d_8c7f_5b43_fe33,
]),
),
(
2,
Scalar::from_raw([
0xb981_9dc8_2d90_607e,
0xa361_ee3f_d48f_df77,
0x52a3_5a8c_1908_dd87,
0x15a3_6d1f_0f39_0d88,
]),
),
(
3,
Scalar::from_raw([
0x7b0d_c53c_4ebf_1891,
0x1f3a_beeb_98fa_d3e8,
0xf789_1142_c001_d925,
0x015d_8c7f_5b43_fe33,
]),
),
];
vm.initialize(¶ms);
let proof = vm.prove();
let public = vm.public();
assert_eq!(public.len(), 2);
// 0x66ced46f14e5616d12b993f60a6e66558d6b6afe4c321ed212e0b9cfbd81061a
// 0x4731570fdd57cf280eadc8946fa00df81112502e44e497e794ab9a221f1bcca
println!("u = {:?}", public[0]);
println!("v = {:?}", public[1]);
assert!(vm.verify(&proof, &public));
}
|
use std::collections::HashMap;
use std::convert::TryFrom;
use std::hash::Hash;
use std::ops::{Deref, DerefMut};
use crate::{Element, Value};
use crate::into::value::ValueType;
/// Maps to `HashMap<Value, Element>` where value is homogeneous
#[derive(Debug)]
pub struct Map<K: ValueType + Hash + Eq>(pub HashMap<K, Element>);
impl<K: ValueType + Hash + Eq> From<Map<K>> for Element {
fn from(m: Map<K>) -> Self {
Element::Map(K::IDENT, m.0.into_iter().map(|(k, v)| (k.into(), v)).collect())
}
}
impl<K: ValueType + Hash + Eq> Deref for Map<K> {
type Target = HashMap<K, Element>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<K: ValueType + Hash + Eq> DerefMut for Map<K> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T: ValueType + Hash + Eq> Map<T> {
/// Create a new empty map.
pub fn new() -> Self { Self(HashMap::new()) }
}
impl<T: ValueType + Hash + Eq> From<HashMap<T, Element>> for Map<T> {
fn from(v: HashMap<T, Element>) -> Self {
Self(v)
}
}
impl<K: ValueType + Hash + Eq + TryFrom<Value>> TryFrom<Element> for Map<K> {
type Error = ();
fn try_from(value: Element) -> Result<Self, Self::Error> {
if let Element::Map(ident, map) = value {
if K::IDENT == ident {
Ok(Map(map.into_iter()
.filter_map(|(k, v)|
Some((K::try_from(k).ok()?, v)))
.collect()))
} else {
Err(())
}
} else {
Err(())
}
}
}
/*
#[cfg(feature="serde")]
use serde::{Serialize, Serializer};
#[cfg(feature="serde")]
use serde::ser::SerializeStruct;
#[cfg(feature="serde")]
use serde::ser::SerializeSeq;
use serde::ser::SerializeMap;
#[cfg(all(feature="serde", feature="serde_types"))]
impl<K: ValueType + Hash + Eq + TryFrom<Value> + Serialize> Serialize for Map<K> {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer {
let mut stu = serializer.serialize_struct("___tycho___/map", 2)?;
stu.serialize_field("ident", &K::IDENT.to_internal_prefix())?;
stu.serialize_field("inner", &self.0)?;
stu.end()
}
}
#[cfg(all(feature="serde", not(feature="serde_types")))]
impl<K: ValueType + Hash + Eq + TryFrom<Value> + Serialize> Serialize for Map<K> {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where
S: Serializer {
let mut seq = serializer.serialize_map(Some(self.0.len()))?;
for (k, v) in self.0 {
seq.serialize_entry(k ,&v)?;
}
seq.end()
}
}
*/ |
/*!
```rudra-poc
[target]
crate = "aovec"
version = "1.1.0"
[report]
issue_date = 2020-12-10
rustsec_url = "https://github.com/RustSec/advisory-db/pull/528"
rustsec_id = "RUSTSEC-2020-0099"
[[bugs]]
analyzer = "SendSyncVariance"
bug_class = "SendSyncVariance"
bug_count = 2
rudra_report_locations = ["src/lib.rs:17:1: 17:36", "src/lib.rs:16:1: 16:36"]
```
!*/
#![forbid(unsafe_code)]
use aovec::Aovec;
use std::rc::Rc;
fn main() {
let vec = Aovec::new(1);
let rc = Rc::new(42);
vec.push(rc.clone());
std::thread::spawn(move || {
println!("Thread: {:p}", vec[0]);
for _ in 0..100_000_000 {
vec[0].clone();
}
});
println!("Main: {:p}", rc);
for _ in 0..100_000_000 {
rc.clone();
}
}
|
use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::join;
use futures::stream::StreamExt;
use tokio::spawn;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Send 10 queries");
send_receive(10).await?;
Ok(())
}
async fn send_receive(n: usize) -> Result<(), Box<dyn std::error::Error>> {
let (tx, rx) = unbounded();
let send = spawn(async move {
send_task(tx, n).await;
});
let receive = spawn(async move {
receive_task(rx).await;
});
let (send_res, receive_res) = join!(send, receive);
send_res?;
receive_res?;
Ok(())
}
async fn send_task(tx: UnboundedSender<usize>, n: usize) {
for i in 0..n {
tx.unbounded_send(i).unwrap();
}
}
async fn receive_task(rx: UnboundedReceiver<usize>) {
rx.for_each(|i| async move { println!("# query({})", i) })
.await;
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Dimensions_ListByBillingAccount(#[from] dimensions::list_by_billing_account::Error),
#[error(transparent)]
Dimensions_ListByEnrollmentAccount(#[from] dimensions::list_by_enrollment_account::Error),
#[error(transparent)]
Dimensions_ListByDepartment(#[from] dimensions::list_by_department::Error),
#[error(transparent)]
Dimensions_ListByManagementGroup(#[from] dimensions::list_by_management_group::Error),
#[error(transparent)]
Dimensions_ListBySubscription(#[from] dimensions::list_by_subscription::Error),
#[error(transparent)]
Query_UsageBySubscription(#[from] query::usage_by_subscription::Error),
#[error(transparent)]
Forecast_UsageBySubscription(#[from] forecast::usage_by_subscription::Error),
#[error(transparent)]
Dimensions_ListByResourceGroup(#[from] dimensions::list_by_resource_group::Error),
#[error(transparent)]
Query_UsageByResourceGroup(#[from] query::usage_by_resource_group::Error),
#[error(transparent)]
Forecast_UsageByResourceGroup(#[from] forecast::usage_by_resource_group::Error),
#[error(transparent)]
Query_UsageByBillingAccount(#[from] query::usage_by_billing_account::Error),
#[error(transparent)]
Forecast_UsageByBillingAccount(#[from] forecast::usage_by_billing_account::Error),
#[error(transparent)]
Query_UsageByEnrollmentAccount(#[from] query::usage_by_enrollment_account::Error),
#[error(transparent)]
Forecast_UsageByEnrollmentAccount(#[from] forecast::usage_by_enrollment_account::Error),
#[error(transparent)]
Query_UsageByDepartment(#[from] query::usage_by_department::Error),
#[error(transparent)]
Forecast_UsageByDepartment(#[from] forecast::usage_by_department::Error),
#[error(transparent)]
Query_UsageByManagementGroup(#[from] query::usage_by_management_group::Error),
#[error(transparent)]
Forecast_UsageByManagementGroup(#[from] forecast::usage_by_management_group::Error),
#[error(transparent)]
Forecast_UsageByExternalBillingAccount(#[from] forecast::usage_by_external_billing_account::Error),
#[error(transparent)]
CloudConnector_List(#[from] cloud_connector::list::Error),
#[error(transparent)]
CloudConnector_Get(#[from] cloud_connector::get::Error),
#[error(transparent)]
CloudConnector_CreateOrUpdate(#[from] cloud_connector::create_or_update::Error),
#[error(transparent)]
CloudConnector_Update(#[from] cloud_connector::update::Error),
#[error(transparent)]
CloudConnector_Delete(#[from] cloud_connector::delete::Error),
#[error(transparent)]
Connector_CheckEligibility(#[from] connector::check_eligibility::Error),
#[error(transparent)]
ExternalBillingAccount_List(#[from] external_billing_account::list::Error),
#[error(transparent)]
ExternalBillingAccount_Get(#[from] external_billing_account::get::Error),
#[error(transparent)]
ExternalSubscription_ListByExternalBillingAccount(#[from] external_subscription::list_by_external_billing_account::Error),
#[error(transparent)]
ExternalSubscription_List(#[from] external_subscription::list::Error),
#[error(transparent)]
ExternalSubscription_Get(#[from] external_subscription::get::Error),
#[error(transparent)]
ExternalSubscription_ListByManagementGroup(#[from] external_subscription::list_by_management_group::Error),
#[error(transparent)]
ExternalSubscription_UpdateManagementGroup(#[from] external_subscription::update_management_group::Error),
#[error(transparent)]
ShowbackRules_List(#[from] showback_rules::list::Error),
#[error(transparent)]
ShowbackRule_GetBillingAccountId(#[from] showback_rule::get_billing_account_id::Error),
#[error(transparent)]
ShowbackRule_CreateUpdateRule(#[from] showback_rule::create_update_rule::Error),
#[error(transparent)]
Operations_List(#[from] operations::list::Error),
}
pub mod dimensions {
use super::{models, API_VERSION};
pub async fn list_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
filter: Option<&str>,
expand: Option<&str>,
skiptoken: Option<&str>,
top: Option<i64>,
) -> std::result::Result<models::DimensionsListResult, list_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.CostManagement/dimensions",
operation_config.base_path(),
billing_account_id
);
let mut url = url::Url::parse(url_str).map_err(list_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(skiptoken) = skiptoken {
url.query_pairs_mut().append_pair("$skiptoken", skiptoken);
}
if let Some(top) = top {
url.query_pairs_mut().append_pair("$top", top.to_string().as_str());
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DimensionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
enrollment_account_id: &str,
filter: Option<&str>,
expand: Option<&str>,
skiptoken: Option<&str>,
top: Option<i64>,
) -> std::result::Result<models::DimensionsListResult, list_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/providers/Microsoft.CostManagement/dimensions",
operation_config.base_path(),
billing_account_id,
enrollment_account_id
);
let mut url = url::Url::parse(url_str).map_err(list_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(skiptoken) = skiptoken {
url.query_pairs_mut().append_pair("$skiptoken", skiptoken);
}
if let Some(top) = top {
url.query_pairs_mut().append_pair("$top", top.to_string().as_str());
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DimensionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_department(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
department_id: &str,
filter: Option<&str>,
expand: Option<&str>,
skiptoken: Option<&str>,
top: Option<i64>,
) -> std::result::Result<models::DimensionsListResult, list_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/providers/Microsoft.CostManagement/dimensions",
operation_config.base_path(),
billing_account_id,
department_id
);
let mut url = url::Url::parse(url_str).map_err(list_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(skiptoken) = skiptoken {
url.query_pairs_mut().append_pair("$skiptoken", skiptoken);
}
if let Some(top) = top {
url.query_pairs_mut().append_pair("$top", top.to_string().as_str());
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DimensionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_management_group(
operation_config: &crate::OperationConfig,
management_group_id: &str,
filter: Option<&str>,
expand: Option<&str>,
skiptoken: Option<&str>,
top: Option<i64>,
) -> std::result::Result<models::DimensionsListResult, list_by_management_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Management/managementGroups/{}/providers/Microsoft.CostManagement/dimensions",
operation_config.base_path(),
management_group_id
);
let mut url = url::Url::parse(url_str).map_err(list_by_management_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_management_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(skiptoken) = skiptoken {
url.query_pairs_mut().append_pair("$skiptoken", skiptoken);
}
if let Some(top) = top {
url.query_pairs_mut().append_pair("$top", top.to_string().as_str());
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_management_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_management_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DimensionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_management_group::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_management_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_subscription(
operation_config: &crate::OperationConfig,
subscription_id: &str,
filter: Option<&str>,
expand: Option<&str>,
skiptoken: Option<&str>,
top: Option<i64>,
) -> std::result::Result<models::DimensionsListResult, list_by_subscription::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.CostManagement/dimensions",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).map_err(list_by_subscription::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_subscription::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(skiptoken) = skiptoken {
url.query_pairs_mut().append_pair("$skiptoken", skiptoken);
}
if let Some(top) = top {
url.query_pairs_mut().append_pair("$top", top.to_string().as_str());
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list_by_subscription::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_subscription::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DimensionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_subscription::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_subscription::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_subscription::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_subscription {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_resource_group(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
filter: Option<&str>,
expand: Option<&str>,
skiptoken: Option<&str>,
top: Option<i64>,
) -> std::result::Result<models::DimensionsListResult, list_by_resource_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.CostManagement/dimensions",
operation_config.base_path(),
subscription_id,
resource_group_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_resource_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_resource_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(filter) = filter {
url.query_pairs_mut().append_pair("$filter", filter);
}
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
if let Some(skiptoken) = skiptoken {
url.query_pairs_mut().append_pair("$skiptoken", skiptoken);
}
if let Some(top) = top {
url.query_pairs_mut().append_pair("$top", top.to_string().as_str());
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_resource_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_resource_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::DimensionsListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_resource_group::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_resource_group::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_resource_group::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod query {
use super::{models, API_VERSION};
pub async fn usage_by_subscription(
operation_config: &crate::OperationConfig,
subscription_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_subscription::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.CostManagement/Query",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_subscription::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_subscription::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_subscription::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_subscription::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_subscription::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_subscription::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_subscription::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_subscription::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_subscription {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_resource_group(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_resource_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.CostManagement/Query",
operation_config.base_path(),
subscription_id,
resource_group_name
);
let mut url = url::Url::parse(url_str).map_err(usage_by_resource_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_resource_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_resource_group::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_resource_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_resource_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_resource_group::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_resource_group::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_resource_group::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.CostManagement/Query",
operation_config.base_path(),
billing_account_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_billing_account::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
enrollment_account_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/providers/Microsoft.CostManagement/Query",
operation_config.base_path(),
billing_account_id,
enrollment_account_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_enrollment_account::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_department(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
department_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/providers/Microsoft.CostManagement/Query",
operation_config.base_path(),
billing_account_id,
department_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_department::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(usage_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_management_group(
operation_config: &crate::OperationConfig,
management_group_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_management_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Management/managementGroups/{}/providers/Microsoft.CostManagement/Query",
operation_config.base_path(),
management_group_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_management_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_management_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_management_group::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_management_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_management_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_management_group::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_management_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod forecast {
use super::{models, API_VERSION};
pub async fn usage_by_subscription(
operation_config: &crate::OperationConfig,
subscription_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_subscription::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.CostManagement/Forecast",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_subscription::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_subscription::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_subscription::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_subscription::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_subscription::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_subscription::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_subscription::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_subscription::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_subscription {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_resource_group(
operation_config: &crate::OperationConfig,
subscription_id: &str,
resource_group_name: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_resource_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.CostManagement/Forecast",
operation_config.base_path(),
subscription_id,
resource_group_name
);
let mut url = url::Url::parse(url_str).map_err(usage_by_resource_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_resource_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_resource_group::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_resource_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_resource_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_resource_group::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_resource_group::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_resource_group::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_billing_account(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.CostManagement/Forecast",
operation_config.base_path(),
billing_account_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_billing_account::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_enrollment_account(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
enrollment_account_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_enrollment_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/enrollmentAccounts/{}/providers/Microsoft.CostManagement/Forecast",
operation_config.base_path(),
billing_account_id,
enrollment_account_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_enrollment_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_enrollment_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_enrollment_account::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_enrollment_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_enrollment_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_enrollment_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_enrollment_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_enrollment_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_department(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
department_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_department::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/departments/{}/providers/Microsoft.CostManagement/Forecast",
operation_config.base_path(),
billing_account_id,
department_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_department::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_department::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_department::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(usage_by_department::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_department::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_department::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_department::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_department {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_management_group(
operation_config: &crate::OperationConfig,
management_group_id: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_management_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Management/managementGroups/{}/providers/Microsoft.CostManagement/Forecast",
operation_config.base_path(),
management_group_id
);
let mut url = url::Url::parse(url_str).map_err(usage_by_management_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_management_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_management_group::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_management_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_management_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_management_group::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_management_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn usage_by_external_billing_account(
operation_config: &crate::OperationConfig,
external_billing_account_name: &str,
parameters: &models::ReportConfigDefinition,
) -> std::result::Result<models::QueryResult, usage_by_external_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/externalBillingAccounts/{}/Forecast",
operation_config.base_path(),
external_billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(usage_by_external_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(usage_by_external_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(parameters).map_err(usage_by_external_billing_account::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(usage_by_external_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(usage_by_external_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::QueryResult = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_external_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| usage_by_external_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(usage_by_external_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod usage_by_external_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod cloud_connector {
use super::{models, API_VERSION};
pub async fn list(
operation_config: &crate::OperationConfig,
) -> std::result::Result<models::ConnectorDefinitionListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/cloudConnectors",
operation_config.base_path(),
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ConnectorDefinitionListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
connector_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::ConnectorDefinition, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/cloudConnectors/{}",
operation_config.base_path(),
connector_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ConnectorDefinition =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn create_or_update(
operation_config: &crate::OperationConfig,
connector_name: &str,
connector: &models::ConnectorDefinition,
) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/cloudConnectors/{}",
operation_config.base_path(),
connector_name
);
let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(create_or_update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(connector).map_err(create_or_update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(create_or_update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ConnectorDefinition = serde_json::from_slice(rsp_body)
.map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(create_or_update::Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = rsp.body();
let rsp_value: models::ConnectorDefinition = serde_json::from_slice(rsp_body)
.map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(create_or_update::Response::Created201(rsp_value))
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?;
Err(create_or_update::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::ConnectorDefinition),
Created201(models::ConnectorDefinition),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
connector_name: &str,
connector: &models::ConnectorDefinition,
) -> std::result::Result<models::ConnectorDefinition, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/cloudConnectors/{}",
operation_config.base_path(),
connector_name
);
let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(connector).map_err(update::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ConnectorDefinition =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?;
Err(update::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn delete(operation_config: &crate::OperationConfig, connector_name: &str) -> std::result::Result<(), delete::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/cloudConnectors/{}",
operation_config.base_path(),
connector_name
);
let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(delete::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => Ok(()),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?;
Err(delete::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod connector {
use super::{models, API_VERSION};
pub async fn check_eligibility(
operation_config: &crate::OperationConfig,
connector_credentials: &models::CheckEligibilityDefinition,
) -> std::result::Result<models::ConnectorDefinition, check_eligibility::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/checkConnectorEligibility",
operation_config.base_path(),
);
let mut url = url::Url::parse(url_str).map_err(check_eligibility::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(check_eligibility::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(connector_credentials).map_err(check_eligibility::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(check_eligibility::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(check_eligibility::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ConnectorDefinition = serde_json::from_slice(rsp_body)
.map_err(|source| check_eligibility::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| check_eligibility::Error::DeserializeError(source, rsp_body.clone()))?;
Err(check_eligibility::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod check_eligibility {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod external_billing_account {
use super::{models, API_VERSION};
pub async fn list(
operation_config: &crate::OperationConfig,
) -> std::result::Result<models::ExternalBillingAccountDefinitionListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/externalBillingAccounts",
operation_config.base_path(),
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ExternalBillingAccountDefinitionListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
external_billing_account_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::ExternalBillingAccountDefinition, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/externalBillingAccounts/{}",
operation_config.base_path(),
external_billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ExternalBillingAccountDefinition =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod external_subscription {
use super::{models, API_VERSION};
pub async fn list_by_external_billing_account(
operation_config: &crate::OperationConfig,
external_billing_account_name: &str,
) -> std::result::Result<models::ExternalSubscriptionDefinitionListResult, list_by_external_billing_account::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/externalBillingAccounts/{}/externalSubscriptions",
operation_config.base_path(),
external_billing_account_name
);
let mut url = url::Url::parse(url_str).map_err(list_by_external_billing_account::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_external_billing_account::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_external_billing_account::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_external_billing_account::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ExternalSubscriptionDefinitionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_external_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_external_billing_account::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_external_billing_account::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_external_billing_account {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list(
operation_config: &crate::OperationConfig,
) -> std::result::Result<models::ExternalSubscriptionDefinitionListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/externalSubscriptions",
operation_config.base_path(),
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ExternalSubscriptionDefinitionListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
external_subscription_name: &str,
expand: Option<&str>,
) -> std::result::Result<models::ExternalSubscriptionDefinition, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.CostManagement/externalSubscriptions/{}",
operation_config.base_path(),
external_subscription_name
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ExternalSubscriptionDefinition =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list_by_management_group(
operation_config: &crate::OperationConfig,
management_group_id: &str,
recurse: Option<bool>,
) -> std::result::Result<models::ExternalSubscriptionDefinitionListResult, list_by_management_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Management/managementGroups/{}/providers/Microsoft.CostManagement/externalSubscriptions",
operation_config.base_path(),
management_group_id
);
let mut url = url::Url::parse(url_str).map_err(list_by_management_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list_by_management_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(recurse) = recurse {
url.query_pairs_mut().append_pair("$recurse", recurse.to_string().as_str());
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(list_by_management_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(list_by_management_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ExternalSubscriptionDefinitionListResult = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| list_by_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list_by_management_group::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list_by_management_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn update_management_group(
operation_config: &crate::OperationConfig,
management_group_id: &str,
external_subscription_name: &str,
) -> std::result::Result<(), update_management_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Management/managementGroups/{}/providers/Microsoft.CostManagement/externalSubscriptions/{}",
operation_config.base_path(),
management_group_id,
external_subscription_name
);
let mut url = url::Url::parse(url_str).map_err(update_management_group::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(update_management_group::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(update_management_group::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(update_management_group::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::NO_CONTENT => Ok(()),
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| update_management_group::Error::DeserializeError(source, rsp_body.clone()))?;
Err(update_management_group::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod update_management_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod showback_rules {
use super::{models, API_VERSION};
pub async fn list(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
) -> std::result::Result<models::ShowbackRuleListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.CostManagement/showbackRules",
operation_config.base_path(),
billing_account_id
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ShowbackRuleListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod showback_rule {
use super::{models, API_VERSION};
pub async fn get_billing_account_id(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
rule_name: &str,
) -> std::result::Result<models::ShowbackRule, get_billing_account_id::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.CostManagement/showbackRules/{}",
operation_config.base_path(),
billing_account_id,
rule_name
);
let mut url = url::Url::parse(url_str).map_err(get_billing_account_id::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_billing_account_id::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.map_err(get_billing_account_id::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_billing_account_id::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ShowbackRule = serde_json::from_slice(rsp_body)
.map_err(|source| get_billing_account_id::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| get_billing_account_id::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_billing_account_id::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_billing_account_id {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn create_update_rule(
operation_config: &crate::OperationConfig,
billing_account_id: &str,
rule_name: &str,
showback_rule: &models::ShowbackRule,
) -> std::result::Result<models::ShowbackRule, create_update_rule::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.CostManagement/showbackRules/{}",
operation_config.base_path(),
billing_account_id,
rule_name
);
let mut url = url::Url::parse(url_str).map_err(create_update_rule::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(create_update_rule::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(showback_rule).map_err(create_update_rule::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(create_update_rule::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(create_update_rule::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::ShowbackRule = serde_json::from_slice(rsp_body)
.map_err(|source| create_update_rule::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse = serde_json::from_slice(rsp_body)
.map_err(|source| create_update_rule::Error::DeserializeError(source, rsp_body.clone()))?;
Err(create_update_rule::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod create_update_rule {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod operations {
use super::{models, API_VERSION};
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<models::OperationListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!("{}/providers/Microsoft.CostManagement/operations", operation_config.base_path(),);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: models::OperationListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: models::ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
|
/*
* -- lib.rs
* msel
* by viz (https://github.com/vizs)
*
* licensed under BSD 2-Clause "Simplified" License
*/
pub mod ui;
pub struct Items {
pub all_items: Vec<String>,
pub sel_items: Vec<String>
}
impl Items {
pub fn new(all_item: &Vec<String>) -> Items {
Items {
all_items: all_item.to_vec(),
sel_items: vec![],
}
}
/*
* add or delete item from sel_items vector
* if item is already in the vector, it is
* removed
*/
#[allow(unused_assignments)]
pub fn add_rm_sel(&mut self, new_item: &String) {
if self.sel_items.contains(new_item) {
let item_ind = self.sel_items.iter()
.position(|x| x == new_item);
let mut ind: usize = 0;
match item_ind.ok_or(0) {
Ok(n) => { ind = n; },
_ => { return (); },
}
self.sel_items.remove(ind);
} else {
self.sel_items.push(new_item.to_string());
}
}
/*
* return all items
*/
pub fn get_items(&self) -> Vec<String> {
self.all_items.to_vec()
}
}
|
extern crate nix;
use nix::sys::signal::{kill, SIGTERM};
use nix::unistd::{fork, getpid, ForkResult};
use std::error::Error;
use std::io::{BufRead, BufReader, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::process::Command;
use std::thread::spawn;
/// Los modos en los que puede correr el servidor
/// son simple, modo fork y modo thread
pub enum Mode {
Simple,
Forked,
Threaded,
}
/// Config struct
/// Una configuracion basica para el servidor
pub struct Config {
host: String,
port: u16,
mode: Mode,
}
/// Metodos para el struct config
impl Config {
/// Crea una nueva config con los argumentos pasados por terminal
pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
// ignora el primer argumento, es el nombre del archivo
args.next();
// el segundo argumento tiene que ser el modo en el que va a correr el servidor
let mode: Mode = match args.next() {
Some(arg) => match arg.as_ref() {
"h" => {
return Err("Help is sily. But you should run with params [MODE] [HOST] [PORT]")
}
"simple" => Mode::Simple,
"threaded" => Mode::Threaded,
"forked" => Mode::Forked,
_ => {
return Err(
"not a valid mode of operation! try 'forked', 'threaded' or 'simple'",
)
}
},
None => return Err("Did not provide any params!"),
};
// la ip en la que va a correr el servidor
let host: String = match args.next() {
Some(arg) => arg.clone(),
None => return Err("Did not provide any host!"),
};
// el puerto donde va a estar escuchando
let port: u16 = match args.next() {
Some(arg) => match arg.parse() {
Ok(n) => n,
Err(_) => return Err("Invalid port number."),
},
None => return Err("Did not get a port to run on."),
};
Ok(Config { host, port, mode })
}
pub fn host(&self) -> &str {
return &self.host;
}
pub fn port(&self) -> &u16 {
return &self.port;
}
}
/// Tiene logica para lidiar con un cliente.
/// Tiene un buffer para escribir y otro para leer del socket tcp.
/// Se le pasa un strem TCP como parametro.
fn handle_client(mut stream: TcpStream, ip: String) -> Result<(), Box<dyn Error>> {
let mut writer = stream.try_clone()?;
let mut reader = BufReader::new(&mut stream);
let mut buffer: String = String::new();
let welcome = format!("Bienvenido {}\n", ip);
writer.write(welcome.as_ref())?;
// hasta que el usuario no escriba "SALIR", el loop no se termina
loop {
match reader.read_line(&mut buffer)? {
0 => return Ok(()),
_ => {
match buffer.trim() {
"usuarios" => {
writer.write(b"OK.\n")?;
writer.write(&Command::new("who").output()?.stdout)?;
writer.write(b"\nFIN.\n")?;
}
"fecha" => {
writer.write(b"OK.\n")?;
writer.write(&Command::new("date").output()?.stdout)?;
writer.write(b"\nFIN.\n")?;
}
"procesos" => {
writer.write(b"OK.\n")?;
writer.write(&Command::new("ps").output()?.stdout)?;
writer.write(b"\nFIN.\n")?;
}
"salir" => {
writer.write(b"ADIOS.\n")?;
writer.shutdown(Shutdown::Both)?;
return Ok(());
}
_ => {
writer.write(b"ERR.\n")?;
}
}
buffer.clear();
}
}
}
}
/// Corre un servidor con una config en particular.
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
match config.mode {
Mode::Simple => return run_single_threaded(config),
Mode::Threaded => return run_with_threads(config),
Mode::Forked => return run_with_fork(config),
}
}
/// Corre el servidor con un solo thread y un solo proceso (ie: secuencialmente)
fn run_single_threaded(config: Config) -> Result<(), Box<dyn Error>> {
let listener = TcpListener::bind(format!("{}:{}", config.host(), config.port()))?;
loop {
let (stream, addr) = listener.accept()?;
handle_client(stream, format!("{}", addr.ip()))?;
}
}
/// Corre usando varios procesos: uno por cliente
fn run_with_fork(config: Config) -> Result<(), Box<dyn Error>> {
let listener = TcpListener::bind(format!("{}:{}", config.host(), config.port()))?;
loop {
let (stream, addr) = listener.accept()?;
// por cada vez que se acepta una conexión, hacé el fork
match fork() {
// no necesita actuarse en el padre :)
Ok(ForkResult::Parent { child: _, .. }) => {}
// en el hijo, maneja el cliente y después terminá el proceso
Ok(ForkResult::Child) => {
let res = handle_client(stream, format!("{}", addr.ip()));
kill(getpid(), SIGTERM)?;
res?
}
Err(e) => return Err(Box::new(e)),
}
}
}
/// Corre con threads!
fn run_with_threads(config: Config) -> Result<(), Box<dyn Error>> {
let listener = TcpListener::bind(format!("{}:{}", config.host(), config.port()))?;
loop {
let (stream, addr) = listener.accept()?;
// por cada conexión aceptada, iniciá un nuevo thread
spawn(move || {
if let Err(e) = handle_client(stream, format!("{}", addr.ip())) {
eprintln!("Thread failed {}", e);
};
});
}
}
|
// Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use std::io;
use std::mem;
use std::os::raw::c_void;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use std::usize;
use kernel32;
use winapi;
use stack::Stack;
extern "system" {
// TODO: kernel32-sys has currently (0.2.1) a bug where lpflOldProtect
// is declared as a DWORD, but should be PDWORD instead.
pub fn VirtualProtect(lpAddress: winapi::LPVOID,
dwSize: winapi::SIZE_T,
flNewProtect: winapi::DWORD,
lpflOldProtect: winapi::PDWORD)
-> winapi::BOOL;
}
pub unsafe fn allocate_stack(size: usize) -> io::Result<Stack> {
const NULL: winapi::LPVOID = 0 as winapi::LPVOID;
const PROT: winapi::DWORD = winapi::PAGE_READWRITE;
const TYPE: winapi::DWORD = winapi::MEM_COMMIT | winapi::MEM_RESERVE;
let ptr = kernel32::VirtualAlloc(NULL, size as winapi::SIZE_T, TYPE, PROT);
if ptr == NULL {
Err(io::Error::last_os_error())
} else {
Ok(Stack::new((ptr as usize + size) as *mut c_void, ptr as *mut c_void))
}
}
pub unsafe fn protect_stack(stack: &Stack) -> io::Result<Stack> {
const TYPE: winapi::DWORD = winapi::PAGE_READWRITE | winapi::PAGE_GUARD;
let page_size = page_size();
let mut old_prot: winapi::DWORD = 0;
debug_assert!(stack.len() % page_size == 0 && stack.len() != 0);
let ret = {
let page_size = page_size as winapi::SIZE_T;
VirtualProtect(stack.bottom(), page_size, TYPE, &mut old_prot)
};
if ret == 0 {
Err(io::Error::last_os_error())
} else {
let bottom = (stack.bottom() as usize + page_size) as *mut c_void;
Ok(Stack::new(stack.top(), bottom))
}
}
pub unsafe fn deallocate_stack(ptr: *mut c_void, _: usize) {
kernel32::VirtualFree(ptr as winapi::LPVOID, 0, winapi::MEM_RELEASE);
}
pub fn page_size() -> usize {
static PAGE_SIZE: AtomicUsize = ATOMIC_USIZE_INIT;
let mut ret = PAGE_SIZE.load(Ordering::Relaxed);
if ret == 0 {
ret = unsafe {
let mut info = mem::zeroed();
kernel32::GetSystemInfo(&mut info);
info.dwPageSize as usize
};
PAGE_SIZE.store(ret, Ordering::Relaxed);
}
ret
}
// Windows does not seem to provide a stack limit API
pub fn min_stack_size() -> usize {
page_size()
}
// Windows does not seem to provide a stack limit API
pub fn max_stack_size() -> usize {
usize::MAX
}
|
extern crate structopt;
use std::fs::File;
use std::io::Read;
use structopt::StructOpt;
mod errors;
mod dos;
mod coff;
mod formats;
mod utils;
#[derive(Debug, StructOpt)]
pub struct Cli {
path: std::path::PathBuf,
#[structopt(short="f", long="format")]
format: Option<String>,
#[structopt(short, long)]
interactive: bool,
#[structopt(short="s", long="show")]
field: Option<String>
}
fn main() {
let args = Cli::from_args();
let mut file: File = File::open(args.path).unwrap();
let mut file_contents: Vec<u8> = Vec::new();
file.read_to_end(&mut file_contents).unwrap();
if args.format.is_none() {
let file_format: formats::Format = utils::infer_format(&mut file_contents);
} else {
let file_format: formats::Format = formats::Format::from_string(
args.format.unwrap());
}
if args.field.is_some() {
unimplemented!();
}
}
|
// hide console window on Windows
#![windows_subsystem="windows"]
#[macro_use] extern crate sciter;
#[cfg(windows)]
use winreg;
struct EventHandler;
#[cfg(windows)]
impl EventHandler {
#[allow(non_snake_case)]
fn createWindowsShortcut(&self, add: bool) -> sciter::Value {
// https://users.rust-lang.org/t/how-to-make-my-exe-autorun-in-windows/49045/12
use std::path::Path;
use winreg::enums::*;
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let path = Path::new("Software").join("Microsoft").join("Windows").join("CurrentVersion").join("Run");
let (key, disp) = hkcu.create_subkey(&path).unwrap();
dbg!(&disp);
let path = format!("\"{}\"", std::env::current_exe().unwrap().to_str().unwrap().to_string());
if add {
key.set_value("temps-lite", &path).unwrap();
} else {
key.delete_value("temps-lite").unwrap();
}
sciter::Value::from(true)
}
}
impl sciter::EventHandler for EventHandler {
#[cfg(windows)]
dispatch_script_call! (
fn createWindowsShortcut(bool);
);
}
fn main() {
// allows CTRL+SHIFT+I to connect to inspector.exe
sciter::set_options(sciter::RuntimeOptions::DebugMode(false)).unwrap();
let archived = include_bytes!("../target/assets.rc");
sciter::set_options(sciter::RuntimeOptions::ScriptFeatures(
sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_SYSINFO as u8 |
sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_FILE_IO as u8 |
sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_EVAL as u8 |
sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_SOCKET_IO as u8
)).unwrap();
let mut frame = sciter::Window::new();
frame.event_handler(EventHandler {});
frame.archive_handler(archived).unwrap();
frame.load_file("this://app/main.html");
frame.run_app();
}
|
#[doc = "Reader of register HOST_EP1_RW2_DR"]
pub type R = crate::R<u32, super::HOST_EP1_RW2_DR>;
#[doc = "Writer for register HOST_EP1_RW2_DR"]
pub type W = crate::W<u32, super::HOST_EP1_RW2_DR>;
#[doc = "Register HOST_EP1_RW2_DR `reset()`'s with value 0"]
impl crate::ResetValue for super::HOST_EP1_RW2_DR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `BFDT16`"]
pub type BFDT16_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `BFDT16`"]
pub struct BFDT16_W<'a> {
w: &'a mut W,
}
impl<'a> BFDT16_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - Data Register for EP1. The 2-Byte data is valid."]
#[inline(always)]
pub fn bfdt16(&self) -> BFDT16_R {
BFDT16_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - Data Register for EP1. The 2-Byte data is valid."]
#[inline(always)]
pub fn bfdt16(&mut self) -> BFDT16_W {
BFDT16_W { w: self }
}
}
|
use byteorder::{ByteOrder, LittleEndian};
use ckb_vm::{
decoder::build_imac_decoder, machine::asm::AsmMachine, CoreMachine, Memory, SupportMachine,
RISCV_GENERAL_REGISTER_NUMBER,
};
use gdb_remote_protocol::{
Breakpoint, Error, Handler, MemoryRegion, ProcessType, StopReason, ThreadId, VCont,
VContFeature,
};
use std::borrow::Cow;
use std::cell::RefCell;
fn format_register_value(v: u64) -> Vec<u8> {
let mut buf = [0u8; 8];
LittleEndian::write_u64(&mut buf, v);
buf.to_vec()
}
pub struct GdbHandler<'a> {
machine: RefCell<AsmMachine<'a>>,
breakpoints: RefCell<Vec<Breakpoint>>,
}
impl<'a> GdbHandler<'a> {
fn at_breakpoint(&self) -> bool {
let pc = *self.machine.borrow().machine.pc();
self.breakpoints.borrow().iter().any(|b| b.addr == pc)
}
pub fn new(machine: AsmMachine<'a>) -> Self {
GdbHandler {
machine: RefCell::new(machine),
breakpoints: RefCell::new(vec![]),
}
}
}
impl<'a> Handler for GdbHandler<'a> {
fn attached(&self, _pid: Option<u64>) -> Result<ProcessType, Error> {
Ok(ProcessType::Created)
}
fn halt_reason(&self) -> Result<StopReason, Error> {
// SIGINT
Ok(StopReason::Signal(2))
}
fn read_general_registers(&self) -> Result<Vec<u8>, Error> {
let registers: Vec<Vec<u8>> = self
.machine
.borrow()
.machine
.registers()
.iter()
.map(|v| format_register_value(*v))
.collect();
Ok(registers.concat())
}
fn read_register(&self, register: u64) -> Result<Vec<u8>, Error> {
let register = register as usize;
if register < RISCV_GENERAL_REGISTER_NUMBER {
Ok(format_register_value(
self.machine.borrow().machine.registers()[register],
))
} else if register == RISCV_GENERAL_REGISTER_NUMBER {
Ok(format_register_value(*self.machine.borrow().machine.pc()))
} else {
Err(Error::Error(1))
}
}
fn write_register(&self, register: u64, contents: &[u8]) -> Result<(), Error> {
let mut buffer = [0u8; 8];
if contents.len() > 8 {
error!("Register value too large!");
return Err(Error::Error(2));
}
buffer[0..contents.len()].copy_from_slice(contents);
let value = LittleEndian::read_u64(&buffer[..]);
let register = register as usize;
if register < RISCV_GENERAL_REGISTER_NUMBER {
self.machine
.borrow_mut()
.machine
.set_register(register, value);
Ok(())
} else if register == RISCV_GENERAL_REGISTER_NUMBER {
self.machine.borrow_mut().machine.set_pc(value);
Ok(())
} else {
Err(Error::Error(2))
}
}
fn read_memory(&self, region: MemoryRegion) -> Result<Vec<u8>, Error> {
let mut values = vec![];
for address in region.address..(region.address + region.length) {
let value = self
.machine
.borrow_mut()
.machine
.memory_mut()
.load8(&address)
.map_err(|e| {
error!("Error reading memory address {:x}: {:?}", address, e);
Error::Error(3)
})?;
values.push(value as u8);
}
Ok(values)
}
fn write_memory(&self, address: u64, bytes: &[u8]) -> Result<(), Error> {
self.machine
.borrow_mut()
.machine
.memory_mut()
.store_bytes(address, bytes)
.map_err(|e| {
error!("Error writing memory address {:x}: {:?}", address, e);
Error::Error(4)
})?;
Ok(())
}
fn query_supported_vcont(&self) -> Result<Cow<'static, [VContFeature]>, Error> {
// Even though we won't support all of vCont features, gdb feature
// detection only work when we include all of them. The other solution
// is to use the plain old s or c, but the RSP parser we are using here
// doesn't support them yet.
Ok(Cow::from(
&[
VContFeature::Continue,
VContFeature::ContinueWithSignal,
VContFeature::Step,
VContFeature::StepWithSignal,
VContFeature::Stop,
VContFeature::RangeStep,
][..],
))
}
fn vcont(&self, request: Vec<(VCont, Option<ThreadId>)>) -> Result<StopReason, Error> {
let decoder = build_imac_decoder::<u64>();
let (vcont, _thread_id) = &request[0];
match vcont {
VCont::Continue => {
self.machine
.borrow_mut()
.machine
.step(&decoder)
.expect("VM error");
while (!self.at_breakpoint()) && self.machine.borrow().machine.running() {
self.machine
.borrow_mut()
.machine
.step(&decoder)
.expect("VM error");
}
}
VCont::Step => {
if self.machine.borrow().machine.running() {
self.machine
.borrow_mut()
.machine
.step(&decoder)
.expect("VM error");
}
}
VCont::RangeStep(range) => {
self.machine
.borrow_mut()
.machine
.step(&decoder)
.expect("VM error");
while self.machine.borrow().machine.pc() >= &range.start
&& self.machine.borrow().machine.pc() < &range.end
&& (!self.at_breakpoint())
&& self.machine.borrow().machine.running()
{
self.machine
.borrow_mut()
.machine
.step(&decoder)
.expect("VM error");
}
}
v => {
debug!("Unspported vcont type: {:?}", v);
return Err(Error::Error(5));
}
}
if self.machine.borrow().machine.running() {
// SIGTRAP
Ok(StopReason::Signal(5))
} else {
Ok(StopReason::Exited(
0,
self.machine.borrow().machine.exit_code() as u8,
))
}
}
fn insert_software_breakpoint(&self, breakpoint: Breakpoint) -> Result<(), Error> {
self.breakpoints.borrow_mut().push(breakpoint);
Ok(())
}
fn remove_software_breakpoint(&self, breakpoint: Breakpoint) -> Result<(), Error> {
self.breakpoints.borrow_mut().retain(|b| b != &breakpoint);
Ok(())
}
}
|
use crate::{marshall_vec, Uuid};
#[test]
fn encode_bool_false() {
assert_eq!(marshall_vec(false).unwrap(), vec![1, 1, 0]);
}
#[test]
fn encode_bool_true() {
assert_eq!(marshall_vec(true).unwrap(), vec![1, 1, 1]);
}
#[test]
fn encode_char_ascii() {
assert_eq!(marshall_vec('A').unwrap(), vec![1, 3, 65]);
}
#[test]
fn encode_char_emoji() {
assert_eq!(marshall_vec('🚀').unwrap(), vec![1, 3, 240, 159, 154, 128]);
}
#[test]
fn encode_string_ascii() {
assert_eq!(
marshall_vec("Hello World!").unwrap(),
vec![1, 2, 12, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]);
}
#[test]
fn encode_string_emoji() {
assert_eq!(
marshall_vec("🎮 !Gamers unite! 🎮").unwrap(),
vec![1, 2, 24, 240, 159, 142, 174, 32, 33, 71, 97, 109, 101, 114, 115, 32, 117, 110, 105,
116, 101, 33, 32, 240, 159, 142, 174]);
}
#[test]
fn encode_uuid() {
let uuid = Uuid::from_string("13c5ded9-50af-4cf7-81e1-5e1f57a58b4c").unwrap();
assert_eq!(
marshall_vec(uuid).unwrap(),
vec![1, 6, 19, 197, 222, 217, 80, 175, 76, 247, 129, 225, 94, 31, 87, 165, 139, 76]);
}
#[test]
fn encode_bytes() {
assert_eq!(
marshall_vec(vec![10_u8, 20_u8, 30_u8, 40_u8, 50_u8]).unwrap(),
vec![1, 5, 5, 10, 20, 30, 40, 50]);
}
|
// Copyright 2018 Steven Bosnick
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 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
//! Defines iterators and other utilities for working with `Span<T>`.
use super::{Location, Span};
use encode_unicode::{U8UtfExt, Utf8Char};
use std::io::prelude::*;
use std::{fmt, io, str};
/// A failure that cannot occur.
///
/// This type is used as the error type in a `Result<T,E>` when no errors
/// are possible.
#[derive(Fail, Debug)] // COV_EXCL_LINE
pub enum Never {}
impl fmt::Display for Never {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"The impossible has occured. Never has occured as a failure."
)
}
}
/// An iterator over the spanned `char`'s of an `str`
pub struct SpannedStrIter<I>
where
I: Iterator<Item = (usize, char)>,
{
inner: I,
}
impl<'a> SpannedStrIter<str::CharIndices<'a>> {
/// Create a new `SpannedStrIter` for the given `str`.
pub fn new(input: &'a str) -> Self {
SpannedStrIter {
inner: input.char_indices(),
}
}
}
impl<I> Iterator for SpannedStrIter<I>
where
I: Iterator<Item = (usize, char)>,
{
type Item = Result<Span<char>, Never>;
fn next(&mut self) -> Option<Self::Item> {
match self.inner.next() {
None => None,
Some(i) => Some(Ok(i.into())),
}
}
}
/// Extention trait for `str` to provide the `spanned_chars` method.
pub trait StrExt {
/// Iterate over the spanned `char`'s of the string.
fn spanned_chars<'a>(&'a self) -> SpannedStrIter<str::CharIndices<'a>>;
}
impl StrExt for str {
fn spanned_chars<'a>(&'a self) -> SpannedStrIter<str::CharIndices<'a>> {
SpannedStrIter::new(self)
}
}
/// An iterator that converts bytes to spanned utf8 `chars`.
///
/// # Errors
/// The iterator will produce an Err(e) item when ever the underlying
/// iterator does so. It will also produce the following errors as a part
/// of converting from bytes to utf8 encoded `char`s:
///
/// - `ErrorKind::UnexpectedEof`: the underlying iterator ended in the middle of a
/// multibyte utf8 `char`
/// - `ErrorKind::InvalidData`: a byte or byte sequence from the underlying iterator
/// was not a valid utf8 encoded `char`
pub struct SpannedUtf8Iter<I>
where
I: Iterator<Item = io::Result<u8>>,
{
inner: I,
current: Location,
}
impl<I> SpannedUtf8Iter<I>
where
I: Iterator<Item = io::Result<u8>>,
{
/// Create a new `SpannedUtf8Iter` over the given bytes iterator.
///
/// The `Location`'s for the `Span<char>`'s that are produced
/// will start at `start`.
pub fn new(start: Location, iter: I) -> SpannedUtf8Iter<I> {
SpannedUtf8Iter {
inner: iter,
current: start,
}
}
fn make_span(&mut self, c: char) -> Span<char> {
let start = self.current;
let len = c.len_utf8();
self.current += len;
Span::new(start, start + (len - 1), c)
}
}
impl<I> Iterator for SpannedUtf8Iter<I>
where
I: Iterator<Item = io::Result<u8>>,
{
type Item = io::Result<Span<char>>;
fn next(&mut self) -> Option<Self::Item> {
match self.inner.next() {
None => None,
Some(Err(e)) => Some(Err(e)),
Some(Ok(first)) => {
Some(extract_utf8_char(first, &mut self.inner).map(|c| self.make_span(c)))
}
}
}
}
fn extract_utf8_char<I>(first: u8, iter: &mut I) -> io::Result<char>
where
I: Iterator<Item = io::Result<u8>>,
{
let count = first.extra_utf8_bytes().map_err(map_invalid_data)?;
let mut buffer = [first, 0, 0, 0];
for index in 1..(count + 1) {
buffer[index] = extract_utf8_continutaion_byte(iter)?;
}
Utf8Char::from_array(buffer)
.map_err(map_invalid_data)
.map(|c| c.to_char())
}
fn map_invalid_data<E>(error: E) -> io::Error
where
E: Into<Box<dyn (::std::error::Error) + Send + Sync>>,
{
io::Error::new(io::ErrorKind::InvalidData, error)
}
fn extract_utf8_continutaion_byte<I>(iter: &mut I) -> io::Result<u8>
where
I: Iterator<Item = io::Result<u8>>,
{
use std::io::{Error, ErrorKind};
match iter.next() {
None => Err(Error::new(
ErrorKind::UnexpectedEof,
"Too few bytes for utf8 character.",
)),
Some(Err(e)) => Err(e),
Some(Ok(byte)) => Ok(byte),
}
} // COV_EXCL_LINE
/// Extention trait for a reader to allow it to prodcue a spanned `char`s iterator.
///
/// Although there is a default implementation for every reader, there will likely
/// be bad performance on any unbuffered readers because the iterator will use many
/// single-byte reads.
pub trait Utf8SpannedChars: Read + Sized {
/// Iterate over the spanned utf8 encoded `char`s for this reader.
fn spanned_chars(self, start: Location) -> SpannedUtf8Iter<io::Bytes<Self>>;
}
impl<R: Read> Utf8SpannedChars for R {
fn spanned_chars(self, start: Location) -> SpannedUtf8Iter<io::Bytes<Self>> {
SpannedUtf8Iter::new(start, self.bytes())
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::ErrorKind;
#[test]
fn string_iterates_expected_spans() {
let results: Result<Vec<_>, _> = "abc℞①".spanned_chars().collect();
assert_eq!(
results.expect("Unexpected error in the spanned_chars() iterator."),
vec![
Span::new(0.into(), 0.into(), 'a'),
Span::new(1.into(), 1.into(), 'b'),
Span::new(2.into(), 2.into(), 'c'),
Span::new(3.into(), 5.into(), '℞'),
Span::new(6.into(), 8.into(), '①'),
]
)
}
#[test]
fn extract_invalid_first_byte_is_error() {
use std::iter;
let continuation_byte: u8 = 0x80;
let result = extract_utf8_char(continuation_byte, &mut iter::empty::<io::Result<u8>>());
assert_matches!(result, Err(ref e) if e.kind() == ErrorKind::InvalidData);
}
#[test]
fn extract_with_too_few_bytes_is_error() {
let first: u8 = 0xe1; // first byte of 3 byte sequence
let rest: Vec<io::Result<u8>> = vec![Ok(90)]; // 1 following byte
let result = extract_utf8_char(first, &mut rest.into_iter());
assert_matches!(result, Err(ref e) if e.kind() == ErrorKind::UnexpectedEof);
}
#[test]
fn extract_with_invalid_continuation_is_error() {
let first: u8 = 0xc2; // first byte of 2 byte sequence
let rest: Vec<io::Result<u8>> = vec![Ok(0xc2)]; // not continuation byte
let result = extract_utf8_char(first, &mut rest.into_iter());
assert_matches!(result, Err(ref e) if e.kind() == ErrorKind::InvalidData);
}
#[test]
fn extract_with_valid_bytes_is_expected_char() {
let first: u8 = 0xe1; // first byte of 3 byte sequence
let rest: Vec<io::Result<u8>> = vec![Ok(0x90), Ok(0x81)];
let result = extract_utf8_char(first, &mut rest.into_iter());
assert_matches!(result, Ok(c) if c == 'ᐁ');
}
#[test]
fn spanned_utf8_decodes_expected_chars() {
let bytes = vec![0x41, 0x42, 0xc2, 0xa2, 0xe1, 0x90, 0x81];
let iter = bytes.into_iter().map(|b| Ok(b));
let results: Result<Vec<_>, _> = SpannedUtf8Iter::new(0.into(), iter).collect();
assert_eq!(
results.expect("Unexpected error in the SpannedUtf8Iter."),
vec![
Span::new(0.into(), 0.into(), 'A'),
Span::new(1.into(), 1.into(), 'B'),
Span::new(2.into(), 3.into(), '¢'),
Span::new(4.into(), 6.into(), 'ᐁ'),
]
);
}
#[test]
fn utf8_spanned_chars_decodes_expected_chars() {
let bytes = vec![0x41, 0x42, 0xc2, 0xa2, 0xe1, 0x90, 0x81];
let results: Result<Vec<_>, _> = bytes.spanned_chars(0.into()).collect();
assert_eq!(
results.expect("Unexpected error in the SpannedUtf8Iter."),
vec![
Span::new(0.into(), 0.into(), 'A'),
Span::new(1.into(), 1.into(), 'B'),
Span::new(2.into(), 3.into(), '¢'),
Span::new(4.into(), 6.into(), 'ᐁ'),
]
);
}
}
|
/// An internal macro used for defining a function to get the user's preferred immutable store (which requires multiple branches).
#[doc(hidden)]
#[macro_export]
macro_rules! define_get_immutable_store {
() => {
pub fn get_immutable_store() -> $crate::stores::ImmutableStore {
// This will be executed in the context of the user's directory, but moved into `.perseus`
// If we're in prod mode on the server though, this is fine too
$crate::stores::ImmutableStore::new("./dist".to_string())
}
};
($dist_path:literal) => {
pub fn get_immutable_store() -> $crate::stores::ImmutableStore {
$crate::stores::ImmutableStore::new($dist_path.to_string())
}
};
}
/// An internal macro used for defining a function to get the user's preferred mutable store (which requires multiple branches).
#[doc(hidden)]
#[macro_export]
macro_rules! define_get_mutable_store {
() => {
pub fn get_mutable_store() -> impl $crate::stores::MutableStore {
// This will be executed in the context of the user's directory, but moved into `.perseus`
// If we're in prod mode on the server though, this is fine too
// Note that this is separated out from the immutable store deliberately
$crate::stores::FsMutableStore::new("./dist/mutable".to_string())
}
};
($mutable_store:expr) => {
pub fn get_mutable_store() -> impl $crate::stores::MutableStore {
$mutable_store
}
};
}
/// An internal macro used for defining the HTML `id` at which to render the Perseus app (which requires multiple branches). The default
/// is `root`.
#[doc(hidden)]
#[macro_export]
macro_rules! define_app_root {
() => {
pub static APP_ROOT: &str = "root";
};
($root_id:literal) => {
pub static APP_ROOT: &str = $root_id;
};
}
/// An internal macro used for defining a function to get the user's preferred translations manager (which requires multiple branches).
#[doc(hidden)]
#[macro_export]
macro_rules! define_get_translations_manager {
($locales:expr) => {
pub async fn get_translations_manager() -> impl $crate::TranslationsManager {
// This will be executed in the context of the user's directory, but moved into `.perseus`
// Note that `translations/` must be next to `src/`, not within it
// By default, all translations are cached
let all_locales: Vec<String> = $locales
.get_all()
.iter()
// We have a `&&String` at this point, hence the double clone
.cloned()
.cloned()
.collect();
// If we're running on a server, we should be using a flattened directory structure
let translations_dir = if ::std::env::var("PERSEUS_STANDALONE").is_ok() {
"./translations"
} else {
"../translations"
};
$crate::FsTranslationsManager::new(
translations_dir.to_string(),
all_locales,
$crate::TRANSLATOR_FILE_EXT.to_string(),
$crate::path_prefix::get_path_prefix_server(),
)
.await
}
};
($locales:expr, $no_i18n:literal) => {
pub async fn get_translations_manager() -> impl $crate::TranslationsManager {
$crate::translations_manager::DummyTranslationsManager::new()
}
};
($locales:expr, $translations_manager:expr) => {
pub async fn get_translations_manager() -> impl $crate::TranslationsManager {
$translations_manager
}
};
// If the user doesn't want i18n but also sets their own transations manager, the latter takes priority
($locales:expr, $no_i18n:literal, $translations_manager:expr) => {
pub async fn get_translations_manager() -> impl $crate::TranslationsManager {
$translations_manager
}
};
}
/// An internal macro used for defining locales data. This is abstracted because it needs multiple branches.
#[doc(hidden)]
#[macro_export]
macro_rules! define_get_locales {
{
default: $default_locale:literal,
other: [$($other_locale:literal),*]
} => {
pub fn get_locales() -> $crate::Locales {
$crate::Locales {
default: $default_locale.to_string(),
other: vec![
$($other_locale.to_string()),*
],
using_i18n: true
}
}
};
// With i18n disabled, the default locale will be `xx-XX`
{
default: $default_locale:literal,
other: [$($other_locale:literal),*],
no_i18n: $no_i18n:literal
} => {
pub fn get_locales() -> $crate::Locales {
$crate::Locales {
default: "xx-XX".to_string(),
other: Vec::new(),
using_i18n: false
}
}
};
}
/// An internal macro for defining a function that gets the user's static content aliases (abstracted because it needs multiple
/// branches).
#[doc(hidden)]
#[macro_export]
macro_rules! define_get_static_aliases {
(
static_aliases: {
$($url:literal => $resource:literal)*
}
) => {
pub fn get_static_aliases() -> ::std::collections::HashMap<String, String> {
let mut static_aliases = ::std::collections::HashMap::new();
$(
let resource = $resource.to_string();
// We need to move this from being scoped to the app to being scoped for `.perseus/`
// TODO make sure this works properly on Windows
let resource = if resource.starts_with("/") {
// Absolute paths are a security risk and are disallowed
panic!("it's a security risk to include absolute paths in `static_aliases`");
} else if resource.starts_with("../") {
// Anything outside this directory is a security risk as well
panic!("it's a security risk to include paths outside the current directory in `static_aliases`");
} else if resource.starts_with("./") {
// `./` -> `../` (moving to execution from `.perseus/`)
// But if we're operating standalone, it stays the same
if ::std::env::var("PERSEUS_STANDALONE").is_ok() {
resource
} else {
format!(".{}", resource)
}
} else {
// Anything else gets a `../` prepended
// But if we're operating standalone, it stays the same
if ::std::env::var("PERSEUS_STANDALONE").is_ok() {
resource
} else {
format!("../{}", resource)
}
};
static_aliases.insert($url.to_string(), resource);
)*
static_aliases
}
};
() => {
pub fn get_static_aliases() -> ::std::collections::HashMap<String, String> {
::std::collections::HashMap::new()
}
};
}
/// Defines the components to create an entrypoint for the app. The actual entrypoint is created in the `.perseus/` crate (where we can
/// get all the dependencies without driving the user's `Cargo.toml` nuts). This also defines the template map. This is intended to make
/// compatibility with the Perseus CLI significantly easier.
///
/// Warning: all properties must currently be in the correct order (`root`, `templates`, `error_pages`, `locales`, `static_aliases`,
/// `dist_path`, `mutable_store`, `translations_manager`).
#[macro_export]
macro_rules! define_app {
// With locales
{
$(root: $root_selector:literal,)?
templates: [
$($template:expr),+
],
error_pages: $error_pages:expr,
// This deliberately enforces verbose i18n definition, and forces developers to consider i18n as integral
locales: {
default: $default_locale:literal,
// The user doesn't have to define any other locales
other: [$($other_locale:literal),*]
}
$(,static_aliases: {
$($url:literal => $resource:literal)*
})?
$(,dist_path: $dist_path:literal)?
$(,mutable_store: $mutable_store:expr)?
$(,translations_manager: $translations_manager:expr)?
} => {
$crate::define_app!(
@define_app,
{
$(root: $root_selector,)?
templates: [
$($template),+
],
error_pages: $error_pages,
locales: {
default: $default_locale,
// The user doesn't have to define any other locales (but they'll still get locale detection and the like)
other: [$($other_locale),*]
}
$(,static_aliases: {
$($url => $resource)*
})?
$(,dist_path: $dist_path)?
$(,mutable_store: $mutable_store)?
$(,translations_manager: $translations_manager)?
}
);
};
// Without locales (default locale is set to xx-XX)
{
$(root: $root_selector:literal,)?
templates: [
$($template:expr),+
],
error_pages: $error_pages:expr
$(,static_aliases: {
$($url:literal => $resource:literal)*
})?
$(,dist_path: $dist_path:literal)?
$(,mutable_store: $mutable_store:expr)?
} => {
$crate::define_app!(
@define_app,
{
$(root: $root_selector,)?
templates: [
$($template),+
],
error_pages: $error_pages,
// This deliberately enforces verbose i18n definition, and forces developers to consider i18n as integral
locales: {
default: "xx-XX",
other: [],
no_i18n: true
}
$(,static_aliases: {
$($url => $resource)*
})?
$(,dist_path: $dist_path)?
$(,mutable_store: $mutable_store)?
}
);
};
// This is internal, and allows syntax abstractions and defaults
(
@define_app,
{
$(root: $root_selector:literal,)?
templates: [
$($template:expr),+
],
error_pages: $error_pages:expr,
// This deliberately enforces verbose i18n definition, and forces developers to consider i18n as integral
locales: {
default: $default_locale:literal,
// The user doesn't have to define any other locales
other: [$($other_locale:literal),*]
// If this is defined at all, i18n will be disabled and the default locale will be set to `xx-XX`
$(,no_i18n: $no_i18n:literal)?
}
$(,static_aliases: {
$($url:literal => $resource:literal)*
})?
$(,dist_path: $dist_path:literal)?
$(,mutable_store: $mutable_store:expr)?
$(,translations_manager: $translations_manager:expr)?
}
) => {
/// The html `id` that will find the app root to render Perseus in. For server-side interpolation, this MUST be an element of
/// the form <div id="root_id">` in your markup (double or single quotes, `root_id` replaced by what this property is set to).
$crate::define_app_root!($($root_selector)?);
/// Gets the immutable store to use. This allows the user to conveniently change the path of distribution artifacts.
$crate::define_get_immutable_store!($($dist_path)?);
/// Gets the mutable store to use. This allows the user to conveniently substitute the default filesystem store for another
/// one in development and production.
$crate::define_get_mutable_store!($($mutable_store)?);
/// Gets the translations manager to use. This allows the user to conveniently test production managers in development. If
/// nothing is given, the filesystem will be used.
$crate::define_get_translations_manager!(get_locales() $(, $no_i18n)? $(, $translations_manager)?);
/// Defines the locales the app should build for, specifying defaults and common locales (which will be built at build-time
/// rather than on-demand).
$crate::define_get_locales! {
default: $default_locale,
other: [
$($other_locale),*
]
$(, no_i18n: $no_i18n)?
}
/// Gets a map of all the templates in the app by their root paths.
pub fn get_templates_map<G: $crate::GenericNode>() -> $crate::TemplateMap<G> {
$crate::get_templates_map![
$($template),+
]
}
/// Gets a list of all the templates in the app in the order the user provided them.
pub fn get_templates_vec<G: $crate::GenericNode>() -> Vec<$crate::Template<G>> {
vec![
$($template),+
]
}
/// Gets the error pages (done here so the user doesn't have to worry about naming).
pub fn get_error_pages<G: $crate::GenericNode>() -> $crate::ErrorPages<G> {
$error_pages
}
/// Gets any static content aliases provided by the user.
$crate::define_get_static_aliases!(
$(static_aliases: {
$($url => $resource)*
})?
);
};
}
|
use gfx;
use io::ndma;
fn make_data() -> [u32; 0x200] {
let mut data = [0u32; 0x200];
for (n, word) in data.iter_mut().enumerate() {
*word = (n as u32) * 0x100;
}
data
}
#[inline(never)]
fn test_memory_fill() {
let mut dst_data = make_data();
print!("Starting NDMA memory fill... ");
let src = ndma::NdmaSrc::FillData(0);
let dst = ndma::NdmaDst::LinearBuf(dst_data.as_mut_ptr(), dst_data.len());
ndma::mem_transfer(src, dst);
let ok = dst_data.iter().all(|word| *word == 0);
gfx::log(if ok { b"SUCCEEDED!\n" } else { b"FAILED!\n" });
}
#[inline(never)]
fn test_memory_copy() {
print!("Starting NDMA memory copy... ");
let src_data = make_data();
let mut dst_data = [0u32; 0x200];
let src = ndma::NdmaSrc::LinearBuf(src_data.as_ptr(), src_data.len());
let dst = ndma::NdmaDst::LinearBuf(dst_data.as_mut_ptr(), dst_data.len());
ndma::mem_transfer(src, dst);
let ok = src_data[..] == dst_data[..];
gfx::log(if ok { b"SUCCEEDED!\n" } else { b"FAILED!\n" });
}
#[inline(never)]
fn test_fixedsrc_copy() {
print!("Starting NDMA memory copy (fixed-src)... ");
let src_data = 0xF000BAAA;
let mut dst_data = [0u32; 0x200];
let src = ndma::NdmaSrc::FixedAddr(&src_data);
let dst = ndma::NdmaDst::LinearBuf(dst_data.as_mut_ptr(), dst_data.len());
ndma::mem_transfer(src, dst);
let ok = dst_data.iter().all(|word| *word == src_data);
gfx::log(if ok { b"SUCCEEDED!\n" } else { b"FAILED!\n" });
}
#[inline(never)]
fn test_random_copy() {
// Shows that NDMA actually loads from memory with each store
print!("Starting NDMA memory copy (rand-src)... ");
let mut dst_data = [0u32; 0x500];
let src = ndma::NdmaSrc::FixedAddr(0x10011000 as *const u32);
let dst = ndma::NdmaDst::LinearBuf(dst_data.as_mut_ptr(), dst_data.len());
ndma::mem_transfer(src, dst);
let avg: u32 = dst_data.iter().map(|x| x / (dst_data.len() as u32)).sum();
// Ideally, distribution is even and has range 0 to FFFFFFFF
let within_mean_range = |x| x > 0x78000000 && x < 0x88000000;
let ok = within_mean_range(avg) && !dst_data.iter().cloned().all(within_mean_range);
gfx::log(if ok { b"SUCCEEDED!\n" } else { b"FAILED!\n" });
}
pub fn main() {
gfx::clear_screen(0xFF, 0xFF, 0xFF);
test_memory_fill();
test_memory_copy();
test_fixedsrc_copy();
test_random_copy();
}
|
use crate::has_attr_key;
use proc_macro as pm;
use proc_macro2 as pm2;
// use quote::quote;
use quote::quote;
use std::collections::HashMap;
use syn::visit_mut::VisitMut;
pub(crate) fn rewrite(_attr: syn::AttributeArgs, mut item: syn::ItemFn) -> pm::TokenStream {
item.sig.generics.params.iter_mut().for_each(|p| {
if let syn::GenericParam::Type(ref mut p) = *p {
p.bounds.push(syn::parse_quote!(Sharable));
}
});
use crate::new_id;
Visitor::default().visit_item_fn_mut(&mut item);
let (ids, tys): (Vec<_>, Vec<_>) = item
.sig
.inputs
.iter()
.map(|x| match x {
syn::FnArg::Receiver(_) => unreachable!(),
syn::FnArg::Typed(t) => (&t.pat, &t.ty),
})
.unzip();
let id = new_id(format!("_{}", item.sig.ident));
let mut wrapper_item = item.clone();
if wrapper_item.sig.asyncness.is_some() {
wrapper_item.block = syn::parse_quote!({ #id(#(#ids,)* ctx).await });
} else {
wrapper_item.block = syn::parse_quote!({ #id(#(#ids,)* ctx) });
}
wrapper_item.sig.inputs = syn::parse_quote!((#(#ids,)*) : (#(#tys,)*), ctx: Context);
item.sig.ident = id;
item.sig.inputs.push(syn::parse_quote!(ctx: Context));
quote::quote!(
#wrapper_item
#item
)
.into()
}
pub(crate) struct Visitor {
scopes: Vec<HashMap<syn::Ident, MemKind>>,
}
impl Default for Visitor {
fn default() -> Self {
Self {
scopes: vec![HashMap::new()],
}
}
}
#[derive(Debug, Clone, Copy)]
enum MemKind {
Heap,
Stack,
}
impl VisitMut for Visitor {
// Every function call must pass an implicit context parameter
fn visit_expr_call_mut(&mut self, i: &mut syn::ExprCall) {
i.args.push(syn::parse_quote!(ctx));
syn::visit_mut::visit_expr_call_mut(self, i);
}
fn visit_pat_ident_mut(&mut self, i: &mut syn::PatIdent) {
let kind = MemKind::Heap;
self.scopes
.last_mut()
.map(|s| s.insert(i.ident.clone(), kind))
.unwrap();
}
fn visit_pat_type_mut(&mut self, i: &mut syn::PatType) {
let kind = if is_primitive(&i.ty) {
MemKind::Stack
} else {
MemKind::Heap
};
let last = self.scopes.last_mut().unwrap();
match i.pat.as_ref() {
syn::Pat::Ident(p) => {
last.insert(p.ident.clone(), kind);
}
syn::Pat::Tuple(p) => {
for p in p.elems.iter() {
match p {
syn::Pat::Ident(p) => {
last.insert(p.ident.clone(), kind);
}
_ => panic!("Expected id- or tuple-id pattern, got {}", quote!(#i)),
}
}
}
_ => panic!("Expected id- or tuple-id pattern, got {}", quote!(#i)),
}
}
fn visit_block_mut(&mut self, i: &mut syn::Block) {
self.scopes.push(HashMap::new());
syn::visit_mut::visit_block_mut(self, i);
self.scopes.pop();
}
fn visit_expr_assign_mut(&mut self, i: &mut syn::ExprAssign) {
syn::visit_mut::visit_expr_mut(self, &mut i.right);
}
fn visit_expr_mut(&mut self, i: &mut syn::Expr) {
syn::visit_mut::visit_expr_mut(self, i);
if let syn::Expr::Path(expr) = i {
if let Some(ident) = get_path_ident(&expr.path) {
if let Some(MemKind::Heap) = self.scopes.iter().rev().find_map(|s| s.get(&ident)) {
*i = syn::parse_quote!(#ident.clone())
}
}
}
}
fn visit_expr_macro_mut(&mut self, i: &mut syn::ExprMacro) {
syn::visit_mut::visit_expr_macro_mut(self, i);
i.mac.tokens = self.visit_token_stream(i.mac.tokens.clone());
}
// Visit expr before pattern
fn visit_local_mut(&mut self, i: &mut syn::Local) {
if let Some(it) = &mut i.init {
self.visit_expr_mut(&mut *(it).1);
}
self.visit_pat_mut(&mut i.pat);
}
// Every let binding must use the context parameter for allocation
fn visit_stmt_mut(&mut self, i: &mut syn::Stmt) {
syn::visit_mut::visit_stmt_mut(self, i);
if let syn::Stmt::Local(l) = i {
if has_attr_key("alloc", &l.attrs) {
let expr = &l.init.as_ref().unwrap().1;
match &l.pat {
syn::Pat::Ident(pat) => {
*i = syn::parse_quote!(letroot!(#pat = ctx.mutator().shadow_stack(), #expr););
}
syn::Pat::Type(pat) => {
if !is_primitive(&*pat.ty) {
*i = syn::parse_quote!(letroot!(#pat = ctx.mutator().shadow_stack(), #expr););
}
}
_ => todo!(),
}
}
}
}
}
fn is_primitive(t: &syn::Type) -> bool {
match t {
syn::Type::Path(p) => [
"i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f32", "f64", "unit",
]
.contains(&p.path.segments.last().unwrap().ident.to_string().as_str()),
syn::Type::Reference(tr) => match &*tr.elem {
syn::Type::Path(p) => {
["str"].contains(&p.path.segments.last().unwrap().ident.to_string().as_str())
}
_ => false,
},
_ => false,
}
}
fn get_path_ident(p: &syn::Path) -> Option<syn::Ident> {
if p.segments.len() == 1 {
Some(p.segments[0].ident.clone())
} else {
None
}
}
impl Visitor {
fn visit_token_stream(&mut self, tokens: pm2::TokenStream) -> pm2::TokenStream {
let mut result = pm2::TokenStream::new();
for token in tokens {
let token = match &token {
pm2::TokenTree::Group(g) => {
let stream = self.visit_token_stream(g.stream());
let delim = g.delimiter();
pm2::Group::new(delim, stream).into()
}
pm2::TokenTree::Punct(_) => token,
pm2::TokenTree::Ident(i) => {
if let Some(MemKind::Heap) = self.scopes.iter().rev().find_map(|s| s.get(&i)) {
result.extend(quote::quote!((#i.clone())));
continue;
}
token
}
pm2::TokenTree::Literal(_) => token,
};
result.extend([token]);
}
result
}
}
|
#[doc = "Register `APB4FZ1` reader"]
pub type R = crate::R<APB4FZ1_SPEC>;
#[doc = "Register `APB4FZ1` writer"]
pub type W = crate::W<APB4FZ1_SPEC>;
#[doc = "Field `DBG_I2C4` reader - I2C4 SMBUS timeout stop in debug"]
pub type DBG_I2C4_R = crate::BitReader;
#[doc = "Field `DBG_I2C4` writer - I2C4 SMBUS timeout stop in debug"]
pub type DBG_I2C4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DBG_LPTIM2` reader - LPTIM2 stop in debug"]
pub type DBG_LPTIM2_R = crate::BitReader;
#[doc = "Field `DBG_LPTIM2` writer - LPTIM2 stop in debug"]
pub type DBG_LPTIM2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DBG_LPTIM3` reader - LPTIM2 stop in debug"]
pub type DBG_LPTIM3_R = crate::BitReader;
#[doc = "Field `DBG_LPTIM3` writer - LPTIM2 stop in debug"]
pub type DBG_LPTIM3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DBG_LPTIM4` reader - LPTIM4 stop in debug"]
pub type DBG_LPTIM4_R = crate::BitReader;
#[doc = "Field `DBG_LPTIM4` writer - LPTIM4 stop in debug"]
pub type DBG_LPTIM4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DBG_LPTIM5` reader - LPTIM5 stop in debug"]
pub type DBG_LPTIM5_R = crate::BitReader;
#[doc = "Field `DBG_LPTIM5` writer - LPTIM5 stop in debug"]
pub type DBG_LPTIM5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DBG_RTC` reader - RTC stop in debug"]
pub type DBG_RTC_R = crate::BitReader;
#[doc = "Field `DBG_RTC` writer - RTC stop in debug"]
pub type DBG_RTC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DBG_WDGLSD1` reader - Independent watchdog for D1 stop in debug"]
pub type DBG_WDGLSD1_R = crate::BitReader;
#[doc = "Field `DBG_WDGLSD1` writer - Independent watchdog for D1 stop in debug"]
pub type DBG_WDGLSD1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 7 - I2C4 SMBUS timeout stop in debug"]
#[inline(always)]
pub fn dbg_i2c4(&self) -> DBG_I2C4_R {
DBG_I2C4_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 9 - LPTIM2 stop in debug"]
#[inline(always)]
pub fn dbg_lptim2(&self) -> DBG_LPTIM2_R {
DBG_LPTIM2_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - LPTIM2 stop in debug"]
#[inline(always)]
pub fn dbg_lptim3(&self) -> DBG_LPTIM3_R {
DBG_LPTIM3_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - LPTIM4 stop in debug"]
#[inline(always)]
pub fn dbg_lptim4(&self) -> DBG_LPTIM4_R {
DBG_LPTIM4_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - LPTIM5 stop in debug"]
#[inline(always)]
pub fn dbg_lptim5(&self) -> DBG_LPTIM5_R {
DBG_LPTIM5_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 16 - RTC stop in debug"]
#[inline(always)]
pub fn dbg_rtc(&self) -> DBG_RTC_R {
DBG_RTC_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 18 - Independent watchdog for D1 stop in debug"]
#[inline(always)]
pub fn dbg_wdglsd1(&self) -> DBG_WDGLSD1_R {
DBG_WDGLSD1_R::new(((self.bits >> 18) & 1) != 0)
}
}
impl W {
#[doc = "Bit 7 - I2C4 SMBUS timeout stop in debug"]
#[inline(always)]
#[must_use]
pub fn dbg_i2c4(&mut self) -> DBG_I2C4_W<APB4FZ1_SPEC, 7> {
DBG_I2C4_W::new(self)
}
#[doc = "Bit 9 - LPTIM2 stop in debug"]
#[inline(always)]
#[must_use]
pub fn dbg_lptim2(&mut self) -> DBG_LPTIM2_W<APB4FZ1_SPEC, 9> {
DBG_LPTIM2_W::new(self)
}
#[doc = "Bit 10 - LPTIM2 stop in debug"]
#[inline(always)]
#[must_use]
pub fn dbg_lptim3(&mut self) -> DBG_LPTIM3_W<APB4FZ1_SPEC, 10> {
DBG_LPTIM3_W::new(self)
}
#[doc = "Bit 11 - LPTIM4 stop in debug"]
#[inline(always)]
#[must_use]
pub fn dbg_lptim4(&mut self) -> DBG_LPTIM4_W<APB4FZ1_SPEC, 11> {
DBG_LPTIM4_W::new(self)
}
#[doc = "Bit 12 - LPTIM5 stop in debug"]
#[inline(always)]
#[must_use]
pub fn dbg_lptim5(&mut self) -> DBG_LPTIM5_W<APB4FZ1_SPEC, 12> {
DBG_LPTIM5_W::new(self)
}
#[doc = "Bit 16 - RTC stop in debug"]
#[inline(always)]
#[must_use]
pub fn dbg_rtc(&mut self) -> DBG_RTC_W<APB4FZ1_SPEC, 16> {
DBG_RTC_W::new(self)
}
#[doc = "Bit 18 - Independent watchdog for D1 stop in debug"]
#[inline(always)]
#[must_use]
pub fn dbg_wdglsd1(&mut self) -> DBG_WDGLSD1_W<APB4FZ1_SPEC, 18> {
DBG_WDGLSD1_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "DBGMCU APB4 peripheral freeze register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb4fz1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb4fz1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB4FZ1_SPEC;
impl crate::RegisterSpec for APB4FZ1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb4fz1::R`](R) reader structure"]
impl crate::Readable for APB4FZ1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb4fz1::W`](W) writer structure"]
impl crate::Writable for APB4FZ1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB4FZ1 to value 0"]
impl crate::Resettable for APB4FZ1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Components for integrating GraphQL endpoints into Tsukuyomi.
#![doc(html_root_url = "https://docs.rs/tsukuyomi-juniper/0.4.0-dev")]
#![deny(
missing_docs,
missing_debug_implementations,
nonstandard_style,
rust_2018_idioms,
rust_2018_compatibility,
unused
)]
#![forbid(clippy::unimplemented)]
mod error;
mod graphiql;
mod request;
pub use crate::{
error::{capture_errors, CaptureErrors},
graphiql::graphiql_source,
request::{request, GraphQLRequest, GraphQLResponse},
};
use {
juniper::{DefaultScalarValue, GraphQLType, RootNode, ScalarRefValue, ScalarValue},
std::sync::Arc,
};
/// A marker trait representing a root node of GraphQL schema.
#[allow(missing_docs)]
pub trait Schema<S = DefaultScalarValue>
where
S: ScalarValue,
for<'a> &'a S: ScalarRefValue<'a>,
{
type Query: GraphQLType<S, Context = Self::Context, TypeInfo = Self::QueryInfo>;
type QueryInfo;
type Mutation: GraphQLType<S, Context = Self::Context, TypeInfo = Self::MutationInfo>;
type MutationInfo;
type Context;
fn as_root_node(&self) -> &RootNode<'static, Self::Query, Self::Mutation, S>;
}
impl<QueryT, MutationT, CtxT, S> Schema<S> for RootNode<'static, QueryT, MutationT, S>
where
QueryT: GraphQLType<S, Context = CtxT>,
MutationT: GraphQLType<S, Context = CtxT>,
S: ScalarValue,
for<'a> &'a S: ScalarRefValue<'a>,
{
type Query = QueryT;
type QueryInfo = QueryT::TypeInfo;
type Mutation = MutationT;
type MutationInfo = MutationT::TypeInfo;
type Context = CtxT;
#[inline]
fn as_root_node(&self) -> &RootNode<'static, Self::Query, Self::Mutation, S> {
self
}
}
impl<T, S> Schema<S> for Box<T>
where
T: Schema<S>,
S: ScalarValue,
for<'a> &'a S: ScalarRefValue<'a>,
{
type Query = T::Query;
type QueryInfo = T::QueryInfo;
type Mutation = T::Mutation;
type MutationInfo = T::MutationInfo;
type Context = T::Context;
#[inline]
fn as_root_node(&self) -> &RootNode<'static, Self::Query, Self::Mutation, S> {
(**self).as_root_node()
}
}
impl<T, S> Schema<S> for Arc<T>
where
T: Schema<S>,
S: ScalarValue,
for<'a> &'a S: ScalarRefValue<'a>,
{
type Query = T::Query;
type QueryInfo = T::QueryInfo;
type Mutation = T::Mutation;
type MutationInfo = T::MutationInfo;
type Context = T::Context;
#[inline]
fn as_root_node(&self) -> &RootNode<'static, Self::Query, Self::Mutation, S> {
(**self).as_root_node()
}
}
|
use crate::convert::{AsGlsl, Glsl, GlslLine};
use std::convert::{TryFrom, TryInto};
use syn::spanned::Spanned;
use syn::{Error, Local, Pat, Result};
use crate::yasl_expr::YaslExprLineScope;
use crate::yasl_ident::YaslIdent;
use crate::yasl_type::YaslType;
#[derive(Debug)]
pub struct YaslLocal {
ident: YaslIdent,
ty: YaslType,
init: Option<YaslExprLineScope>,
}
impl AsGlsl for YaslLocal {
fn as_glsl(&self) -> Glsl {
let init_glsl = if let Some(i) = &self.init {
let mut init_glsl = String::new();
init_glsl += "= ";
init_glsl += &i.as_glsl().to_string();
init_glsl
} else {
String::new()
};
Glsl::Line(GlslLine {
span: Some(self.ident.span()),
ends_with_semi: true,
glsl_string: format!(
"{} {} {}",
self.ty.as_glsl(),
self.ident.to_string(),
init_glsl
),
})
}
}
impl TryFrom<Local> for YaslLocal {
type Error = Error;
fn try_from(l: Local) -> Result<Self> {
let (ident, ty) = if let Pat::Type(t) = l.pat {
let ident = t.clone().try_into()?;
let ty = (*t.ty).try_into()?;
(ident, ty)
} else {
return Err(Error::new(l.pat.span(), "Expected Type"));
};
let init = if let Some((_eq, expr)) = l.init {
let expr: YaslExprLineScope = (*expr).try_into()?;
Some(expr)
} else {
None
};
Ok(Self { ty, ident, init })
}
}
|
use crate::day9::{intcode_computer, parse_program};
#[aoc_generator(day21)]
fn day21_gen(input: &str) -> Vec<i64> {
parse_program(input)
}
#[aoc(day21, part1)]
fn solve_p1(tape: &[i64]) -> i64 {
// if A is a hole, jump
// if A and B are holes, jump,
// if A B and C are holes, jump
// if D is a hole, DO NOT JUMP
let program = &"
NOT A J
NOT B T
OR T J
NOT C T
OR T J
AND D J
WALK
"[1..];
test_program(tape, program).unwrap()
}
#[aoc(day21, part2)]
fn solve_p2(tape: &[i64]) -> i64 {
// If !A, Jump ---- no matter what, otherwise, you will die.
// If !B, Jump if D and !E
// If !C, Jump if D and !F
// !A || (!B && !E && D) || (!C && D && !F)
// !A || !(B || E) && D || !(C || F) && D
// !A || !(B || E) && D
// !((B || E) || !Q)
let program = &"
NOT A J
NOT B T
AND A T
AND C T
OR T J
NOT C T
AND H T
OR T J
AND D J
RUN
"[1..];
test_program(tape, program).unwrap()
}
fn test_program(tape: &[i64], program: &str) -> Option<i64> {
let mut program_feed = program.bytes();
let mut tape = tape.to_owned();
let mut i = 0;
let mut rb = 0;
loop {
let result = intcode_computer(&mut tape, &mut i, &mut rb, || {
program_feed.next().unwrap() as i64
});
if result == -1 {
return None;
}
if result > 127 {
return Some(result);
}
print!("{}", result as u8 as char);
}
}
|
#[doc = "Register `CCMR1` reader"]
pub type R = crate::R<CCMR1_SPEC>;
#[doc = "Register `CCMR1` writer"]
pub type W = crate::W<CCMR1_SPEC>;
#[doc = "Field `CC1SEL` reader - Capture/compare 1 selection This bitfield defines the direction of the channel input (capture) or output mode."]
pub type CC1SEL_R = crate::BitReader;
#[doc = "Field `CC1SEL` writer - Capture/compare 1 selection This bitfield defines the direction of the channel input (capture) or output mode."]
pub type CC1SEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC1E` reader - Capture/compare 1 output enable. This bit determines if a capture of the counter value can actually be done into the input capture/compare register 1 (LPTIM_CCR1) or not."]
pub type CC1E_R = crate::BitReader;
#[doc = "Field `CC1E` writer - Capture/compare 1 output enable. This bit determines if a capture of the counter value can actually be done into the input capture/compare register 1 (LPTIM_CCR1) or not."]
pub type CC1E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC1P` reader - Capture/compare 1 output polarity. Only bit2 is used to set polarity when output mode is enabled, bit3 is don't care. This field is used to select the IC1 polarity for capture operations."]
pub type CC1P_R = crate::FieldReader;
#[doc = "Field `CC1P` writer - Capture/compare 1 output polarity. Only bit2 is used to set polarity when output mode is enabled, bit3 is don't care. This field is used to select the IC1 polarity for capture operations."]
pub type CC1P_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `IC1PSC` reader - Input capture 1 prescaler This bitfield defines the ratio of the prescaler acting on the CC1 input (IC1)."]
pub type IC1PSC_R = crate::FieldReader;
#[doc = "Field `IC1PSC` writer - Input capture 1 prescaler This bitfield defines the ratio of the prescaler acting on the CC1 input (IC1)."]
pub type IC1PSC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `IC1F` reader - Input capture 1 filter This bitfield defines the number of consecutive equal samples that should be detected when a level change occurs on an external input capture signal before it is considered as a valid level transition. An internal clock source must be present to use this feature."]
pub type IC1F_R = crate::FieldReader;
#[doc = "Field `IC1F` writer - Input capture 1 filter This bitfield defines the number of consecutive equal samples that should be detected when a level change occurs on an external input capture signal before it is considered as a valid level transition. An internal clock source must be present to use this feature."]
pub type IC1F_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `CC2SEL` reader - Capture/compare 2 selection This bitfield defines the direction of the channel, input (capture) or output mode."]
pub type CC2SEL_R = crate::BitReader;
#[doc = "Field `CC2SEL` writer - Capture/compare 2 selection This bitfield defines the direction of the channel, input (capture) or output mode."]
pub type CC2SEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC2E` reader - Capture/compare 2 output enable. This bit determines if a capture of the counter value can actually be done into the input capture/compare register 2 (LPTIM_CCR2) or not."]
pub type CC2E_R = crate::BitReader;
#[doc = "Field `CC2E` writer - Capture/compare 2 output enable. This bit determines if a capture of the counter value can actually be done into the input capture/compare register 2 (LPTIM_CCR2) or not."]
pub type CC2E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC2P` reader - Capture/compare 2 output polarity. Only bit2 is used to set polarity when output mode is enabled, bit3 is don't care. This field is used to select the IC2 polarity for capture operations."]
pub type CC2P_R = crate::FieldReader;
#[doc = "Field `CC2P` writer - Capture/compare 2 output polarity. Only bit2 is used to set polarity when output mode is enabled, bit3 is don't care. This field is used to select the IC2 polarity for capture operations."]
pub type CC2P_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `IC2PSC` reader - Input capture 2 prescaler This bitfield defines the ratio of the prescaler acting on the CC2 input (IC2)."]
pub type IC2PSC_R = crate::FieldReader;
#[doc = "Field `IC2PSC` writer - Input capture 2 prescaler This bitfield defines the ratio of the prescaler acting on the CC2 input (IC2)."]
pub type IC2PSC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `IC2F` reader - Input capture 2 filter This bitfield defines the number of consecutive equal samples that should be detected when a level change occurs on an external input capture signal before it is considered as a valid level transition. An internal clock source must be present to use this feature."]
pub type IC2F_R = crate::FieldReader;
#[doc = "Field `IC2F` writer - Input capture 2 filter This bitfield defines the number of consecutive equal samples that should be detected when a level change occurs on an external input capture signal before it is considered as a valid level transition. An internal clock source must be present to use this feature."]
pub type IC2F_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
impl R {
#[doc = "Bit 0 - Capture/compare 1 selection This bitfield defines the direction of the channel input (capture) or output mode."]
#[inline(always)]
pub fn cc1sel(&self) -> CC1SEL_R {
CC1SEL_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Capture/compare 1 output enable. This bit determines if a capture of the counter value can actually be done into the input capture/compare register 1 (LPTIM_CCR1) or not."]
#[inline(always)]
pub fn cc1e(&self) -> CC1E_R {
CC1E_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bits 2:3 - Capture/compare 1 output polarity. Only bit2 is used to set polarity when output mode is enabled, bit3 is don't care. This field is used to select the IC1 polarity for capture operations."]
#[inline(always)]
pub fn cc1p(&self) -> CC1P_R {
CC1P_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 8:9 - Input capture 1 prescaler This bitfield defines the ratio of the prescaler acting on the CC1 input (IC1)."]
#[inline(always)]
pub fn ic1psc(&self) -> IC1PSC_R {
IC1PSC_R::new(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 12:13 - Input capture 1 filter This bitfield defines the number of consecutive equal samples that should be detected when a level change occurs on an external input capture signal before it is considered as a valid level transition. An internal clock source must be present to use this feature."]
#[inline(always)]
pub fn ic1f(&self) -> IC1F_R {
IC1F_R::new(((self.bits >> 12) & 3) as u8)
}
#[doc = "Bit 16 - Capture/compare 2 selection This bitfield defines the direction of the channel, input (capture) or output mode."]
#[inline(always)]
pub fn cc2sel(&self) -> CC2SEL_R {
CC2SEL_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - Capture/compare 2 output enable. This bit determines if a capture of the counter value can actually be done into the input capture/compare register 2 (LPTIM_CCR2) or not."]
#[inline(always)]
pub fn cc2e(&self) -> CC2E_R {
CC2E_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bits 18:19 - Capture/compare 2 output polarity. Only bit2 is used to set polarity when output mode is enabled, bit3 is don't care. This field is used to select the IC2 polarity for capture operations."]
#[inline(always)]
pub fn cc2p(&self) -> CC2P_R {
CC2P_R::new(((self.bits >> 18) & 3) as u8)
}
#[doc = "Bits 24:25 - Input capture 2 prescaler This bitfield defines the ratio of the prescaler acting on the CC2 input (IC2)."]
#[inline(always)]
pub fn ic2psc(&self) -> IC2PSC_R {
IC2PSC_R::new(((self.bits >> 24) & 3) as u8)
}
#[doc = "Bits 28:29 - Input capture 2 filter This bitfield defines the number of consecutive equal samples that should be detected when a level change occurs on an external input capture signal before it is considered as a valid level transition. An internal clock source must be present to use this feature."]
#[inline(always)]
pub fn ic2f(&self) -> IC2F_R {
IC2F_R::new(((self.bits >> 28) & 3) as u8)
}
}
impl W {
#[doc = "Bit 0 - Capture/compare 1 selection This bitfield defines the direction of the channel input (capture) or output mode."]
#[inline(always)]
#[must_use]
pub fn cc1sel(&mut self) -> CC1SEL_W<CCMR1_SPEC, 0> {
CC1SEL_W::new(self)
}
#[doc = "Bit 1 - Capture/compare 1 output enable. This bit determines if a capture of the counter value can actually be done into the input capture/compare register 1 (LPTIM_CCR1) or not."]
#[inline(always)]
#[must_use]
pub fn cc1e(&mut self) -> CC1E_W<CCMR1_SPEC, 1> {
CC1E_W::new(self)
}
#[doc = "Bits 2:3 - Capture/compare 1 output polarity. Only bit2 is used to set polarity when output mode is enabled, bit3 is don't care. This field is used to select the IC1 polarity for capture operations."]
#[inline(always)]
#[must_use]
pub fn cc1p(&mut self) -> CC1P_W<CCMR1_SPEC, 2> {
CC1P_W::new(self)
}
#[doc = "Bits 8:9 - Input capture 1 prescaler This bitfield defines the ratio of the prescaler acting on the CC1 input (IC1)."]
#[inline(always)]
#[must_use]
pub fn ic1psc(&mut self) -> IC1PSC_W<CCMR1_SPEC, 8> {
IC1PSC_W::new(self)
}
#[doc = "Bits 12:13 - Input capture 1 filter This bitfield defines the number of consecutive equal samples that should be detected when a level change occurs on an external input capture signal before it is considered as a valid level transition. An internal clock source must be present to use this feature."]
#[inline(always)]
#[must_use]
pub fn ic1f(&mut self) -> IC1F_W<CCMR1_SPEC, 12> {
IC1F_W::new(self)
}
#[doc = "Bit 16 - Capture/compare 2 selection This bitfield defines the direction of the channel, input (capture) or output mode."]
#[inline(always)]
#[must_use]
pub fn cc2sel(&mut self) -> CC2SEL_W<CCMR1_SPEC, 16> {
CC2SEL_W::new(self)
}
#[doc = "Bit 17 - Capture/compare 2 output enable. This bit determines if a capture of the counter value can actually be done into the input capture/compare register 2 (LPTIM_CCR2) or not."]
#[inline(always)]
#[must_use]
pub fn cc2e(&mut self) -> CC2E_W<CCMR1_SPEC, 17> {
CC2E_W::new(self)
}
#[doc = "Bits 18:19 - Capture/compare 2 output polarity. Only bit2 is used to set polarity when output mode is enabled, bit3 is don't care. This field is used to select the IC2 polarity for capture operations."]
#[inline(always)]
#[must_use]
pub fn cc2p(&mut self) -> CC2P_W<CCMR1_SPEC, 18> {
CC2P_W::new(self)
}
#[doc = "Bits 24:25 - Input capture 2 prescaler This bitfield defines the ratio of the prescaler acting on the CC2 input (IC2)."]
#[inline(always)]
#[must_use]
pub fn ic2psc(&mut self) -> IC2PSC_W<CCMR1_SPEC, 24> {
IC2PSC_W::new(self)
}
#[doc = "Bits 28:29 - Input capture 2 filter This bitfield defines the number of consecutive equal samples that should be detected when a level change occurs on an external input capture signal before it is considered as a valid level transition. An internal clock source must be present to use this feature."]
#[inline(always)]
#[must_use]
pub fn ic2f(&mut self) -> IC2F_W<CCMR1_SPEC, 28> {
IC2F_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "LPTIM capture/compare mode register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccmr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccmr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CCMR1_SPEC;
impl crate::RegisterSpec for CCMR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ccmr1::R`](R) reader structure"]
impl crate::Readable for CCMR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ccmr1::W`](W) writer structure"]
impl crate::Writable for CCMR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CCMR1 to value 0"]
impl crate::Resettable for CCMR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use simple_error::bail;
use closure::closure;
use evmap;
use evmap::{ReadHandle, WriteHandle};
use std::error;
use std::io;
use std::io::BufRead;
use std::sync::mpsc;
use std::thread;
use crate::day;
pub type BoxResult<T> = Result<T, Box<dyn error::Error>>;
struct Intcode {
p: Vec<i64>,
base: i64,
}
impl Intcode {
fn new(p: &[i64]) -> Self { Self { p: p.to_vec(), base: 0 } }
fn op(&self, c: i64) -> i64 { c % 100 }
fn get(&mut self, a: usize) -> i64 {
// eprintln!("get {}", a);
if a >= self.p.len() { self.p.resize(a + 1, 0); }
self.p[a]
}
fn put(&mut self, a: usize, v: i64) {
// eprintln!("put @{} {}", a, v);
if a >= self.p.len() { self.p.resize(a + 1, 0); }
self.p[a] = v;
}
fn addr(&mut self, ip: usize, i: usize) -> usize {
let a = self.get(ip + i);
let v = match self.get(ip) / vec![100, 1000, 10000][i - 1] % 10 {
0 => a as usize,
2 => (a + self.base) as usize,
_ => 0, // XXX
};
v
}
fn val(&mut self, ip: usize, i: usize) -> i64 {
let a = self.get(ip + i);
let v = match self.get(ip) / vec![100, 1000, 10000][i - 1] % 10 {
1 => a,
_ => {
let addr = self.addr(ip, i);
self.get(addr)
},
};
// eprintln!("{} {} {} {} {} {}", ip, self.get(ip), i, a, self.base, v);
v
}
fn run(&mut self, sender: &mpsc::Sender<i64>, receiver: &mpsc::Receiver<i64>,
request: &mpsc::Sender<()>, ack: &mpsc::Receiver<()>) -> BoxResult<i64> {
let mut ip = 0;
let mut o = None;
while { let op = self.get(ip); self.op(op) != 99 } {
// eprintln!("{}: {} {} {} {}", ip, self.p[ip], self.p[ip + 1], self.p[ip + 2], self.p[ip + 3]);
match self.op(self.p[ip]) {
1 => {
let a = self.val(ip, 1);
let b = self.val( ip, 2);
let c = self.addr(ip, 3);
self.put(c, a + b);
ip += 4;
},
2 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2);
let c = self.addr(ip, 3);
self.put(c, a * b);
ip += 4;
},
3 => {
let a = self.addr(ip, 1);
// eprintln!(">recv {}", a);
request.send(())?;
self.put(a as usize, receiver.recv()?);
// eprintln!("<recv {}", self.get(a as usize));
ip += 2;
},
4 => {
let a = self.val(ip, 1);
o = Some(a);
// eprintln!(">send {}", a);
sender.send(a)?;
// eprintln!("<send");
ack.recv()?;
// eprintln!("<<send");
ip += 2;
},
5 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2) as usize;
ip = if a != 0 { b } else { ip + 3 };
},
6 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2) as usize;
ip = if a == 0 { b } else { ip + 3 };
},
7 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2);
let c = self.addr(ip, 3);
self.put(c, if a < b { 1 } else { 0 });
ip += 4;
},
8 => {
let a = self.val(ip, 1);
let b = self.val(ip, 2);
let c = self.addr(ip,3);
self.put(c, if a == b { 1 } else { 0 });
ip += 4;
},
9 => {
self.base += self.val(ip, 1);
// eprintln!("<base {}", self.base);
ip += 2;
}
_ => bail!("unknown opcode {}: {}", ip, self.op(self.p[ip])),
};
}
if o.is_none() { bail!("no output"); }
Ok(o.unwrap())
}
#[allow(dead_code)]
fn arg(&self, ip: usize, offset: usize) -> String {
let a = self.p[ip + offset].to_string();
match self.p[ip] / vec![100, 1000, 10000][offset - 1] % 10 {
0 => format!("@{}", a),
1 => a,
2 => format!("+{}", a),
_ => String::from(""), // XXX
}
}
#[allow(dead_code)]
fn disassemble(&self) {
let mut ip = 0;
while ip < self.p.len() {
match self.op(self.p[ip]) {
1 => {
println!("{}: add {} {} {}", ip, self.arg(ip, 1), self.arg(ip, 2), self.arg(ip, 3));
ip += 4;
},
2 => {
println!("{}: mul {} {} {}", ip, self.arg(ip, 1), self.arg(ip, 2), self.arg(ip, 3));
ip += 4;
},
3 => {
println!("{}: in {}", ip, self.arg(ip, 1));
ip += 2;
},
4 => {
println!("{}: out {}", ip, self.arg(ip, 1));
ip += 2;
},
5 => {
println!("{}: jnz {} {}", ip, self.arg(ip, 1), self.arg(ip, 2));
ip += 3;
},
6 => {
println!("{}: jz {} {}", ip, self.arg(ip, 1), self.arg(ip, 2));
ip += 3;
},
7 => {
println!("{}: testlt {} {} {}", ip, self.arg(ip, 1), self.arg(ip, 2), self.arg(ip, 3));
ip += 4;
},
8 => {
println!("{}: testeq {} {} {}", ip, self.arg(ip, 1), self.arg(ip, 2), self.arg(ip, 3));
ip += 4;
},
9 => {
println!("{}: base {}", ip, self.arg(ip, 1));
ip += 2;
},
99 => {
println!("{}: halt", ip);
ip += 1;
},
_ => {
println!("{}: data ({})", ip, self.p[ip]);
ip += 1;
},
};
}
}
}
pub struct Day19 {}
impl day::Day for Day19 {
fn tag(&self) -> &str { "19" }
fn part1(&self, input: &dyn Fn() -> Box<dyn io::Read>) {
let reader = io::BufReader::new(input());
let p = reader.split(b',')
.map(|v| String::from_utf8(v.unwrap()).unwrap())
.map(|s| s.trim_end().parse::<i64>().unwrap())
.collect::<Vec<_>>();
let (grid_r, mut grid_w) = evmap::new();
println!("{:?}", self.part1_impl(p, &grid_r, &mut grid_w));
}
fn part2(&self, input: &dyn Fn() -> Box<dyn io::Read>) {
let reader = io::BufReader::new(input());
let p = reader.split(b',')
.map(|v| String::from_utf8(v.unwrap()).unwrap())
.map(|s| s.trim_end().parse::<i64>().unwrap())
.collect::<Vec<_>>();
let (grid_r, mut grid_w) = evmap::new();
println!("{:?}", self.part2_impl(p, &grid_r, &mut grid_w));
}
}
impl Day19 {
fn part1_impl(self: &Self, p: Vec<i64>,
grid_r: &ReadHandle<(i64, i64), char>,
grid_w: &mut WriteHandle<(i64, i64), char>)
-> BoxResult<i64> {
let (input_sender, input_receiver) = mpsc::channel::<i64>();
let (output_sender, output_receiver) = mpsc::channel::<i64>();
let (request_sender, request_receiver) = mpsc::channel::<()>();
let (ack_sender, ack_receiver) = mpsc::channel::<()>();
let (start_sender, start_receiver) = mpsc::channel::<()>();
let _cpu = thread::spawn(move || {
while start_receiver.recv().is_ok() {
let mut ic = Intcode::new(&p.clone());
ic.run(&output_sender, &input_receiver, &request_sender, &ack_receiver)
.unwrap_or(0);
}
});
Ok((0..50).flat_map(|x|
(0..50).map(closure!(
ref start_sender, ref request_receiver, ref input_sender,
ref output_receiver, ref ack_sender
|y| {
start_sender.send(()).unwrap();
request_receiver.recv().unwrap();
input_sender.send(x).unwrap();
request_receiver.recv().unwrap();
input_sender.send(y).unwrap();
let o = output_receiver.recv().unwrap();
ack_sender.send(()).unwrap();
o
})))
.sum())
}
fn part2_impl(self: &Self, p: Vec<i64>,
grid_r: &ReadHandle<(i64, i64), i64>,
grid_w: &mut WriteHandle<(i64, i64), i64>)
-> BoxResult<i64> {
let (input_sender, input_receiver) = mpsc::channel::<i64>();
let (output_sender, output_receiver) = mpsc::channel::<i64>();
let (request_sender, request_receiver) = mpsc::channel::<()>();
let (ack_sender, ack_receiver) = mpsc::channel::<()>();
let (start_sender, start_receiver) = mpsc::channel::<()>();
let _cpu = thread::spawn(move || {
while start_receiver.recv().is_ok() {
let mut ic = Intcode::new(&p.clone());
ic.run(&output_sender, &input_receiver, &request_sender, &ack_receiver)
.unwrap_or(0);
}
});
let (mut x, mut y) = (2, 3);
let mut look_for_one = true;
let mut ox = -1;
loop {
start_sender.send(()).unwrap();
request_receiver.recv().unwrap();
input_sender.send(x).unwrap();
request_receiver.recv().unwrap();
input_sender.send(y).unwrap();
let o = output_receiver.recv().unwrap();
ack_sender.send(()).unwrap();
grid_w.update((x, y), o);
grid_w.refresh();
if x >= 99 && y >= 99 && o == 1 {
if grid_r.get_and(&(x - 99, y - 99), |c| { c[0] }) == Some(1)
&& grid_r.get_and(&(x - 99, y), |c| { c[0] }) == Some(1)
&& grid_r.get_and(&(x, y - 99), |c| { c[0] }) == Some(1) {
break;
};
};
if o == 0 {
if look_for_one {
x += 1;
} else {
x = ox;
y += 1;
look_for_one = true;
};
} else {
if look_for_one {
ox = x;
};
x += 1;
look_for_one = false;
};
};
Ok((x - 99) * 10000 + (y - 99))
}
}
#[cfg(test)]
mod tests {
// use super::*;
fn test1(s: &str, v: usize) {
// assert_eq!(Day19 {}.part1_impl(s), v);
}
#[test]
fn part1() {
test1("
..#..........
..#..........
#######...###
#.#...#...#.#
#############
..#...#...#..
..#####...^..", 76);
}
} |
/// Unwraps a successful result or returns the error, with the path included in
/// the error description.
macro_rules! try_with_path {
($x:expr, $y:expr) => {{
match $x {
Ok(r) => r,
Err(e) => {
return Err(io::Error::new(
e.kind(),
format!("{} ({})", $y.display(), e.description()),
))
}
}
}};
}
|
use std::fs::File;
use std::io::{BufRead, BufReader, Error};
fn calculate_trees_on_the_way(xpath: usize, ypath: usize, map: &Vec<Vec<char>>) -> usize {
let mut trees = 0;
let mut xpos = 0;
for y in (0..map.len()).step_by(ypath) {
println!("{:?}", map[y]);
println!("{}", map[y][xpos]);
if map[y][xpos] == '#' {
trees += 1;
}
xpos += xpath;
}
trees
}
fn main() -> Result<(), Error> {
let path = "input";
let mut map: Vec<Vec<char>> = Vec::new();
const NB_PATTERNS: usize = 73;
let mut solution_trees = Vec::new();
let input = File::open(path)?;
let buffered = BufReader::new(input);
// Parse
for line in buffered.lines() {
let mut horiz_char = Vec::new();
let s = line.unwrap();
// Add patterns to the right
for _ in 0..NB_PATTERNS {
for c in s.chars() {
horiz_char.push(c);
}
}
map.push(horiz_char.clone());
}
solution_trees.push(calculate_trees_on_the_way(1, 1, &map));
solution_trees.push(calculate_trees_on_the_way(3, 1, &map));
solution_trees.push(calculate_trees_on_the_way(5, 1, &map));
solution_trees.push(calculate_trees_on_the_way(7, 1, &map));
solution_trees.push(calculate_trees_on_the_way(1, 2, &map));
println!("Trees: {:?}", solution_trees);
let solution: usize = solution_trees.iter().fold(1, |acc, x| acc * x);
println!("Nb trees: {}", solution);
Ok(())
}
|
use crypto::buffer::{self, BufferResult, ReadBuffer, WriteBuffer};
use rand::Rng;
fn main() {
let (guessed, actual) = detect_mode(&generate_random_key());
if guessed {
println!("We guess ECB");
} else {
println!("We guess CBC");
}
if guessed == actual {
println!("We were correct");
} else {
println!("We were wrong");
}
}
fn detect_mode(key: &[u8]) -> (bool, bool) {
let plaintext = &[b'a'; 32];
let (actual_mode, cyphertext) = encryption_oracle(plaintext, &key);
(detect_ecb(&cyphertext), actual_mode)
}
fn detect_ecb(line: &[u8]) -> bool {
let mut chunks: Vec<_> = line.chunks(16).collect();
let initial_len = chunks.len();
chunks.sort();
chunks.dedup();
return chunks.len() < initial_len;
}
fn generate_random_key() -> [u8; 16] {
rand::thread_rng().gen()
}
fn encryption_oracle(input: &[u8], key: &[u8]) -> (bool, Vec<u8>) {
let mut rng = rand::thread_rng();
// add 5-10 random bytes before and after the plaintext
let prefix_len: u8 = rng.gen_range(5..=10);
let suffix_len: u8 = rng.gen_range(5..=10);
let mut message = vec![];
message.extend((0..prefix_len).map(|_| rng.gen::<u8>()));
message.extend(input.iter());
message.extend((0..suffix_len).map(|_| rng.gen::<u8>()));
// We want to return this to check our results
let ecb: bool = rng.gen();
let encryptor = if ecb == true {
crypto::aes::ecb_encryptor(
crypto::aes::KeySize::KeySize128,
key,
crypto::blockmodes::PkcsPadding,
)
} else {
let iv: [u8; 16] = rng.gen();
crypto::aes::cbc_encryptor(
crypto::aes::KeySize::KeySize128,
key,
&iv,
crypto::blockmodes::PkcsPadding,
)
};
(ecb, encrypt(input, encryptor))
}
fn encrypt(
plaintext: &[u8],
mut encryptor: Box<dyn crypto::symmetriccipher::Encryptor>,
) -> Vec<u8> {
let mut final_result = Vec::<u8>::new();
let mut input = buffer::RefReadBuffer::new(plaintext);
let mut buffer = [0; 4096];
let mut output = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = encryptor.encrypt(&mut input, &mut output, true).unwrap();
final_result.extend(
output
.take_read_buffer()
.take_remaining()
.iter()
.map(|&i| i),
);
if let BufferResult::BufferUnderflow = result {
break;
}
}
return final_result;
}
#[test]
fn test_detect_mode() {
let plaintext = &[b'a'; 32];
for _ in 0..1000 {
let (actual_mode, cyphertext) = encryption_oracle(plaintext, &generate_random_key());
if detect_ecb(&cyphertext) != actual_mode {
panic!("We were wrong")
}
}
}
|
pub mod v2;
mod ini;
mod md5;
mod client;
pub use self::v2::Manifest;
pub use self::md5::MD5;
pub use self::ini::{IniManifest, IniData};
|
use crate::{node::NodeId, OperatorId};
/// Trait that must be implemented by any operator.
pub trait Operator {
/// Implement this method if you want to take control of the execution loop of an
/// operator (e.g., pull messages from streams).
/// Note: No callbacks are invoked before the completion of this method.
fn run(&mut self) {}
/// Implement this method if you need to do clean-up before the operator completes.
/// An operator completes after it has received top watermark on all its read streams.
fn destroy(&mut self) {}
}
pub trait OperatorConfigT {
fn name(&self) -> Option<String>;
fn id(&self) -> OperatorId;
}
#[derive(Clone)]
pub struct OperatorConfig<T: Clone> {
pub name: Option<String>,
/// A unique identifier for every operator.
pub id: OperatorId,
pub arg: Option<T>,
pub flow_watermarks: bool,
pub node_id: NodeId,
}
impl<T: Clone> OperatorConfig<T> {
pub fn new() -> Self {
Self {
id: OperatorId::nil(),
name: None,
arg: None,
flow_watermarks: true,
node_id: 0,
}
}
pub fn name(&mut self, name: &str) -> &mut Self {
self.name = Some(name.to_string());
self
}
pub fn arg(&mut self, arg: T) -> &mut Self {
self.arg = Some(arg);
self
}
/// `flow_watermarks` is true by default.
pub fn flow_watermarks(&mut self, flow_watermarks: bool) -> &mut Self {
self.flow_watermarks = flow_watermarks;
self
}
/// `node_id` is 0 by default.
// TODO: replace this with scheduling constraints.
pub fn node(&mut self, node_id: NodeId) -> &mut Self {
self.node_id = node_id;
self
}
}
impl<T: Clone> OperatorConfigT for OperatorConfig<T> {
fn name(&self) -> Option<String> {
self.name.clone()
}
fn id(&self) -> OperatorId {
self.id
}
}
|
/// Provides copysign intrinsics that don't rely on nightly
use core::intrinsics::transmute;
#[cfg(target_endian = "little")]
pub fn copysignf32(x: f32, y: f32) -> f32 {
unsafe {
let sign = transmute::<f32, u32>(x) & (1 << 31);
let yi = (transmute::<f32, u32>(y) & ((1 << 31) - 1)) | sign;
transmute::<u32, f32>(yi)
}
}
#[cfg(target_endian = "little")]
pub fn copysignf64(x: f64, y: f64) -> f64 {
unsafe {
let sign = transmute::<f64, u64>(x) & (1 << 63);
let yi = (transmute::<f64, u64>(y) & ((1 << 63) - 1)) | sign;
transmute::<u64, f64>(yi)
}
}
mod tests {
use super::{copysignf32, copysignf64};
#[test]
fn test_copysignf32() {
assert_eq!(copysignf32(-1.0, 5.0), -5.0);
assert_eq!(copysignf32(1.0, -5.0), 5.0);
}
#[test]
fn test_copysignf64() {
assert_eq!(copysignf64(-1.0, 5.0), -5.0);
assert_eq!(copysignf64(1.0, -5.0), 5.0);
}
}
|
use std::error::Error;
use std::result::Result;
use tensorflow::ops;
use tensorflow::train::AdadeltaOptimizer;
use tensorflow::train::MinimizeOptions;
use tensorflow::train::Optimizer;
use tensorflow::Code;
use tensorflow::DataType;
use tensorflow::Output;
use tensorflow::Scope;
use tensorflow::Session;
use tensorflow::SessionOptions;
use tensorflow::SessionRunArgs;
use tensorflow::Shape;
use tensorflow::Status;
use tensorflow::Tensor;
use tensorflow::Variable;
// Helper for building a layer.
//
// `activation` is a function which takes a tensor and applies an activation
// function such as tanh.
//
// Returns variables created and the layer output.
fn layer<O1: Into<Output>>(
input: O1,
input_size: u64,
output_size: u64,
activation: &dyn Fn(Output, &mut Scope) -> Result<Output, Status>,
scope: &mut Scope,
) -> Result<(Vec<Variable>, Output), Status> {
let mut scope = scope.new_sub_scope("layer");
let scope = &mut scope;
let w_shape = ops::constant(&[input_size as i64, output_size as i64][..], scope)?;
let w = Variable::builder()
.initial_value(ops::random_normal(w_shape, scope)?)
.data_type(DataType::Float)
.shape(Shape::from(&[input_size, output_size][..]))
.build(&mut scope.with_op_name("w"))?;
let b = Variable::builder()
.const_initial_value(Tensor::<f32>::new(&[output_size]))
.build(&mut scope.with_op_name("b"))?;
Ok((
vec![w.clone(), b.clone()],
activation(
ops::add(
ops::mat_mul(input, w.output().clone(), scope)?,
b.output().clone(),
scope,
)?
.into(),
scope,
)?,
))
}
fn main() -> Result<(), Box<Error>> {
// ================
// Build the model.
// ================
let mut scope = Scope::new_root_scope();
let scope = &mut scope;
// Size of the hidden layer.
// This is far more than is necessary, but makes it train more reliably.
let hidden_size: u64 = 8;
let input = ops::Placeholder::new()
.data_type(DataType::Float)
.shape(Shape::from(&[1u64, 2][..]))
.build(&mut scope.with_op_name("input"))?;
let label = ops::Placeholder::new()
.data_type(DataType::Float)
.shape(Shape::from(&[1u64][..]))
.build(&mut scope.with_op_name("label"))?;
// Hidden layer.
let (vars1, layer1) = layer(
input.clone(),
2,
hidden_size,
&|x, scope| Ok(ops::tanh(x, scope)?.into()),
scope,
)?;
// Output layer.
let (vars2, layer2) = layer(layer1.clone(), hidden_size, 1, &|x, _| Ok(x), scope)?;
let error = ops::subtract(layer2.clone(), label.clone(), scope)?;
let error_squared = ops::multiply(error.clone(), error, scope)?;
let mut optimizer = AdadeltaOptimizer::new();
optimizer.set_learning_rate(ops::constant(1.0f32, scope)?);
let mut variables = Vec::new();
variables.extend(vars1);
variables.extend(vars2);
let (minimizer_vars, minimize) = optimizer.minimize(
scope,
error_squared.clone().into(),
MinimizeOptions::default().with_variables(&variables),
)?;
// =========================
// Initialize the variables.
// =========================
let options = SessionOptions::new();
let g = scope.graph_mut();
let session = Session::new(&options, &g)?;
let mut run_args = SessionRunArgs::new();
// Initialize variables we defined.
for var in &variables {
run_args.add_target(&var.initializer());
}
// Initialize variables the optimizer defined.
for var in &minimizer_vars {
run_args.add_target(&var.initializer());
}
session.run(&mut run_args)?;
// ================
// Train the model.
// ================
let mut input_tensor = Tensor::<f32>::new(&[1, 2]);
let mut label_tensor = Tensor::<f32>::new(&[1]);
// Helper that generates a training example from an integer, trains on that
// example, and returns the error.
let mut train = |i| -> Result<f32, Box<Error>> {
input_tensor[0] = (i & 1) as f32;
input_tensor[1] = ((i >> 1) & 1) as f32;
label_tensor[0] = ((i & 1) ^ ((i >> 1) & 1)) as f32;
let mut run_args = SessionRunArgs::new();
run_args.add_target(&minimize);
let error_squared_fetch = run_args.request_fetch(&error_squared, 0);
run_args.add_feed(&input, 0, &input_tensor);
run_args.add_feed(&label, 0, &label_tensor);
session.run(&mut run_args)?;
Ok(run_args.fetch::<f32>(error_squared_fetch)?[0])
};
for i in 0..10000 {
train(i)?;
}
// ===================
// Evaluate the model.
// ===================
for i in 0..4 {
let error = train(i)?;
println!("Error: {}", error);
if error > 0.1 {
return Err(Box::new(Status::new_set(
Code::Internal,
&format!("Error too high: {}", error),
)?));
}
}
Ok(())
}
|
fn main(){
let max = 0;
let primes = make_primes(1000).iter().rev();
for p in primes {
if max > p {
break;
} else {
max_primes = max_quadratic_primes(*p, &primes);
if max < max_primes {
max = max_primes;
}
}
}
println!("{}",max);
}
fn make_primes(upper: usize) -> Vec<usize>{
let mut list = (0..).take(upper).collect::<Vec<usize>>();
let mut primes = Vec::new();
list[1] = 0;
for i in 0..upper {
match list[i]{
0 => continue,
_ => {
for j in 2..((upper - 1) / i) + 1 {
list[i * j] = 0;
}
primes.push(i);
}
}
}
primes
}
fn is_prime(num: usize, primelist: &Vec<usize>) -> bool {
for p in primelist {
if num == *p {
return true;
}
}
false
}
fn max_quadratic_primes(num: usize, primelist: &Vec<usize>) -> usize {
let mut max = 0;
for a in 0..2 {
let sign = i * 2 - 1;
for coef in 0..1000 {
for i in 0.. {
let result = i * i + sign * (coef * i) as isize + num as isize;
if (result <= 1 || !is_prime(result, primelist)) && max < i {
max = i;
}
}
}
}
max
}
|
use crate::render::svg::*;
use svg::Node;
const DEFAULT_LABEL_VISIBLE: bool = true;
const DEFAULT_LABEL_POSITION: PointLabelPosition = PointLabelPosition::Top;
const DEFAULT_STROKE_WIDTH: &str = "2px";
const DEFAULT_X_LABEL_HORIZONTAL: i32 = 8;
const DEFAULT_X_LABEL_VERTICAL: i32 = 0;
const DEFAULT_X_LABEL_BETWEEN: i32 = 4;
const DEFAULT_Y_LABEL_HORIZONTAL: i32 = 0;
const DEFAULT_Y_LABEL_VERTICAL: i32 = 12;
const DEFAULT_Y_LABEL_BETWEEN: i32 = 8;
const DEFAULT_FONT_SIZE: &str = "14px";
const DEFAULT_POINT_VISIBLE: bool = true;
/// PointType contains available types of points.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub enum PointType {
Circle,
Square,
X,
}
/// PointLabelPosition contains available types of point label positions.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub enum PointLabelPosition {
Top,
TopRight,
TopLeft,
Left,
Right,
Bottom,
BottomLeft,
BottomRight,
}
/// Point represents a point shape.
#[derive(Clone)]
pub struct Point {
x: f32,
y: f32,
label_visible: bool,
label_position: PointLabelPosition,
point_visible: bool,
point_type: PointType,
size: i32,
x_label: String,
y_label: String,
fill_color: String,
stroke_color: String,
label_text_anchor: String,
label_x_attr: i32,
label_y_attr: i32,
}
impl Point {
/// Create a new Point.
pub fn new(
x: f32,
y: f32,
point_type: PointType,
size: i32,
y_label: &str,
fill_color: &str,
stroke_color: &str,
) -> Self {
Point {
x,
y,
point_visible: DEFAULT_POINT_VISIBLE,
point_type,
size,
x_label: String::new(),
y_label: y_label.to_string(),
fill_color: fill_color.to_string(),
stroke_color: stroke_color.to_string(),
label_visible: DEFAULT_LABEL_VISIBLE,
label_position: DEFAULT_LABEL_POSITION,
label_text_anchor: Self::label_text_anchor(DEFAULT_LABEL_POSITION),
label_x_attr: Self::label_x_attr(DEFAULT_LABEL_POSITION, size),
label_y_attr: Self::label_y_attr(DEFAULT_LABEL_POSITION, size),
}
}
/// Set point visibility.
pub fn set_point_visible(mut self, point_visible: bool) -> Self {
self.point_visible = point_visible;
self
}
/// Set custom x for label.
pub fn set_x_label(mut self, x_label: &str) -> Self {
self.x_label = x_label.to_string();
self
}
/// Set point visibility.
pub fn set_label_visible(mut self, label_visible: bool) -> Self {
self.label_visible = label_visible;
self
}
/// Set position for point label.
pub fn set_label_position(mut self, label_position: PointLabelPosition) -> Self {
self.label_position = label_position;
self.label_text_anchor = Self::label_text_anchor(label_position);
self.label_x_attr = Self::label_x_attr(label_position, self.size);
self.label_y_attr = Self::label_y_attr(label_position, self.size);
self
}
/// Get x value of a point.
pub fn x(&self) -> f32 {
self.x
}
/// Get y x value of a point.
pub fn y(&self) -> f32 {
self.y
}
fn label_text_anchor(label_position: PointLabelPosition) -> String {
match label_position {
PointLabelPosition::Top | PointLabelPosition::Bottom => TEXT_ANCHOR_MIDDLE.to_string(),
PointLabelPosition::TopRight
| PointLabelPosition::BottomRight
| PointLabelPosition::Right => TEXT_ANCHOR_START.to_string(),
PointLabelPosition::TopLeft
| PointLabelPosition::BottomLeft
| PointLabelPosition::Left => TEXT_ANCHOR_END.to_string(),
}
}
fn label_x_attr(label_position: PointLabelPosition, size: i32) -> i32 {
match label_position {
PointLabelPosition::Top | PointLabelPosition::Bottom => DEFAULT_X_LABEL_VERTICAL,
PointLabelPosition::TopRight | PointLabelPosition::BottomRight => {
size + DEFAULT_X_LABEL_BETWEEN
}
PointLabelPosition::Right => size + DEFAULT_X_LABEL_HORIZONTAL,
PointLabelPosition::TopLeft | PointLabelPosition::BottomLeft => {
-size - DEFAULT_X_LABEL_BETWEEN
}
PointLabelPosition::Left => -size - DEFAULT_X_LABEL_HORIZONTAL,
}
}
fn label_y_attr(label_position: PointLabelPosition, size: i32) -> i32 {
match label_position {
PointLabelPosition::Top => -size - DEFAULT_Y_LABEL_VERTICAL,
PointLabelPosition::TopRight | PointLabelPosition::TopLeft => {
-size - DEFAULT_Y_LABEL_BETWEEN
}
PointLabelPosition::Right | PointLabelPosition::Left => DEFAULT_Y_LABEL_HORIZONTAL,
PointLabelPosition::BottomRight | PointLabelPosition::BottomLeft => {
size + DEFAULT_Y_LABEL_BETWEEN
}
PointLabelPosition::Bottom => size + DEFAULT_Y_LABEL_VERTICAL,
}
}
/// Get point SVG representation.
pub fn to_svg(&self) -> svg::node::element::Group {
let mut res = svg::node::element::Group::new()
.set(TRANSFORM_ATTR, translate_x_y(self.x, self.y))
.set(CLASS_ATTR, CLASS_POINT);
// Draw point if needed.
if self.point_visible {
match self.point_type {
PointType::Circle => {
res.append(
svg::node::element::Circle::new()
.set(CX_ATTR, START)
.set(CY_ATTR, START)
.set(R_ATTR, self.size)
.set(FILL_ATTR, self.fill_color.as_ref())
.set(STROKE_ATTR, self.stroke_color.as_ref()),
);
}
PointType::Square => {
res.append(
svg::node::element::Rectangle::new()
.set(X_ATTR, -(self.size as i32))
.set(Y_ATTR, -(self.size as i32))
.set(WIDTH_ATTR, 2 * self.size)
.set(HEIGHT_ATTR, 2 * self.size)
.set(FILL_ATTR, self.fill_color.as_ref())
.set(STROKE_ATTR, self.stroke_color.as_ref()),
);
}
PointType::X => {
res.append(
svg::node::element::Group::new()
.add(
svg::node::element::Line::new()
.set(X1_ATTR, -(self.size as i32))
.set(Y1_ATTR, -(self.size as i32))
.set(X2_ATTR, self.size)
.set(Y2_ATTR, self.size)
.set(STROKE_WIDTH_ATTR, DEFAULT_STROKE_WIDTH)
.set(STROKE_ATTR, self.stroke_color.as_ref()),
)
.add(
svg::node::element::Line::new()
.set(X1_ATTR, self.size)
.set(Y1_ATTR, -(self.size as i32))
.set(X2_ATTR, -(self.size as i32))
.set(Y2_ATTR, self.size)
.set(STROKE_WIDTH_ATTR, DEFAULT_STROKE_WIDTH)
.set(STROKE_ATTR, self.stroke_color.as_ref()),
),
);
}
}
};
// Draw label if needed.
if self.label_visible {
let mut label: svg::node::element::Text;
// X label will be empty in case of Area or Line chart.
if self.x_label.is_empty() {
label = svg::node::element::Text::new()
.set(DY_ATTR, DEFAULT_DY)
.set(FONT_FAMILY_ATTR, DEFAULT_FONT_FAMILY)
.set(FILL_ATTR, DEFAULT_FONT_COLOR)
.set(FONT_SIZE_ATTR, DEFAULT_FONT_SIZE)
.add(svg::node::Text::new(self.y_label.to_string()));
} else {
label = svg::node::element::Text::new()
.set(DY_ATTR, DEFAULT_DY)
.set(FONT_FAMILY_ATTR, DEFAULT_FONT_FAMILY)
.set(FILL_ATTR, DEFAULT_FONT_COLOR)
.set(FONT_SIZE_ATTR, DEFAULT_FONT_SIZE)
.add(svg::node::Text::new(pair_x_y(&self.x_label, &self.y_label)));
}
label.assign(X_ATTR, self.label_x_attr);
label.assign(Y_ATTR, self.label_y_attr);
label.assign(TEXT_ANCHOR_ATTR, self.label_text_anchor.clone());
res.append(label);
}
res
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bar_basic() {
let expected_svg_group = r##"<g class="point" transform="translate(10,20)">
<circle cx="0" cy="0" fill="#f289ff" r="21" stroke="#8a87f6"/>
<text dy=".35em" fill="#080808" font-family="sans-serif" font-size="14px" text-anchor="end" x="-25" y="29">
thirty
</text>
</g>"##;
let point_svg = Point::new(
10_f32,
20_f32,
PointType::Circle,
21,
"thirty",
"#f289ff",
"#8a87f6",
)
.set_label_position(PointLabelPosition::BottomLeft)
.to_svg();
assert_eq!(point_svg.to_string(), expected_svg_group);
}
}
|
pub mod ntru_prime;
pub use ntru_prime::*;
|
//! <div align="center">
//! <img alt="Rune Logo" src="https://raw.githubusercontent.com/rune-rs/rune/master/assets/icon.png" />
//! </div>
//!
//! <br>
//!
//! <div align="center">
//! <a href="https://rune-rs.github.io">
//! <b>Visit the site 🌐</b>
//! </a>
//! -
//! <a href="https://rune-rs.github.io/book/">
//! <b>Read the book 📖</b>
//! </a>
//! </div>
//!
//! <br>
//!
//! <div align="center">
//! <a href="https://github.com/rune-rs/rune/actions">
//! <img alt="Build Status" src="https://github.com/rune-rs/rune/workflows/Build/badge.svg">
//! </a>
//!
//! <a href="https://github.com/rune-rs/rune/actions">
//! <img alt="Site Status" src="https://github.com/rune-rs/rune/workflows/Site/badge.svg">
//! </a>
//!
//! <a href="https://crates.io/crates/rune">
//! <img alt="crates.io" src="https://img.shields.io/crates/v/rune.svg">
//! </a>
//!
//! <a href="https://docs.rs/rune">
//! <img alt="docs.rs" src="https://docs.rs/rune/badge.svg">
//! </a>
//!
//! <a href="https://discord.gg/v5AeNkT">
//! <img alt="Chat on Discord" src="https://img.shields.io/discord/558644981137670144.svg?logo=discord&style=flat-square">
//! </a>
//! </div>
//!
//! <br>
//!
//! Macros for Rune.
//!
//! This is part of the [Rune language].
//! [Rune Language]: https://rune-rs.github.io
extern crate proc_macro;
use quote::quote;
mod context;
mod internals;
mod option_spanned;
mod parse;
mod spanned;
mod to_tokens;
/// Helper derive to implement `ToTokens`.
#[proc_macro_derive(ToTokens, attributes(rune))]
#[doc(hidden)]
pub fn to_tokens(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let derive = syn::parse_macro_input!(input as to_tokens::Derive);
derive.expand().unwrap_or_else(to_compile_errors).into()
}
/// Helper derive to implement `Parse`.
#[proc_macro_derive(Parse, attributes(rune))]
#[doc(hidden)]
pub fn parse(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let derive = syn::parse_macro_input!(input as parse::Derive);
derive.expand().unwrap_or_else(to_compile_errors).into()
}
/// Helper derive to implement `Spanned`.
#[proc_macro_derive(Spanned, attributes(rune))]
#[doc(hidden)]
pub fn spanned(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let derive = syn::parse_macro_input!(input as spanned::Derive);
derive.expand().unwrap_or_else(to_compile_errors).into()
}
/// Helper derive to implement `OptionSpanned`.
#[proc_macro_derive(OptionSpanned, attributes(rune))]
#[doc(hidden)]
pub fn option_spanned(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let derive = syn::parse_macro_input!(input as option_spanned::Derive);
derive.expand().unwrap_or_else(to_compile_errors).into()
}
fn to_compile_errors(errors: Vec<syn::Error>) -> proc_macro2::TokenStream {
let compile_errors = errors.iter().map(syn::Error::to_compile_error);
quote!(#(#compile_errors)*)
}
|
use wfc::{rels::get_2d_rels, util::generate_2d_positions, WaveFunctionCollapse};
fn main() {
let (width, height) = (50, 10);
let locs = generate_2d_positions(width, height);
let example = vec![
vec![0, 0, 0, 0],
vec![0, 0, 0, 0],
vec![0, 0, 0, 0],
vec![0, 0, 0, 0],
vec![0, 0, 0, 0],
vec![0, 0, 0, 0],
vec![0, 1, 1, 0],
vec![1, 2, 2, 1],
vec![2, 2, 2, 2],
vec![2, 2, 2, 2],
];
let relations = get_2d_rels(&example);
let mut wfc = WaveFunctionCollapse::new(locs, example.iter().flatten().copied(), relations);
while !wfc.is_fully_collapsed() {
match wfc.observe() {
Ok(()) => (),
Err(e) => {
println!("{:?}", e);
return;
},
}
}
let mut flat = wfc
.get_collapsed()
.unwrap()
.map(|v| v.1)
.collect::<Vec<_>>();
flat.sort_unstable();
(0..height).for_each(|y| {
(0..width).for_each(|x| {
print!("{} ", flat[(x * height + y) as usize]);
});
println!();
});
}
|
#![allow(non_snake_case)]
use std::collections::HashMap;
use std::path::Path;
use cgmath::{vec2, vec3};
use tobj;
use super::common::*;
use crate::mesh::{Mesh, Texture, Vertex};
pub struct Model {
pub meshes: Vec<Mesh>,
pub texturesLoaded: HashMap<String, Texture>,
directory: String,
}
impl Model {
pub fn new(path: &str) -> Model {
let mut model = Model { meshes: vec![], texturesLoaded: HashMap::default(), directory: String::default() };
model.loadModel(path);
model
}
fn loadModel(&mut self, path: &str) {
let path = Path::new(path);
self.directory = path.parent().unwrap_or_else(|| Path::new("")).to_str().unwrap().into();
let obj = tobj::load_obj(path);
let (models, materials) = obj.unwrap();
for model in models {
let mesh = &model.mesh;
let num_vertices = mesh.positions.len() / 3;
let mut vertices: Vec<Vertex> = Vec::with_capacity(num_vertices);
let indices: Vec<u32> = mesh.indices.clone();
let (p, n, t) = (&mesh.positions, &mesh.normals, &mesh.texcoords);
for i in 0..num_vertices {
vertices.push(Vertex {
Position: vec3(p[i*3], p[i*3+1], p[i*3+2]),
Normal: vec3(n[i * 3], n[i * 3 + 1], n[i * 3 + 2]),
TexCoords: vec2(t[i * 2], t[i * 2 + 1]),
..Vertex::default()
})
}
let mut textures = Vec::new();
if let Some(material_id) = mesh.material_id {
let material = &materials[material_id];
if !material.diffuse_texture.is_empty() {
let texture = self.loadMaterialTexture(&material.diffuse_texture, "texture_diffuse");
textures.push(texture);
}
if !material.specular_texture.is_empty() {
let texture = self.loadMaterialTexture(&material.specular_texture, "texture_specular");
textures.push(texture);
}
if !material.normal_texture.is_empty() {
let texture = self.loadMaterialTexture(&material.normal_texture, "texture_normal");
textures.push(texture);
}
}
self.meshes.push(Mesh::new(vertices, indices, textures));
}
}
fn loadMaterialTexture(&mut self, path: &str, typeName: &str) -> Texture {
{
let texOpt = self.texturesLoaded.get(path);
if let Some(tex) = texOpt {
return tex.clone();
}
}
let texture = Texture {
id: unsafe { textureFromFile(path, &self.directory) },
type_: typeName.into(),
path: path.into(),
};
self.texturesLoaded.insert(path.into(), texture.clone());
texture
}
}
|
use futures::prelude::*;
use state_machine_future::RentToOwn;
use std::cmp;
use std::io;
use std::marker::PhantomData;
use std::time::Duration;
use super::{encode, Connection, MAX_FRAGMENT_LEN, Packet, PacketData, recv_packet};
use tokio_core::reactor::Timeout;
pub struct SendReliable<T> where T: AsRef<[u8]> {
pub(crate) state: StateFuture<T>,
}
impl<T> Future for SendReliable<T> where T: AsRef<[u8]> {
type Item = (Connection, T);
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.state.poll().map_err(|(error, _)| error)
}
}
#[derive(StateMachineFuture)]
#[allow(dead_code)]
pub(crate) enum State<T> where T: AsRef<[u8]> {
#[state_machine_future(start, transitions(WaitingForAck))]
Sending {
connection: Connection,
buffer: T,
// The sequence number for the message being sent.
sequence_number: u32,
// Values tracking how many fragments need to be sent and how many have been sent so far.
num_fragments: u8,
fragment_number: u8,
// The duration for how long to wait for the ack, and a handle to the reactor so we can
// create the `Timeout` future after sending the message the first time.
timeout: Duration,
retry_interval: Duration,
},
#[state_machine_future(transitions(Resending, Ready))]
WaitingForAck {
connection: Connection,
buffer: T,
// The sequence number for the message being sent.
sequence_number: u32,
// Values tracking how many fragments need to be sent and how many have been sent so far.
num_fragments: u8,
timeout: Timeout,
retry_timeout: Timeout,
retry_interval: Duration,
},
#[state_machine_future(transitions(WaitingForAck, Ready))]
Resending {
connection: Connection,
buffer: T,
// The sequence number for the message being sent.
sequence_number: u32,
// Values tracking how many fragments need to be sent and how many have been sent so far.
num_fragments: u8,
fragment_number: u8,
timeout: Timeout,
retry_interval: Duration,
},
#[state_machine_future(ready)]
Ready((Connection, T)),
#[state_machine_future(error)]
// HACK: The error type should just be `io::Error`, but state_machine_future doesn't support
// having variants that don't reference all generic parameters.
Error((io::Error, PhantomData<T>)),
}
impl<T> PollState<T> for State<T> where T: AsRef<[u8]> {
fn poll_sending<'a>(
sending: &'a mut RentToOwn<'a, Sending<T>>,
) -> Poll<AfterSending<T>, (io::Error, PhantomData<T>)> {
// Keep sending fragments until we've sent them all or we would block.
loop {
let sending = &mut **sending;
let buffer = sending.buffer.as_ref();
let send_result = sending.connection.socket.send_to(
&sending.connection.send_buffer,
&sending.connection.peer_address,
);
let bytes_sent = match send_result {
Ok(bytes) => { bytes }
Err(error) => {
if error.kind() == io::ErrorKind::WouldBlock {
return Ok(Async::NotReady);
}
// HACK: We should be able to use `try_nb!` here, but since we need to bundle
// the error with some `PhantomData` we end up having to do this manually.
return Err((error, PhantomData));
}
};
// If we send a datagram that doesn't include all the bytes in the packet,
// then an error occurred.
if bytes_sent != sending.connection.send_buffer.len() {
return Err((
io::Error::new(
io::ErrorKind::Other,
"Failed to send all bytes of the fragment",
),
PhantomData
));
}
// If we've sent all the fragments of the message, then we're done sending
// the message.
if sending.fragment_number == sending.num_fragments { break; }
// Write the next fragment of the message.
let fragment_start = (sending.fragment_number) as usize * MAX_FRAGMENT_LEN;
let fragment_end = cmp::min(fragment_start + MAX_FRAGMENT_LEN, buffer.len());
let fragment = &buffer[fragment_start .. fragment_end];
encode(
Packet {
connection_id: sending.connection.connection_id,
data: PacketData::Message {
sequence_number: sending.sequence_number,
fragment,
num_fragments: sending.num_fragments,
fragment_number: sending.fragment_number,
},
},
&mut sending.connection.send_buffer,
).map_err(|error| (error, PhantomData))?;
// Update the current sequence number.
sending.fragment_number += 1;
}
// We've finished sending the message for the first time, so create the `WaitingForAck`
// state from the current state.
let Sending {
connection,
buffer,
sequence_number,
num_fragments,
timeout,
retry_interval,
..
} = sending.take();
// Create the timeout for waiting for the ack.
let timeout = Timeout::new(timeout, &connection.handle)
.map_err(|error| (error, PhantomData))?;
let retry_timeout = Timeout::new(retry_interval, &connection.handle)
.map_err(|error| (error, PhantomData))?;
// return the `WaitingForAck` state.
let waiting = WaitingForAck {
connection,
buffer,
sequence_number,
num_fragments,
timeout,
retry_timeout,
retry_interval,
};
Ok(Async::Ready(waiting.into()))
}
fn poll_waiting_for_ack<'a>(
waiting: &'a mut RentToOwn<'a, WaitingForAck<T>>,
) -> Poll<AfterWaitingForAck<T>, (io::Error, PhantomData<T>)> {
// Repeatedly poll the socket until we receive the acknowledgement packet or there are no
// more packets to read.
loop {
{
let waiting = &mut **waiting;
match recv_packet(
&waiting.connection.socket,
waiting.connection.peer_address,
&mut waiting.connection.recv_buffer,
) {
Ok(packet) => {
if packet.data != PacketData::Ack(waiting.sequence_number) { continue; }
}
// If we get a `WouldBlock` error, we don't want to return early because we still
// have the timeout futures to poll.
Err(error) => {
if error.kind() != io::ErrorKind::WouldBlock {
return Err((error, PhantomData));
}
break;
}
}
}
// We're done! We've received the acknowledgement from the peer.
let WaitingForAck {
connection,
buffer,
..
} = waiting.take();
return Ok(Async::Ready(Ready((connection, buffer)).into()));
}
// Check if we've timed out waiting for the acknowledgement.
if let Async::Ready(()) = waiting.timeout.poll().map_err(|error| (error, PhantomData))? {
return Err((io::ErrorKind::TimedOut.into(), PhantomData))
}
// Check if it's time to retry sending the message.
let retry = waiting.retry_timeout.poll().map_err(|error| (error, PhantomData))?;
if let Async::Ready(()) = retry {
let WaitingForAck {
mut connection,
buffer,
sequence_number,
num_fragments,
timeout,
retry_interval,
..
} = waiting.take();
// Write the first fragment of the message into the send buffer.
{
let buffer = buffer.as_ref();
let fragment_len = cmp::min(buffer.len(), MAX_FRAGMENT_LEN);
encode(
Packet {
connection_id: connection.connection_id,
data: PacketData::Message {
sequence_number: sequence_number,
fragment: &buffer[.. fragment_len],
num_fragments,
fragment_number: 0,
},
},
&mut connection.send_buffer,
).expect("Error encoding packet");
}
// Return the new state.
let resending = Resending {
connection,
buffer,
sequence_number,
num_fragments,
fragment_number: 1,
timeout,
retry_interval,
};
return Ok(Async::Ready(resending.into()));
}
Ok(Async::NotReady)
}
fn poll_resending<'a>(
sending: &'a mut RentToOwn<'a, Resending<T>>,
) -> Poll<AfterResending<T>, (io::Error, PhantomData<T>)> {
// Keep sending fragments until we've sent them all or we would block.
loop {
let sending = &mut **sending;
let buffer = sending.buffer.as_ref();
let send_result = sending.connection.socket.send_to(
&sending.connection.send_buffer,
&sending.connection.peer_address,
);
let bytes_sent = match send_result {
Ok(bytes) => { bytes }
Err(error) => {
if error.kind() == io::ErrorKind::WouldBlock {
return Ok(Async::NotReady);
}
// HACK: We should be able to use `try_nb!` here, but since we need to bundle
// the error with some `PhantomData` we end up having to do this manually.
return Err((error, PhantomData));
}
};
// If we send a datagram that doesn't include all the bytes in the packet,
// then an error occurred.
if bytes_sent != sending.connection.send_buffer.len() {
return Err((
io::Error::new(
io::ErrorKind::Other,
"Failed to send all bytes of the fragment",
),
PhantomData
));
}
// If we've sent all the fragments of the message, then we're done sending
// the message.
if sending.fragment_number == sending.num_fragments { break; }
// Write the next fragment of the message.
let fragment_start = (sending.fragment_number) as usize * MAX_FRAGMENT_LEN;
let fragment_end = cmp::min(fragment_start + MAX_FRAGMENT_LEN, buffer.len());
let fragment = &buffer[fragment_start .. fragment_end];
encode(
Packet {
connection_id: sending.connection.connection_id,
data: PacketData::Message {
sequence_number: sending.sequence_number,
fragment,
num_fragments: sending.num_fragments,
fragment_number: sending.fragment_number,
},
},
&mut sending.connection.send_buffer,
).map_err(|error| (error, PhantomData))?;
// Update the current sequence number.
sending.fragment_number += 1;
}
// We've finished sending the message for the first time, so create the `WaitingForAck`
// state from the current state.
let Resending {
connection,
buffer,
sequence_number,
num_fragments,
timeout,
retry_interval,
..
} = sending.take();
// Create the retry timeout.
let retry_timeout = Timeout::new(retry_interval, &connection.handle)
.map_err(|error| (error, PhantomData))?;
// return the `WaitingForAck` state.
let waiting = WaitingForAck {
connection,
buffer,
sequence_number,
num_fragments,
timeout,
retry_timeout,
retry_interval,
};
Ok(Async::Ready(waiting.into()))
}
}
|
use core::f64::consts::FRAC_PI_2;
use crate::circle::Circle;
use crate::coord_plane::LatLonPoint;
use crate::coord_plane::CartPoint;
pub struct Indicatrix {
pub center: LatLonPoint,
pub points: Vec<LatLonPoint>,
}
struct CartPointsWithCenter {
pub center: CartPoint,
pub points: Vec<CartPoint>,
}
impl CartPointsWithCenter {
// This function pushes points further away from the radius
pub fn expand(self, increase_ratio: f64) -> Vec<CartPoint> {
self.points.iter().map(
|end| self.extend_line(*end, increase_ratio)
).collect()
}
pub fn extend_line(&self, end: CartPoint, increase_ratio: f64) -> CartPoint {
let x_diff = end.x - self.center.x;
let y_diff = end.y - self.center.y;
CartPoint {
x: self.center.x + x_diff * increase_ratio,
y: self.center.y + y_diff * increase_ratio,
}
}
}
impl Indicatrix {
// Transform according to projection
fn project<'a>(self, mapping_function: &'a Box<dyn Fn(Vec<LatLonPoint>) -> Vec<CartPoint>>) -> CartPointsWithCenter {
CartPointsWithCenter {
points: mapping_function(self.points),
center: mapping_function(vec![self.center])[0],
}
}
}
pub fn gen_indicatrices(mapping_function: Box<dyn Fn(Vec<LatLonPoint>) -> Vec<CartPoint>>, num_lines: usize,
num_points: usize, area_to_check: f64, radius: f64) -> Vec<CartPoint> {
super::lat_lon_lines::intersections_of_pars_and_merids(num_lines).iter()
.map(|p|
Circle {
center: *p,
radius: radius,
num_points: num_points,
}.to_indicatrix(num_points, area_to_check).project(&mapping_function)
.expand(75.0))
.flatten().collect()
}
|
use super::leaf::{Scanner, ARRAY_SIZE};
use super::Leaf;
use super::{InsertError, RemoveError, SearchError};
use crate::ebr::{Arc, AtomicArc, Barrier, Ptr, Tag};
use crate::LinkedList;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt::Display;
use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release};
/// Leaf node.
///
/// The layout of a leaf node: |ptr(entry array)/max(child keys)|...|ptr(entry array)|
pub struct LeafNode<K, V>
where
K: 'static + Clone + Ord + Send + Sync,
V: 'static + Clone + Send + Sync,
{
/// Child leaves.
///
/// The pointer to the unbounded leaf storing a non-zero tag indicates that the leaf is obsolete.
#[allow(clippy::type_complexity)]
leaves: (Leaf<K, AtomicArc<Leaf<K, V>>>, AtomicArc<Leaf<K, V>>),
/// New leaves in an intermediate state during merge and split.
///
/// A valid pointer stored in the variable acts as a mutex for merge and split operations.
new_leaves: AtomicArc<NewLeaves<K, V>>,
}
impl<K, V> LeafNode<K, V>
where
K: 'static + Clone + Ord + Send + Sync,
V: 'static + Clone + Send + Sync,
{
/// Creates a new empty leaf node.
pub fn new() -> LeafNode<K, V> {
LeafNode {
leaves: (Leaf::new(), AtomicArc::null()),
new_leaves: AtomicArc::null(),
}
}
/// Takes the memory address of the instance as an identifier.
pub fn id(&self) -> usize {
self as *const _ as usize
}
/// Checks if the leaf node is obsolete.
pub fn obsolete(&self, barrier: &Barrier) -> bool {
if self.leaves.0.obsolete() {
let unbounded_ptr = self.leaves.1.load(Relaxed, barrier);
// The unbounded leaf is specially marked when becoming obsolete.
return unbounded_ptr.tag() == Tag::First;
}
false
}
/// Searches for an entry associated with the given key.
pub fn search<'b, Q>(&self, key: &Q, barrier: &'b Barrier) -> Result<Option<&'b V>, SearchError>
where
K: 'b + Borrow<Q>,
Q: Ord + ?Sized,
{
loop {
let result = (self.leaves.0).min_greater_equal(key);
if let Some((_, child)) = result.0 {
let child_ptr = child.load(Acquire, barrier);
if !(self.leaves.0).validate(result.1) {
// Data race resolution: validate metadata.
// - Writer: start to insert an intermediate low key leaf
// - Reader: read the metadata not including the intermediate low key leaf
// - Writer: insert the intermediate low key leaf and replace the high key leaf pointer
// - Reader: read the new high key leaf pointer
// Consequently, the reader may miss keys in the low key leaf.
continue;
}
if let Some(child_ref) = child_ptr.as_ref() {
return Ok(child_ref.search(key));
}
// `child_ptr` being null indicates that the leaf node is bound to be freed.
return Err(SearchError::Retry);
}
let unbounded_ptr = (self.leaves.1).load(Acquire, barrier);
if let Some(unbounded_ref) = unbounded_ptr.as_ref() {
debug_assert!(unbounded_ptr.tag() == Tag::None);
if !(self.leaves.0).validate(result.1) {
// Data race resolution - see above.
continue;
}
return Ok(unbounded_ref.search(key));
}
if unbounded_ptr.tag() == Tag::First {
// The leaf node has become obsolete.
return Err(SearchError::Retry);
}
// The `TreeIndex` is empty.
return Err(SearchError::Empty);
}
}
/// Returns the minimum key entry.
pub fn min<'b>(&self, barrier: &'b Barrier) -> Result<Scanner<'b, K, V>, SearchError> {
loop {
let mut scanner = Scanner::new(&self.leaves.0);
let metadata = scanner.metadata();
if let Some((_, child)) = scanner.next() {
let child_ptr = child.load(Acquire, barrier);
if !(self.leaves.0).validate(metadata) {
// Data race resolution - see LeafNode::search.
continue;
}
if let Some(child_ref) = child_ptr.as_ref() {
return Ok(Scanner::new(child_ref));
}
// `child_ptr` being null indicates that the leaf node is bound to be freed.
return Err(SearchError::Retry);
}
let unbounded_ptr = (self.leaves.1).load(Acquire, barrier);
if let Some(unbounded_ref) = unbounded_ptr.as_ref() {
debug_assert!(unbounded_ptr.tag() == Tag::None);
if !(self.leaves.0).validate(metadata) {
// Data race resolution - see LeafNode::search.
continue;
}
return Ok(Scanner::new(unbounded_ref));
}
if unbounded_ptr.tag() == Tag::First {
// The leaf node has become obsolete.
return Err(SearchError::Retry);
}
// The `TreeIndex` is empty.
return Err(SearchError::Empty);
}
}
/// Returns the maximum key entry less than the given key.
pub fn max_less<'b>(
&self,
key: &K,
barrier: &'b Barrier,
) -> Result<Scanner<'b, K, V>, SearchError> {
loop {
let mut scanner = Scanner::max_less(&self.leaves.0, key);
let metadata = scanner.metadata();
if let Some((_, child)) = scanner.next() {
let child_ptr = child.load(Acquire, barrier);
if !(self.leaves.0).validate(metadata) {
// Data race resolution - see LeafNode::search.
continue;
}
if let Some(child_ref) = child_ptr.as_ref() {
return Ok(Scanner::max_less(child_ref, key));
}
// `child_ptr` being null indicates that the leaf node is bound to be freed.
return Err(SearchError::Retry);
}
let unbounded_ptr = (self.leaves.1).load(Acquire, barrier);
if let Some(unbounded_ref) = unbounded_ptr.as_ref() {
debug_assert!(unbounded_ptr.tag() == Tag::None);
if !(self.leaves.0).validate(metadata) {
// Data race resolution - see LeafNode::search.
continue;
}
return Ok(Scanner::max_less(unbounded_ref, key));
}
if unbounded_ptr.tag() == Tag::First {
// The leaf node has become obsolete.
return Err(SearchError::Retry);
}
// The `TreeIndex` is empty.
return Err(SearchError::Empty);
}
}
/// Inserts a key-value pair.
pub fn insert(&self, key: K, value: V, barrier: &Barrier) -> Result<(), InsertError<K, V>> {
loop {
let result = (self.leaves.0).min_greater_equal(&key);
if let Some((child_key, child)) = result.0 {
let child_ptr = child.load(Acquire, barrier);
if !(self.leaves.0).validate(result.1) {
// Data race resolution - see LeafNode::search.
continue;
}
if let Some(child_ref) = child_ptr.as_ref() {
return child_ref.insert(key, value).map_or_else(
|| Ok(()),
|result| {
if result.1 {
return Err(InsertError::Duplicated(result.0));
}
debug_assert!(child_ref.full());
if !self.split_leaf(Some(child_key.clone()), child_ptr, child, barrier)
{
return Err(InsertError::Full(result.0));
}
Err(InsertError::Retry(result.0))
},
);
}
// `child_ptr` being null indicates that the leaf node is bound to be freed.
return Err(InsertError::Retry((key, value)));
}
let mut unbounded_ptr = self.leaves.1.load(Acquire, barrier);
while unbounded_ptr.is_null() {
if unbounded_ptr.tag() == Tag::First {
// The leaf node has become obsolete.
break;
}
// Tries to allocate a new leaf.
// - It only happens when the first entry is being inserted into the
// `TreeIndex`.
match self.leaves.1.compare_exchange(
unbounded_ptr,
(Some(Arc::new(Leaf::new())), Tag::None),
AcqRel,
Acquire,
) {
Ok((_, ptr)) => {
unbounded_ptr = ptr;
break;
}
Err((_, actual)) => {
unbounded_ptr = actual;
}
}
}
if let Some(unbounded_ref) = unbounded_ptr.as_ref() {
debug_assert!(unbounded_ptr.tag() == Tag::None);
if !(self.leaves.0).validate(result.1) {
// Data race resolution - see 'InternalNode::search'.
continue;
}
// Tries to insert into the unbounded leaf, and tries to split the unbounded if
// it is full.
return unbounded_ref.insert(key, value).map_or_else(
|| Ok(()),
|result| {
if result.1 {
return Err(InsertError::Duplicated(result.0));
}
debug_assert!(unbounded_ref.full());
if !self.split_leaf(None, unbounded_ptr, &self.leaves.1, barrier) {
return Err(InsertError::Full(result.0));
}
Err(InsertError::Retry(result.0))
},
);
}
// unbounded_shared being null indicates that the leaf node is bound to be freed.
return Err(InsertError::Retry((key, value)));
}
}
/// Removes an entry associated with the given key.
pub fn remove_if<Q, F: FnMut(&V) -> bool>(
&self,
key_ref: &Q,
condition: &mut F,
barrier: &Barrier,
) -> Result<bool, RemoveError>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
loop {
let result = (self.leaves.0).min_greater_equal(key_ref);
if let Some((_, child)) = result.0 {
let child_ptr = child.load(Acquire, barrier);
if !(self.leaves.0).validate(result.1) {
// Data race resolution - see LeafNode::search.
continue;
}
if let Some(child_ref) = child_ptr.as_ref() {
let (removed, full, empty) = child_ref.remove_if(key_ref, condition);
if full && !self.check_full_leaf(key_ref, child_ptr, barrier) {
// Data race resolution.
// - Insert: start to insert into a full leaf
// - Remove: start removing an entry from the leaf after pointer validation
// - Insert: find the leaf full, thus splitting and update
// - Remove: find the leaf full, and the leaf node is not locked, returning 'Ok(true)'
// Consequently, the key remains.
// In order to resolve this, check the pointer again.
return Err(RemoveError::Retry(removed));
}
if empty {
if !child_ref.retire() {
return Err(RemoveError::Retry(removed));
}
return self.coalesce(removed, barrier);
}
return Ok(removed);
}
// `child_ptr` being null indicates that the leaf node is bound to be freed.
return Err(RemoveError::Retry(false));
}
let unbounded_ptr = (self.leaves.1).load(Acquire, barrier);
if let Some(unbounded_ref) = unbounded_ptr.as_ref() {
debug_assert!(unbounded_ptr.tag() == Tag::None);
if !(self.leaves.0).validate(result.1) {
// Data race resolution - see LeafNode::search.
continue;
}
let (removed, full, empty) = unbounded_ref.remove_if(key_ref, condition);
if full && !self.check_full_leaf(key_ref, unbounded_ptr, barrier) {
// Data race resolution - see above.
return Err(RemoveError::Retry(removed));
}
if empty {
if !unbounded_ref.retire() {
return Err(RemoveError::Retry(removed));
}
return self.coalesce(removed, barrier);
}
return Ok(removed);
}
if unbounded_ptr.tag() == Tag::First {
// The leaf node has become obsolete.
return Err(RemoveError::Empty(false));
}
// The `TreeIndex` is empty.
return Ok(false);
}
}
/// Splits a full leaf.
///
/// Returns `true` if the leaf is successfully split or a conflict is detected, false
/// otherwise.
fn split_leaf(
&self,
full_leaf_key: Option<K>,
full_leaf_ptr: Ptr<Leaf<K, V>>,
full_leaf: &AtomicArc<Leaf<K, V>>,
barrier: &Barrier,
) -> bool {
let new_leaves_ptr;
match self.new_leaves.compare_exchange(
Ptr::null(),
(
Some(Arc::new(NewLeaves {
origin_leaf_key: full_leaf_key,
origin_leaf_ptr: full_leaf.clone(Relaxed, barrier),
low_key_leaf: AtomicArc::null(),
high_key_leaf: AtomicArc::null(),
})),
Tag::None,
),
Acquire,
Relaxed,
) {
Ok((_, ptr)) => new_leaves_ptr = ptr,
Err(_) => return true,
}
// Checks the full leaf pointer and the leaf node state after locking the leaf node.
if full_leaf_ptr != full_leaf.load(Relaxed, barrier) {
drop(self.new_leaves.swap((None, Tag::None), Relaxed));
return true;
}
// Checks if the leaf node has already been deprecated.
if self.leaves.1.load(Relaxed, barrier).tag() == Tag::First {
drop(self.new_leaves.swap((None, Tag::None), Relaxed));
return true;
}
let full_leaf_ref = full_leaf_ptr.as_ref().unwrap();
debug_assert!(full_leaf_ref.full());
// Copies entries to the newly allocated leaves.
let new_leaves_ref = new_leaves_ptr.as_ref().unwrap();
let mut low_key_leaf_arc = None;
let mut high_key_leaf_arc = None;
full_leaf_ref.distribute(&mut low_key_leaf_arc, &mut high_key_leaf_arc);
if let Some(low_key_leaf_boxed) = low_key_leaf_arc.take() {
// The number of valid entries is small enough to fit into a single leaf.
new_leaves_ref
.low_key_leaf
.swap((Some(low_key_leaf_boxed), Tag::None), Relaxed);
if let Some(high_key_leaf) = high_key_leaf_arc.take() {
new_leaves_ref
.high_key_leaf
.swap((Some(high_key_leaf), Tag::None), Relaxed);
}
} else {
// No valid keys in the full leaf.
new_leaves_ref
.low_key_leaf
.swap((Some(Arc::new(Leaf::new())), Tag::None), Relaxed);
}
// Inserts the newly added leaves into the main array.
// - Inserts the new leaves into the linked list, and removes the full leaf from it.
let low_key_leaf_ptr = new_leaves_ref.low_key_leaf.load(Relaxed, barrier);
let high_key_leaf_ptr = new_leaves_ref.high_key_leaf.load(Relaxed, barrier);
let unused_leaf = if high_key_leaf_ptr.is_null() {
// From here, Scanners can reach the new leaf.
let result = full_leaf_ref.push_back(
low_key_leaf_ptr.try_into_arc().unwrap(),
true,
Release,
barrier,
);
debug_assert!(result.is_ok());
// Replaces the full leaf with the low-key leaf.
full_leaf.swap((low_key_leaf_ptr.try_into_arc(), Tag::None), Release)
} else {
// From here, Scanners can reach the new leaves.
//
// Immediately unlinking the full leaf causes active scanners reading the full leaf
// to omit a number of leaves.
// - Leaf: l, insert: i, split: s, rollback: r.
// - Insert 1-2: i1(l1)| |i2(l2)|s(l2)|l12:l2:l21:l22|l12:l21:l22|
// - Insert 0 : i0(l1)|s(l1)|l1:l11:l12:l2| |r|l1:l12...
// In this scenario, without keeping l1, l2 in the linked list, l1 would point to
// l2, and therefore a range scanner would start from l1, and cannot traverse l21
// and l22, missing newly inserted entries in l21 and l22 before starting the
// range scanner.
let result = full_leaf_ref.push_back(
high_key_leaf_ptr.try_into_arc().unwrap(),
true,
Release,
barrier,
);
debug_assert!(result.is_ok());
let result = full_leaf_ref.push_back(
low_key_leaf_ptr.try_into_arc().unwrap(),
true,
Release,
barrier,
);
debug_assert!(result.is_ok());
// Takes the max key value stored in the low key leaf as the leaf key.
let max_key = low_key_leaf_ptr.as_ref().unwrap().max().unwrap().0;
if self
.leaves
.0
.insert(
max_key.clone(),
new_leaves_ref.low_key_leaf.clone(Relaxed, barrier),
)
.is_some()
{
// Insertion failed: expects that the parent splits the leaf node.
return false;
}
// Replaces the full leaf with the high-key leaf.
full_leaf.swap((high_key_leaf_ptr.try_into_arc(), Tag::None), Release)
};
// Drops the deprecated leaf.
if let Some(unused_leaf) = unused_leaf {
debug_assert!(unused_leaf.full());
let deleted = unused_leaf.delete_self(Release);
debug_assert!(deleted);
barrier.reclaim(unused_leaf);
}
// Unlocks the leaf node.
self.new_leaves.swap((None, Tag::None), Release);
true
}
/// Splits itself into the given leaf nodes, and returns the middle key value.
pub fn split_leaf_node(
&self,
low_key_leaf_node: &LeafNode<K, V>,
high_key_leaf_node: &LeafNode<K, V>,
barrier: &Barrier,
) -> Option<K> {
let mut middle_key = None;
debug_assert!(!self.new_leaves.load(Relaxed, barrier).is_null());
let new_leaves_ref = self.new_leaves.load(Relaxed, barrier).as_ref().unwrap();
let low_key_leaves = &low_key_leaf_node.leaves;
let high_key_leaves = &high_key_leaf_node.leaves;
// Builds a list of valid leaves
#[allow(clippy::type_complexity)]
let mut entry_array: [Option<(Option<&K>, AtomicArc<Leaf<K, V>>)>; ARRAY_SIZE + 2] =
Default::default();
let mut num_entries = 0;
let low_key_leaf_ref = new_leaves_ref
.low_key_leaf
.load(Relaxed, barrier)
.as_ref()
.unwrap();
let middle_key_ref = low_key_leaf_ref.max().unwrap().0;
for entry in Scanner::new(&self.leaves.0) {
if new_leaves_ref
.origin_leaf_key
.as_ref()
.map_or_else(|| false, |key| entry.0.cmp(key) == Ordering::Equal)
{
entry_array[num_entries].replace((
Some(middle_key_ref),
new_leaves_ref.low_key_leaf.clone(Relaxed, barrier),
));
num_entries += 1;
if !new_leaves_ref
.high_key_leaf
.load(Relaxed, barrier)
.is_null()
{
entry_array[num_entries].replace((
Some(entry.0),
new_leaves_ref.high_key_leaf.clone(Relaxed, barrier),
));
num_entries += 1;
}
} else {
entry_array[num_entries].replace((Some(entry.0), entry.1.clone(Relaxed, barrier)));
num_entries += 1;
}
}
#[allow(clippy::branches_sharing_code)]
if new_leaves_ref.origin_leaf_key.is_some() {
// If the origin is a bounded node, assign the unbounded node to the high key node's unbounded.
entry_array[num_entries].replace((None, self.leaves.1.clone(Relaxed, barrier)));
num_entries += 1;
} else {
// If the origin is an unbounded node, assign the high key node to the high key node's unbounded.
entry_array[num_entries].replace((
Some(middle_key_ref),
new_leaves_ref.low_key_leaf.clone(Relaxed, barrier),
));
num_entries += 1;
if !new_leaves_ref
.high_key_leaf
.load(Relaxed, barrier)
.is_null()
{
entry_array[num_entries]
.replace((None, new_leaves_ref.high_key_leaf.clone(Relaxed, barrier)));
num_entries += 1;
}
}
debug_assert!(num_entries >= 2);
let low_key_leaf_array_size = num_entries / 2;
for (index, entry) in entry_array.iter().enumerate() {
if let Some(entry) = entry {
match (index + 1).cmp(&low_key_leaf_array_size) {
Ordering::Less => {
low_key_leaves
.0
.insert(entry.0.unwrap().clone(), entry.1.clone(Relaxed, barrier));
}
Ordering::Equal => {
middle_key.replace(entry.0.unwrap().clone());
low_key_leaves
.1
.swap((entry.1.get_arc(Relaxed, barrier), Tag::None), Relaxed);
}
Ordering::Greater => {
if let Some(key) = entry.0 {
high_key_leaves
.0
.insert(key.clone(), entry.1.clone(Relaxed, barrier));
} else {
high_key_leaves
.1
.swap((entry.1.get_arc(Relaxed, barrier), Tag::None), Relaxed);
}
}
}
} else {
break;
}
}
debug_assert!(middle_key.is_some());
middle_key
}
/// Checks the given full leaf whether it is being split.
fn check_full_leaf<Q>(&self, key_ref: &Q, leaf_ptr: Ptr<Leaf<K, V>>, barrier: &Barrier) -> bool
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
// There is a chance that the target key value pair has been copied to new_leaves,
// and the following scenario cannot be prevented by memory fences.
// - Remove: release(leaf)|load(mutex_old)|acquire|load(leaf_ptr_old)
// - Insert: load(leaf)|store(mutex)|acquire|release|store(leaf_ptr)|release|store(mutex)
// Therefore, it performs CAS to check the freshness of the pointer value.
// - Remove: release(leaf)|cas(mutex)|acquire|release|load(leaf_ptr)
// - Insert: load(leaf)|store(mutex)|acquire|release|store(leaf_ptr)|release|store(mutex)
if self
.new_leaves
.compare_exchange(Ptr::null(), (None, Tag::None), AcqRel, Relaxed)
.is_err()
{
return false;
}
let result = (self.leaves.0).min_greater_equal(key_ref);
let leaf_current_ptr = if let Some((_, child)) = result.0 {
child.load(Relaxed, barrier)
} else {
self.leaves.1.load(Relaxed, barrier)
};
leaf_current_ptr == leaf_ptr
}
/// Tries to coalesce empty or obsolete leaves.
fn coalesce(&self, removed: bool, barrier: &Barrier) -> Result<bool, RemoveError> {
let lock = Locker::try_lock(self);
if lock.is_none() {
return Err(RemoveError::Retry(removed));
}
let mut num_valid_leaves = 0;
for entry in Scanner::new(&self.leaves.0) {
let leaf_ptr = entry.1.load(Relaxed, barrier);
let leaf_ref = leaf_ptr.as_ref().unwrap();
if leaf_ref.obsolete() {
// Data race resolution - see LeafScanner::jump.
let deleted = leaf_ref.delete_self(Relaxed);
debug_assert!(deleted);
self.leaves.0.remove_if(entry.0, &mut |_| true);
// Data race resolution - see LeafNode::search.
if let Some(leaf) = entry.1.swap((None, Tag::None), Release) {
barrier.reclaim(leaf);
}
} else {
num_valid_leaves += 1;
}
}
// Checks the unbounded leaf only when all the other leaves have become obsolete.
let check_unbounded = if num_valid_leaves == 0 && self.leaves.0.retire() {
true
} else {
self.leaves.0.obsolete()
};
// The unbounded leaf becomes unreachable after all the other leaves are gone.
let fully_empty = if check_unbounded {
let unbounded_ptr = self.leaves.1.load(Relaxed, barrier);
if let Some(unbounded_ref) = unbounded_ptr.as_ref() {
if unbounded_ref.obsolete() {
// Data race resolution - see LeafScanner::jump.
let deleted = unbounded_ref.delete_self(Relaxed);
debug_assert!(deleted);
if let Some(obsolete_leaf) = self.leaves.1.swap((None, Tag::First), Release) {
barrier.reclaim(obsolete_leaf);
}
true
} else {
false
}
} else {
debug_assert!(unbounded_ptr.tag() == Tag::First);
true
}
} else {
false
};
if fully_empty {
Err(RemoveError::Empty(removed))
} else {
Ok(removed)
}
}
/// Rolls back the ongoing split operation recursively.
pub fn rollback(&self, barrier: &Barrier) {
let new_leaves_ptr = self.new_leaves.load(Relaxed, barrier);
if let Some(new_leaves_ref) = new_leaves_ptr.as_ref() {
// Inserts the origin leaf into the linked list.
let low_key_leaf_ptr = new_leaves_ref.low_key_leaf.load(Relaxed, barrier);
let high_key_leaf_ptr = new_leaves_ref.high_key_leaf.load(Relaxed, barrier);
// Rolls back the linked list state.
//
// `high_key_leaf` must be deleted first in order for scanners not to omit entries.
if let Some(leaf_ref) = high_key_leaf_ptr.as_ref() {
let deleted = leaf_ref.delete_self(Relaxed);
debug_assert!(deleted);
}
if let Some(leaf_ref) = low_key_leaf_ptr.as_ref() {
let deleted = leaf_ref.delete_self(Release);
debug_assert!(deleted);
}
if let Some(origin_leaf) = new_leaves_ref
.origin_leaf_ptr
.swap((None, Tag::None), Relaxed)
{
// Remove marks from the full leaf node.
//
// This unmarking has to be a release-store, otherwise it can be re-ordered
// before previous `delete_self` calls.
let unmarked = origin_leaf.unmark(Release);
debug_assert!(unmarked);
}
// Unlocks the leaf node.
if let Some(new_leaves) = self.new_leaves.swap((None, Tag::None), Release) {
barrier.reclaim(new_leaves);
}
};
}
/// Unlinks all the leaves.
///
/// It is called only when the leaf node is a temporary one for split/merge,
/// or has become unreachable after split/merge/remove.
pub fn unlink(&self, barrier: &Barrier) {
for entry in Scanner::new(&self.leaves.0) {
entry.1.swap((None, Tag::None), Relaxed);
}
self.leaves.1.swap((None, Tag::First), Relaxed);
// Keeps the leaf node locked to prevent locking attempts.
if let Some(unused_leaves) = self.new_leaves.swap((None, Tag::First), Relaxed) {
if let Some(obsolete_leaf) = unused_leaves
.origin_leaf_ptr
.swap((None, Tag::None), Relaxed)
{
// Makes the leaf unreachable before dropping it.
obsolete_leaf.delete_self(Relaxed);
barrier.reclaim(obsolete_leaf);
}
}
}
}
impl<K: Clone + Display + Ord + Send + Sync, V: Clone + Display + Send + Sync> LeafNode<K, V> {
pub fn print<T: std::io::Write>(
&self,
output: &mut T,
depth: usize,
barrier: &Barrier,
) -> std::io::Result<()> {
// Collects information.
#[allow(clippy::type_complexity)]
let mut leaf_ref_array: [Option<(Option<&Leaf<K, V>>, Option<&K>, usize)>;
ARRAY_SIZE + 1] = [None; ARRAY_SIZE + 1];
let mut scanner = Scanner::new_including_removed(&self.leaves.0);
let mut index = 0;
while let Some(entry) = scanner.next() {
if scanner.removed() {
leaf_ref_array[index].replace((None, Some(entry.0), index));
} else {
let leaf_ptr = entry.1.load(Relaxed, barrier);
leaf_ref_array[index].replace((leaf_ptr.as_ref(), Some(entry.0), index));
}
index += 1;
}
let unbounded_ptr = self.leaves.1.load(Relaxed, barrier);
if let Some(unbounded_ref) = unbounded_ptr.as_ref() {
leaf_ref_array[index].replace((Some(unbounded_ref), None, index));
}
// Prints the label.
output.write_fmt(format_args!(
"{} [shape=plaintext\nlabel=<\n<table border='1' cellborder='1'>\n<tr><td colspan='{}'>ID: {}, Level: {}, Cardinality: {}</td></tr>\n<tr>",
self.id(),
index + 1,
self.id(),
depth,
index + 1,
))?;
#[allow(clippy::manual_flatten)]
for leaf_info in &leaf_ref_array {
if let Some((leaf_ref, key_ref, index)) = leaf_info {
let font_color = if leaf_ref.is_some() { "black" } else { "red" };
if let Some(key_ref) = key_ref {
output.write_fmt(format_args!(
"<td port='p_{}'><font color='{}'>{}</font></td>",
index, font_color, key_ref,
))?;
} else {
output.write_fmt(format_args!(
"<td port='p_{}'><font color='{}'>\u{221e}</font></td>",
index, font_color,
))?;
}
}
}
output.write_fmt(format_args!("</tr>\n</table>\n>]\n"))?;
// Prints the edges and children.
#[allow(clippy::manual_flatten)]
for leaf_info in &leaf_ref_array {
if let Some((Some(leaf_ref), _, index)) = leaf_info {
output.write_fmt(format_args!(
"{}:p_{} -> {}\n",
self.id(),
index,
leaf_ref.id()
))?;
output.write_fmt(format_args!(
"{} [shape=plaintext\nlabel=<\n<table border='1' cellborder='1'>\n<tr><td colspan='3'>ID: {}</td></tr><tr><td>Rank</td><td>Key</td><td>Value</td></tr>\n",
leaf_ref.id(),
leaf_ref.id(),
))?;
let mut leaf_scanner = Scanner::new_including_removed(leaf_ref);
let mut rank = 0;
while let Some(entry) = leaf_scanner.next() {
let (entry_rank, font_color) = if leaf_scanner.removed() {
(0, "red")
} else {
rank += 1;
(rank, "black")
};
output.write_fmt(format_args!(
"<tr><td><font color=\"{}\">{}</font></td><td>{}</td><td>{}</td></tr>\n",
font_color, entry_rank, entry.0, entry.1,
))?;
}
output.write_fmt(format_args!("</table>\n>]\n"))?;
}
}
std::io::Result::Ok(())
}
}
/// Leaf node locker.
pub struct Locker<'n, K, V>
where
K: 'static + Clone + Ord + Send + Sync,
V: 'static + Clone + Send + Sync,
{
lock: &'n AtomicArc<NewLeaves<K, V>>,
/// When the leaf node is bound to be dropped, the flag may be set true.
deprecate: bool,
}
impl<'n, K, V> Locker<'n, K, V>
where
K: 'static + Clone + Ord + Send + Sync,
V: 'static + Clone + Send + Sync,
{
pub fn try_lock(leaf_node: &'n LeafNode<K, V>) -> Option<Locker<'n, K, V>> {
if leaf_node
.new_leaves
.compare_exchange(Ptr::null(), (None, Tag::First), Acquire, Relaxed)
.is_ok()
{
Some(Locker {
lock: &leaf_node.new_leaves,
deprecate: false,
})
} else {
None
}
}
pub fn deprecate(&mut self) {
self.deprecate = true;
}
}
impl<'n, K, V> Drop for Locker<'n, K, V>
where
K: Clone + Ord + Send + Sync,
V: Clone + Send + Sync,
{
fn drop(&mut self) {
if !self.deprecate {
let unlocked = self
.lock
.update_tag_if(Tag::None, |t| t == Tag::First, Release);
debug_assert!(unlocked);
}
}
}
/// Intermediate split leaf.
///
/// It owns all the instances, thus dropping them all when it is being dropped.
pub struct NewLeaves<K, V>
where
K: 'static + Clone + Ord + Send + Sync,
V: 'static + Clone + Send + Sync,
{
origin_leaf_key: Option<K>,
origin_leaf_ptr: AtomicArc<Leaf<K, V>>,
low_key_leaf: AtomicArc<Leaf<K, V>>,
high_key_leaf: AtomicArc<Leaf<K, V>>,
}
|
use register::{mmio::*, register_bitfields, register_structs};
register_bitfields! {
u32,
/// Serial Clock Divisor Register
SCKDIV [
/// Divisor for serial clock. div_width bits wide
DIV OFFSET(0) NUMBITS(12) []
],
/// Serial Clock Mode Register
SCKMODE [
/// Serial clock phase
PHA OFFSET(0) NUMBITS(1) [
/// Data is sampled on the leading edge of SCK and shifted on the trailing edge of SCK
LeadingEdgeSample = 0,
/// Data is shifted on the leading edge of SCK and sampled on the trailing edge of SCK
TrailingEdgeSample = 1
],
/// Serial clock polarity
POL OFFSET(1) NUMBITS(1) [
/// Inactive state of SCK is logical 0
InactiveSCKLogical0 = 0,
/// Inactive state of SCK is logical 1
InactiveSCKLogical1 = 1
]
],
/// Chip Select ID Register
CSID [
/// Chip select ID. log_2(cs_width) bits wide.
CSID OFFSET(0) NUMBITS(32) []
],
/// Chip Select Default Register
CSDEF [
/// Chip select default value. cs_width bits wide, reset to all-1s.
CSDEF OFFSET(0) NUMBITS(32) []
],
/// Chip Select Mode Register
CSMODE [
/// Chip select mode
MODE OFFSET(0) NUMBITS(2) [
/// Assert/deassert CS at the beginning/end of each frame
AUTO = 0,
/// Keep CS continuously asserted after the initial frame
HOLD = 2,
/// Disable hardware control of the CS pin
OFF = 3
]
],
/// Delay Control Register 0
DELAY0 [
/// CS to SCK Delay
CSSCK OFFSET(0) NUMBITS(8) [],
/// SCK to CS Delay
SCKCS OFFSET(16) NUMBITS(8) []
],
/// Delay Control Register 1
DELAY1 [
/// Minimum CS inactive time
INTERCS OFFSET(0) NUMBITS(8) [],
/// Maximum interframe delay
INTERXFR OFFSET(16) NUMBITS(8) []
],
/// Frame Format Register
FMT [
/// SPI protocol
PROTO OFFSET(0) NUMBITS(2) [
/// DQ0 (MOSI), DQ1 (MISO)
SINGLE = 0,
/// DQ0, DQ1
DUAL = 1,
/// DQ0, DQ1, DQ2, DQ3
QUAD = 2
],
/// SPI Endianness
ENDIAN OFFSET(2) NUMBITS(1) [
/// Transmit most-significant bit (MSB) first
MSBFIRST = 0,
/// Transmit least-significant bit (LSB) first
LSBFIRST = 1
],
/// SPI I/O direction. This is reset to 1 for flash-enabled SPI controllers, 0 otherwise.
DIR OFFSET(3) NUMBITS(1) [
/// Rx: For dual and quad protocols, the DQ pins are tri-stated. For the single protocol, the DQ0 pin is driven with the transmit data as normal.
RX = 0,
/// Tx: The receive FIFO is not populated.
TX = 1
]
],
/// Transmit Data Register
TXDATA [
/// Transmit Data
DATA OFFSET(0) NUMBITS(8) [],
/// FIFO Full Flag
FULL OFFSET(31) NUMBITS(1) []
],
/// Receive Data Register
RXDATA [
/// Received Data
DATA OFFSET(0) NUMBITS(8) [],
/// FIFO Empty Flag
EMPTY OFFSET(31) NUMBITS(1) []
],
/// Transmit Watermark Register
TXMARK [
/// Transmit watermark. The reset value is 1 for flash-enabled controllers, 0 otherwise.
TXMARK OFFSET(0) NUMBITS(3) []
],
/// Receive Watermark Register
RXMARK [
/// Receive watermark
RXMARK OFFSET(0) NUMBITS(3) []
],
/// SPI Interrupt Enable Register
IE [
/// Transmit watermark enable
TXWM OFFSET(0) NUMBITS(1) [],
/// Receive watermark enable
RXWM OFFSET(1) NUMBITS(1) []
],
/// SPI Watermark Interrupt Pending Register
IP [
/// Transmit watermark pending
TXWM OFFSET(0) NUMBITS(1) [],
/// Receive watermark pending
RXWM OFFSET(1) NUMBITS(1) []
],
/// SPI Flash Interface Control Register
FCTRL [
/// SPI Flash Mode Select
EN OFFSET(0) NUMBITS(1) []
],
/// SPI Flash Instruction Format Register
FFMT [
/// Enable sending of command
CMDEN OFFSET(0) NUMBITS(1) [],
/// Number of address bytes (0 to 4)
ADDRLEN OFFSET(1) NUMBITS(3) [],
/// Number of dummy cycles
PADCNT OFFSET(4) NUMBITS(4) [],
/// Protocol for transmitting command
CMDPROTO OFFSET(8) NUMBITS(2) [],
/// Protocol for transmitting address and padding
ADDRPROTO OFFSET(10) NUMBITS(2) [],
/// Protocol for receiving data bytes
DATAPROTO OFFSET(12) NUMBITS(2) [],
/// Value of command byte
CMDCODE OFFSET(16) NUMBITS(8) [],
/// First 8 bits to transmit during dummy cycles
PADCODE OFFSET(24) NUMBITS(8) []
]
}
register_structs! {
#[allow(non_snake_case)]
pub RegisterBlock {
(0x00 => SCKDIV : ReadWrite<u32, SCKDIV::Register>),
(0x04 => SCKMODE : ReadWrite<u32, SCKMODE::Register>),
(0x08 => _reserved0),
(0x10 => CSID : ReadWrite<u32, CSID::Register>),
(0x14 => CSDEF : ReadWrite<u32, CSDEF::Register>),
(0x18 => CSMODE : ReadWrite<u32, CSMODE::Register>),
(0x1C => _reserved1),
(0x28 => DELAY0 : ReadWrite<u32, DELAY0::Register>),
(0x2C => DELAY1 : ReadWrite<u32, DELAY1::Register>),
(0x30 => _reserved2),
(0x40 => FMT : ReadWrite<u32, FMT::Register>),
(0x44 => _reserved3),
(0x48 => TXDATA : ReadWrite<u32, TXDATA::Register>),
(0x4C => RXDATA : ReadWrite<u32, RXDATA::Register>),
(0x50 => TXMARK : ReadWrite<u32, TXMARK::Register>),
(0x54 => RXMARK : ReadWrite<u32, RXMARK::Register>),
(0x58 => _reserved4),
(0x60 => FCTRL : ReadWrite<u32, FCTRL::Register>),
(0x64 => FFMT : ReadWrite<u32, FFMT::Register>),
(0x68 => _reserved5),
(0x70 => IE : ReadWrite<u32, IE::Register>),
(0x74 => IP : ReadWrite<u32, IP::Register>),
(0x78 => @END),
}
}
pub struct SPIDriver {
base_address: usize,
}
impl core::ops::Deref for SPIDriver {
type Target = RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*self.ptr() }
}
}
impl SPIDriver {
pub fn new(base_address: usize) -> Self {
SPIDriver { base_address }
}
fn ptr(&self) -> *const RegisterBlock {
self.base_address as *const _
}
pub fn init(&self) -> crate::interface::driver::Result {
Ok(())
}
pub fn set_clk_div(&mut self, div: u32) {
self.SCKDIV.write(SCKDIV::DIV.val(div))
}
}
|
use std::path::Path;
use crate::{
create::buffered_index_to_direct_index,
error::VelociError,
indices::{metadata::*, *},
persistence::{Persistence, *},
plan_creator::execution_plan::PlanRequestSearchPart,
search, search_field,
util::StringAdd,
};
use buffered_index_writer::{self, BufferedIndexWriter};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TokenValuesConfig {
path: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct TokenValueData {
text: String,
value: Option<f32>,
}
// Add boost values for a list of tokens
pub fn add_token_values_to_tokens(persistence: &mut Persistence, data_str: &str, config: &str) -> Result<(), VelociError> {
let data: Vec<TokenValueData> = serde_json::from_str(data_str)?;
let config: TokenValuesConfig = serde_json::from_str(config)?;
let mut options: search::RequestSearchPart = search::RequestSearchPart {
path: config.path.clone(),
levenshtein_distance: Some(0),
..Default::default()
};
let mut buffered_index_data = BufferedIndexWriter::new_unstable_sorted(persistence.directory.box_clone());
for el in data {
if let Some(value) = el.value {
options.terms = vec![el.text];
options.ignore_case = Some(false);
let mut options = PlanRequestSearchPart {
request: options.clone(),
get_scores: true,
..Default::default()
};
let hits = search_field::get_term_ids_in_field(persistence, &mut options)?;
if !hits.hits_scores.is_empty() {
buffered_index_data.add(hits.hits_scores[0].id, value.to_bits())?;
}
}
}
let path = config.path.add(TEXTINDEX).add(TOKEN_VALUES).add(BOOST_VALID_TO_VALUE);
let mut store = buffered_index_to_direct_index(&persistence.directory, &path, buffered_index_data)?;
store.flush()?;
let index_metadata = IndexMetadata {
index_category: IndexCategory::Boost,
path: path.to_string(),
is_empty: store.is_empty(),
metadata: store.metadata,
index_cardinality: IndexCardinality::IndexIdToOneParent,
data_type: DataType::U32,
};
let entry = persistence.metadata.columns.entry(config.path).or_insert_with(|| FieldInfo {
has_fst: false,
..Default::default()
});
entry.indices.push(index_metadata);
persistence.write_metadata()?;
//TODO FIX LOAD FOR IN_MEMORY
let data = persistence.directory.get_file_bytes(Path::new(&path))?;
let store = SingleArrayPacked::<u32>::from_data(data, store.metadata);
persistence.indices.boost_valueid_to_value.insert(path, Box::new(store));
Ok(())
}
|
use std::collections::HashSet;
use std::fs::File;
use std::io::BufReader;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use glob::glob;
use lazy_static::lazy_static;
use serde::Deserialize;
use structopt::clap::arg_enum;
lazy_static! {
static ref HOME_DIR: String = dirs::home_dir()
.expect("could not get home directory path")
.to_str()
.expect("home directory contains non unicode characters")
.to_string();
}
#[inline]
fn home_dir() -> &'static str {
&*HOME_DIR
}
pub fn expanduser(path: &str) -> String {
if path.starts_with("~/") {
format!("{}/{}", home_dir(), &path[2..])
} else {
path.to_string()
}
}
#[derive(Debug, Deserialize)]
pub struct Settings {
#[serde(default)]
pub shell: Option<String>,
#[serde(default)]
pub configs: Configs,
#[serde(default)]
pub prompt: Prompt,
#[serde(default)]
pub behavior: Behavior,
}
impl Settings {
pub fn path() -> String {
format!("{}/.kube/kubie.yaml", home_dir())
}
pub fn load() -> Result<Settings> {
let settings_path_str = Self::path();
let settings_path = Path::new(&settings_path_str);
let mut settings = if settings_path.exists() {
let file = File::open(settings_path)?;
let reader = BufReader::new(file);
serde_yaml::from_reader(reader).context("could not parse kubie config")?
} else {
Settings::default()
};
// Very important to exclude kubie's own config file ~/.kube/kubie.yaml from the results.
settings.configs.exclude.push(settings_path_str);
Ok(settings)
}
pub fn get_kube_configs_paths(&self) -> Result<HashSet<PathBuf>> {
let mut paths = HashSet::new();
for inc in &self.configs.include {
let expanded = expanduser(&inc);
for entry in glob(&expanded)? {
paths.insert(entry?);
}
}
for exc in &self.configs.exclude {
let expanded = expanduser(&exc);
for entry in glob(&expanded)? {
paths.remove(&entry?);
}
}
Ok(paths)
}
}
impl Default for Settings {
fn default() -> Self {
Settings {
shell: Default::default(),
configs: Configs::default(),
prompt: Prompt::default(),
behavior: Behavior::default(),
}
}
}
#[derive(Debug, Deserialize)]
pub struct Configs {
#[serde(default = "default_include_path")]
pub include: Vec<String>,
#[serde(default = "default_exclude_path")]
pub exclude: Vec<String>,
}
impl Default for Configs {
fn default() -> Self {
Configs {
include: default_include_path(),
exclude: default_exclude_path(),
}
}
}
fn default_include_path() -> Vec<String> {
let home_dir = home_dir();
vec![
format!("{}/.kube/config", home_dir),
format!("{}/.kube/*.yml", home_dir),
format!("{}/.kube/*.yaml", home_dir),
format!("{}/.kube/configs/*.yml", home_dir),
format!("{}/.kube/configs/*.yaml", home_dir),
format!("{}/.kube/kubie/*.yml", home_dir),
format!("{}/.kube/kubie/*.yaml", home_dir),
]
}
fn default_exclude_path() -> Vec<String> {
vec![]
}
#[derive(Debug, Deserialize)]
pub struct Prompt {
#[serde(default = "def_bool_false")]
pub disable: bool,
#[serde(default = "def_bool_true")]
pub show_depth: bool,
#[serde(default = "def_bool_false")]
pub zsh_use_rps1: bool,
#[serde(default = "def_bool_false")]
pub fish_use_rprompt: bool,
}
impl Default for Prompt {
fn default() -> Self {
Prompt {
disable: false,
show_depth: true,
zsh_use_rps1: false,
fish_use_rprompt: false,
}
}
}
arg_enum! {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ContextHeaderBehavior {
Auto,
Always,
Never,
}
}
impl ContextHeaderBehavior {
pub fn should_print_headers(&self) -> bool {
match self {
ContextHeaderBehavior::Auto => atty::is(atty::Stream::Stdout),
ContextHeaderBehavior::Always => true,
ContextHeaderBehavior::Never => false,
}
}
}
impl Default for ContextHeaderBehavior {
fn default() -> Self {
ContextHeaderBehavior::Auto
}
}
#[derive(Debug, Deserialize)]
pub struct Behavior {
#[serde(default = "def_bool_true")]
pub validate_namespaces: bool,
#[serde(default)]
pub print_context_in_exec: ContextHeaderBehavior,
}
impl Default for Behavior {
fn default() -> Self {
Behavior {
validate_namespaces: true,
print_context_in_exec: Default::default(),
}
}
}
fn def_bool_true() -> bool {
true
}
fn def_bool_false() -> bool {
false
}
#[test]
fn test_expanduser() {
assert_eq!(
expanduser("~/hello/world/*.foo"),
format!("{}/hello/world/*.foo", home_dir())
);
}
|
use crate::sync::Semaphore;
use crate::syscall::{SemBuf, SysResult, TimeSpec};
use alloc::{collections::BTreeMap, sync::Arc, sync::Weak, vec::Vec};
use core::ops::Index;
use spin::{Mutex, RwLock};
// structure specifies the access permissions on the semaphore set
// key_t?
#[derive(Clone, Copy)]
pub struct IpcPerm {
pub key: usize, /* Key supplied to semget(2) */
pub uid: u32, /* Effective UID of owner */
pub gid: u32, /* Effective GID of owner */
pub cuid: u32, /* Effective UID of creator */
pub cgid: u32, /* Effective GID of creator */
pub mode: u16, /* Permissions */
pub __seq: u16, /* Sequence number */
}
// semid data structure
#[derive(Clone, Copy)]
pub struct SemidDs {
pub perm: IpcPerm, /* Ownership and permissions */
pub otime: usize, /* Last semop time */
pub ctime: usize, /* Last change time */
pub nsems: usize, /* number of semaphores in set */
}
/// A System V semaphore set
pub struct SemArray {
pub semid_ds: Mutex<SemidDs>,
sems: Vec<Semaphore>,
}
impl Index<usize> for SemArray {
type Output = Semaphore;
fn index(&self, idx: usize) -> &Semaphore {
&self.sems[idx]
}
}
lazy_static! {
static ref KEY2SEM: RwLock<BTreeMap<usize, Weak<SemArray>>> = RwLock::new(BTreeMap::new());
}
impl SemArray {
// remove semaphores
pub fn remove(&self) {
for sem in self.sems.iter() {
sem.remove();
}
}
pub fn otime(&self) {
self.semid_ds.lock().otime = TimeSpec::get_epoch().sec;
}
pub fn ctime(&self) {
self.semid_ds.lock().ctime = TimeSpec::get_epoch().sec;
}
/// Get the semaphore array with `key`.
/// If not exist, create a new one with `nsems` elements.
pub fn get_or_create(key: usize, nsems: usize, flags: usize) -> Arc<Self> {
let mut key2sem = KEY2SEM.write();
// found in the map
if let Some(weak_array) = key2sem.get(&key) {
if let Some(array) = weak_array.upgrade() {
return array;
}
}
// not found, create one
let mut semaphores = Vec::new();
for _ in 0..nsems {
semaphores.push(Semaphore::new(0));
}
// insert to global map
let array = Arc::new(SemArray {
semid_ds: Mutex::new(SemidDs {
perm: IpcPerm {
key,
uid: 0,
gid: 0,
cuid: 0,
cgid: 0,
mode: (flags as u16) & 0x1ff,
__seq: 0,
},
otime: 0,
ctime: TimeSpec::get_epoch().sec,
nsems,
}),
sems: semaphores,
});
key2sem.insert(key, Arc::downgrade(&array));
array
}
}
|
pub mod rectangle {
#[derive(Copy, Clone)]
pub struct Rectangle {
pub x: usize,
pub y: usize,
pub width: usize,
pub height: usize,
pub end_x: usize,
pub end_y: usize,
}
impl Rectangle {
pub fn new(x: usize, y: usize, width: usize, height: usize) -> Rectangle {
Rectangle {
x,
y,
width,
height,
end_x: x + width,
end_y: y + height,
}
}
}
} |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample_tests() {
assert_eq!(parse("iiisdoso"),
vec![8, 64]);
assert_eq!(parse("iiisdosodddddiso"),
vec![8, 64, 3600]);
}
}
fn parse(code: &str) -> Vec<i32> {
let mut result = Vec::new();
let mut temp:i32 = 0;
for ch in code.chars() {
match ch {
'i' => {
temp += 1;
},
'd' => {
temp -= 1;
},
's' => {
temp = temp.pow(2);
},
'o' => {
result.push(temp);
//temp = 0;
},
_ => {},
};
}
result
} |
use super::super::ascii85;
use anyhow::{anyhow, ensure, Result};
use openssl::aes::{unwrap_key, AesKey};
use openssl::symm::{decrypt, Cipher};
use std::convert::TryInto;
pub fn run(bytes: &[u8]) -> Result<Vec<u8>> {
let bytes = ascii85::decode(bytes)?;
ensure!(bytes.len() > 96 && bytes.len() % 8 == 0, "Invalid input");
let key_encrypting_key_bytes: [u8; 32] = bytes[0..32].try_into()?;
let key_encrypting_key = AesKey::new_decrypt(&key_encrypting_key_bytes)
.map_err(|e| anyhow!("Key error: {:?}", e))?;
let kek_iv: [u8; 8] = bytes[32..40].try_into()?;
let mut decrypted_aes_key = [0u8; 32];
let encrypted_aes_key = &bytes[40..80];
unwrap_key(
&key_encrypting_key,
Some(kek_iv),
&mut decrypted_aes_key,
&encrypted_aes_key,
)
.map_err(|e| anyhow!("Key error: {:?}", e))?;
let aes_iv: [u8; 16] = bytes[80..96].try_into()?;
let encrypted_data = &bytes[96..];
decrypt(
Cipher::aes_256_cbc(),
&decrypted_aes_key,
Some(&aes_iv),
encrypted_data,
)
.map_err(|e| anyhow!("Key error: {:?}", e))
}
|
#[derive(Debug, PartialEq)]
pub struct DNA {
nucleotides: String,
}
#[derive(Debug, PartialEq)]
pub struct RNA {
nucleotides: String,
}
impl DNA {
pub fn new(dna: &str) -> Result<DNA, usize> {
match collect_valid_nucleotides(dna, "ACGT") {
Ok(nucleotides) => Ok(DNA { nucleotides }),
Err(i) => Err(i),
}
}
pub fn into_rna(self) -> RNA {
RNA::new(
&self
.nucleotides
.chars()
.map(|nuc| match nuc {
'A' => 'U',
'C' => 'G',
'G' => 'C',
'T' => 'A',
_ => nuc,
})
.collect::<String>(),
)
.unwrap()
}
}
impl RNA {
pub fn new(rna: &str) -> Result<RNA, usize> {
match collect_valid_nucleotides(rna, "ACGU") {
Ok(nucleotides) => Ok(RNA { nucleotides }),
Err(i) => Err(i),
}
}
}
fn collect_valid_nucleotides(
nucleotide_string: &str,
valid_nucleotides: &str,
) -> Result<String, usize> {
let result: String = nucleotide_string
.chars()
.take_while(|&c| valid_nucleotides.contains(c))
.collect();
if result.len() == nucleotide_string.len() {
Ok(result)
} else {
Err(result.len())
}
}
|
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote_spanned};
use syn::Ident;
use crate::codegen::component::{CodeGenChild, CodeGenComponent, CodeGenComponentNames};
use crate::codegen::unique::{CodeGenUnique, CodeGenUniqueNames};
use crate::validation::{
query::{Atom, Query},
AllComponents, AllUniques,
};
pub fn gen_mod_queries(ecs: &Ident, all: &AllComponents, uniques: &AllUniques) -> TokenStream {
let span = ecs.span();
let component_imports: Vec<TokenStream> = all.values().map(|c| c.gen_imports()).collect();
let unique_imports: Vec<TokenStream> = unique.values().map(|c| c.gen_imports()).collect();
let comp_store_atoms: Vec<TokenStream> = all
.values()
.map(|c| c.gen_store_atom(all, uniques))
.collect();
quote_spanned! {span =>
mod queries {
use super::components::*;
use super::uniques::*;
use rl_ecs::stores::{StoreExBasic, StoreExBasicMut,
StoreExCreate,StoreExGetParent,StoreExSetParent,
StoreExGetChild, StoreExPurge};
#(#component_imports)*
#(#unique_imports)*
// #(#queries_ecs_impls)*
}
}
}
pub trait CodeGenQueryNames {
fn to_query_struct_name(&self) -> Ident;
fn to_query_member_name(&self) -> Ident;
fn to_query_atom_name(&self) -> Ident;
}
impl CodeGenQueryNames for Query {
fn to_query_struct_name(&self) -> Ident {
let span = self.name.span();
format_ident!("{}Query", self.name, span = span)
}
fn to_query_struct_name(&self) -> Ident {
let span = self.name.span();
format_ident!("{}_query", self.name.to_lowercase(), span = span)
}
fn to_query_atom_name(&self) -> Ident {
let span = self.name.span();
format_ident!("{}Atom", self.name, span = span)
}
}
trait CodeGenQueryPriv {
fn gen_query_struct(&self, components: &AllComponents) -> TokenStream;
}
impl CodeGenQueryPriv for Query {
fn gen_query_struct(&self, components: &AllComponents) -> TokenStream {
let name = self.to_query_struct_name();
let types = self
.children
.iter()
.map(|c| components.get(c.id).unwrap().to_key_struct())
.collect::<Vec<Ident>>();
quote_spanned! {span =>
struct #name {
list: Vec<#(#types)*>,
}
impl #name {
pub fn new() -> Self {
Self {
list: Vec::new(),
}
}
pub fn update(&mut self) {
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.