text stringlengths 8 4.13M |
|---|
//! CPU-level input/output instructions, including `inb`, `outb`, etc., and
//! a high level Rust wrapper.
#![feature(asm)]
#![feature(const_fn)]
#![no_std]
use core::marker::PhantomData;
#[cfg(any(target_arch="x86", target_arch="x86_64"))]
pub use x86::{inb, outb, inw, outw, inl, outl};
#[cfg(any(target_arch="x86", target_arch="x86_64"))]
mod x86;
/// This trait is defined for any type which can be read or written over a
/// port.
///
/// The processor suppors I/O with `u8`, `u16`, and `u32`. The functions in
/// this trait are all unsafe because they can write to arbitrary ports, which
/// is an inherently unsafe operation.
pub trait InOut {
/// Read a value from the specified port.
unsafe fn port_in(port: u16) -> Self;
/// Write a value to the specified port.
unsafe fn port_out(port: u16, value: Self);
}
impl InOut for u8 {
unsafe fn port_in(port: u16) -> u8 { inb(port) }
unsafe fn port_out(port: u16, value: u8) { outb(port, value) }
}
impl InOut for u16 {
unsafe fn port_in(port: u16) -> u16 { inw(port) }
unsafe fn port_out(port: u16, value: u16) { outw(port, value) }
}
impl InOut for u32 {
unsafe fn port_in(port: u16) -> u32 { inl(port) }
unsafe fn port_out(port: u16, value: u32) { outl(port, value) }
}
pub struct Port<T: InOut> {
port: u16,
phantom: PhantomData<T>,
}
impl<T: InOut> Port<T> {
/// Constructs a new I/O port.
pub const unsafe fn new(port: u16) -> Port<T> {
Port { port: port, phantom: PhantomData }
}
/// Read data from the port.
pub unsafe fn read(&mut self) -> T {
T::port_in(self.port)
}
/// Write data to the port.
pub unsafe fn write(&mut self, value: T) {
T::port_out(self.port, value);
}
}
|
use std::boxed::Box;
use diesel::{self, prelude::*};
use diesel::pg::PgConnection;
use job_juggler::{ExecutableJob, JobResult, LoggableJob};
#[derive(Serialize, Deserialize, LoggableJob)]
#[LogName = "log_data"]
pub struct CreateImageThumbnail {
pub image_id: String,
pub image_data: Vec<u8>,
pub log_data: String
}
impl ExecutableJob for CreateImageThumbnail {
fn execute(self, conn: &PgConnection) -> (Box<Self>, JobResult) {
// We only need imagemagick for one command, so we run it directly.
}
}
/// A job that can be executed
pub trait ExecutableJob
{
/// Execute this job, returning the object itself at the end alongside the result.
fn execute(self, conn: &PgConnection) -> (Box<Self>, JobResult);
}
|
use std::sync::Arc;
use vulkano::buffer::{CpuAccessibleBuffer, BufferUsage};
use vulkano::command_buffer::AutoCommandBufferBuilder;
use vulkano::descriptor::descriptor_set::{DescriptorSet, PersistentDescriptorSet};
use vulkano::descriptor::pipeline_layout::PipelineLayoutAbstract;
use vulkano::device::DeviceOwned;
use vulkano::format::R8Unorm;
use vulkano::pipeline::GraphicsPipeline;
use vulkano::image::{StorageImage, ImageUsage, ImageDimensions, ImageCreateFlags};
use vulkano::image::view::ImageView;
use vulkano::sampler::{Sampler, Filter, MipmapMode, SamplerAddressMode};
use rusttype::PositionedGlyph;
use rusttype::gpu_cache::Cache;
use gristmill::renderer::{PipelineArc, LoadContext, RenderContext};
use gristmill::util::handle::HandleOwner;
use gristmill::new_handle_type;
const TEXT_CACHE_WIDTH: u32 = 1000;
const TEXT_CACHE_HEIGHT: u32 = 1000;
mod vs {
vulkano_shaders::shader!{
ty: "vertex",
src: "
#version 450
layout(push_constant) uniform PushConstants {
vec2 screen_size;
vec2 position;
vec4 color;
} constants;
layout(location = 0) in vec2 position;
layout(location = 1) in vec2 tex_position;
layout(location = 0) out vec2 v_tex_position;
layout(location = 1) out vec4 v_color;
void main() {
vec2 normalized_position = (constants.position + position) / constants.screen_size;
gl_Position = vec4((normalized_position - 0.5) * 2.0, 0.0, 1.0);
v_tex_position = tex_position;
v_color = constants.color;
}
"
}
}
mod fs {
vulkano_shaders::shader!{
ty: "fragment",
src: "
#version 450
layout(location = 0) in vec2 v_tex_position;
layout(location = 1) in vec4 v_color;
layout(location = 0) out vec4 f_color;
layout(set = 0, binding = 0) uniform sampler2D tex;
void main() {
f_color = v_color;
f_color.a *= texture(tex, v_tex_position)[0];
}
"
}
}
pub use vs::ty::PushConstants;
#[derive(Default, Debug, Clone)]
struct Vertex {
position: [f32; 2],
tex_position: [f32; 2],
}
vulkano::impl_vertex!(Vertex, position, tex_position);
impl Vertex {
fn new(position: [i32; 2], tex_position: [f32; 2]) -> Vertex {
Vertex {
position: [position[0] as f32, position[1] as f32],
tex_position,
}
}
}
new_handle_type!(TextHandle);
struct TextSection {
text_glyphs: Vec<PositionedGlyph<'static>>,
vertex_buffer: Option<Arc<CpuAccessibleBuffer<[Vertex]>>>,
}
pub struct TextPipeline {
pipeline: PipelineArc,
cache: Cache<'static>,
cache_pixel_buffer: Vec<u8>,
cache_image: Arc<StorageImage<R8Unorm>>,
descriptor_set: Arc<dyn DescriptorSet + Send + Sync>,
sections: HandleOwner<TextHandle, TextSection>,
}
impl TextPipeline {
pub fn new(context: &mut LoadContext) -> TextPipeline {
let vs = vs::Shader::load(context.device()).unwrap();
let fs = fs::Shader::load(context.device()).unwrap();
let pipeline = Arc::new(
GraphicsPipeline::start()
.vertex_input_single_buffer::<Vertex>()
.vertex_shader(vs.main_entry_point(), ())
.triangle_list()
.viewports_dynamic_scissors_irrelevant(1)
.fragment_shader(fs.main_entry_point(), ())
.blend_alpha_blending()
.render_pass(context.subpass())
.build(context.device())
.unwrap()
);
let cache = Cache::builder().dimensions(TEXT_CACHE_WIDTH, TEXT_CACHE_HEIGHT).build();
let cache_pixel_buffer = vec!(0; (TEXT_CACHE_WIDTH * TEXT_CACHE_HEIGHT) as usize);
let cache_image = StorageImage::with_usage(
context.device(),
ImageDimensions::Dim2d { width: TEXT_CACHE_WIDTH, height: TEXT_CACHE_HEIGHT, array_layers: 1 },
R8Unorm,
ImageUsage {
sampled: true,
transfer_destination: true,
.. ImageUsage::none()
},
ImageCreateFlags::none(),
vec![context.queue().family()], // TODO should be BOTH graphics and transfer queue families.
).unwrap();
let cache_image_view = ImageView::new(cache_image.clone()).unwrap();
let sampler = Sampler::new(
context.device(),
Filter::Linear,
Filter::Linear,
MipmapMode::Nearest,
SamplerAddressMode::Repeat,
SamplerAddressMode::Repeat,
SamplerAddressMode::Repeat,
0.0, 1.0, 0.0, 0.0
).unwrap();
let descriptor_set = Arc::new(
PersistentDescriptorSet::start(pipeline.descriptor_set_layout(0).unwrap().clone())
.add_sampled_image(cache_image_view, sampler).unwrap()
.build().unwrap()
);
TextPipeline { pipeline, cache, cache_pixel_buffer, cache_image, descriptor_set, sections: HandleOwner::new() }
}
pub fn draw(&self, context: &mut RenderContext, text: &Arc<TextHandle>, push_constants: PushConstants) {
let vertex_buffer = self.sections.get(text).vertex_buffer.as_ref().expect("text cache needs update").clone();
context.draw(
self.pipeline.clone(),
vec![vertex_buffer],
self.descriptor_set.clone(),
push_constants
);
}
pub fn add_section(&mut self, text_glyphs: Vec<PositionedGlyph<'static>>) -> Arc<TextHandle> {
self.sections.insert(TextSection { text_glyphs, vertex_buffer: None })
}
pub fn update_cache(&mut self, builder: &mut AutoCommandBufferBuilder) {
self.sections.cleanup();
for section in self.sections.iter() {
for glyph in section.text_glyphs.iter() {
self.cache.queue_glyph(0, glyph.clone());
}
}
// Update the cache, so that all glyphs in the queue are present in the cache texture.
// TODO this builds the full cache image on the CPU, then reuploades the ENTIRE image whenever it changes.
// should just allocate on the GPU and have cache_queued directly update the corresponding region.
let cache_pixel_buffer = &mut self.cache_pixel_buffer;
self.cache.cache_queued(
|rect, src_data| {
let width = (rect.max.x - rect.min.x) as usize;
let height = (rect.max.y - rect.min.y) as usize;
let mut dst_index = ((rect.min.y * TEXT_CACHE_WIDTH) + rect.min.x) as usize;
let mut src_index = 0;
for _ in 0..height {
let dst_slice = &mut cache_pixel_buffer[dst_index..dst_index+width];
let src_slice = &src_data[src_index..src_index+width];
dst_slice.copy_from_slice(src_slice);
dst_index += TEXT_CACHE_WIDTH as usize;
src_index += width;
}
}
).unwrap();
let buffer = CpuAccessibleBuffer::<[u8]>::from_iter(
builder.device().clone(),
BufferUsage::transfer_source(),
false,
cache_pixel_buffer.iter().cloned()
).unwrap();
builder.copy_buffer_to_image(
buffer.clone(),
self.cache_image.clone(),
).unwrap();
// TODO reuse valid vertex buffers if cache_queued returns CachedBy::Adding
let cache = &self.cache;
for section in self.sections.iter_mut() {
let vertices: Vec<Vertex> = section.text_glyphs.iter().flat_map(|g| {
if let Ok(Some((uv_rect, screen_rect))) = cache.rect_for(0, g) {
vec!(
Vertex::new([screen_rect.min.x, screen_rect.max.y], [uv_rect.min.x, uv_rect.max.y]),
Vertex::new([screen_rect.min.x, screen_rect.min.y], [uv_rect.min.x, uv_rect.min.y]),
Vertex::new([screen_rect.max.x, screen_rect.min.y], [uv_rect.max.x, uv_rect.min.y]),
Vertex::new([screen_rect.max.x, screen_rect.min.y], [uv_rect.max.x, uv_rect.min.y]),
Vertex::new([screen_rect.max.x, screen_rect.max.y], [uv_rect.max.x, uv_rect.max.y]),
Vertex::new([screen_rect.min.x, screen_rect.max.y], [uv_rect.min.x, uv_rect.max.y]),
).into_iter()
}
else {
vec!().into_iter()
}
}).collect();
// TODO use CpuBufferPool
section.vertex_buffer = Some(
CpuAccessibleBuffer::from_iter(
builder.device().clone(),
BufferUsage::vertex_buffer(),
false,
vertices.into_iter(),
).unwrap());
}
}
}
|
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, ShellError,
Signature, Span, Value,
};
use std::cmp::Ordering;
#[derive(Clone)]
pub struct Sort;
impl Command for Sort {
fn name(&self) -> &str {
"sort"
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("sort")
.switch("reverse", "Sort in reverse order", Some('r'))
.switch(
"insensitive",
"Sort string-based columns case-insensitively",
Some('i'),
)
.switch(
"values",
"If input is a single record, sort the record by values, ignored if input is not a single record",
Some('v'),
)
.category(Category::Filters)
}
fn usage(&self) -> &str {
"Sort in increasing order."
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "[2 0 1] | sort",
description: "sort the list by increasing value",
result: Some(Value::List {
vals: vec![Value::test_int(0), Value::test_int(1), Value::test_int(2)],
span: Span::test_data(),
}),
},
Example {
example: "[2 0 1] | sort -r",
description: "sort the list by decreasing value",
result: Some(Value::List {
vals: vec![Value::test_int(2), Value::test_int(1), Value::test_int(0)],
span: Span::test_data(),
}),
},
Example {
example: "[betty amy sarah] | sort",
description: "sort a list of strings",
result: Some(Value::List {
vals: vec![
Value::test_string("amy"),
Value::test_string("betty"),
Value::test_string("sarah"),
],
span: Span::test_data(),
}),
},
Example {
example: "[betty amy sarah] | sort -r",
description: "sort a list of strings in reverse",
result: Some(Value::List {
vals: vec![
Value::test_string("sarah"),
Value::test_string("betty"),
Value::test_string("amy"),
],
span: Span::test_data(),
}),
},
Example {
description: "Sort strings (case-insensitive)",
example: "echo [airplane Truck Car] | sort -i",
result: Some(Value::List {
vals: vec![
Value::test_string("airplane"),
Value::test_string("Car"),
Value::test_string("Truck"),
],
span: Span::test_data(),
}),
},
Example {
description: "Sort strings (reversed case-insensitive)",
example: "echo [airplane Truck Car] | sort -i -r",
result: Some(Value::List {
vals: vec![
Value::test_string("Truck"),
Value::test_string("Car"),
Value::test_string("airplane"),
],
span: Span::test_data(),
}),
},
Example {
description: "Sort record by key",
example: "{b: 3, a: 4} | sort",
result: Some(Value::Record {
cols: vec!["a".to_string(), "b".to_string()],
vals: vec![Value::test_int(4), Value::test_int(3)],
span: Span::test_data(),
}),
},
Example {
description: "Sort record by value",
example: "{a: 4, b: 3} | sort",
result: Some(Value::Record {
cols: vec!["b".to_string(), "a".to_string()],
vals: vec![Value::test_int(3), Value::test_int(4)],
span: Span::test_data(),
}),
},
]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let reverse = call.has_flag("reverse");
let insensitive = call.has_flag("insensitive");
let metadata = &input.metadata();
match input {
PipelineData::Value(Value::Record { cols, vals, span }, ..) => {
let sort_by_value = call.has_flag("values");
let record = sort_record(cols, vals, span, sort_by_value);
Ok(record.into_pipeline_data())
}
PipelineData::Value(v, ..)
if !matches!(v, Value::List { .. } | Value::Range { .. }) =>
{
Ok(v.into_pipeline_data())
}
pipe_data => {
let mut vec: Vec<_> = pipe_data.into_iter().collect();
sort(&mut vec, call.head, insensitive)?;
if reverse {
vec.reverse()
}
let iter = vec.into_iter();
match metadata {
Some(m) => Ok(iter
.into_pipeline_data_with_metadata(m.clone(), engine_state.ctrlc.clone())),
None => Ok(iter.into_pipeline_data(engine_state.ctrlc.clone())),
}
}
}
}
}
fn sort_record(cols: Vec<String>, vals: Vec<Value>, rec_span: Span, sort_by_value: bool) -> Value {
let mut input_pairs: Vec<(String, Value)> = cols.into_iter().zip(vals).collect();
if sort_by_value {
input_pairs.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal));
} else {
input_pairs.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));
}
let mut new_cols = Vec::with_capacity(input_pairs.len());
let mut new_vals = Vec::with_capacity(input_pairs.len());
for (col, val) in input_pairs {
new_cols.push(col);
new_vals.push(val)
}
Value::Record {
cols: new_cols,
vals: new_vals,
span: rec_span,
}
}
pub fn sort(vec: &mut [Value], span: Span, insensitive: bool) -> Result<(), ShellError> {
if vec.is_empty() {
return Err(ShellError::GenericError(
"no values to work with".to_string(),
"".to_string(),
None,
Some("no values to work with".to_string()),
Vec::new(),
));
}
match &vec[0] {
Value::Record {
cols,
vals: _input_vals,
..
} => {
let columns = cols.clone();
vec.sort_by(|a, b| process(a, b, &columns, span, insensitive));
}
_ => {
vec.sort_by(|a, b| {
if insensitive {
let lowercase_left = match a {
Value::String { val, span } => Value::String {
val: val.to_ascii_lowercase(),
span: *span,
},
_ => a.clone(),
};
let lowercase_right = match b {
Value::String { val, span } => Value::String {
val: val.to_ascii_lowercase(),
span: *span,
},
_ => b.clone(),
};
lowercase_left
.partial_cmp(&lowercase_right)
.unwrap_or(Ordering::Equal)
} else {
a.partial_cmp(b).unwrap_or(Ordering::Equal)
}
});
}
}
Ok(())
}
pub fn process(
left: &Value,
right: &Value,
columns: &[String],
span: Span,
insensitive: bool,
) -> Ordering {
for column in columns {
let left_value = left.get_data_by_key(column);
let left_res = match left_value {
Some(left_res) => left_res,
None => Value::Nothing { span },
};
let right_value = right.get_data_by_key(column);
let right_res = match right_value {
Some(right_res) => right_res,
None => Value::Nothing { span },
};
let result = if insensitive {
let lowercase_left = match left_res {
Value::String { val, span } => Value::String {
val: val.to_ascii_lowercase(),
span,
},
_ => left_res,
};
let lowercase_right = match right_res {
Value::String { val, span } => Value::String {
val: val.to_ascii_lowercase(),
span,
},
_ => right_res,
};
lowercase_left
.partial_cmp(&lowercase_right)
.unwrap_or(Ordering::Equal)
} else {
left_res.partial_cmp(&right_res).unwrap_or(Ordering::Equal)
};
if result != Ordering::Equal {
return result;
}
}
Ordering::Equal
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Sort {})
}
}
|
#[doc = "Register `ISR0` reader"]
pub type R = crate::R<ISR0_SPEC>;
#[doc = "Register `ISR0` writer"]
pub type W = crate::W<ISR0_SPEC>;
#[doc = "Field `AE0` reader - Acknowledge error 0"]
pub type AE0_R = crate::BitReader;
#[doc = "Field `AE0` writer - Acknowledge error 0"]
pub type AE0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE1` reader - Acknowledge error 1"]
pub type AE1_R = crate::BitReader;
#[doc = "Field `AE1` writer - Acknowledge error 1"]
pub type AE1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE2` reader - Acknowledge error 2"]
pub type AE2_R = crate::BitReader;
#[doc = "Field `AE2` writer - Acknowledge error 2"]
pub type AE2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE3` reader - Acknowledge error 3"]
pub type AE3_R = crate::BitReader;
#[doc = "Field `AE3` writer - Acknowledge error 3"]
pub type AE3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE4` reader - Acknowledge error 4"]
pub type AE4_R = crate::BitReader;
#[doc = "Field `AE4` writer - Acknowledge error 4"]
pub type AE4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE5` reader - Acknowledge error 5"]
pub type AE5_R = crate::BitReader;
#[doc = "Field `AE5` writer - Acknowledge error 5"]
pub type AE5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE6` reader - Acknowledge error 6"]
pub type AE6_R = crate::BitReader;
#[doc = "Field `AE6` writer - Acknowledge error 6"]
pub type AE6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE7` reader - Acknowledge error 7"]
pub type AE7_R = crate::BitReader;
#[doc = "Field `AE7` writer - Acknowledge error 7"]
pub type AE7_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE8` reader - Acknowledge error 8"]
pub type AE8_R = crate::BitReader;
#[doc = "Field `AE8` writer - Acknowledge error 8"]
pub type AE8_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE9` reader - Acknowledge error 9"]
pub type AE9_R = crate::BitReader;
#[doc = "Field `AE9` writer - Acknowledge error 9"]
pub type AE9_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE10` reader - Acknowledge error 10"]
pub type AE10_R = crate::BitReader;
#[doc = "Field `AE10` writer - Acknowledge error 10"]
pub type AE10_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE11` reader - Acknowledge error 11"]
pub type AE11_R = crate::BitReader;
#[doc = "Field `AE11` writer - Acknowledge error 11"]
pub type AE11_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE12` reader - Acknowledge error 12"]
pub type AE12_R = crate::BitReader;
#[doc = "Field `AE12` writer - Acknowledge error 12"]
pub type AE12_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE13` reader - Acknowledge error 13"]
pub type AE13_R = crate::BitReader;
#[doc = "Field `AE13` writer - Acknowledge error 13"]
pub type AE13_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE14` reader - Acknowledge error 14"]
pub type AE14_R = crate::BitReader;
#[doc = "Field `AE14` writer - Acknowledge error 14"]
pub type AE14_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AE15` reader - Acknowledge error 15"]
pub type AE15_R = crate::BitReader;
#[doc = "Field `AE15` writer - Acknowledge error 15"]
pub type AE15_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PE0` reader - PHY error 0"]
pub type PE0_R = crate::BitReader;
#[doc = "Field `PE0` writer - PHY error 0"]
pub type PE0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PE1` reader - PHY error 1"]
pub type PE1_R = crate::BitReader;
#[doc = "Field `PE1` writer - PHY error 1"]
pub type PE1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PE2` reader - PHY error 2"]
pub type PE2_R = crate::BitReader;
#[doc = "Field `PE2` writer - PHY error 2"]
pub type PE2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PE3` reader - PHY error 3"]
pub type PE3_R = crate::BitReader;
#[doc = "Field `PE3` writer - PHY error 3"]
pub type PE3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PE4` reader - PHY error 4"]
pub type PE4_R = crate::BitReader;
#[doc = "Field `PE4` writer - PHY error 4"]
pub type PE4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Acknowledge error 0"]
#[inline(always)]
pub fn ae0(&self) -> AE0_R {
AE0_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Acknowledge error 1"]
#[inline(always)]
pub fn ae1(&self) -> AE1_R {
AE1_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Acknowledge error 2"]
#[inline(always)]
pub fn ae2(&self) -> AE2_R {
AE2_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Acknowledge error 3"]
#[inline(always)]
pub fn ae3(&self) -> AE3_R {
AE3_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Acknowledge error 4"]
#[inline(always)]
pub fn ae4(&self) -> AE4_R {
AE4_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Acknowledge error 5"]
#[inline(always)]
pub fn ae5(&self) -> AE5_R {
AE5_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Acknowledge error 6"]
#[inline(always)]
pub fn ae6(&self) -> AE6_R {
AE6_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Acknowledge error 7"]
#[inline(always)]
pub fn ae7(&self) -> AE7_R {
AE7_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - Acknowledge error 8"]
#[inline(always)]
pub fn ae8(&self) -> AE8_R {
AE8_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Acknowledge error 9"]
#[inline(always)]
pub fn ae9(&self) -> AE9_R {
AE9_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Acknowledge error 10"]
#[inline(always)]
pub fn ae10(&self) -> AE10_R {
AE10_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Acknowledge error 11"]
#[inline(always)]
pub fn ae11(&self) -> AE11_R {
AE11_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - Acknowledge error 12"]
#[inline(always)]
pub fn ae12(&self) -> AE12_R {
AE12_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - Acknowledge error 13"]
#[inline(always)]
pub fn ae13(&self) -> AE13_R {
AE13_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - Acknowledge error 14"]
#[inline(always)]
pub fn ae14(&self) -> AE14_R {
AE14_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - Acknowledge error 15"]
#[inline(always)]
pub fn ae15(&self) -> AE15_R {
AE15_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - PHY error 0"]
#[inline(always)]
pub fn pe0(&self) -> PE0_R {
PE0_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - PHY error 1"]
#[inline(always)]
pub fn pe1(&self) -> PE1_R {
PE1_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - PHY error 2"]
#[inline(always)]
pub fn pe2(&self) -> PE2_R {
PE2_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - PHY error 3"]
#[inline(always)]
pub fn pe3(&self) -> PE3_R {
PE3_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - PHY error 4"]
#[inline(always)]
pub fn pe4(&self) -> PE4_R {
PE4_R::new(((self.bits >> 20) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Acknowledge error 0"]
#[inline(always)]
#[must_use]
pub fn ae0(&mut self) -> AE0_W<ISR0_SPEC, 0> {
AE0_W::new(self)
}
#[doc = "Bit 1 - Acknowledge error 1"]
#[inline(always)]
#[must_use]
pub fn ae1(&mut self) -> AE1_W<ISR0_SPEC, 1> {
AE1_W::new(self)
}
#[doc = "Bit 2 - Acknowledge error 2"]
#[inline(always)]
#[must_use]
pub fn ae2(&mut self) -> AE2_W<ISR0_SPEC, 2> {
AE2_W::new(self)
}
#[doc = "Bit 3 - Acknowledge error 3"]
#[inline(always)]
#[must_use]
pub fn ae3(&mut self) -> AE3_W<ISR0_SPEC, 3> {
AE3_W::new(self)
}
#[doc = "Bit 4 - Acknowledge error 4"]
#[inline(always)]
#[must_use]
pub fn ae4(&mut self) -> AE4_W<ISR0_SPEC, 4> {
AE4_W::new(self)
}
#[doc = "Bit 5 - Acknowledge error 5"]
#[inline(always)]
#[must_use]
pub fn ae5(&mut self) -> AE5_W<ISR0_SPEC, 5> {
AE5_W::new(self)
}
#[doc = "Bit 6 - Acknowledge error 6"]
#[inline(always)]
#[must_use]
pub fn ae6(&mut self) -> AE6_W<ISR0_SPEC, 6> {
AE6_W::new(self)
}
#[doc = "Bit 7 - Acknowledge error 7"]
#[inline(always)]
#[must_use]
pub fn ae7(&mut self) -> AE7_W<ISR0_SPEC, 7> {
AE7_W::new(self)
}
#[doc = "Bit 8 - Acknowledge error 8"]
#[inline(always)]
#[must_use]
pub fn ae8(&mut self) -> AE8_W<ISR0_SPEC, 8> {
AE8_W::new(self)
}
#[doc = "Bit 9 - Acknowledge error 9"]
#[inline(always)]
#[must_use]
pub fn ae9(&mut self) -> AE9_W<ISR0_SPEC, 9> {
AE9_W::new(self)
}
#[doc = "Bit 10 - Acknowledge error 10"]
#[inline(always)]
#[must_use]
pub fn ae10(&mut self) -> AE10_W<ISR0_SPEC, 10> {
AE10_W::new(self)
}
#[doc = "Bit 11 - Acknowledge error 11"]
#[inline(always)]
#[must_use]
pub fn ae11(&mut self) -> AE11_W<ISR0_SPEC, 11> {
AE11_W::new(self)
}
#[doc = "Bit 12 - Acknowledge error 12"]
#[inline(always)]
#[must_use]
pub fn ae12(&mut self) -> AE12_W<ISR0_SPEC, 12> {
AE12_W::new(self)
}
#[doc = "Bit 13 - Acknowledge error 13"]
#[inline(always)]
#[must_use]
pub fn ae13(&mut self) -> AE13_W<ISR0_SPEC, 13> {
AE13_W::new(self)
}
#[doc = "Bit 14 - Acknowledge error 14"]
#[inline(always)]
#[must_use]
pub fn ae14(&mut self) -> AE14_W<ISR0_SPEC, 14> {
AE14_W::new(self)
}
#[doc = "Bit 15 - Acknowledge error 15"]
#[inline(always)]
#[must_use]
pub fn ae15(&mut self) -> AE15_W<ISR0_SPEC, 15> {
AE15_W::new(self)
}
#[doc = "Bit 16 - PHY error 0"]
#[inline(always)]
#[must_use]
pub fn pe0(&mut self) -> PE0_W<ISR0_SPEC, 16> {
PE0_W::new(self)
}
#[doc = "Bit 17 - PHY error 1"]
#[inline(always)]
#[must_use]
pub fn pe1(&mut self) -> PE1_W<ISR0_SPEC, 17> {
PE1_W::new(self)
}
#[doc = "Bit 18 - PHY error 2"]
#[inline(always)]
#[must_use]
pub fn pe2(&mut self) -> PE2_W<ISR0_SPEC, 18> {
PE2_W::new(self)
}
#[doc = "Bit 19 - PHY error 3"]
#[inline(always)]
#[must_use]
pub fn pe3(&mut self) -> PE3_W<ISR0_SPEC, 19> {
PE3_W::new(self)
}
#[doc = "Bit 20 - PHY error 4"]
#[inline(always)]
#[must_use]
pub fn pe4(&mut self) -> PE4_W<ISR0_SPEC, 20> {
PE4_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 = "DSI Host interrupt and status register 0\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr0::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 [`isr0::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ISR0_SPEC;
impl crate::RegisterSpec for ISR0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`isr0::R`](R) reader structure"]
impl crate::Readable for ISR0_SPEC {}
#[doc = "`write(|w| ..)` method takes [`isr0::W`](W) writer structure"]
impl crate::Writable for ISR0_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets ISR0 to value 0"]
impl crate::Resettable for ISR0_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::mem;
use random;
use glsl::icosahedron;
use chunk::{IntCoord, Chunk, Cell, CellPos, Root, ROOT_QUADS};
use nalgebra;
use nalgebra::{Point2, Point3, Vector3};
use rand;
type Pt2 = Point2<f64>;
type Pt3 = Point3<f64>;
pub struct Spec {
seed: usize,
radius: f64,
cells_per_chunk: IntCoord,
chunks_per_root_side: IntCoord,
resolution: IntCoord,
}
pub struct Globe {
spec: Spec,
rand: random::RandomGenerator,
chunk: Vec<Chunk>,
}
impl Globe {
pub fn new(spec: Spec) -> Globe {
let mut globe = Globe {
rand: random::RandomGenerator::new(spec.seed),
spec: spec,
chunk: vec![],
};
globe.create_chunks();
globe
}
pub fn new_example() -> Globe {
Globe::new(Spec {
seed: 42,
radius: 1.2,
chunks_per_root_side: 4,
resolution: 3,
cells_per_chunk: 1,
})
}
// fn split_triangle(&self, triangle: &[[f64;2]; 3]) -> Vec<[Pt2; 3]> {
fn split_triangle(&self, triangle: &[Pt2; 3]) -> Vec<[Pt2; 3]> {
let mut triangles: Vec<[Pt2; 3]> = vec![];
let a = triangle[0];
let b = triangle[1];
let c = triangle[2];
let ab = nalgebra::center(&a, &b);
let ac = nalgebra::center(&a, &c);
let cb = nalgebra::center(&c, &b);
triangles.push([a, ac, ab]);
triangles.push([ab, b, cb]);
triangles.push([ac, cb, ab]);
triangles.push([ac, cb, c]);
triangles
}
pub fn make_geometry(&self) -> (Vec<::Vertex>, Vec<u16>) {
let mut triangles: Vec<[Pt2; 3]> = vec![];
for triangle in icosahedron::VERTEX_IN_ROOT.iter() {
let a = Pt2::from_coordinates(triangle[0].into());
let b = Pt2::from_coordinates(triangle[1].into());
let c = Pt2::from_coordinates(triangle[2].into());
triangles.push([a, b, c]);
}
for _ in 0..self.spec.resolution {
let mut temp = mem::replace(&mut triangles, vec![]);
for triangle in &temp {
triangles.extend(self.split_triangle(triangle));
}
}
let mut vertex_data: Vec<::Vertex> = Vec::new();
let mut index_data: Vec<u16> = Vec::new();
for root_index in 0..ROOT_QUADS {
for triangle in triangles.iter() {
for point in triangle.iter() {
let pt3 = Globe::project_to_world(&Root::new(root_index), point);
let mut root_color = icosahedron::RAINBOW[root_index as usize];
for mut color_channel in root_color.iter_mut() {
*color_channel *= rand::random();
}
let vertex = ::Vertex::new([pt3[0] as f32, pt3[1] as f32, pt3[2] as f32],
root_color);
let vertex_count = vertex_data.len();
vertex_data.push(vertex);
index_data.push(vertex_count as u16);
}
}
}
(vertex_data, index_data)
}
fn make_geometry_chunk(&self,
origin: CellPos,
vertex_data: &mut Vec<::Vertex>,
index_data: &mut Vec<u16>) {
let chunks_in_two_triangles = self.spec.chunks_per_root_side / 2; // 1 root = 4 triangles
let pt_a = icosahedron::VERTEX_IN_ROOT[0][0];
let pt_f = icosahedron::VERTEX_IN_ROOT[3][2];
let length_in_x = pt_f[0] - pt_a[0];
let length_in_y = pt_f[1] - pt_a[1];
let chunk_length_in_x = length_in_x / chunks_in_two_triangles as f64;
let chunk_length_in_y = length_in_y / chunks_in_two_triangles as f64;
for x in 0..chunks_in_two_triangles {
for y in 0..chunks_in_two_triangles {
//create cells instead of single vertex
let pt3 = Globe::project_to_world(&origin.root,
&Pt2::new(chunk_length_in_x * x as f64,
chunk_length_in_y * y as f64));
let root_color = icosahedron::RAINBOW[origin.root.index() as usize];
let vertex = ::Vertex::new([pt3[0] as f32, pt3[1] as f32, pt3[2] as f32],
root_color);
let vertex_count = vertex_data.len();
vertex_data.push(vertex);
index_data.push(vertex_count as u16);
}
}
}
fn create_chunks(&mut self) {
for root in 0..ROOT_QUADS {
let root = Root::new(root);
for y in 0..self.spec.chunks_per_root_side {
for x in 0..self.spec.chunks_per_root_side {
let origin = CellPos {
root: root.clone(),
x: x * self.spec.chunks_per_root_side,
y: y * self.spec.chunks_per_root_side,
};
self.build_chunk(origin);
}
}
}
}
fn build_chunk(&mut self, origin: CellPos) {
let mut cells: Vec<Cell> = vec![];
let end_x = origin.x + self.spec.cells_per_chunk;
let end_y = origin.y + self.spec.cells_per_chunk;
for cell_y in origin.y..end_y {
for cell_x in origin.x..end_x {
let p = [1.0, 2.0, 3.0];
let height = 1.0 + self.rand.next(&p) * 0.1;
cells.push(Cell { height: height })
}
}
}
pub fn project_to_world(root: &Root, pt_in_root_quad: &Pt2) -> Pt3 {
// TODO : use half-edge-mesh to calculate this automatically instead of
// relying on hardcoded order of icosahedron triangles
// TODO : think about keeping positive x in [a,b,c,d] and negative x in [c,d,e,f]
// and similar for y coordinates
/*
*a
*b *c
*d *e
*f
Assumptions:
-5 root quads (0, 4),
-i_north triangle contains [a, b, c]
-i_south triangle contains [d, e, f]
-inner triangles: [d, b, c], [d, e, c]
*/
let mut pt_in_root_quad = pt_in_root_quad.clone();
let (i_north, i_south) = (root.index() as usize * 2, root.index() as usize * 2 + 11);
assert!(i_north < 9 && i_north % 2 == 0);
assert!(i_south > 9 && i_south < 20 && i_south % 2 == 1);
//TODO Pt3::from(slice) Pt3 seems broken atm
//TODO assert correct order of intermediate triangles
let (a, b, c) = Globe::icosahedron_triangle_to_points(i_north);
let (d, e, f) = Globe::icosahedron_triangle_to_points(i_south);
let point: Pt3 = if pt_in_root_quad.x + pt_in_root_quad.y < 1.0 {
//triangle abc
a + (b - a) * pt_in_root_quad.x + (c - a) * pt_in_root_quad.y
} else if pt_in_root_quad.y < 1.0 {
//triangle bcd
pt_in_root_quad.x = 1.0 - pt_in_root_quad.x;
pt_in_root_quad.y = 1.0 - pt_in_root_quad.y;
d + (c - d) * pt_in_root_quad.x + (b - d) * pt_in_root_quad.y
} else if pt_in_root_quad.x + pt_in_root_quad.y < 2.0 {
//triangle cde
pt_in_root_quad.y -= 1.0;
c + (d - c) * pt_in_root_quad.x + (e - c) * pt_in_root_quad.y
} else {
//triangle def
pt_in_root_quad.y -= 1.0;
pt_in_root_quad.x = 1.0 - pt_in_root_quad.x;
pt_in_root_quad.y = 1.0 - pt_in_root_quad.y;
f + (e - f) * pt_in_root_quad.x + (d - f) * pt_in_root_quad.y
};
Pt3::from_coordinates(nalgebra::normalize(&point.coords))
}
fn icosahedron_triangle_to_points(triangle_index: usize) -> (Pt3, Pt3, Pt3) {
let triangle = icosahedron::TRIANGLE_LIST[triangle_index];
let x: Vec<Pt3> = triangle
.into_iter()
.map(|p| {
let vertex = icosahedron::VERTICES[p.clone()];
Pt3::new(vertex[0], vertex[1], vertex[2])
})
.collect();
(x[0], x[1], x[2])
}
}
//TODO more tests
#[cfg(test)]
mod project_to_first_triangle {
use super::*;
use glsl::icosahedron::{S, X};
#[test]
fn in_vertex() {
let x = Globe::project_to_world(&Root::new(0), Pt2::new(0.0, 0.0));
assert_eq!(Pt3::new(-S, X, 0.0), x);
}
}
|
extern crate cryptopals_lib;
extern crate rusty_aes;
use crate::cryptopals_lib::base64;
use crate::cryptopals_lib::utils::file_io_utils;
use crate::rusty_aes::decrypt::Decrypt;
use crate::cryptopals_lib::hex;
pub fn main() {
let file_name = "challenge_files/7.txt";
//read file to string
let input = file_io_utils::read_file_by_lines_to_str(&file_name);
//base64 decode file
let input = base64::decoder::decode_str_to_u8(&input);
let key = "YELLOW SUBMARINE".as_bytes().to_vec();
//instantiate our aes decryptor
let decrypt: Decrypt = Decrypt::ecb(key);
let results = decrypt.decrypt(input);
// let mut buf: Vec<u8> = Vec::new();
// let buf_len = 16;
// println!();
// let mut count = 0;
// while count < input.len() {
// if count + buf_len >= input.len() {
// // buf = enc_str[count..(enc_str.len() - count)].to_vec();
// let mut slice = input[count..count + (input.len() - count)].to_vec();
// let padding = buf_len - slice.len() ;
// for _z in 0..padding {
// slice.push(0x80);
// }
// buf.append(&mut decrypt.decrypt(slice));
// }
// else {
// let slice = input[count..(count + buf_len)].to_vec();
// assert_eq!(slice.len(), buf_len);
// buf.append(&mut decrypt.decrypt(slice));
// }
// count += buf_len;
// }
for r in results {
print!("{}", r as char);
}
println!();
} |
use rand::random;
pub const CHIP8_SCREEN_WIDTH: usize = 64;
pub const CHIP8_SCREEN_HEIGHT: usize = 32;
// Only included for documentation purposes
//pub const CHIP8_NUM_PIXELS: usize = CHIP8_SCREEN_WIDTH * CHIP8_SCREEN_HEIGHT;
pub const SCHIP8_SCREEN_WIDTH: usize = 128;
pub const SCHIP8_SCREEN_HEIGHT: usize = 64;
pub const SCHIP8_NUM_PIXELS: usize = SCHIP8_SCREEN_WIDTH * SCHIP8_SCREEN_HEIGHT;
const CHIP8_FONT: [u8; 80] = [
0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0,
0x10, 0xF0, 0x10, 0xF0, 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, 0xF0, 0x80,
0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, 0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0,
0x10, 0xF0, 0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0, 0xF0, 0x80, 0x80, 0x80,
0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80,
];
// See https://github.com/mattmikolay/chip-8/issues/3
// From https://github.com/zaymat/super-chip8/blob/master/cpu.cpp
const SCHIP8_FONT: [u8; 100] = [
0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC3, 0xC3, 0xE7, 0x7E, 0x3C, 0x18, 0x38, 0x58, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x3C, 0x3E, 0x7F, 0xC3, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xFF, 0xFF, 0x3C, 0x7E,
0xC3, 0x03, 0x0E, 0x0E, 0x03, 0xC3, 0x7E, 0x3C, 0x06, 0x0E, 0x1E, 0x36, 0x66, 0xC6, 0xFF, 0xFF,
0x06, 0x06, 0xFF, 0xFF, 0xC0, 0xC0, 0xFC, 0xFE, 0x03, 0xC3, 0x7E, 0x3C, 0x3E, 0x7C, 0xC0, 0xC0,
0xFC, 0xFE, 0xC3, 0xC3, 0x7E, 0x3C, 0xFF, 0xFF, 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x60, 0x60,
0x3C, 0x7E, 0xC3, 0xC3, 0x7E, 0x7E, 0xC3, 0xC3, 0x7E, 0x3C, 0x3C, 0x7E, 0xC3, 0xC3, 0x7F, 0x3F,
0x03, 0x03, 0x3E, 0x7C,
];
pub struct SChip8 {
pc: usize, //
ar: u16, // Address register
sp: usize, //
r: [u8; 8], // RPL Flags
v: [u16; 16], //
pub dt: u8, // Delay timer
pub st: u8, // Sound timer
stack: [usize; 48], // Stack implemented as empty ascending
ram: [u8; 0x1000], //
pub screen: [u8; SCHIP8_NUM_PIXELS], //
pub screen_width: usize, //
pub screen_height: usize, //
pub extended_screen: bool, //
pub key_pad: [bool; 16], //
}
impl SChip8 {
pub fn new(program: Vec<u8>) -> SChip8 {
let mut schip8 = SChip8 {
pc: 512,
ar: 0,
sp: 0,
r: [0; 8],
v: [0; 16],
dt: 0,
st: 0,
stack: [0; 48],
ram: [0; 0x1000],
screen: [0; SCHIP8_NUM_PIXELS],
screen_width: CHIP8_SCREEN_WIDTH,
screen_height: CHIP8_SCREEN_HEIGHT,
extended_screen: false,
key_pad: [false; 16],
};
let (reserved, ram) = schip8.ram.split_at_mut(512);
assert!(reserved.len() == 512);
let (ram_l, _ram_r) = ram.split_at_mut(program.len());
ram_l.copy_from_slice(program.as_slice());
// Insert font data
let mut chip8_font_area = schip8.ram.split_at_mut(80);
assert!(chip8_font_area.0.len() == 80);
chip8_font_area.0.copy_from_slice(&CHIP8_FONT);
chip8_font_area = schip8.ram.split_at_mut(80);
let schip8_font_area = chip8_font_area.1.split_at_mut(100);
assert!(schip8_font_area.0.len() == 100);
schip8_font_area.0.copy_from_slice(&SCHIP8_FONT);
#[cfg(debug_assertions)]
{
println!("----- SCHIP8 Oxidized Interactive Debugger -----");
}
return schip8;
}
pub fn run(&mut self, key: usize, redraw: &mut bool) -> bool {
let first_half: u8 = self.ram[self.pc];
let second_half: u8 = self.ram[self.pc + 1];
let instruction: [u8; 4] = [
(first_half & 0xF0) >> 4,
first_half & 0xF,
(second_half & 0xF0) >> 4,
second_half & 0xF,
];
#[cfg(debug_assertions)]
{
println!(
"Opcode: {:01X}{:01X}{:01X}{:01X}",
instruction[0], instruction[1], instruction[2], instruction[3]
);
}
match instruction {
// 00CN - Scroll display N lines down
[0x0, 0x0, 0xC, c] => {
let num_pixels = self.screen_width * self.screen_height;
let offset = (c as usize) * self.screen_width;
let mut new_screen = [0; SCHIP8_NUM_PIXELS];
new_screen[offset..num_pixels].copy_from_slice(&self.screen[0..(num_pixels - offset)]);
self.screen = new_screen;
}
// 00E0 - Clears the screen.
[0x0, 0x0, 0xE, 0x0] => {
self.screen = [0; SCHIP8_NUM_PIXELS];
*redraw = true;
}
// 00EE - Returns from a subroutine.
[0x0, 0x0, 0xE, 0xE] => {
self.sp -= 1;
self.pc = self.stack[self.sp];
}
// 00FB - Scroll display 4 pixels right
[0x0, 0x0, 0xF, 0xB] => {
let mut y = 0;
while y < self.screen_height {
let cur_row = y * self.screen_width;
for i in (0..cur_row - 4).rev() {
self.screen[i + 4] = self.screen[i];
}
for i in 0..4 {
self.screen[i] = 0;
}
y += 1;
}
}
// 00FC - Scroll display 4 pixels left
[0x0, 0x0, 0xF, 0xC] => {
let mut y = 0;
while y < self.screen_height {
let cur_row = y * self.screen_width;
for i in cur_row + 4..cur_row + self.screen_width {
self.screen[i - 4] = self.screen[i];
}
for i in self.screen_width - 4..self.screen_width {
self.screen[i] = 0;
}
y += 1;
}
}
// 00FD - Exit CHIP interpreter
[0x0, 0x0, 0xF, 0xD] => {
return false;
}
// 00FE - Disable extended screen mode
[0x0, 0x0, 0xF, 0xE] => {
self.extended_screen = false;
self.screen_width = CHIP8_SCREEN_WIDTH;
self.screen_height = CHIP8_SCREEN_HEIGHT;
}
// 00FF - Enable extended screen mode for full-screen graphics
[0x0, 0x0, 0xF, 0xF] => {
self.extended_screen = true;
self.screen_width = SCHIP8_SCREEN_WIDTH;
self.screen_height = SCHIP8_SCREEN_HEIGHT;
}
// 0NNN - Calls RCA 1802 program at address NNN. Not necessary for most ROMs.
// See issue.
[0x0, _, _, _] => {
unimplemented!();
}
// 1NNN - Jumps to address NNN.
[0x1, a, b, c] => {
let addr = (((a as u16) << 8) | ((b as u16) << 4) | (c as u16)) as usize;
self.pc = addr - 2;
}
// 2NNN - Calls subroutine at NNN.
[0x2, a, b, c] => {
let addr = (((a as u16) << 8) | ((b as u16) << 4) | (c as u16)) as usize;
self.stack[self.sp] = self.pc;
self.sp += 1;
self.pc = addr - 2;
}
// 3XNN - Skips the next instruction if VX equals NN. (Usually the next instruction is a jump to skip a code block)
[0x3, x, b, c] => {
let nn = ((b << 4) | c) as u16;
if self.v[x as usize] == nn {
self.pc += 2;
}
}
// 4XNN - Skips the next instruction if VX doesn't equal NN. (Usually the next instruction is a jump to skip a code block)
[0x4, x, b, c] => {
let nn = ((b << 4) | c) as u16;
if self.v[x as usize] != nn {
self.pc += 2;
}
}
// 5XNN - Skips the next instruction if VX equals VY. (Usually the next instruction is a jump to skip a code block)
[0x5, x, y, 0] => {
if self.v[x as usize] == self.v[y as usize] {
self.pc += 2;
}
}
// 6XNN - Sets VX to NN.
[0x6, x, b, c] => {
let nn = ((b << 4) | c) as u16;
self.v[x as usize] = nn;
}
// 7XNN - Adds NN to VX. (Carry flag is not changed)
[0x7, x, b, c] => {
let nn = ((b << 4) | c) as u16;
let sum = self.v[x as usize] + nn;
self.v[x as usize] = (sum & 0xFF) as u16;
}
// 8XY0 - Sets VX to the value of VY.
[0x8, x, y, 0x0] => {
self.v[x as usize] = self.v[y as usize];
}
// 8XY1 - Sets VX to VX or VY. (Bitwise OR operation)
[0x8, x, y, 0x1] => {
self.v[x as usize] |= self.v[y as usize];
}
// 8XY2 - Sets VX to VX and VY. (Bitwise AND operation)
[0x8, x, y, 0x2] => {
self.v[x as usize] &= self.v[y as usize];
}
// 8XY3 - Sets VX to VX xor VY.
[0x8, x, y, 0x3] => {
self.v[x as usize] ^= self.v[y as usize];
}
// 8XY4 - Adds VY to VX. VF is set to 1 when there's a carry, and to 0 when there isn't.
[0x8, x, y, 0x4] => {
let sum = self.v[x as usize] + self.v[y as usize];
if sum < 0x100 {
self.v[0xF] = 0;
} else {
self.v[0xF] = 1;
}
self.v[x as usize] = sum & 0xFF;
}
// 8XY5 - VY is subtracted from VX. VF is set to 0 when there's a borrow, and 1 when there isn't.
[0x8, x, y, 0x5] => {
let mut diff = (self.v[x as usize] as i32) - (self.v[y as usize] as i32);
if diff >= 0 {
self.v[0xF] = 1;
} else {
self.v[0xF] = 0;
diff = -diff;
}
self.v[x as usize] = diff as u16;
}
// 8XY6 - Stores the least significant bit of VX in VF and then shifts VX to the right by 1.
[0x8, x, _y, 0x6] => {
self.v[0xF] = self.v[x as usize] & 0x1;
self.v[x as usize] >>= 1;
}
// 8XY7 - Sets VX to VY minus VX. VF is set to 0 when there's a borrow, and 1 when there isn't.
[0x8, x, y, 0x7] => {
let mut diff = (self.v[y as usize] as i32) - (self.v[x as usize] as i32);
if diff >= 0 {
self.v[0xF] = 1;
} else {
self.v[0xF] = 0;
diff = -diff;
}
self.v[x as usize] = diff as u16;
}
// 8XYE - Stores the most significant bit of VX in VF and then shifts VX to the left by 1.
[0x8, x, _y, 0xE] => {
self.v[0xF] = (self.v[x as usize] & 0x8000) >> 15;
self.v[x as usize] <<= 1;
}
// 9XY0 - Skips the next instruction if VX doesn't equal VY.
[0x9, x, y, 0x0] => {
if self.v[x as usize] != self.v[y as usize] {
self.pc += 2;
}
}
// ANNN - Sets I to the address NNN.
[0xA, a, b, c] => {
let addr = ((a as u16) << 8) | ((b as u16) << 4) | (c as u16);
self.ar = addr;
}
// BNNN - Jumps to the address NNN plus V0.
[0xB, a, b, c] => {
let mut addr = ((a as usize) << 8) | ((b as usize) << 4) | (c as usize);
addr += self.v[0] as usize;
self.pc = addr - 2;
}
// CXNN - Sets VX to the result of a bitwise and operation on a random number (Typically: 0 to 255) and NN.
[0xC, x, b, c] => {
let nn = ((b << 4) | c) as u16;
let rand = random::<u8>() as u16;
self.v[x as usize] = rand & nn;
}
// DXYN - Draws a sprite at coordinate (VX, VY) that has a width of 8 pixels and a height of N pixels. Each row of 8 pixels is read as bit-coded starting from memory location I; I value doesn’t change after the execution of this instruction. As described above, VF is set to 1 if any screen pixels are flipped from set to unset when the sprite is drawn, and to 0 if that doesn’t happen
[0xD, x, y, c] => {
self.render(x, y, c);
*redraw = true;
}
// EX9E - Skips the next instruction if the key stored in VX is pressed. (Usually the next instruction is a jump to skip a code block)
[0xE, x, 0x9, 0xE] => {
let vx = self.v[x as usize];
let keyp = self.key_pad[vx as usize];
if keyp {
self.pc += 2;
}
}
// EXA1 - Skips the next instruction if the key stored in VX isn't pressed. (Usually the next instruction is a jump to skip a code block)
[0xE, x, 0xA, 0x1] => {
let vx = self.v[x as usize];
let keyp = self.key_pad[vx as usize];
if !keyp {
self.pc += 2;
}
}
// FX07 - Sets VX to the value of the delay timer.
[0xF, x, 0x0, 0x7] => {
self.v[x as usize] = self.dt as u16;
}
// FX0A - A key press is awaited, and then stored in VX. (Blocking Operation. All instruction halted until next key event)
[0xF, x, 0x0, 0xA] => {
if key < 16 {
self.v[x as usize] = key as u16;
} else {
self.pc -= 2;
}
}
// FX15 - Sets the delay timer to VX.
[0xF, x, 0x1, 0x5] => {
self.dt = self.v[x as usize] as u8;
}
// FX18 - Sets the sound timer to VX.
[0xF, x, 0x1, 0x8] => {
self.st = self.v[x as usize] as u8;
}
// FX1E - Adds VX to I. VF is set to 1 when there is a range overflow (I+VX>0xFFF), and to 0 when there isn't.
[0xF, x, 0x1, 0xE] => {
self.ar += self.v[x as usize];
if self.ar > 0xFFF {
self.v[0xF] = 1;
self.ar &= 0xFFF;
} else {
self.v[0xF] = 0;
}
}
// FX29 - Sets I to the location of the sprite for the character in VX. Characters 0-F (in hexadecimal) are represented by a 4x5 font.
[0xF, x, 0x2, 0x9] => {
self.ar = self.v[x as usize] * 5;
}
// FX30 - Point I to 10-byte font sprite for digit VX (0..9)
[0xF, x, 0x3, 0x0] => {
self.ar = 80 + self.v[x as usize] * 10;
}
// FX33 - Stores the binary-coded decimal representation of VX, with the most significant of three digits at the address in I, the middle digit at I plus 1, and the least significant digit at I plus 2. (In other words, take the decimal representation of VX, place the hundreds digit in memory at location in I, the tens digit at location I+1, and the ones digit at location I+2.)
[0xF, x, 0x3, 0x3] => {
let ar = self.ar as usize;
let vx = self.v[x as usize];
self.ram[ar] = ((vx - (vx % 100)) / 100) as u8;
self.ram[(ar + 1)] = ((vx - vx % 10) / 10) as u8;
self.ram[(ar + 2)] = (vx % 10) as u8;
}
// FX55 - Stores V0 to VX (including VX) in memory starting at address I. The offset from I is increased by 1 for each value written, but I itself is left unmodified.
[0xF, x, 0x5, 0x5] => {
let ar = self.ar as usize;
let mut xi = 0;
while xi <= (x as usize) {
self.ram[ar + xi] = self.v[xi] as u8;
xi += 1;
}
}
// FX65 - Fills V0 to VX (including VX) with values from memory starting at address I. The offset from I is increased by 1 for each value written, but I itself is left unmodified.
[0xF, x, 0x6, 0x5] => {
let ar = self.ar as usize;
let mut xi = 0;
while xi <= (x as usize) {
self.v[xi] = self.ram[ar + xi] as u16;
xi += 1;
}
}
// FX75 - Store V0..VX in RPL user flags (X <= 7)
[0xF, x, 0x7, 0x5] => {
for i in 0..(x as usize) + 1 {
self.r[i] = self.v[i] as u8;
}
}
// FX85 - Read V0..VX from RPL user flags (X <= 7)
[0xF, x, 0x8, 0x5] => {
for i in 0..(x as usize) + 1 {
self.v[i] = self.r[i] as u16;
}
}
[_, _, _, _] => {
panic!("Unknown instruction!");
}
}
self.pc += 2;
#[cfg(debug_assertions)]
{
loop {
use std::io::Write;
print!("> ");
std::io::stdout().flush().unwrap();
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
match line.trim() {
"reg" => {
println!("pc: {:X}", self.pc);
println!("ar: {:X}", self.ar);
println!("sp: {:X}", self.sp);
for (i, reg) in self.r.iter().enumerate() {
println!("R{:X}: {:X}", i, reg);
}
for (i, reg) in self.v.iter().enumerate() {
println!("V{:X}: {:X}", i, reg);
}
println!("dt: {:X}", self.dt);
println!("st: {:X}", self.st);
println!("extended_screen: {}", self.extended_screen);
}
"stack" => {
for (i, elem) in self.stack.iter().rev().enumerate() {
println!("{:02X}: {:03X}", (0x2F - i), elem);
}
}
"ram" => {
for (i, elem) in self.ram.iter().rev().enumerate() {
println!("{:03X}: {:02X}", (0xFFF - i), elem);
}
}
"disp" => {
for (i, pixel) in self.screen.iter().enumerate() {
if (i > 0) && (i % SCHIP8_SCREEN_WIDTH == 0) {
println!("");
}
print!("{}", pixel);
}
println!("");
}
"h" => {
println!("Available commands: reg, stack, ram, disp, h, c, q");
}
"c" | "" => {
break;
}
"q" => {
return false;
}
_ => {
println!("Unknown command");
}
}
}
}
return true;
}
// - Coordinate (VX, VY) - Check
// - 8x{1-F} sprite, starts at I - Check
// - Each row bit coded - Check
// - I does not change - Check
// - Flip from set to unset => VF=1, otherwise VF=0 - Check
// For SCHIP8: Show N-byte sprite from M(I) at coords (VX,VY), VF := collision. If N=0 and extended mode, show 16x16 sprite.
fn render(&mut self, x: u8, y: u8, c: u8) {
self.v[0xF] = 0;
let pixels = &mut self.screen;
let num_pixels = self.screen_width * self.screen_height;
let mut col_size = 8;
let mut ar = self.ar as usize;
let x = (self.v[x as usize] as usize) % self.screen_width;
let mut yi = (self.v[y as usize] as usize) % self.screen_height;
let mut ye = yi + (c as usize);
if c == 0 && self.extended_screen {
col_size += 8;
ye += 8;
}
while yi < ye {
if yi >= self.screen_height {
break;
}
// Extract each bit from sprite
let sprite_data = self.ram[ar];
let sprite_row = [
(sprite_data & 0x80) >> 7,
(sprite_data & 0x40) >> 6,
(sprite_data & 0x20) >> 5,
(sprite_data & 0x10) >> 4,
(sprite_data & 0x08) >> 3,
(sprite_data & 0x04) >> 2,
(sprite_data & 0x02) >> 1,
sprite_data & 0x01,
];
// Get the current row in the screen buffer
let pixel_row_coord = yi * self.screen_width + x;
let pixel_row_left = pixel_row_coord;
let mut pixel_row_right = pixel_row_coord + col_size;
if pixel_row_left >= num_pixels {
break;
}
if pixel_row_right > num_pixels {
pixel_row_right = num_pixels;
}
let pixel_row = &mut pixels[pixel_row_left..pixel_row_right];
// Iterate over sprite pixels
let mut xi = 0;
for sprite_pixel in sprite_row.iter() {
let pixel = pixel_row[xi];
// Collision detection
if pixel == 1 && *sprite_pixel == 1 {
self.v[0xF] = 1;
}
// XOR the pixels from the screen buffer and the sprite
let result = pixel ^ *sprite_pixel;
pixel_row[xi] = result;
xi += 1;
if xi >= pixel_row.len() {
break;
}
}
ar += 1;
yi += 1;
}
}
}
|
extern crate pest;
#[macro_use]
extern crate pest_derive;
use std::collections::HashMap;
use pest::iterators::Pair;
use std::fs;
use pest::Parser;
#[derive(Parser)]
#[grammar = "grammar/sgf.pest"]
pub struct SgfParser;
///
/// Represents the FOO[BAR]
/// A property can have multiple values like AW[][][]
///
#[derive(Clone, Debug)]
pub struct Property {
pub ident: String,
pub values: Vec<String>,
}
impl Property {
///
/// Needs the Pair with the rule property
///
fn from_pair_pest(pair: Pair<Rule>) -> Property {
let inner = pair.into_inner();
let mut ident = "".to_string();
let mut values = Vec::<String>::new();
for i in inner {
match i.as_rule() {
Rule::prop_ident => {
ident = i.as_str().to_string();
}
Rule::prop_value => {
values.push(i.as_str().to_string());
}
_ => unreachable!()
}
}
Property { ident, values }
}
}
///
/// A node is a group of properties indexed by the Id
/// ;XX[FOO]AZ[BAR]FR[FOO]
///
pub type Node = HashMap<String, Property>;
///
/// Sequence of nodes.
/// ;XX[FOO]AZ[BAR]FR[FOO];XX[FOO]
///
pub type NodeSeq = Vec<Node>;
#[derive(Clone, Debug)]
pub struct GameTree {
/// Contains the information of the game
pub root: Node,
/// Contains the game plays
pub seq: NodeSeq,
}
impl GameTree {
pub fn from_pair(pair: Pair<Rule>) -> GameTree {
let iner = pair.into_inner();
let mut root = HashMap::new();
let mut seq = Vec::new();
for p in iner {
match p.as_rule() {
Rule::node => root = parse_node(p),
Rule::node_seq => seq = parse_nodeseq(p),
_ => unimplemented!("The tail is not implemented for the moment"),
}
}
GameTree { root, seq }
}
}
///
/// Needs a pair with the node rule
///
pub fn parse_node(pair: Pair<Rule>) -> Node {
let mut new = Node::new();
pair.into_inner().into_iter()
.for_each(|property| {
let pop = Property::from_pair_pest(property);
new.insert(pop.ident.clone(), pop);
});
new
}
///
/// Needs a pair of rule node seq
///
fn parse_nodeseq(pair: Pair<Rule>) -> NodeSeq {
pair.into_inner().into_iter()
.map(|node| parse_node(node))
.collect()
}
///
/// Needs a pair of rule collection
///
pub fn parse_collection(pair: Pair<Rule>) -> Collection {
pair.into_inner().into_iter()
.map(|gametree| GameTree::from_pair(gametree))
.collect()
}
pub type Collection = Vec<GameTree>;
#[derive(Clone, Debug)]
pub struct Sgf {
pub collection: Collection
}
impl Sgf {
pub fn from_str(lines: &str) -> Result<Sgf, String> {
if let Ok(mut x) = SgfParser::parse(Rule::file, lines) {
Ok(Sgf::from_pair(x.next().unwrap()))
} else {
Err("Parsing error".to_string())
}
}
pub fn from_file(path: &str) -> Result<Sgf, String> {
if let Ok(lines) = fs::read_to_string(path) {
Sgf::from_str(&lines)
} else {
Err("Reading the file error.".to_string())
}
}
pub fn from_pair(pair: Pair<Rule>) -> Sgf {
Sgf { collection: parse_collection(pair) }
}
}
#[cfg(test)]
mod tests {
use pest::Parser;
use std::fs;
use crate::*;
#[test]
fn parser() {
let unparsed_file = fs::read_to_string("test.sgf").expect("cannot readfile");
let collection = SgfParser::parse(Rule::file, &unparsed_file)
.expect("unsuccessful parse") // unwrap the parse result
.next().unwrap(); // get and unwrap the `file` rule; never fails
dbg!(Sgf::from_pair(collection));
}
#[test]
fn from_file_test() {
let sgf = Sgf::from_file("test.sgf").unwrap();
assert_eq!(sgf.collection.first().unwrap().root["FF"].values.first().unwrap(), "4")
}
}
|
//! This file contains automated tests, but they require virtual ports and therefore can't work on Windows or Web MIDI ...
#![cfg(not(any(windows, target_arch = "wasm32")))]
extern crate midir;
use std::thread::sleep;
use std::time::Duration;
use midir::os::unix::{VirtualInput, VirtualOutput};
use midir::{Ignore, MidiInput, MidiOutput, MidiOutputPort};
#[test]
fn end_to_end() {
let mut midi_in = MidiInput::new("My Test Input").unwrap();
midi_in.ignore(Ignore::None);
let midi_out = MidiOutput::new("My Test Output").unwrap();
let previous_count = midi_out.port_count();
println!("Creating virtual input port ...");
let conn_in = midi_in
.create_virtual(
"midir-test",
|stamp, message, _| {
println!("{}: {:?} (len = {})", stamp, message, message.len());
},
(),
)
.unwrap();
assert_eq!(midi_out.port_count(), previous_count + 1);
let new_port: MidiOutputPort = midi_out.ports().into_iter().rev().next().unwrap();
println!(
"Connecting to port '{}' ...",
midi_out.port_name(&new_port).unwrap()
);
let mut conn_out = midi_out.connect(&new_port, "midir-test").unwrap();
println!("Starting to send messages ...");
conn_out.send(&[144, 60, 1]).unwrap();
sleep(Duration::from_millis(200));
conn_out.send(&[144, 60, 0]).unwrap();
sleep(Duration::from_millis(50));
conn_out.send(&[144, 60, 1]).unwrap();
sleep(Duration::from_millis(200));
conn_out.send(&[144, 60, 0]).unwrap();
sleep(Duration::from_millis(50));
println!("Closing output ...");
let midi_out = conn_out.close();
println!("Closing virtual input ...");
let midi_in = conn_in.close().0;
assert_eq!(midi_out.port_count(), previous_count);
let previous_count = midi_in.port_count();
// reuse midi_in and midi_out, but swap roles
println!("\nCreating virtual output port ...");
let mut conn_out = midi_out.create_virtual("midir-test").unwrap();
assert_eq!(midi_in.port_count(), previous_count + 1);
let new_port = midi_in.ports().into_iter().rev().next().unwrap();
println!(
"Connecting to port '{}' ...",
midi_in.port_name(&new_port).unwrap()
);
let conn_in = midi_in
.connect(
&new_port,
"midir-test",
|stamp, message, _| {
println!("{}: {:?} (len = {})", stamp, message, message.len());
},
(),
)
.unwrap();
println!("Starting to send messages ...");
conn_out.send(&[144, 60, 1]).unwrap();
sleep(Duration::from_millis(200));
conn_out.send(&[144, 60, 0]).unwrap();
sleep(Duration::from_millis(50));
conn_out.send(&[144, 60, 1]).unwrap();
sleep(Duration::from_millis(200));
conn_out.send(&[144, 60, 0]).unwrap();
sleep(Duration::from_millis(50));
println!("Closing input ...");
let midi_in = conn_in.close().0;
println!("Closing virtual output ...");
conn_out.close();
assert_eq!(midi_in.port_count(), previous_count);
}
|
use crate::errors::*;
use hyper::body::Body as HyperBody;
use hyper::http::Response as HyperResponse;
use hyper::{header::HeaderValue, HeaderMap};
// Extends HyperResponse
pub struct RhodResponse {
res: Option<HyperResponse<HyperBody>>, // Is allways Some(..)
}
impl RhodResponse {
pub fn new(res: HyperResponse<HyperBody>) -> RhodResponse {
RhodResponse { res: Some(res) }
}
pub fn headers(&self) -> &HeaderMap<HeaderValue> {
self.res.as_ref().unwrap().headers()
}
pub fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue> {
self.res.as_mut().unwrap().headers_mut()
}
pub fn into_hyper_response(self) -> HyperResponse<HyperBody> {
self.res.unwrap()
}
pub fn status_as_int(&self) -> u16 {
self.res.as_ref().unwrap().status().as_u16()
}
pub async fn body(&mut self) -> RhodResult<Vec<u8>> {
let r = self.res.take().unwrap();
let (header, body) = r.into_parts();
match hyper::body::to_bytes(body).await {
Ok(b) => {
let cloned = b.clone();
self.res = Some(HyperResponse::from_parts(header, HyperBody::from(b)));
Ok(cloned.to_vec())
}
Err(e) => {
// If error, body cant be recovered.
self.res = Some(HyperResponse::from_parts(header, HyperBody::empty()));
Err(RhodError::from_string(
format!("Cant parse response body to bytes. {}", e),
RhodErrorLevel::Error,
))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_headers() {
let mut res = RhodResponse::new(
HyperResponse::builder()
.header("Foo", "Bar")
.body(HyperBody::empty())
.unwrap(),
);
assert_eq!(res.headers().get("Foo").unwrap(), "Bar");
assert!(res.headers().get("Accept").is_none());
res.headers_mut()
.insert("Accept", "text/html".parse().unwrap());
assert_eq!(res.headers().get("Accept").unwrap(), "text/html");
}
#[test]
fn test_status() {
let res = RhodResponse::new(
HyperResponse::builder()
.status(404)
.body(HyperBody::empty())
.unwrap(),
);
assert_eq!(res.status_as_int(), 404);
}
#[tokio::test]
async fn test_body() {
let mut response = RhodResponse::new(
HyperResponse::builder()
.body(HyperBody::from("response bodyy %% #"))
.unwrap(),
);
assert_eq!(
response.body().await.unwrap(),
"response bodyy %% #".as_bytes().to_vec()
);
let mut response =
RhodResponse::new(HyperResponse::builder().body(HyperBody::empty()).unwrap());
assert_eq!(response.body().await.unwrap(), [])
}
}
|
extern crate futures;
extern crate grpcio;
extern crate grpc_rs;
use std::io::Read;
use std::sync::Arc;
use std::{io, thread};
use futures::Future;
use futures::sync::oneshot;
use grpcio::{Environment, RpcContext, ServerBuilder, UnarySink};
use grpc_rs::user::{UserRequest, UserResponse};
use grpc_rs::user_grpc::{self, UserLogin};
#[derive(Clone)]
struct UserServiceImpl;
impl UserLogin for UserServiceImpl {
fn login(&self, ctx: ::grpcio::RpcContext, req: UserRequest, sink: ::grpcio::UnarySink<UserResponse>){
let msg = format!("Hello from dalongrong {}", req.get_name());
let mut resp = UserResponse::new();
resp.set_message(msg);
let f = sink.success(resp)
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f)
}
}
fn main(){
let env = Arc::new(Environment::new(1));
let service = user_grpc::create_user_login(UserServiceImpl);
let mut server = ServerBuilder::new(env)
.register_service(service)
.bind("0.0.0.0", 50052)
.build()
.unwrap();
server.start();
for &(ref host, port) in server.bind_addrs() {
println!("listening on {}:{}", host, port);
}
let (tx, rx) = oneshot::channel();
thread::spawn(move || {
println!("Press ENTER to exit...");
let _ = io::stdin().read(&mut [0]).unwrap();
tx.send(())
});
let _ = rx.wait();
let _ = server.shutdown().wait();
}
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Required for enabling benchmark tests.
#![feature(test)]
#![feature(async_closure)]
use anyhow::Context;
use log::Level;
use oak_functions_loader::{
grpc::{create_and_start_grpc_server, create_wasm_handler},
logger::Logger,
lookup::{LookupData, LookupDataAuth, LookupDataSource},
server::Policy,
};
#[cfg(feature = "oak-tf")]
use oak_functions_loader::tf::{TensorFlowFactory, TensorFlowModelConfig};
#[cfg(feature = "oak-metrics")]
use oak_functions_loader::metrics::PrivateMetricsConfig;
use serde_derive::Deserialize;
use std::{
fs,
net::{Ipv6Addr, SocketAddr},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use structopt::StructOpt;
#[cfg(test)]
mod tests;
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct Config {
/// URL of a file containing key / value entries in protobuf binary format for lookup.
///
/// If the schema is `http` or `https`, then the file is downloaded via HTTP GET.
///
/// If the schema is `file`, then the file is read from the local file system.
///
/// If empty or not provided, no data is available for lookup.
#[serde(default)]
lookup_data_url: String,
/// How often to refresh the lookup data.
////
/// If empty or not provided, data is only loaded once at startup.
#[serde(default, with = "humantime_serde")]
lookup_data_download_period: Option<Duration>,
/// Whether to use the GCP metadata service to obtain an authentication token for downloading
/// the lookup data.
#[serde(default = "LookupDataAuth::default")]
lookup_data_auth: LookupDataAuth,
/// Number of worker threads available to the async runtime.
///
/// Defaults to 4 if unset.
///
/// Note that the CPU core detection logic does not seem to work reliably on Google Cloud Run,
/// so it is advisable to set this value to the number of cores available on the Cloud Run
/// instance.
///
/// See https://docs.rs/tokio/1.5.0/tokio/runtime/struct.Builder.html#method.worker_threads.
worker_threads: Option<usize>,
/// Security policy guaranteed by the server.
policy: Option<Policy>,
/// Configuration for TensorFlow model
#[cfg(feature = "oak-tf")]
#[serde(default)]
tf_model: Option<TensorFlowModelConfig>,
/// Differentially private metrics configuration.
#[cfg(feature = "oak-metrics")]
#[serde(default)]
metrics: Option<PrivateMetricsConfig>,
}
/// Command line options for the Oak loader.
///
/// In general, when adding new configuration parameters, they should go in the `Config` struct
/// instead of here, and provided as part of the config TOML file by the developer, who would
/// normally bundle it with the Docker image of the Oak Functions Loader.
#[derive(StructOpt, Clone, Debug)]
#[structopt(about = "Oak Functions Loader")]
pub struct Opt {
#[structopt(
long,
default_value = "8080",
help = "Port number that the server listens on."
)]
http_listen_port: u16,
#[structopt(
long,
help = "Path to a Wasm file to be loaded and executed per invocation. The Wasm module must export a function named `main`."
)]
wasm_path: String,
#[structopt(
long,
help = "Path to a file containing configuration parameters in TOML format."
)]
config_path: String,
}
async fn background_refresh_lookup_data(
lookup_data: &LookupData,
period: Duration,
logger: &Logger,
) {
// Create an interval that starts after `period`, since the data was already refreshed
// initially.
let mut interval = tokio::time::interval_at(tokio::time::Instant::now() + period, period);
loop {
interval.tick().await;
// If there is an error, we skip the current refresh and wait for the next tick.
if let Err(err) = lookup_data.refresh().await {
logger.log_public(
Level::Error,
&format!("error refreshing lookup data: {}", err),
);
}
}
}
fn main() -> anyhow::Result<()> {
let opt = Opt::from_args();
let config_file_bytes = fs::read(&opt.config_path)
.with_context(|| format!("Couldn't read config file {}", &opt.config_path))?;
let config: Config =
toml::from_slice(&config_file_bytes).context("Couldn't parse config file")?;
// TODO(#1971): Make maximum log level configurable.
let logger = Logger::default();
logger.log_public(Level::Info, &format!("parsed config file:\n{:#?}", config));
tokio::runtime::Builder::new_multi_thread()
.worker_threads(config.worker_threads.unwrap_or(4))
.enable_all()
.build()
.unwrap()
.block_on(async_main(opt, config, logger))
}
/// Main execution point for the Oak Functions Loader.
async fn async_main(opt: Opt, config: Config, logger: Logger) -> anyhow::Result<()> {
let (notify_sender, notify_receiver) = tokio::sync::oneshot::channel::<()>();
let lookup_data = load_lookup_data(&config, logger.clone()).await?;
#[allow(unused_mut)]
let mut extensions = Vec::new();
#[cfg(feature = "oak-tf")]
if let Some(tf_model_factory) = create_tensorflow_factory(&config, logger.clone()).await? {
extensions.push(tf_model_factory);
}
#[cfg(feature = "oak-metrics")]
if let Some(metrics_factory) = create_metrics_proxy_factory(&config, logger.clone()).await? {
extensions.push(metrics_factory);
}
let wasm_module_bytes = fs::read(&opt.wasm_path)
.with_context(|| format!("Couldn't read Wasm file {}", &opt.wasm_path))?;
// Make sure that a policy is specified and is valid.
config
.policy
.as_ref()
.ok_or_else(|| anyhow::anyhow!("a valid policy must be provided"))
.and_then(|policy| policy.validate())?;
let address = SocketAddr::from((Ipv6Addr::UNSPECIFIED, opt.http_listen_port));
let tee_certificate = vec![];
let wasm_handler =
create_wasm_handler(&wasm_module_bytes, lookup_data, extensions, logger.clone())?;
// Start server.
let server_handle = tokio::spawn(async move {
create_and_start_grpc_server(
&address,
wasm_handler,
tee_certificate,
config.policy.unwrap(),
async { notify_receiver.await.unwrap() },
logger,
)
.await
.context("error while waiting for the server to terminate")
});
// Wait for the termination signal.
let done = Arc::new(AtomicBool::new(false));
signal_hook::flag::register(signal_hook::consts::signal::SIGINT, Arc::clone(&done))
.context("could not register signal handler")?;
// The server is started in its own thread, so just block the current thread until a signal
// arrives. This is needed for getting the correct status code when running with `runner`.
while !done.load(Ordering::Relaxed) {
// There are few synchronization mechanisms that are allowed to be used in a signal
// handler context, so use a primitive sleep loop to watch for the termination
// notification (rather than something more accurate like `std::sync::Condvar`).
// See e.g.: http://man7.org/linux/man-pages/man7/signal-safety.7.html
std::thread::sleep(std::time::Duration::from_millis(100));
}
notify_sender
.send(())
.expect("Couldn't send completion signal.");
server_handle
.await
.context("error while waiting for the server to terminate")?
}
async fn load_lookup_data(config: &Config, logger: Logger) -> anyhow::Result<Arc<LookupData>> {
let lookup_data_source = if config.lookup_data_url.is_empty() {
None
} else {
let url =
url::Url::parse(&config.lookup_data_url).context("could not parse lookup data URL")?;
match url.scheme() {
"file" => {
let file_path = url
.to_file_path()
.map_err(|()| anyhow::anyhow!("could not convert url to file path"))?;
Some(LookupDataSource::File(file_path))
}
"http" | "https" => Some(LookupDataSource::Http {
url: config.lookup_data_url.clone(),
auth: config.lookup_data_auth,
}),
scheme => anyhow::bail!("unknown scheme in lookup data URL: {}", scheme),
}
};
let lookup_data = Arc::new(LookupData::new_empty(
lookup_data_source.clone(),
logger.clone(),
));
if lookup_data_source.is_some() {
// First load the lookup data upfront in a blocking fashion.
// TODO(#1930): Retry the initial lookup a few times if it fails.
lookup_data
.refresh()
.await
.context("Couldn't perform initial load of lookup data")?;
if let Some(lookup_data_download_period) = config.lookup_data_download_period {
// Create background task to periodically refresh the lookup data.
let lookup_data = lookup_data.clone();
let logger = logger.clone();
tokio::spawn(async move {
background_refresh_lookup_data(&lookup_data, lookup_data_download_period, &logger)
.await
});
};
}
Ok(lookup_data)
}
/// Load the TensorFlow model from the given path in the config, or return `None` if a path is not
/// provided.
#[cfg(feature = "oak-tf")]
async fn create_tensorflow_factory(
config: &Config,
logger: Logger,
) -> anyhow::Result<Option<oak_functions_loader::server::BoxedExtensionFactory>> {
match &config.tf_model {
Some(tf_model_config) => {
let model =
oak_functions_loader::tf::read_model_from_path(&tf_model_config.path).await?;
let tf_model_factory =
TensorFlowFactory::new(model, tf_model_config.shape.clone(), logger)?;
let tf_model_factory: oak_functions_loader::server::BoxedExtensionFactory =
Box::new(tf_model_factory);
Ok(Some(tf_model_factory))
}
None => Ok(None),
}
}
/// Create and return a metrics proxy factory if metrics configuration is provided, or return `None`
/// otherwise.
#[cfg(feature = "oak-metrics")]
async fn create_metrics_proxy_factory(
config: &Config,
logger: Logger,
) -> anyhow::Result<Option<oak_functions_loader::server::BoxedExtensionFactory>> {
match &config.metrics {
Some(metrics_config) => {
metrics_config.validate()?;
let metrics_factory = oak_functions_loader::metrics::PrivateMetricsProxyFactory::new(
metrics_config,
logger,
)?;
let metrics_factory: oak_functions_loader::server::BoxedExtensionFactory =
Box::new(metrics_factory);
Ok(Some(metrics_factory))
}
None => Ok(None),
}
}
|
/*
MIT License
Copyright (c) 2021 Philipp Schuster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//! Module for the struct [`FrequencyLimit`].
/// Can be used to specify a desired frequency limit. If you know that you only
/// need frequencies `f <= 1000Hz`, `1000 <= f <= 6777`, or `10000 <= f`, then this
/// can help you to accelerate overall computation speed and memory usage.
///
/// Please note that due to frequency inaccuracies the FFT result may not contain
/// a value for `1000Hz` but for `998.76Hz`!
#[derive(Debug, Copy, Clone)]
pub enum FrequencyLimit {
/// Interested in all frequencies. [0, sampling_rate/2] (Nyquist theorem).
All,
/// Only interested in frequencies `f <= 1000Hz` for example. Limit is inclusive.
Min(f32),
/// Only interested in frequencies `10000 <= f` for example. Limit is inclusive.
Max(f32),
/// Only interested in frequencies `1000 <= f <= 6777` for example. Both values are inclusive.
Range(f32, f32),
}
impl FrequencyLimit {
#[inline(always)]
pub fn maybe_min(&self) -> Option<f32> {
match self {
FrequencyLimit::Min(min) => Some(*min),
FrequencyLimit::Range(min, _) => Some(*min),
_ => None,
}
}
#[inline(always)]
pub fn maybe_max(&self) -> Option<f32> {
match self {
FrequencyLimit::Max(max) => Some(*max),
FrequencyLimit::Range(_, max) => Some(*max),
_ => None,
}
}
#[inline(always)]
pub fn min(&self) -> f32 {
self.maybe_min().expect("Must contain a value!")
}
#[inline(always)]
pub fn max(&self) -> f32 {
self.maybe_max().expect("Must contain a value!")
}
}
|
#![allow(unused)]
#[allow(non_camel_case_types)]
#[cfg(test)]
mod test_toplevel {
use arc_runtime::prelude::*;
declare_functions!(f);
#[rewrite]
fn f(a: i32) -> i32 {
a + a
}
#[rewrite(main)]
#[test]
fn test() {
let x: function!((i32) -> i32) = function!(f);
let y: function!((i32,) -> i32) = function!(f);
let y: i32 = call_indirect!(x(1));
let y: i32 = call_indirect!(x(1,));
let z: i32 = call!(f(1));
let z: i32 = call!(f(1,));
}
}
|
pub struct JoinMapIterator<A, B> {a: A, b: B}
pub fn join_maps<KEY: Ord, DataA, DataB, IterA: Iterator<(KEY, DataA)>, IterB: Iterator<(KEY, DataB)>>
(a: IterA, b: IterB) -> JoinMapIterator<IterA, IterB>
{
JoinMapIterator {a: a, b: b}
}
impl<KEY: Ord, DataA, DataB, IterA: Iterator<(KEY, DataA)>, IterB: Iterator<(KEY, DataB)>>
Iterator<(KEY, (DataA, DataB))> for JoinMapIterator<IterA, IterB>
{
#[inline(never)]
fn next(&mut self) -> Option<(KEY, (DataA, DataB))>
{
let (mut key_a, mut data_a) = match self.a.next() {
None => return None,
Some((key, data)) => (key, data)
};
let (mut key_b, mut data_b) = match self.b.next() {
None => return None,
Some((key, data)) => (key, data)
};
loop {
match key_a.cmp(&key_b) {
Less => {
match self.a.next() {
None => return None,
Some((key, data)) => {
key_a = key;
data_a = data;
}
};
},
Equal => return Some((key_a, (data_a, data_b))),
Greater => {
match self.b.next() {
None => return None,
Some((key, data)) => {
key_b = key;
data_b = data;
}
};
}
}
}
}
}
pub struct JoinSetIterator<A, B> {a: A, b: B}
pub fn join_sets<KEY: Ord, IterA: Iterator<KEY>, IterB: Iterator<KEY>>
(a: IterA, b: IterB) -> JoinSetIterator<IterA, IterB>
{
JoinSetIterator {a: a, b: b}
}
impl<KEY: Ord, IterA: Iterator<KEY>, IterB: Iterator<KEY>>
Iterator<KEY> for JoinSetIterator<IterA, IterB>
{
#[inline(never)]
fn next(&mut self) -> Option<KEY>
{
let mut key_a = match self.a.next() {
None => return None,
Some(key) => key
};
let mut key_b = match self.b.next() {
None => return None,
Some(key) => key
};
loop {
match key_a.cmp(&key_b) {
Less => {
match self.a.next() {
None => return None,
Some(key) => { key_a = key; }
};
},
Equal => return Some(key_a),
Greater => {
match self.b.next() {
None => return None,
Some(key) => { key_b = key; }
};
}
}
}
}
}
pub struct JoinMapSetIterator<A, B> {set: A, map: B}
pub fn join_set_to_map<KEY: Ord, DATA, SetIter: Iterator<KEY>, MapIter: Iterator<(KEY, DATA)>>
(set: SetIter, map: MapIter) -> JoinMapSetIterator<SetIter, MapIter>
{
JoinMapSetIterator {set: set, map: map}
}
impl<KEY: Ord, DATA, SetIter: Iterator<KEY>, MapIter: Iterator<(KEY, DATA)>>
Iterator<(KEY, DATA)> for JoinMapSetIterator<SetIter, MapIter>
{
#[inline(never)]
fn next(&mut self) -> Option<(KEY, DATA)>
{
let mut key_set = match self.set.next() {
None => return None,
Some(key) => key
};
let (mut key_map, mut data) = match self.map.next() {
None => return None,
Some((key, data)) => (key, data)
};
loop {
match key_set.cmp(&key_map) {
Less => {
match self.set.next() {
None => return None,
Some(key) => { key_set = key; }
};
},
Equal => return Some((key_set, data)),
Greater => {
match self.map.next() {
None => return None,
Some((key, d)) => {
key_map = key;
data = d;
}
};
}
}
}
}
} |
//! Crate `ruma_events_macros` provides a procedural macro for generating
//! [ruma-events](https://github.com/ruma/ruma-events) events.
//!
//! See the documentation for the individual macros for usage details.
#![deny(missing_copy_implementations, missing_debug_implementations, missing_docs)]
extern crate proc_macro;
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput};
use self::{
content_enum::{expand_content_enum, ContentEnumInput},
event::expand_event,
event_content::{
expand_basic_event_content, expand_ephemeral_room_event_content, expand_event_content,
expand_message_event_content, expand_room_event_content, expand_state_event_content,
},
};
mod content_enum;
mod event;
mod event_content;
/// Generates a content enum to represent the various Matrix event types.
///
/// This macro also implements the necessary traits for the type to serialize and deserialize
/// itself.
#[proc_macro]
pub fn event_content_enum(input: TokenStream) -> TokenStream {
let content_enum_input = syn::parse_macro_input!(input as ContentEnumInput);
expand_content_enum(content_enum_input).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Generates an implementation of `ruma_events::EventContent`.
#[proc_macro_derive(EventContent, attributes(ruma_event))]
pub fn derive_event_content(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand_event_content(input).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Generates an implementation of `ruma_events::BasicEventContent` and it's super traits.
#[proc_macro_derive(BasicEventContent, attributes(ruma_event))]
pub fn derive_basic_event_content(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand_basic_event_content(input).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Generates an implementation of `ruma_events::RoomEventContent` and it's super traits.
#[proc_macro_derive(RoomEventContent, attributes(ruma_event))]
pub fn derive_room_event_content(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand_room_event_content(input).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Generates an implementation of `ruma_events::MessageEventContent` and it's super traits.
#[proc_macro_derive(MessageEventContent, attributes(ruma_event))]
pub fn derive_message_event_content(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand_message_event_content(input).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Generates an implementation of `ruma_events::StateEventContent` and it's super traits.
#[proc_macro_derive(StateEventContent, attributes(ruma_event))]
pub fn derive_state_event_content(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand_state_event_content(input).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Generates an implementation of `ruma_events::EphemeralRoomEventContent` and it's super traits.
#[proc_macro_derive(EphemeralRoomEventContent, attributes(ruma_event))]
pub fn derive_ephemeral_room_event_content(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand_ephemeral_room_event_content(input).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Generates implementations needed to serialize and deserialize Matrix events.
#[proc_macro_derive(Event, attributes(ruma_event))]
pub fn derive_state_event(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand_event(input).unwrap_or_else(|err| err.to_compile_error()).into()
}
|
pub mod auth;
pub mod login;
pub mod logout;
|
use std::fs::File;
use std::io;
// use std::io::ErrorKind;
use std::io::Read;
fn main() {
// panic!("crash and burn");
// let v = vec![1, 2, 3, 4];
// v[99];
let f = read_username_from_file();
let f = match f {
Ok(file) => file,
Err(error) => panic!("There was a problem opening the file: {:?}", error),
};
println!("{}", f);
// let e = File::open("hello.txt").unwrap();
// let _e = File::open("hell.txt").expect("Failed to open hello.txt");
}
fn read_username_from_file() -> Result<String, io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - RIDR register"]
pub ddrphyc_ridr: DDRPHYC_RIDR,
#[doc = "0x04 - PIR register"]
pub ddrphyc_pir: DDRPHYC_PIR,
#[doc = "0x08 - PGCR register"]
pub ddrphyc_pgcr: DDRPHYC_PGCR,
#[doc = "0x0c - PGSR register"]
pub ddrphyc_pgsr: DDRPHYC_PGSR,
#[doc = "0x10 - DLLGCR register"]
pub ddrphyc_dllgcr: DDRPHYC_DLLGCR,
#[doc = "0x14 - ACDLLCR register"]
pub ddrphyc_acdllcr: DDRPHYC_ACDLLCR,
#[doc = "0x18 - PTR0 register"]
pub ddrphyc_ptr0: DDRPHYC_PTR0,
#[doc = "0x1c - PTR1 register"]
pub ddrphyc_ptr1: DDRPHYC_PTR1,
#[doc = "0x20 - PTR2 register"]
pub ddrphyc_ptr2: DDRPHYC_PTR2,
#[doc = "0x24 - ACIOCR register"]
pub ddrphyc_aciocr: DDRPHYC_ACIOCR,
#[doc = "0x28 - DXCCR register"]
pub ddrphyc_dxccr: DDRPHYC_DXCCR,
#[doc = "0x2c - DSGCR register"]
pub ddrphyc_dsgcr: DDRPHYC_DSGCR,
#[doc = "0x30 - DCR register"]
pub ddrphyc_dcr: DDRPHYC_DCR,
#[doc = "0x34 - DTPR0 register"]
pub ddrphyc_dtpr0: DDRPHYC_DTPR0,
#[doc = "0x38 - DTPR1 register"]
pub ddrphyc_dtpr1: DDRPHYC_DTPR1,
#[doc = "0x3c - DTPR2 register"]
pub ddrphyc_dtpr2: DDRPHYC_DTPR2,
#[doc = "0x40 - MR0 register for DDR3"]
pub ddrphyc_mr0: DDRPHYC_MR0,
_reserved17: [u8; 2usize],
#[doc = "0x44 - MR1 register for LPDDR2"]
pub ddrphyc_mr1: DDRPHYC_MR1,
_reserved18: [u8; 2usize],
#[doc = "0x48 - MR2 register for LPDDR2"]
pub ddrphyc_mr2: DDRPHYC_MR2,
_reserved19: [u8; 2usize],
#[doc = "0x4c - MR3 register for DDR3"]
pub ddrphyc_mr3: DDRPHYC_MR3,
_reserved20: [u8; 3usize],
#[doc = "0x50 - ODTCR register"]
pub ddrphyc_odtcr: DDRPHYC_ODTCR,
#[doc = "0x54 - DTAR register"]
pub ddrphyc_dtar: DDRPHYC_DTAR,
#[doc = "0x58 - DTDR0 register"]
pub ddrphyc_dtdr0: DDRPHYC_DTDR0,
#[doc = "0x5c - DTDR1 register"]
pub ddrphyc_dtdr1: DDRPHYC_DTDR1,
_reserved24: [u8; 96usize],
#[doc = "0xc0 - DCUAR register"]
pub ddrphyc_dcuar: DDRPHYC_DCUAR,
_reserved25: [u8; 2usize],
#[doc = "0xc4 - DCUDR register"]
pub ddrphyc_dcudr: DDRPHYC_DCUDR,
#[doc = "0xc8 - DCURR register"]
pub ddrphyc_dcurr: DDRPHYC_DCURR,
#[doc = "0xcc - DCULR register"]
pub ddrphyc_dculr: DDRPHYC_DCULR,
#[doc = "0xd0 - DCUGCR register"]
pub ddrphyc_dcugcr: DDRPHYC_DCUGCR,
_reserved29: [u8; 2usize],
#[doc = "0xd4 - DCUTPR register"]
pub ddrphyc_dcutpr: DDRPHYC_DCUTPR,
#[doc = "0xd8 - DCUSR0 register"]
pub ddrphyc_dcusr0: DDRPHYC_DCUSR0,
_reserved31: [u8; 3usize],
#[doc = "0xdc - DCUSR1 register"]
pub ddrphyc_dcusr1: DDRPHYC_DCUSR1,
_reserved32: [u8; 32usize],
#[doc = "0x100 - BISTRR register"]
pub ddrphyc_bistrr: DDRPHYC_BISTRR,
#[doc = "0x104 - BISTMSKR0 register"]
pub ddrphyc_bistmskr0: DDRPHYC_BISTMSKR0,
#[doc = "0x108 - BISTMSKR1 register"]
pub ddrphyc_bistmskr1: DDRPHYC_BISTMSKR1,
#[doc = "0x10c - BISTWCR register"]
pub ddrphyc_bistwcr: DDRPHYC_BISTWCR,
_reserved36: [u8; 2usize],
#[doc = "0x110 - BISTLSR register"]
pub ddrphyc_bistlsr: DDRPHYC_BISTLSR,
#[doc = "0x114 - BISTAR0 register"]
pub ddrphyc_bistar0: DDRPHYC_BISTAR0,
#[doc = "0x118 - BISTAR1 register"]
pub ddrphyc_bistar1: DDRPHYC_BISTAR1,
_reserved39: [u8; 2usize],
#[doc = "0x11c - BISTAR2 register"]
pub ddrphyc_bistar2: DDRPHYC_BISTAR2,
#[doc = "0x120 - BISTUDPR register"]
pub ddrphyc_bistudpr: DDRPHYC_BISTUDPR,
#[doc = "0x124 - BISTGSR register"]
pub ddrphyc_bistgsr: DDRPHYC_BISTGSR,
#[doc = "0x128 - BISTWER register"]
pub ddrphyc_bistwer: DDRPHYC_BISTWER,
#[doc = "0x12c - BISTBER0 register"]
pub ddrphyc_bistber0: DDRPHYC_BISTBER0,
#[doc = "0x130 - BISTBER1 register"]
pub ddrphyc_bistber1: DDRPHYC_BISTBER1,
#[doc = "0x134 - BISTBER2 register"]
pub ddrphyc_bistber2: DDRPHYC_BISTBER2,
#[doc = "0x138 - BISTWCSR register"]
pub ddrphyc_bistwcsr: DDRPHYC_BISTWCSR,
#[doc = "0x13c - BISTFWR0 register"]
pub ddrphyc_bistfwr0: DDRPHYC_BISTFWR0,
#[doc = "0x140 - BISTFWR1 register"]
pub ddrphyc_bistfwr1: DDRPHYC_BISTFWR1,
_reserved49: [u8; 52usize],
#[doc = "0x178 - General Purpose Register 0"]
pub ddrphyc_gpr0: DDRPHYC_GPR0,
#[doc = "0x17c - General Purpose Register register 1"]
pub ddrphyc_gpr1: DDRPHYC_GPR1,
#[doc = "0x180 - ZQ0CR0 register"]
pub ddrphyc_zq0cr0: DDRPHYC_ZQ0CR0,
#[doc = "0x184 - ZQ0CR1 register"]
pub ddrphyc_zq0cr1: DDRPHYC_ZQ0CR1,
_reserved53: [u8; 3usize],
#[doc = "0x188 - ZQ0SR0 register"]
pub ddrphyc_zq0sr0: DDRPHYC_ZQ0SR0,
#[doc = "0x18c - ZQ0SR1 register"]
pub ddrphyc_zq0sr1: DDRPHYC_ZQ0SR1,
_reserved55: [u8; 51usize],
#[doc = "0x1c0 - DX 0 GCR register"]
pub ddrphyc_dx0gcr: DDRPHYC_DX0GCR,
#[doc = "0x1c4 - DX 0 GSR0 register"]
pub ddrphyc_dx0gsr0: DDRPHYC_DX0GSR0,
_reserved57: [u8; 2usize],
#[doc = "0x1c8 - DX 0 GSR1 register"]
pub ddrphyc_dx0gsr1: DDRPHYC_DX0GSR1,
#[doc = "0x1cc - DX 0 DLLCR register"]
pub ddrphyc_dx0dllcr: DDRPHYC_DX0DLLCR,
#[doc = "0x1d0 - DX 0 DQTR register"]
pub ddrphyc_dx0dqtr: DDRPHYC_DX0DQTR,
#[doc = "0x1d4 - DX 0 DQSTR register"]
pub ddrphyc_dx0dqstr: DDRPHYC_DX0DQSTR,
_reserved61: [u8; 40usize],
#[doc = "0x200 - DX 1 GCR register"]
pub ddrphyc_dx1gcr: DDRPHYC_DX1GCR,
#[doc = "0x204 - DX 1 GSR0 register"]
pub ddrphyc_dx1gsr0: DDRPHYC_DX1GSR0,
_reserved63: [u8; 2usize],
#[doc = "0x208 - DX 1 GSR1 register"]
pub ddrphyc_dx1gsr1: DDRPHYC_DX1GSR1,
#[doc = "0x20c - DX 1 DLLCR register"]
pub ddrphyc_dx1dllcr: DDRPHYC_DX1DLLCR,
#[doc = "0x210 - DX 1 DQTR register"]
pub ddrphyc_dx1dqtr: DDRPHYC_DX1DQTR,
#[doc = "0x214 - DX 1 DQSTR register"]
pub ddrphyc_dx1dqstr: DDRPHYC_DX1DQSTR,
_reserved67: [u8; 40usize],
#[doc = "0x240 - DX 2 GCR register"]
pub ddrphyc_dx2gcr: DDRPHYC_DX2GCR,
#[doc = "0x244 - DX 2 GSR0 register"]
pub ddrphyc_dx2gsr0: DDRPHYC_DX2GSR0,
_reserved69: [u8; 2usize],
#[doc = "0x248 - DX 2 GSR1 register"]
pub ddrphyc_dx2gsr1: DDRPHYC_DX2GSR1,
#[doc = "0x24c - DX 2 DLLCR register"]
pub ddrphyc_dx2dllcr: DDRPHYC_DX2DLLCR,
#[doc = "0x250 - DX 2 DQTR register"]
pub ddrphyc_dx2dqtr: DDRPHYC_DX2DQTR,
#[doc = "0x254 - DX 2 DQSTR register"]
pub ddrphyc_dx2dqstr: DDRPHYC_DX2DQSTR,
_reserved73: [u8; 40usize],
#[doc = "0x280 - DX 3 GCR register"]
pub ddrphyc_dx3gcr: DDRPHYC_DX3GCR,
#[doc = "0x284 - DX 3 GSR0 register"]
pub ddrphyc_dx3gsr0: DDRPHYC_DX3GSR0,
_reserved75: [u8; 2usize],
#[doc = "0x288 - DX 3 GSR1 register"]
pub ddrphyc_dx3gsr1: DDRPHYC_DX3GSR1,
#[doc = "0x28c - DX 3 DLLCR register"]
pub ddrphyc_dx3dllcr: DDRPHYC_DX3DLLCR,
#[doc = "0x290 - DX 3 DQTR register"]
pub ddrphyc_dx3dqtr: DDRPHYC_DX3DQTR,
#[doc = "0x294 - DX 3 DQSTR register"]
pub ddrphyc_dx3dqstr: DDRPHYC_DX3DQSTR,
}
#[doc = "RIDR register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_ridr](ddrphyc_ridr) module"]
pub type DDRPHYC_RIDR = crate::Reg<u32, _DDRPHYC_RIDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_RIDR;
#[doc = "`read()` method returns [ddrphyc_ridr::R](ddrphyc_ridr::R) reader structure"]
impl crate::Readable for DDRPHYC_RIDR {}
#[doc = "RIDR register"]
pub mod ddrphyc_ridr;
#[doc = "PIR register\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 [ddrphyc_pir](ddrphyc_pir) module"]
pub type DDRPHYC_PIR = crate::Reg<u32, _DDRPHYC_PIR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_PIR;
#[doc = "`read()` method returns [ddrphyc_pir::R](ddrphyc_pir::R) reader structure"]
impl crate::Readable for DDRPHYC_PIR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_pir::W](ddrphyc_pir::W) writer structure"]
impl crate::Writable for DDRPHYC_PIR {}
#[doc = "PIR register"]
pub mod ddrphyc_pir;
#[doc = "PGCR register\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 [ddrphyc_pgcr](ddrphyc_pgcr) module"]
pub type DDRPHYC_PGCR = crate::Reg<u32, _DDRPHYC_PGCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_PGCR;
#[doc = "`read()` method returns [ddrphyc_pgcr::R](ddrphyc_pgcr::R) reader structure"]
impl crate::Readable for DDRPHYC_PGCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_pgcr::W](ddrphyc_pgcr::W) writer structure"]
impl crate::Writable for DDRPHYC_PGCR {}
#[doc = "PGCR register"]
pub mod ddrphyc_pgcr;
#[doc = "PGSR register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_pgsr](ddrphyc_pgsr) module"]
pub type DDRPHYC_PGSR = crate::Reg<u32, _DDRPHYC_PGSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_PGSR;
#[doc = "`read()` method returns [ddrphyc_pgsr::R](ddrphyc_pgsr::R) reader structure"]
impl crate::Readable for DDRPHYC_PGSR {}
#[doc = "PGSR register"]
pub mod ddrphyc_pgsr;
#[doc = "DLLGCR register\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 [ddrphyc_dllgcr](ddrphyc_dllgcr) module"]
pub type DDRPHYC_DLLGCR = crate::Reg<u32, _DDRPHYC_DLLGCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DLLGCR;
#[doc = "`read()` method returns [ddrphyc_dllgcr::R](ddrphyc_dllgcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DLLGCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dllgcr::W](ddrphyc_dllgcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DLLGCR {}
#[doc = "DLLGCR register"]
pub mod ddrphyc_dllgcr;
#[doc = "ACDLLCR register\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 [ddrphyc_acdllcr](ddrphyc_acdllcr) module"]
pub type DDRPHYC_ACDLLCR = crate::Reg<u32, _DDRPHYC_ACDLLCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_ACDLLCR;
#[doc = "`read()` method returns [ddrphyc_acdllcr::R](ddrphyc_acdllcr::R) reader structure"]
impl crate::Readable for DDRPHYC_ACDLLCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_acdllcr::W](ddrphyc_acdllcr::W) writer structure"]
impl crate::Writable for DDRPHYC_ACDLLCR {}
#[doc = "ACDLLCR register"]
pub mod ddrphyc_acdllcr;
#[doc = "PTR0 register\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 [ddrphyc_ptr0](ddrphyc_ptr0) module"]
pub type DDRPHYC_PTR0 = crate::Reg<u32, _DDRPHYC_PTR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_PTR0;
#[doc = "`read()` method returns [ddrphyc_ptr0::R](ddrphyc_ptr0::R) reader structure"]
impl crate::Readable for DDRPHYC_PTR0 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_ptr0::W](ddrphyc_ptr0::W) writer structure"]
impl crate::Writable for DDRPHYC_PTR0 {}
#[doc = "PTR0 register"]
pub mod ddrphyc_ptr0;
#[doc = "PTR1 register\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 [ddrphyc_ptr1](ddrphyc_ptr1) module"]
pub type DDRPHYC_PTR1 = crate::Reg<u32, _DDRPHYC_PTR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_PTR1;
#[doc = "`read()` method returns [ddrphyc_ptr1::R](ddrphyc_ptr1::R) reader structure"]
impl crate::Readable for DDRPHYC_PTR1 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_ptr1::W](ddrphyc_ptr1::W) writer structure"]
impl crate::Writable for DDRPHYC_PTR1 {}
#[doc = "PTR1 register"]
pub mod ddrphyc_ptr1;
#[doc = "PTR2 register\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 [ddrphyc_ptr2](ddrphyc_ptr2) module"]
pub type DDRPHYC_PTR2 = crate::Reg<u32, _DDRPHYC_PTR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_PTR2;
#[doc = "`read()` method returns [ddrphyc_ptr2::R](ddrphyc_ptr2::R) reader structure"]
impl crate::Readable for DDRPHYC_PTR2 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_ptr2::W](ddrphyc_ptr2::W) writer structure"]
impl crate::Writable for DDRPHYC_PTR2 {}
#[doc = "PTR2 register"]
pub mod ddrphyc_ptr2;
#[doc = "ACIOCR register\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 [ddrphyc_aciocr](ddrphyc_aciocr) module"]
pub type DDRPHYC_ACIOCR = crate::Reg<u32, _DDRPHYC_ACIOCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_ACIOCR;
#[doc = "`read()` method returns [ddrphyc_aciocr::R](ddrphyc_aciocr::R) reader structure"]
impl crate::Readable for DDRPHYC_ACIOCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_aciocr::W](ddrphyc_aciocr::W) writer structure"]
impl crate::Writable for DDRPHYC_ACIOCR {}
#[doc = "ACIOCR register"]
pub mod ddrphyc_aciocr;
#[doc = "DXCCR register\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 [ddrphyc_dxccr](ddrphyc_dxccr) module"]
pub type DDRPHYC_DXCCR = crate::Reg<u32, _DDRPHYC_DXCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DXCCR;
#[doc = "`read()` method returns [ddrphyc_dxccr::R](ddrphyc_dxccr::R) reader structure"]
impl crate::Readable for DDRPHYC_DXCCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dxccr::W](ddrphyc_dxccr::W) writer structure"]
impl crate::Writable for DDRPHYC_DXCCR {}
#[doc = "DXCCR register"]
pub mod ddrphyc_dxccr;
#[doc = "DSGCR register\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 [ddrphyc_dsgcr](ddrphyc_dsgcr) module"]
pub type DDRPHYC_DSGCR = crate::Reg<u32, _DDRPHYC_DSGCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DSGCR;
#[doc = "`read()` method returns [ddrphyc_dsgcr::R](ddrphyc_dsgcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DSGCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dsgcr::W](ddrphyc_dsgcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DSGCR {}
#[doc = "DSGCR register"]
pub mod ddrphyc_dsgcr;
#[doc = "DCR register\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 [ddrphyc_dcr](ddrphyc_dcr) module"]
pub type DDRPHYC_DCR = crate::Reg<u32, _DDRPHYC_DCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCR;
#[doc = "`read()` method returns [ddrphyc_dcr::R](ddrphyc_dcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dcr::W](ddrphyc_dcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DCR {}
#[doc = "DCR register"]
pub mod ddrphyc_dcr;
#[doc = "DTPR0 register\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 [ddrphyc_dtpr0](ddrphyc_dtpr0) module"]
pub type DDRPHYC_DTPR0 = crate::Reg<u32, _DDRPHYC_DTPR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DTPR0;
#[doc = "`read()` method returns [ddrphyc_dtpr0::R](ddrphyc_dtpr0::R) reader structure"]
impl crate::Readable for DDRPHYC_DTPR0 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dtpr0::W](ddrphyc_dtpr0::W) writer structure"]
impl crate::Writable for DDRPHYC_DTPR0 {}
#[doc = "DTPR0 register"]
pub mod ddrphyc_dtpr0;
#[doc = "DTPR1 register\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 [ddrphyc_dtpr1](ddrphyc_dtpr1) module"]
pub type DDRPHYC_DTPR1 = crate::Reg<u32, _DDRPHYC_DTPR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DTPR1;
#[doc = "`read()` method returns [ddrphyc_dtpr1::R](ddrphyc_dtpr1::R) reader structure"]
impl crate::Readable for DDRPHYC_DTPR1 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dtpr1::W](ddrphyc_dtpr1::W) writer structure"]
impl crate::Writable for DDRPHYC_DTPR1 {}
#[doc = "DTPR1 register"]
pub mod ddrphyc_dtpr1;
#[doc = "DTPR2 register\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 [ddrphyc_dtpr2](ddrphyc_dtpr2) module"]
pub type DDRPHYC_DTPR2 = crate::Reg<u32, _DDRPHYC_DTPR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DTPR2;
#[doc = "`read()` method returns [ddrphyc_dtpr2::R](ddrphyc_dtpr2::R) reader structure"]
impl crate::Readable for DDRPHYC_DTPR2 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dtpr2::W](ddrphyc_dtpr2::W) writer structure"]
impl crate::Writable for DDRPHYC_DTPR2 {}
#[doc = "DTPR2 register"]
pub mod ddrphyc_dtpr2;
#[doc = "MR0 register for DDR3\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 [ddrphyc_mr0](ddrphyc_mr0) module"]
pub type DDRPHYC_MR0 = crate::Reg<u16, _DDRPHYC_MR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_MR0;
#[doc = "`read()` method returns [ddrphyc_mr0::R](ddrphyc_mr0::R) reader structure"]
impl crate::Readable for DDRPHYC_MR0 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_mr0::W](ddrphyc_mr0::W) writer structure"]
impl crate::Writable for DDRPHYC_MR0 {}
#[doc = "MR0 register for DDR3"]
pub mod ddrphyc_mr0;
#[doc = "MR1 register for LPDDR2\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 [ddrphyc_mr1](ddrphyc_mr1) module"]
pub type DDRPHYC_MR1 = crate::Reg<u16, _DDRPHYC_MR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_MR1;
#[doc = "`read()` method returns [ddrphyc_mr1::R](ddrphyc_mr1::R) reader structure"]
impl crate::Readable for DDRPHYC_MR1 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_mr1::W](ddrphyc_mr1::W) writer structure"]
impl crate::Writable for DDRPHYC_MR1 {}
#[doc = "MR1 register for LPDDR2"]
pub mod ddrphyc_mr1;
#[doc = "MR2 register for LPDDR2\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 [ddrphyc_mr2](ddrphyc_mr2) module"]
pub type DDRPHYC_MR2 = crate::Reg<u16, _DDRPHYC_MR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_MR2;
#[doc = "`read()` method returns [ddrphyc_mr2::R](ddrphyc_mr2::R) reader structure"]
impl crate::Readable for DDRPHYC_MR2 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_mr2::W](ddrphyc_mr2::W) writer structure"]
impl crate::Writable for DDRPHYC_MR2 {}
#[doc = "MR2 register for LPDDR2"]
pub mod ddrphyc_mr2;
#[doc = "MR3 register for DDR3\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 [ddrphyc_mr3](ddrphyc_mr3) module"]
pub type DDRPHYC_MR3 = crate::Reg<u8, _DDRPHYC_MR3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_MR3;
#[doc = "`read()` method returns [ddrphyc_mr3::R](ddrphyc_mr3::R) reader structure"]
impl crate::Readable for DDRPHYC_MR3 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_mr3::W](ddrphyc_mr3::W) writer structure"]
impl crate::Writable for DDRPHYC_MR3 {}
#[doc = "MR3 register for DDR3"]
pub mod ddrphyc_mr3;
#[doc = "ODTCR register\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 [ddrphyc_odtcr](ddrphyc_odtcr) module"]
pub type DDRPHYC_ODTCR = crate::Reg<u32, _DDRPHYC_ODTCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_ODTCR;
#[doc = "`read()` method returns [ddrphyc_odtcr::R](ddrphyc_odtcr::R) reader structure"]
impl crate::Readable for DDRPHYC_ODTCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_odtcr::W](ddrphyc_odtcr::W) writer structure"]
impl crate::Writable for DDRPHYC_ODTCR {}
#[doc = "ODTCR register"]
pub mod ddrphyc_odtcr;
#[doc = "DTAR register\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 [ddrphyc_dtar](ddrphyc_dtar) module"]
pub type DDRPHYC_DTAR = crate::Reg<u32, _DDRPHYC_DTAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DTAR;
#[doc = "`read()` method returns [ddrphyc_dtar::R](ddrphyc_dtar::R) reader structure"]
impl crate::Readable for DDRPHYC_DTAR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dtar::W](ddrphyc_dtar::W) writer structure"]
impl crate::Writable for DDRPHYC_DTAR {}
#[doc = "DTAR register"]
pub mod ddrphyc_dtar;
#[doc = "DTDR0 register\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 [ddrphyc_dtdr0](ddrphyc_dtdr0) module"]
pub type DDRPHYC_DTDR0 = crate::Reg<u32, _DDRPHYC_DTDR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DTDR0;
#[doc = "`read()` method returns [ddrphyc_dtdr0::R](ddrphyc_dtdr0::R) reader structure"]
impl crate::Readable for DDRPHYC_DTDR0 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dtdr0::W](ddrphyc_dtdr0::W) writer structure"]
impl crate::Writable for DDRPHYC_DTDR0 {}
#[doc = "DTDR0 register"]
pub mod ddrphyc_dtdr0;
#[doc = "DTDR1 register\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 [ddrphyc_dtdr1](ddrphyc_dtdr1) module"]
pub type DDRPHYC_DTDR1 = crate::Reg<u32, _DDRPHYC_DTDR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DTDR1;
#[doc = "`read()` method returns [ddrphyc_dtdr1::R](ddrphyc_dtdr1::R) reader structure"]
impl crate::Readable for DDRPHYC_DTDR1 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dtdr1::W](ddrphyc_dtdr1::W) writer structure"]
impl crate::Writable for DDRPHYC_DTDR1 {}
#[doc = "DTDR1 register"]
pub mod ddrphyc_dtdr1;
#[doc = "DCUAR register\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 [ddrphyc_dcuar](ddrphyc_dcuar) module"]
pub type DDRPHYC_DCUAR = crate::Reg<u16, _DDRPHYC_DCUAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCUAR;
#[doc = "`read()` method returns [ddrphyc_dcuar::R](ddrphyc_dcuar::R) reader structure"]
impl crate::Readable for DDRPHYC_DCUAR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dcuar::W](ddrphyc_dcuar::W) writer structure"]
impl crate::Writable for DDRPHYC_DCUAR {}
#[doc = "DCUAR register"]
pub mod ddrphyc_dcuar;
#[doc = "DCUDR register\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 [ddrphyc_dcudr](ddrphyc_dcudr) module"]
pub type DDRPHYC_DCUDR = crate::Reg<u32, _DDRPHYC_DCUDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCUDR;
#[doc = "`read()` method returns [ddrphyc_dcudr::R](ddrphyc_dcudr::R) reader structure"]
impl crate::Readable for DDRPHYC_DCUDR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dcudr::W](ddrphyc_dcudr::W) writer structure"]
impl crate::Writable for DDRPHYC_DCUDR {}
#[doc = "DCUDR register"]
pub mod ddrphyc_dcudr;
#[doc = "DCURR register\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 [ddrphyc_dcurr](ddrphyc_dcurr) module"]
pub type DDRPHYC_DCURR = crate::Reg<u32, _DDRPHYC_DCURR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCURR;
#[doc = "`read()` method returns [ddrphyc_dcurr::R](ddrphyc_dcurr::R) reader structure"]
impl crate::Readable for DDRPHYC_DCURR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dcurr::W](ddrphyc_dcurr::W) writer structure"]
impl crate::Writable for DDRPHYC_DCURR {}
#[doc = "DCURR register"]
pub mod ddrphyc_dcurr;
#[doc = "DCULR register\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 [ddrphyc_dculr](ddrphyc_dculr) module"]
pub type DDRPHYC_DCULR = crate::Reg<u32, _DDRPHYC_DCULR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCULR;
#[doc = "`read()` method returns [ddrphyc_dculr::R](ddrphyc_dculr::R) reader structure"]
impl crate::Readable for DDRPHYC_DCULR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dculr::W](ddrphyc_dculr::W) writer structure"]
impl crate::Writable for DDRPHYC_DCULR {}
#[doc = "DCULR register"]
pub mod ddrphyc_dculr;
#[doc = "DCUGCR register\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 [ddrphyc_dcugcr](ddrphyc_dcugcr) module"]
pub type DDRPHYC_DCUGCR = crate::Reg<u16, _DDRPHYC_DCUGCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCUGCR;
#[doc = "`read()` method returns [ddrphyc_dcugcr::R](ddrphyc_dcugcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DCUGCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dcugcr::W](ddrphyc_dcugcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DCUGCR {}
#[doc = "DCUGCR register"]
pub mod ddrphyc_dcugcr;
#[doc = "DCUTPR register\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 [ddrphyc_dcutpr](ddrphyc_dcutpr) module"]
pub type DDRPHYC_DCUTPR = crate::Reg<u32, _DDRPHYC_DCUTPR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCUTPR;
#[doc = "`read()` method returns [ddrphyc_dcutpr::R](ddrphyc_dcutpr::R) reader structure"]
impl crate::Readable for DDRPHYC_DCUTPR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dcutpr::W](ddrphyc_dcutpr::W) writer structure"]
impl crate::Writable for DDRPHYC_DCUTPR {}
#[doc = "DCUTPR register"]
pub mod ddrphyc_dcutpr;
#[doc = "DCUSR0 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dcusr0](ddrphyc_dcusr0) module"]
pub type DDRPHYC_DCUSR0 = crate::Reg<u8, _DDRPHYC_DCUSR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCUSR0;
#[doc = "`read()` method returns [ddrphyc_dcusr0::R](ddrphyc_dcusr0::R) reader structure"]
impl crate::Readable for DDRPHYC_DCUSR0 {}
#[doc = "DCUSR0 register"]
pub mod ddrphyc_dcusr0;
#[doc = "DCUSR1 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dcusr1](ddrphyc_dcusr1) module"]
pub type DDRPHYC_DCUSR1 = crate::Reg<u32, _DDRPHYC_DCUSR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DCUSR1;
#[doc = "`read()` method returns [ddrphyc_dcusr1::R](ddrphyc_dcusr1::R) reader structure"]
impl crate::Readable for DDRPHYC_DCUSR1 {}
#[doc = "DCUSR1 register"]
pub mod ddrphyc_dcusr1;
#[doc = "BISTRR register\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 [ddrphyc_bistrr](ddrphyc_bistrr) module"]
pub type DDRPHYC_BISTRR = crate::Reg<u32, _DDRPHYC_BISTRR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTRR;
#[doc = "`read()` method returns [ddrphyc_bistrr::R](ddrphyc_bistrr::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTRR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistrr::W](ddrphyc_bistrr::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTRR {}
#[doc = "BISTRR register"]
pub mod ddrphyc_bistrr;
#[doc = "BISTMSKR0 register\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 [ddrphyc_bistmskr0](ddrphyc_bistmskr0) module"]
pub type DDRPHYC_BISTMSKR0 = crate::Reg<u32, _DDRPHYC_BISTMSKR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTMSKR0;
#[doc = "`read()` method returns [ddrphyc_bistmskr0::R](ddrphyc_bistmskr0::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTMSKR0 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistmskr0::W](ddrphyc_bistmskr0::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTMSKR0 {}
#[doc = "BISTMSKR0 register"]
pub mod ddrphyc_bistmskr0;
#[doc = "BISTMSKR1 register\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 [ddrphyc_bistmskr1](ddrphyc_bistmskr1) module"]
pub type DDRPHYC_BISTMSKR1 = crate::Reg<u32, _DDRPHYC_BISTMSKR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTMSKR1;
#[doc = "`read()` method returns [ddrphyc_bistmskr1::R](ddrphyc_bistmskr1::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTMSKR1 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistmskr1::W](ddrphyc_bistmskr1::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTMSKR1 {}
#[doc = "BISTMSKR1 register"]
pub mod ddrphyc_bistmskr1;
#[doc = "BISTWCR register\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 [ddrphyc_bistwcr](ddrphyc_bistwcr) module"]
pub type DDRPHYC_BISTWCR = crate::Reg<u16, _DDRPHYC_BISTWCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTWCR;
#[doc = "`read()` method returns [ddrphyc_bistwcr::R](ddrphyc_bistwcr::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTWCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistwcr::W](ddrphyc_bistwcr::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTWCR {}
#[doc = "BISTWCR register"]
pub mod ddrphyc_bistwcr;
#[doc = "BISTLSR register\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 [ddrphyc_bistlsr](ddrphyc_bistlsr) module"]
pub type DDRPHYC_BISTLSR = crate::Reg<u32, _DDRPHYC_BISTLSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTLSR;
#[doc = "`read()` method returns [ddrphyc_bistlsr::R](ddrphyc_bistlsr::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTLSR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistlsr::W](ddrphyc_bistlsr::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTLSR {}
#[doc = "BISTLSR register"]
pub mod ddrphyc_bistlsr;
#[doc = "BISTAR0 register\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 [ddrphyc_bistar0](ddrphyc_bistar0) module"]
pub type DDRPHYC_BISTAR0 = crate::Reg<u32, _DDRPHYC_BISTAR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTAR0;
#[doc = "`read()` method returns [ddrphyc_bistar0::R](ddrphyc_bistar0::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTAR0 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistar0::W](ddrphyc_bistar0::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTAR0 {}
#[doc = "BISTAR0 register"]
pub mod ddrphyc_bistar0;
#[doc = "BISTAR1 register\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 [ddrphyc_bistar1](ddrphyc_bistar1) module"]
pub type DDRPHYC_BISTAR1 = crate::Reg<u16, _DDRPHYC_BISTAR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTAR1;
#[doc = "`read()` method returns [ddrphyc_bistar1::R](ddrphyc_bistar1::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTAR1 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistar1::W](ddrphyc_bistar1::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTAR1 {}
#[doc = "BISTAR1 register"]
pub mod ddrphyc_bistar1;
#[doc = "BISTAR2 register\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 [ddrphyc_bistar2](ddrphyc_bistar2) module"]
pub type DDRPHYC_BISTAR2 = crate::Reg<u32, _DDRPHYC_BISTAR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTAR2;
#[doc = "`read()` method returns [ddrphyc_bistar2::R](ddrphyc_bistar2::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTAR2 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistar2::W](ddrphyc_bistar2::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTAR2 {}
#[doc = "BISTAR2 register"]
pub mod ddrphyc_bistar2;
#[doc = "BISTUDPR register\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 [ddrphyc_bistudpr](ddrphyc_bistudpr) module"]
pub type DDRPHYC_BISTUDPR = crate::Reg<u32, _DDRPHYC_BISTUDPR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTUDPR;
#[doc = "`read()` method returns [ddrphyc_bistudpr::R](ddrphyc_bistudpr::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTUDPR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_bistudpr::W](ddrphyc_bistudpr::W) writer structure"]
impl crate::Writable for DDRPHYC_BISTUDPR {}
#[doc = "BISTUDPR register"]
pub mod ddrphyc_bistudpr;
#[doc = "BISTGSR register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_bistgsr](ddrphyc_bistgsr) module"]
pub type DDRPHYC_BISTGSR = crate::Reg<u32, _DDRPHYC_BISTGSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTGSR;
#[doc = "`read()` method returns [ddrphyc_bistgsr::R](ddrphyc_bistgsr::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTGSR {}
#[doc = "BISTGSR register"]
pub mod ddrphyc_bistgsr;
#[doc = "BISTWER register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_bistwer](ddrphyc_bistwer) module"]
pub type DDRPHYC_BISTWER = crate::Reg<u32, _DDRPHYC_BISTWER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTWER;
#[doc = "`read()` method returns [ddrphyc_bistwer::R](ddrphyc_bistwer::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTWER {}
#[doc = "BISTWER register"]
pub mod ddrphyc_bistwer;
#[doc = "BISTBER0 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_bistber0](ddrphyc_bistber0) module"]
pub type DDRPHYC_BISTBER0 = crate::Reg<u32, _DDRPHYC_BISTBER0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTBER0;
#[doc = "`read()` method returns [ddrphyc_bistber0::R](ddrphyc_bistber0::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTBER0 {}
#[doc = "BISTBER0 register"]
pub mod ddrphyc_bistber0;
#[doc = "BISTBER1 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_bistber1](ddrphyc_bistber1) module"]
pub type DDRPHYC_BISTBER1 = crate::Reg<u32, _DDRPHYC_BISTBER1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTBER1;
#[doc = "`read()` method returns [ddrphyc_bistber1::R](ddrphyc_bistber1::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTBER1 {}
#[doc = "BISTBER1 register"]
pub mod ddrphyc_bistber1;
#[doc = "BISTBER2 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_bistber2](ddrphyc_bistber2) module"]
pub type DDRPHYC_BISTBER2 = crate::Reg<u32, _DDRPHYC_BISTBER2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTBER2;
#[doc = "`read()` method returns [ddrphyc_bistber2::R](ddrphyc_bistber2::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTBER2 {}
#[doc = "BISTBER2 register"]
pub mod ddrphyc_bistber2;
#[doc = "BISTWCSR register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_bistwcsr](ddrphyc_bistwcsr) module"]
pub type DDRPHYC_BISTWCSR = crate::Reg<u32, _DDRPHYC_BISTWCSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTWCSR;
#[doc = "`read()` method returns [ddrphyc_bistwcsr::R](ddrphyc_bistwcsr::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTWCSR {}
#[doc = "BISTWCSR register"]
pub mod ddrphyc_bistwcsr;
#[doc = "BISTFWR0 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_bistfwr0](ddrphyc_bistfwr0) module"]
pub type DDRPHYC_BISTFWR0 = crate::Reg<u32, _DDRPHYC_BISTFWR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTFWR0;
#[doc = "`read()` method returns [ddrphyc_bistfwr0::R](ddrphyc_bistfwr0::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTFWR0 {}
#[doc = "BISTFWR0 register"]
pub mod ddrphyc_bistfwr0;
#[doc = "BISTFWR1 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_bistfwr1](ddrphyc_bistfwr1) module"]
pub type DDRPHYC_BISTFWR1 = crate::Reg<u32, _DDRPHYC_BISTFWR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_BISTFWR1;
#[doc = "`read()` method returns [ddrphyc_bistfwr1::R](ddrphyc_bistfwr1::R) reader structure"]
impl crate::Readable for DDRPHYC_BISTFWR1 {}
#[doc = "BISTFWR1 register"]
pub mod ddrphyc_bistfwr1;
#[doc = "General Purpose Register 0\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 [ddrphyc_gpr0](ddrphyc_gpr0) module"]
pub type DDRPHYC_GPR0 = crate::Reg<u32, _DDRPHYC_GPR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_GPR0;
#[doc = "`read()` method returns [ddrphyc_gpr0::R](ddrphyc_gpr0::R) reader structure"]
impl crate::Readable for DDRPHYC_GPR0 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_gpr0::W](ddrphyc_gpr0::W) writer structure"]
impl crate::Writable for DDRPHYC_GPR0 {}
#[doc = "General Purpose Register 0"]
pub mod ddrphyc_gpr0;
#[doc = "General Purpose Register register 1\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 [ddrphyc_gpr1](ddrphyc_gpr1) module"]
pub type DDRPHYC_GPR1 = crate::Reg<u32, _DDRPHYC_GPR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_GPR1;
#[doc = "`read()` method returns [ddrphyc_gpr1::R](ddrphyc_gpr1::R) reader structure"]
impl crate::Readable for DDRPHYC_GPR1 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_gpr1::W](ddrphyc_gpr1::W) writer structure"]
impl crate::Writable for DDRPHYC_GPR1 {}
#[doc = "General Purpose Register register 1"]
pub mod ddrphyc_gpr1;
#[doc = "ZQ0CR0 register\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 [ddrphyc_zq0cr0](ddrphyc_zq0cr0) module"]
pub type DDRPHYC_ZQ0CR0 = crate::Reg<u32, _DDRPHYC_ZQ0CR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_ZQ0CR0;
#[doc = "`read()` method returns [ddrphyc_zq0cr0::R](ddrphyc_zq0cr0::R) reader structure"]
impl crate::Readable for DDRPHYC_ZQ0CR0 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_zq0cr0::W](ddrphyc_zq0cr0::W) writer structure"]
impl crate::Writable for DDRPHYC_ZQ0CR0 {}
#[doc = "ZQ0CR0 register"]
pub mod ddrphyc_zq0cr0;
#[doc = "ZQ0CR1 register\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 [ddrphyc_zq0cr1](ddrphyc_zq0cr1) module"]
pub type DDRPHYC_ZQ0CR1 = crate::Reg<u8, _DDRPHYC_ZQ0CR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_ZQ0CR1;
#[doc = "`read()` method returns [ddrphyc_zq0cr1::R](ddrphyc_zq0cr1::R) reader structure"]
impl crate::Readable for DDRPHYC_ZQ0CR1 {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_zq0cr1::W](ddrphyc_zq0cr1::W) writer structure"]
impl crate::Writable for DDRPHYC_ZQ0CR1 {}
#[doc = "ZQ0CR1 register"]
pub mod ddrphyc_zq0cr1;
#[doc = "ZQ0SR0 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_zq0sr0](ddrphyc_zq0sr0) module"]
pub type DDRPHYC_ZQ0SR0 = crate::Reg<u32, _DDRPHYC_ZQ0SR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_ZQ0SR0;
#[doc = "`read()` method returns [ddrphyc_zq0sr0::R](ddrphyc_zq0sr0::R) reader structure"]
impl crate::Readable for DDRPHYC_ZQ0SR0 {}
#[doc = "ZQ0SR0 register"]
pub mod ddrphyc_zq0sr0;
#[doc = "ZQ0SR1 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_zq0sr1](ddrphyc_zq0sr1) module"]
pub type DDRPHYC_ZQ0SR1 = crate::Reg<u8, _DDRPHYC_ZQ0SR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_ZQ0SR1;
#[doc = "`read()` method returns [ddrphyc_zq0sr1::R](ddrphyc_zq0sr1::R) reader structure"]
impl crate::Readable for DDRPHYC_ZQ0SR1 {}
#[doc = "ZQ0SR1 register"]
pub mod ddrphyc_zq0sr1;
#[doc = "DX 0 GCR register\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 [ddrphyc_dx0gcr](ddrphyc_dx0gcr) module"]
pub type DDRPHYC_DX0GCR = crate::Reg<u32, _DDRPHYC_DX0GCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX0GCR;
#[doc = "`read()` method returns [ddrphyc_dx0gcr::R](ddrphyc_dx0gcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX0GCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx0gcr::W](ddrphyc_dx0gcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX0GCR {}
#[doc = "DX 0 GCR register"]
pub mod ddrphyc_dx0gcr;
#[doc = "DX 0 GSR0 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dx0gsr0](ddrphyc_dx0gsr0) module"]
pub type DDRPHYC_DX0GSR0 = crate::Reg<u16, _DDRPHYC_DX0GSR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX0GSR0;
#[doc = "`read()` method returns [ddrphyc_dx0gsr0::R](ddrphyc_dx0gsr0::R) reader structure"]
impl crate::Readable for DDRPHYC_DX0GSR0 {}
#[doc = "DX 0 GSR0 register"]
pub mod ddrphyc_dx0gsr0;
#[doc = "DX 0 GSR1 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dx0gsr1](ddrphyc_dx0gsr1) module"]
pub type DDRPHYC_DX0GSR1 = crate::Reg<u32, _DDRPHYC_DX0GSR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX0GSR1;
#[doc = "`read()` method returns [ddrphyc_dx0gsr1::R](ddrphyc_dx0gsr1::R) reader structure"]
impl crate::Readable for DDRPHYC_DX0GSR1 {}
#[doc = "DX 0 GSR1 register"]
pub mod ddrphyc_dx0gsr1;
#[doc = "DX 0 DLLCR register\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 [ddrphyc_dx0dllcr](ddrphyc_dx0dllcr) module"]
pub type DDRPHYC_DX0DLLCR = crate::Reg<u32, _DDRPHYC_DX0DLLCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX0DLLCR;
#[doc = "`read()` method returns [ddrphyc_dx0dllcr::R](ddrphyc_dx0dllcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX0DLLCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx0dllcr::W](ddrphyc_dx0dllcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX0DLLCR {}
#[doc = "DX 0 DLLCR register"]
pub mod ddrphyc_dx0dllcr;
#[doc = "DX 0 DQTR register\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 [ddrphyc_dx0dqtr](ddrphyc_dx0dqtr) module"]
pub type DDRPHYC_DX0DQTR = crate::Reg<u32, _DDRPHYC_DX0DQTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX0DQTR;
#[doc = "`read()` method returns [ddrphyc_dx0dqtr::R](ddrphyc_dx0dqtr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX0DQTR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx0dqtr::W](ddrphyc_dx0dqtr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX0DQTR {}
#[doc = "DX 0 DQTR register"]
pub mod ddrphyc_dx0dqtr;
#[doc = "DX 0 DQSTR register\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 [ddrphyc_dx0dqstr](ddrphyc_dx0dqstr) module"]
pub type DDRPHYC_DX0DQSTR = crate::Reg<u32, _DDRPHYC_DX0DQSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX0DQSTR;
#[doc = "`read()` method returns [ddrphyc_dx0dqstr::R](ddrphyc_dx0dqstr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX0DQSTR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx0dqstr::W](ddrphyc_dx0dqstr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX0DQSTR {}
#[doc = "DX 0 DQSTR register"]
pub mod ddrphyc_dx0dqstr;
#[doc = "DX 1 GCR register\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 [ddrphyc_dx1gcr](ddrphyc_dx1gcr) module"]
pub type DDRPHYC_DX1GCR = crate::Reg<u32, _DDRPHYC_DX1GCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX1GCR;
#[doc = "`read()` method returns [ddrphyc_dx1gcr::R](ddrphyc_dx1gcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX1GCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx1gcr::W](ddrphyc_dx1gcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX1GCR {}
#[doc = "DX 1 GCR register"]
pub mod ddrphyc_dx1gcr;
#[doc = "DX 1 GSR0 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dx1gsr0](ddrphyc_dx1gsr0) module"]
pub type DDRPHYC_DX1GSR0 = crate::Reg<u16, _DDRPHYC_DX1GSR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX1GSR0;
#[doc = "`read()` method returns [ddrphyc_dx1gsr0::R](ddrphyc_dx1gsr0::R) reader structure"]
impl crate::Readable for DDRPHYC_DX1GSR0 {}
#[doc = "DX 1 GSR0 register"]
pub mod ddrphyc_dx1gsr0;
#[doc = "DX 1 GSR1 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dx1gsr1](ddrphyc_dx1gsr1) module"]
pub type DDRPHYC_DX1GSR1 = crate::Reg<u32, _DDRPHYC_DX1GSR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX1GSR1;
#[doc = "`read()` method returns [ddrphyc_dx1gsr1::R](ddrphyc_dx1gsr1::R) reader structure"]
impl crate::Readable for DDRPHYC_DX1GSR1 {}
#[doc = "DX 1 GSR1 register"]
pub mod ddrphyc_dx1gsr1;
#[doc = "DX 1 DLLCR register\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 [ddrphyc_dx1dllcr](ddrphyc_dx1dllcr) module"]
pub type DDRPHYC_DX1DLLCR = crate::Reg<u32, _DDRPHYC_DX1DLLCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX1DLLCR;
#[doc = "`read()` method returns [ddrphyc_dx1dllcr::R](ddrphyc_dx1dllcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX1DLLCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx1dllcr::W](ddrphyc_dx1dllcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX1DLLCR {}
#[doc = "DX 1 DLLCR register"]
pub mod ddrphyc_dx1dllcr;
#[doc = "DX 1 DQTR register\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 [ddrphyc_dx1dqtr](ddrphyc_dx1dqtr) module"]
pub type DDRPHYC_DX1DQTR = crate::Reg<u32, _DDRPHYC_DX1DQTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX1DQTR;
#[doc = "`read()` method returns [ddrphyc_dx1dqtr::R](ddrphyc_dx1dqtr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX1DQTR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx1dqtr::W](ddrphyc_dx1dqtr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX1DQTR {}
#[doc = "DX 1 DQTR register"]
pub mod ddrphyc_dx1dqtr;
#[doc = "DX 1 DQSTR register\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 [ddrphyc_dx1dqstr](ddrphyc_dx1dqstr) module"]
pub type DDRPHYC_DX1DQSTR = crate::Reg<u32, _DDRPHYC_DX1DQSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX1DQSTR;
#[doc = "`read()` method returns [ddrphyc_dx1dqstr::R](ddrphyc_dx1dqstr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX1DQSTR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx1dqstr::W](ddrphyc_dx1dqstr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX1DQSTR {}
#[doc = "DX 1 DQSTR register"]
pub mod ddrphyc_dx1dqstr;
#[doc = "DX 2 GCR register\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 [ddrphyc_dx2gcr](ddrphyc_dx2gcr) module"]
pub type DDRPHYC_DX2GCR = crate::Reg<u32, _DDRPHYC_DX2GCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX2GCR;
#[doc = "`read()` method returns [ddrphyc_dx2gcr::R](ddrphyc_dx2gcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX2GCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx2gcr::W](ddrphyc_dx2gcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX2GCR {}
#[doc = "DX 2 GCR register"]
pub mod ddrphyc_dx2gcr;
#[doc = "DX 2 GSR0 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dx2gsr0](ddrphyc_dx2gsr0) module"]
pub type DDRPHYC_DX2GSR0 = crate::Reg<u16, _DDRPHYC_DX2GSR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX2GSR0;
#[doc = "`read()` method returns [ddrphyc_dx2gsr0::R](ddrphyc_dx2gsr0::R) reader structure"]
impl crate::Readable for DDRPHYC_DX2GSR0 {}
#[doc = "DX 2 GSR0 register"]
pub mod ddrphyc_dx2gsr0;
#[doc = "DX 2 GSR1 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dx2gsr1](ddrphyc_dx2gsr1) module"]
pub type DDRPHYC_DX2GSR1 = crate::Reg<u32, _DDRPHYC_DX2GSR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX2GSR1;
#[doc = "`read()` method returns [ddrphyc_dx2gsr1::R](ddrphyc_dx2gsr1::R) reader structure"]
impl crate::Readable for DDRPHYC_DX2GSR1 {}
#[doc = "DX 2 GSR1 register"]
pub mod ddrphyc_dx2gsr1;
#[doc = "DX 2 DLLCR register\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 [ddrphyc_dx2dllcr](ddrphyc_dx2dllcr) module"]
pub type DDRPHYC_DX2DLLCR = crate::Reg<u32, _DDRPHYC_DX2DLLCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX2DLLCR;
#[doc = "`read()` method returns [ddrphyc_dx2dllcr::R](ddrphyc_dx2dllcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX2DLLCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx2dllcr::W](ddrphyc_dx2dllcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX2DLLCR {}
#[doc = "DX 2 DLLCR register"]
pub mod ddrphyc_dx2dllcr;
#[doc = "DX 2 DQTR register\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 [ddrphyc_dx2dqtr](ddrphyc_dx2dqtr) module"]
pub type DDRPHYC_DX2DQTR = crate::Reg<u32, _DDRPHYC_DX2DQTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX2DQTR;
#[doc = "`read()` method returns [ddrphyc_dx2dqtr::R](ddrphyc_dx2dqtr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX2DQTR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx2dqtr::W](ddrphyc_dx2dqtr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX2DQTR {}
#[doc = "DX 2 DQTR register"]
pub mod ddrphyc_dx2dqtr;
#[doc = "DX 2 DQSTR register\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 [ddrphyc_dx2dqstr](ddrphyc_dx2dqstr) module"]
pub type DDRPHYC_DX2DQSTR = crate::Reg<u32, _DDRPHYC_DX2DQSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX2DQSTR;
#[doc = "`read()` method returns [ddrphyc_dx2dqstr::R](ddrphyc_dx2dqstr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX2DQSTR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx2dqstr::W](ddrphyc_dx2dqstr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX2DQSTR {}
#[doc = "DX 2 DQSTR register"]
pub mod ddrphyc_dx2dqstr;
#[doc = "DX 3 GCR register\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 [ddrphyc_dx3gcr](ddrphyc_dx3gcr) module"]
pub type DDRPHYC_DX3GCR = crate::Reg<u32, _DDRPHYC_DX3GCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX3GCR;
#[doc = "`read()` method returns [ddrphyc_dx3gcr::R](ddrphyc_dx3gcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX3GCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx3gcr::W](ddrphyc_dx3gcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX3GCR {}
#[doc = "DX 3 GCR register"]
pub mod ddrphyc_dx3gcr;
#[doc = "DX 3 GSR0 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dx3gsr0](ddrphyc_dx3gsr0) module"]
pub type DDRPHYC_DX3GSR0 = crate::Reg<u16, _DDRPHYC_DX3GSR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX3GSR0;
#[doc = "`read()` method returns [ddrphyc_dx3gsr0::R](ddrphyc_dx3gsr0::R) reader structure"]
impl crate::Readable for DDRPHYC_DX3GSR0 {}
#[doc = "DX 3 GSR0 register"]
pub mod ddrphyc_dx3gsr0;
#[doc = "DX 3 GSR1 register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ddrphyc_dx3gsr1](ddrphyc_dx3gsr1) module"]
pub type DDRPHYC_DX3GSR1 = crate::Reg<u32, _DDRPHYC_DX3GSR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX3GSR1;
#[doc = "`read()` method returns [ddrphyc_dx3gsr1::R](ddrphyc_dx3gsr1::R) reader structure"]
impl crate::Readable for DDRPHYC_DX3GSR1 {}
#[doc = "DX 3 GSR1 register"]
pub mod ddrphyc_dx3gsr1;
#[doc = "DX 3 DLLCR register\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 [ddrphyc_dx3dllcr](ddrphyc_dx3dllcr) module"]
pub type DDRPHYC_DX3DLLCR = crate::Reg<u32, _DDRPHYC_DX3DLLCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX3DLLCR;
#[doc = "`read()` method returns [ddrphyc_dx3dllcr::R](ddrphyc_dx3dllcr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX3DLLCR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx3dllcr::W](ddrphyc_dx3dllcr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX3DLLCR {}
#[doc = "DX 3 DLLCR register"]
pub mod ddrphyc_dx3dllcr;
#[doc = "DX 3 DQTR register\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 [ddrphyc_dx3dqtr](ddrphyc_dx3dqtr) module"]
pub type DDRPHYC_DX3DQTR = crate::Reg<u32, _DDRPHYC_DX3DQTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX3DQTR;
#[doc = "`read()` method returns [ddrphyc_dx3dqtr::R](ddrphyc_dx3dqtr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX3DQTR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx3dqtr::W](ddrphyc_dx3dqtr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX3DQTR {}
#[doc = "DX 3 DQTR register"]
pub mod ddrphyc_dx3dqtr;
#[doc = "DX 3 DQSTR register\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 [ddrphyc_dx3dqstr](ddrphyc_dx3dqstr) module"]
pub type DDRPHYC_DX3DQSTR = crate::Reg<u32, _DDRPHYC_DX3DQSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DDRPHYC_DX3DQSTR;
#[doc = "`read()` method returns [ddrphyc_dx3dqstr::R](ddrphyc_dx3dqstr::R) reader structure"]
impl crate::Readable for DDRPHYC_DX3DQSTR {}
#[doc = "`write(|w| ..)` method takes [ddrphyc_dx3dqstr::W](ddrphyc_dx3dqstr::W) writer structure"]
impl crate::Writable for DDRPHYC_DX3DQSTR {}
#[doc = "DX 3 DQSTR register"]
pub mod ddrphyc_dx3dqstr;
|
use std::env;
use aoc_2020::*;
// use fmt::write;
use std::time::{Instant};
fn main() {
let args: Vec<String> = env::args().collect();
let start = Instant::now();
let fname = format!("src/day{}.txt", args[1]);
match &args[1][..]{
"1" => day1(&fname),
"2" => day2(&fname),
"3" => day3(&fname),
"4" => day4(&fname),
"5" => day5(&fname),
"6" => day6(&fname),
"7" => day7(&fname),
"8" => day8(&fname),
"9" => day9(&fname),
"10" => day10(&fname),
"11" => day11(&fname),
"12" => day12(&fname),
"13" => day13(&fname),
"14" => day14(&fname),
"15" => day15(&fname),
"16" => day16(&fname),
"17" => day17(&fname),
"18" => day18(&fname),
"19" => day19(&fname),
"20" => day20(&fname),
"21" => day21(&fname),
"22" => day22(&fname),
"24" => day24(&fname),
"25" => day25(&fname),
"test.txt" => day24(&"test.txt".to_string()),
_ => {
println!("Day {} is not a potential day yet, or ever", args[1]);
}
};
let duration = start.elapsed();
println!("overall it took {:?}", duration);
}
use std::collections::{HashMap, HashSet};
pub fn day19(filename: &String){
let contents = file2vec::<String>(filename);
let contents:Vec<String> = contents.iter().map(|x| x.to_owned().unwrap()).collect();
let mut rules = HashMap::new();
let mut messages = Vec::new();
for line in &contents{
if line.contains(':') {
let mut key = "";
// let mut key = String::from("");
for (i, s) in line.split(':').enumerate(){
if i == 0 {
key = s;
} else {
rules.insert(key.to_owned(), s.trim().to_owned());
}
}
} else if line.len()>0{
messages.push(line.to_owned());
};
};
println!("{:?}", rules);
println!("{:?}", messages);
}
use std::collections::VecDeque;
pub fn day22(filename: &String){
let contents = file2vec::<String>(filename);
let contents:Vec<String> = contents.iter().map(|x| x.to_owned().unwrap()).collect();
let mut player1 = VecDeque::new();
let mut player2 = VecDeque::new();
let mut p1 = true;
for line in &contents[1..]{
match line.chars().nth(0){
Some(x) if x.is_numeric()=>{
if p1 {
player1.push_back(line.parse::<i32>().unwrap());
} else {
player2.push_back(line.parse::<i32>().unwrap());
}
},
Some(x) if x == 'P' => {
p1 = false;
},
_ => ()
}
}
let part1_ans = combat(&mut player1.clone(), &mut player2.clone());
println!("{:?}", part1_ans);
println!("{:?}", player2);
let part2_ans = recursive_combat(&mut player1, &mut player2);
println!("{:?}", part2_ans);
}
fn deck_score(deck: &VecDeque<i32>)->i32{
let mut score = 0;
let mut idx = deck.len() as i32;
for card in deck {
score += *card * idx;
idx -= 1;
}
score
}
fn turn(p1: &mut VecDeque<i32>, p2: &mut VecDeque<i32>){
let card1 = p1.pop_front().unwrap();
let card2 = p2.pop_front().unwrap();
if card1 > card2 {
p1.push_back(card1);
p1.push_back(card2);
} else {
p2.push_back(card2);
p2.push_back(card1);
}
}
fn combat(player1: &mut VecDeque<i32>, player2: &mut VecDeque<i32>)->GameResult{
while !(player1.is_empty() | player2.is_empty()){
turn(player1, player2);
}
let part1_ans = if player1.is_empty() {
GameResult{ winner: Winner::Player2, cause: Cause::AllCards, score: deck_score(&player2)}
} else {
GameResult{ winner: Winner::Player1, cause: Cause::AllCards, score:deck_score(&player1)}
};
part1_ans
}
fn recursive_turn(p1: &mut VecDeque<i32>, p2: &mut VecDeque<i32>, seen: &mut HashSet<Vec<i32>>, level: usize)->Option<GameResult>{
println!("Recursion level {}", level);
if seen.contains(&to_key(p1, p2)){
println!("This happened: {:?}", seen);
return Some(GameResult{ winner: Winner::Player1, cause: Cause::Recursion, score: deck_score(p1)})
};
seen.insert(to_key(&p1, &p2));
if p1.is_empty() {
return Some(GameResult{ winner: Winner::Player2, cause: Cause::SubGame, score: deck_score(p2)})
}
if p2.is_empty() {
return Some(GameResult{ winner: Winner::Player1, cause: Cause::SubGame, score: deck_score(p1)})
}
let card1 = p1.pop_front().unwrap();
let card2 = p2.pop_front().unwrap();
let mut res =None;
if (p1.len() >= card1 as usize) & (p2.len() >= card2 as usize ){
println!("card 1 {}, p1 len {}, card 2 {}, p2 len {}", card1, p1.len(), card2, p2.len());
let mut new_p1 = p1.clone().drain(..card1 as usize).collect();
let mut new_p2: VecDeque<i32> = p2.clone().drain(..card2 as usize).collect();
// seen.insert(to_key(&new_p2));
if let Some(r) = recursive_turn(&mut new_p1, &mut new_p2, seen, level+1){
if r.cause == Cause::Recursion {
res = Some(r);
}
match r.winner {
Winner::Player1 => {
p1.push_back(card1);
p1.push_back(card2);
},
Winner::Player2 =>{
println!("{}-{}", card1, card2);
p2.push_back(card2);
p2.push_back(card1);
}
}
println!("{:?}", to_key(p1, p2));
}
} else {
if card1 > card2 {
p1.push_back(card1);
p1.push_back(card2);
} else {
p2.push_back(card2);
p2.push_back(card1);
}
}
res
}
fn to_key(v1: &VecDeque<i32>, v2: &VecDeque<i32>)->Vec<i32>{
let mut out = Vec::new();
for elt in v1{
out.push(*elt);
}
for elt in v2{
out.push(*elt);
}
out
}
fn recursive_combat(player1: &mut VecDeque<i32>, player2: &mut VecDeque<i32>)->GameResult{
let mut seen = HashSet::new();
let mut turns = 1;
while !(player1.is_empty() | player2.is_empty()){
println!("turn {}", turns);
println!("Player 1: {:?}", player1);
println!("Player 2: {:?}", player2);
let res = recursive_turn(player1, player2, &mut seen, 0);
println!("{:?}", res);
if let Some(r) = res{
if r.cause == Cause::Recursion {
return GameResult{ winner: Winner::Player1, cause: Cause::AllCards, score:deck_score(&player1) }
}
};
turns +=1;
}
if player1.is_empty() {
println!("{:?}", player2);
GameResult{ winner: Winner::Player2, cause: Cause::AllCards, score: deck_score(&player2)}
} else {
GameResult{ winner: Winner::Player1, cause: Cause::AllCards, score:deck_score(&player1)}
}
}
#[derive(Debug,Clone, Copy)]
enum Winner{
Player1,
Player2
}
#[derive(Debug,Clone, Copy, PartialEq, Eq)]
enum Cause{
Recursion,
SubGame,
AllCards
}
#[derive(Debug,Clone, Copy)]
struct GameResult{
winner: Winner,
cause: Cause,
score: i32
}
|
#[derive(Debug, Deserialize, PartialEq, Eq)]
pub struct ButtonSettings {
pub name: String,
pub gpio: u8
}
|
#[macro_use] extern crate colorify;
extern crate ocl;
use ocl::{Result as OclResult, Platform, Device, Context, Image, Queue};
use ocl::enums::MemObjectType;
use ocl::core::{OclPrm};
fn img_formats() -> OclResult<()> {
for (p_idx, platform) in Platform::list().into_iter().enumerate() {
for (d_idx, device) in Device::list_all(&platform)?.into_iter().enumerate() {
printlnc!(blue: "Platform [{}]: {}", p_idx, platform.name()?);
printlnc!(teal: "Device [{}]: {} {}", d_idx, device.vendor()?, device.name()?);
let context = Context::builder().platform(platform).devices(device).build()?;
let sup_img_formats = Image::<u8>::supported_formats(&context, ocl::flags::MEM_READ_WRITE,
MemObjectType::Image2d)?;
println!("Image Formats: {:#?}.", sup_img_formats);
// let queue = Queue::new(&context, device, Some(ocl::core::QUEUE_PROFILING_ENABLE))?;
// let image = Image::<u8>::builder()
// .dims(2048)
// .queue(queue.clone())
// .build()?;
// fn print_image_info<S: OclPrm>(image: &Image<S>) {
// printlnc!(peach: "{}", image);
// }
// print_image_info(&image);
}
}
Ok(())
}
pub fn main() {
match img_formats() {
Ok(_) => (),
Err(err) => println!("{}", err),
}
}
// Platform [0]: Intel(R) OpenCL
// Device [0]: Intel(R) Corporation Intel(R) HD Graphics 520
// Image Formats: [
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Bgra,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Depth,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Depth,
// channel_data_type: UnormInt16,
// },
// ),
// ].
// Platform [0]: Intel(R) OpenCL
// Device [1]: Intel(R) Corporation Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz
// Image Formats: [
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Bgra,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Depth,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Depth,
// channel_data_type: UnormInt16,
// },
// ),
// ].
// Platform [1]: AMD Accelerated Parallel Processing
// Device [0]: Advanced Micro Devices, Inc. Iceland
// Image Formats: [
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: R,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: A,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rg,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: SignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: UnsignedInt32,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgba,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Argb,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Argb,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Argb,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Argb,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Bgra,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Bgra,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Bgra,
// channel_data_type: SignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Bgra,
// channel_data_type: UnsignedInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Luminance,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: SnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: SnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: UnormInt8,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: HalfFloat,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Intensity,
// channel_data_type: Float,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Rgb,
// channel_data_type: UnormInt101010,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Depth,
// channel_data_type: UnormInt16,
// },
// ),
// Ok(
// ImageFormat {
// channel_order: Depth,
// channel_data_type: Float,
// },
// ),
// ] |
#[doc = "Register `MDMA_C13ESR` reader"]
pub type R = crate::R<MDMA_C13ESR_SPEC>;
#[doc = "Field `TEA` reader - TEA"]
pub type TEA_R = crate::FieldReader;
#[doc = "Field `TED` reader - TED"]
pub type TED_R = crate::BitReader;
#[doc = "Field `TELD` reader - TELD"]
pub type TELD_R = crate::BitReader;
#[doc = "Field `TEMD` reader - TEMD"]
pub type TEMD_R = crate::BitReader;
#[doc = "Field `ASE` reader - ASE"]
pub type ASE_R = crate::BitReader;
#[doc = "Field `BSE` reader - BSE"]
pub type BSE_R = crate::BitReader;
impl R {
#[doc = "Bits 0:6 - TEA"]
#[inline(always)]
pub fn tea(&self) -> TEA_R {
TEA_R::new((self.bits & 0x7f) as u8)
}
#[doc = "Bit 7 - TED"]
#[inline(always)]
pub fn ted(&self) -> TED_R {
TED_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - TELD"]
#[inline(always)]
pub fn teld(&self) -> TELD_R {
TELD_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - TEMD"]
#[inline(always)]
pub fn temd(&self) -> TEMD_R {
TEMD_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - ASE"]
#[inline(always)]
pub fn ase(&self) -> ASE_R {
ASE_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - BSE"]
#[inline(always)]
pub fn bse(&self) -> BSE_R {
BSE_R::new(((self.bits >> 11) & 1) != 0)
}
}
#[doc = "MDMA channel 13 error status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mdma_c13esr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MDMA_C13ESR_SPEC;
impl crate::RegisterSpec for MDMA_C13ESR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mdma_c13esr::R`](R) reader structure"]
impl crate::Readable for MDMA_C13ESR_SPEC {}
#[doc = "`reset()` method sets MDMA_C13ESR to value 0"]
impl crate::Resettable for MDMA_C13ESR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Live window rendering.
use crate::{
input::Shader,
output::Data,
parts::{Camera, Scene, Tracer},
run::engine::paint,
};
use arctk::{
err::Error,
math::Vec3,
ord::{BLUE, GREEN, RED},
tools::{ProgressBar, SilentProgressBar},
};
use minifb::{Scale, Window, WindowOptions};
use palette::{LinSrgba, Pixel};
use rand::thread_rng;
use rayon::prelude::*;
use std::{
fmt::Display,
sync::{Arc, Mutex},
time::Instant,
};
/// Render an image in a live window.
/// # Errors
/// if a mutex unwrapping failed or
/// an arc unwrapping failed or
/// if the progress bar can not be locked inside a running thread.
#[allow(clippy::expect_used)]
#[inline]
pub fn window_thread<T: Display + Ord + Sync>(
update_size: u64,
window_scale: Scale,
scene: &Scene<T>,
shader: &Shader,
cam: &Camera,
) -> Result<Data, Error> {
debug_assert!(update_size > 0);
let num_pixels = cam.sensor().num_pixels();
let mut main_bar = ProgressBar::new("Rendering", num_pixels as u64);
let order = scene.sett.order().gen_list(num_pixels);
let w = cam.sensor().res().0 as usize;
let h = cam.sensor().res().1 as usize;
let buffer: Vec<u32> = vec![0; w * h];
let buffer = Arc::new(Mutex::new(buffer));
let window_options = WindowOptions {
borderless: true,
title: true,
resize: false,
scale: window_scale,
scale_mode: minifb::ScaleMode::Stretch,
topmost: true,
transparency: true,
};
let mut window = Window::new("Antler", w, h, window_options).unwrap_or_else(|e| {
panic!("Could not create gui window: {}", e);
});
// window.limit_update_rate(Some(std::time::Duration::from_micros(16600)));
let data = Data::new([w, h]);
let data = Arc::new(Mutex::new(data));
let threads: Vec<usize> = (0..num_cpus::get()).collect();
while let Some((start, end)) = main_bar.block(update_size) {
let pb = SilentProgressBar::new(end - start);
let pb = Arc::new(Mutex::new(pb));
while !pb.lock()?.is_done() {
threads
.par_iter()
.map(|_id| {
render_range(
start,
&order,
&Arc::clone(&pb),
scene,
shader,
cam,
&Arc::clone(&data),
&Arc::clone(&buffer),
)
})
.collect::<()>();
}
window
.update_with_buffer(&buffer.lock()?, w, h)
.expect("Could not update window buffer.");
}
main_bar.finish_with_message("Render complete.");
if let Ok(d) = Arc::try_unwrap(data) {
return Ok(d.into_inner()?);
}
unreachable!("Failed to unwrap data.");
}
/// Render pixels using a single thread.
/// # Errors
/// if the progress bar can not be locked
#[allow(clippy::expect_used)]
#[inline]
fn render_range<T: Display + Ord>(
offset: u64,
order: &[u64],
pb: &Arc<Mutex<SilentProgressBar>>,
scene: &Scene<T>,
shader: &Shader,
cam: &Camera,
data: &Arc<Mutex<Data>>,
buffer: &Arc<Mutex<Vec<u32>>>,
) {
let super_samples = cam.sensor().super_samples();
let h_res = cam.sensor().res().0;
let total_pixels = cam.sensor().num_pixels();
let block_size = (scene.sett.block_size() / super_samples as u64).max(1);
let weight = 1.0 / f64::from(super_samples);
let mut rng = thread_rng();
if let Some((start, end)) = {
let mut pb = pb.lock().expect("Could not lock progress bar.");
let block = pb.block(block_size);
std::mem::drop(pb);
block
} {
for i in start..end {
let p = i + offset;
let p = order[p as usize];
let pixel = [(p % h_res) as usize, (p / h_res) as usize];
let mut total_col = LinSrgba::new(0.0, 0.0, 0.0, 0.0);
let mut total_dist = 0.0;
let start_time = Instant::now();
let mut total_dir = Vec3::default();
for sub_sample in 0..super_samples {
let ray = cam.gen_ray(pixel, sub_sample);
let (col, dist, dir) = paint(&mut rng, scene, shader, cam, Tracer::new(ray));
total_col += col * weight as f32;
total_dist += dist * weight;
total_dir += dir * weight;
}
let calc_time = start_time.elapsed().as_micros();
data.lock().expect("Could not lock data.").end_dir[pixel] += total_dir;
data.lock().expect("Could not lock data.").dist[pixel] += total_dist;
data.lock().expect("Could not lock data.").time[pixel] += calc_time as f64;
data.lock().expect("Could not lock data.").img.pixels_mut()[pixel] += total_col;
let raw_col: [u8; 4] = total_col.into_format().into_raw();
buffer.lock().expect("Could not lock window buffer.")
[(total_pixels - 1 - p) as usize] =
components_to_u32(raw_col[RED], raw_col[GREEN], raw_col[BLUE]);
}
}
}
/// Create a 32 bit colour representation from 8 bit components.
#[inline]
#[must_use]
pub const fn components_to_u32(r: u8, g: u8, b: u8) -> u32 {
((r as u32) << 16) | ((g as u32) << 8) | (b as u32)
}
|
use serde::{Deserialize, Serialize};
use std::collections::hash_map::Entry;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::{collections::HashMap, io::BufReader};
use super::compression;
const BLOCK_SIZE: usize = 128;
#[derive(Serialize, Deserialize, Debug)]
struct Compressed {
block_map: Vec<u32>,
blocks: Vec<Vec<u8>>,
}
pub struct BlockCompression {}
/// Compresses a file by looking for matching block patterns.block_compress
///
/// Inspired by the rsync algo - this algorithm reads in a file block by block, taking a
/// checksum of the block. When we take a block's checksum we check it against all other previously
/// seen checksums. If we find a hit then we store a reference to the previous block, rather than storing
/// the raw data again.
///
/// This is a poor compression method - there is a good chance that it makes your file larger
/// due to the overheads of the data structure on disk.
impl compression::Algorithm for BlockCompression {
fn compress(&self, mut file: File, output_file_path: &str) -> io::Result<()> {
let mut buffer = [0; BLOCK_SIZE];
let mut block_map = Vec::new();
let mut block_hashes = HashMap::new();
let mut blocks: Vec<Vec<u8>> = Vec::new();
println!("Original Size: {}", file.metadata()?.len());
loop {
let n = file.read(&mut buffer[..])?;
if n == 0 {
break;
}
let b = &buffer[..n];
let strong = strong_hash(b);
match block_hashes.entry(strong) {
Entry::Occupied(entry) => block_map.push(*entry.get()),
Entry::Vacant(entry) => {
blocks.push(b.to_vec());
let new_block_index = (blocks.len() - 1) as u32;
entry.insert(new_block_index);
block_map.push(new_block_index);
}
};
}
let compressed = Compressed { block_map, blocks };
compression::write_compressed(&compressed, output_file_path)
}
fn decompress(&self, compressed_file: File, output_file_path: &str) -> io::Result<()> {
let buf_reader = BufReader::new(compressed_file);
let compressed: Compressed = bincode::deserialize_from(buf_reader).unwrap();
let mut file = File::create(output_file_path)?;
for index in compressed.block_map {
let block_data = &compressed.blocks[index as usize];
file.write_all(&block_data)?;
}
Ok(())
}
}
fn strong_hash(buf: &[u8]) -> String {
let hash_digest = md5::compute(buf);
hex::encode(hash_digest.0)
}
|
use aoc2019::io::slurp_stdin;
#[derive(Clone, Copy)]
enum Step {
Right(i32),
Left(i32),
Up(i32),
Down(i32),
}
fn parse_entry(s: &str) -> Step {
let n: i32 = s[1..].parse().unwrap();
match &s[0..1] {
"R" => Step::Right(n),
"L" => Step::Left(n),
"U" => Step::Up(n),
"D" => Step::Down(n),
_ => { assert!(false); Step::Right(0) }
}
}
type Point = (i32, i32);
fn step_movement(step: &Step) -> (i32, i32, i32) {
match *step {
Step::Left(n) => (-1, 0, n),
Step::Right(n) => (1, 0, n),
Step::Up(n) => (0, 1, n),
Step::Down(n) => (0, -1, n),
}
}
struct PathIterator<I> where I: Iterator<Item=Step> {
x: i32,
y: i32,
dx: i32,
dy: i32,
n: i32,
step_iter: I
}
fn path_iter<I>(step_iter: I) -> PathIterator<I> where I: Iterator<Item=Step> {
PathIterator::<I> { x: 0, y: 0, dx: 0, dy: 0, n: 0, step_iter }
}
impl<I> Iterator for PathIterator<I> where I: Iterator<Item=Step> {
type Item = Point;
fn next(&mut self) -> Option<Self::Item> {
while self.n <= 0 {
match self.step_iter.next() {
Some(s) => {
let (dx, dy, n) = step_movement(&s.into());
self.dx = dx;
self.dy = dy;
self.n = n;
},
None => return None
}
}
self.x += self.dx;
self.y += self.dy;
self.n -= 1;
Some((self.x,self.y))
}
}
fn mh_norm(p: &Point) -> i32 {
p.0.abs() + p.1.abs()
}
fn distance_to(steps: &[Step], destination: Point) -> Option<i32> {
path_iter(steps.iter().cloned())
.zip(1i32..)
.find_map(|(p, index)| {
if p == destination {
Some(index)
} else {
None
}
})
}
fn combined_distance(steps0: &[Step], steps1: &[Step], destination: Point) -> i32 {
let dist0 = distance_to(steps0, destination).unwrap();
let dist1 = distance_to(steps1, destination).unwrap();
dist0 + dist1
}
fn main() {
let lines: Vec<String> = slurp_stdin().split("\n").map(|s| { s.to_string() }).collect();
let path0: Vec<Step> = lines[0].split(",").map(|s| { parse_entry(s) }).collect();
let path1: Vec<Step> = lines[1].split(",").map(|s| { parse_entry(s) }).collect();
let points0: std::collections::HashSet<Point> = path_iter(path0.iter().cloned()).collect();
let points1: std::collections::HashSet<Point> = path_iter(path1.iter().cloned()).collect();
let intersection_points: Vec<Point> = points0.intersection(&points1)
.cloned()
.collect();
let minnorm = intersection_points
.iter()
.map(|p| mh_norm(&p))
.min()
.unwrap();
println!("{}", minnorm);
let mindist = intersection_points
.iter()
.cloned()
.map(|p| combined_distance(&path0, &path1, p))
.min()
.unwrap();
println!("{}", mindist);
}
|
use enum_kinds::EnumKind;
use enum_map::Enum;
use crate::pos::Spanned;
#[derive(Debug, Clone, EnumKind)]
#[enum_kind(TokenKind, derive(Enum))]
pub enum TokenData {
// Values
String(String),
Integer(isize),
Identifier(String),
// Paired Tokens
OpenBrace,
CloseBrace,
OpenParen,
CloseParen,
OpenBrack,
CloseBrack,
// Symbols
Comma,
Colon,
Semicolon,
Dot,
Plus,
Minus,
Star,
Slash,
Equals,
NotEquals,
LessThan,
LessThanEquals,
GreaterThan,
GreaterThanEquals,
Ampersand,
VerticalBar,
ColonEquals,
// Keywords
KwWhile,
KwFor,
KwTo,
KwBreak,
KwLet,
KwIn,
KwEnd,
KwFunction,
KwVar,
KwType,
KwArray,
KwIf,
KwThen,
KwElse,
KwDo,
KwOf,
KwNil,
// etc.
Eof,
}
impl TokenData {
pub fn from_single_char(ch: char) -> Option<Self> {
match ch {
'[' => Some(TokenData::OpenBrack),
']' => Some(TokenData::CloseBrack),
'(' => Some(TokenData::OpenParen),
')' => Some(TokenData::CloseParen),
'{' => Some(TokenData::OpenBrace),
'}' => Some(TokenData::CloseBrace),
'+' => Some(TokenData::Plus),
'-' => Some(TokenData::Minus),
'*' => Some(TokenData::Star),
'=' => Some(TokenData::Equals),
'&' => Some(TokenData::Ampersand),
'|' => Some(TokenData::VerticalBar),
'/' => Some(TokenData::Slash),
',' => Some(TokenData::Comma),
';' => Some(TokenData::Semicolon),
'.' => Some(TokenData::Dot),
_ => None,
}
}
pub fn from_string(maybe_identifer: String) -> Self {
match <AsRef<str>>::as_ref(&maybe_identifer) {
"while" => TokenData::KwWhile,
"for" => TokenData::KwFor,
"to" => TokenData::KwTo,
"break" => TokenData::KwBreak,
"let" => TokenData::KwLet,
"in" => TokenData::KwIn,
"end" => TokenData::KwEnd,
"function" => TokenData::KwFunction,
"var" => TokenData::KwVar,
"type" => TokenData::KwType,
"array" => TokenData::KwArray,
"if" => TokenData::KwIf,
"then" => TokenData::KwThen,
"else" => TokenData::KwElse,
"do" => TokenData::KwDo,
"of" => TokenData::KwOf,
"nil" => TokenData::KwNil,
_ => TokenData::Identifier(maybe_identifer),
}
}
}
pub(crate) type Token = Spanned<TokenData>;
|
#[doc = "Register `CR` reader"]
pub type R = crate::R<CR_SPEC>;
#[doc = "Register `CR` writer"]
pub type W = crate::W<CR_SPEC>;
#[doc = "Field `PG` reader - Programming"]
pub type PG_R = crate::BitReader;
#[doc = "Field `PG` writer - Programming"]
pub type PG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SER` reader - Sector Erase"]
pub type SER_R = crate::BitReader;
#[doc = "Field `SER` writer - Sector Erase"]
pub type SER_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MER` reader - Mass Erase"]
pub type MER_R = crate::BitReader;
#[doc = "Field `MER` writer - Mass Erase"]
pub type MER_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SNB` reader - Sector number"]
pub type SNB_R = crate::FieldReader;
#[doc = "Field `SNB` writer - Sector number"]
pub type SNB_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `PSIZE` reader - Program size"]
pub type PSIZE_R = crate::FieldReader;
#[doc = "Field `PSIZE` writer - Program size"]
pub type PSIZE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `STRT` reader - Start"]
pub type STRT_R = crate::BitReader;
#[doc = "Field `STRT` writer - Start"]
pub type STRT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EOPIE` reader - End of operation interrupt enable"]
pub type EOPIE_R = crate::BitReader;
#[doc = "Field `EOPIE` writer - End of operation interrupt enable"]
pub type EOPIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ERRIE` reader - Error interrupt enable"]
pub type ERRIE_R = crate::BitReader;
#[doc = "Field `ERRIE` writer - Error interrupt enable"]
pub type ERRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LOCK` reader - Lock"]
pub type LOCK_R = crate::BitReader;
#[doc = "Field `LOCK` writer - Lock"]
pub type LOCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Programming"]
#[inline(always)]
pub fn pg(&self) -> PG_R {
PG_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Sector Erase"]
#[inline(always)]
pub fn ser(&self) -> SER_R {
SER_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Mass Erase"]
#[inline(always)]
pub fn mer(&self) -> MER_R {
MER_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bits 3:6 - Sector number"]
#[inline(always)]
pub fn snb(&self) -> SNB_R {
SNB_R::new(((self.bits >> 3) & 0x0f) as u8)
}
#[doc = "Bits 8:9 - Program size"]
#[inline(always)]
pub fn psize(&self) -> PSIZE_R {
PSIZE_R::new(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bit 16 - Start"]
#[inline(always)]
pub fn strt(&self) -> STRT_R {
STRT_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 24 - End of operation interrupt enable"]
#[inline(always)]
pub fn eopie(&self) -> EOPIE_R {
EOPIE_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Error interrupt enable"]
#[inline(always)]
pub fn errie(&self) -> ERRIE_R {
ERRIE_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 31 - Lock"]
#[inline(always)]
pub fn lock(&self) -> LOCK_R {
LOCK_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Programming"]
#[inline(always)]
#[must_use]
pub fn pg(&mut self) -> PG_W<CR_SPEC, 0> {
PG_W::new(self)
}
#[doc = "Bit 1 - Sector Erase"]
#[inline(always)]
#[must_use]
pub fn ser(&mut self) -> SER_W<CR_SPEC, 1> {
SER_W::new(self)
}
#[doc = "Bit 2 - Mass Erase"]
#[inline(always)]
#[must_use]
pub fn mer(&mut self) -> MER_W<CR_SPEC, 2> {
MER_W::new(self)
}
#[doc = "Bits 3:6 - Sector number"]
#[inline(always)]
#[must_use]
pub fn snb(&mut self) -> SNB_W<CR_SPEC, 3> {
SNB_W::new(self)
}
#[doc = "Bits 8:9 - Program size"]
#[inline(always)]
#[must_use]
pub fn psize(&mut self) -> PSIZE_W<CR_SPEC, 8> {
PSIZE_W::new(self)
}
#[doc = "Bit 16 - Start"]
#[inline(always)]
#[must_use]
pub fn strt(&mut self) -> STRT_W<CR_SPEC, 16> {
STRT_W::new(self)
}
#[doc = "Bit 24 - End of operation interrupt enable"]
#[inline(always)]
#[must_use]
pub fn eopie(&mut self) -> EOPIE_W<CR_SPEC, 24> {
EOPIE_W::new(self)
}
#[doc = "Bit 25 - Error interrupt enable"]
#[inline(always)]
#[must_use]
pub fn errie(&mut self) -> ERRIE_W<CR_SPEC, 25> {
ERRIE_W::new(self)
}
#[doc = "Bit 31 - Lock"]
#[inline(always)]
#[must_use]
pub fn lock(&mut self) -> LOCK_W<CR_SPEC, 31> {
LOCK_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 = "Control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::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 [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CR_SPEC;
impl crate::RegisterSpec for CR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cr::R`](R) reader structure"]
impl crate::Readable for CR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"]
impl crate::Writable for CR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CR to value 0x8000_0000"]
impl crate::Resettable for CR_SPEC {
const RESET_VALUE: Self::Ux = 0x8000_0000;
}
|
use crate::attr;
use proc_macro2::{Ident, Span, TokenStream};
use quote::{ToTokens, TokenStreamExt};
use syn::Attribute;
#[derive(Debug, Clone, Default)]
pub struct SchemaMetadata {
pub title: Option<String>,
pub description: Option<String>,
pub read_only: bool,
pub write_only: bool,
pub default: Option<TokenStream>,
}
impl ToTokens for SchemaMetadata {
fn to_tokens(&self, tokens: &mut TokenStream) {
let setters = self.make_setters();
if setters.is_empty() {
tokens.append(Ident::new("None", Span::call_site()))
} else {
tokens.extend(quote! {
Some({
let mut metadata = schemars::schema::Metadata::default();
#(#setters)*
metadata
})
})
}
}
}
impl SchemaMetadata {
pub fn from_doc_attrs(attrs: &[Attribute]) -> SchemaMetadata {
let (title, description) = attr::get_title_and_desc_from_doc(attrs);
SchemaMetadata {
title,
description,
..Default::default()
}
}
pub fn apply_to_schema(&self, schema_expr: TokenStream) -> TokenStream {
quote! {
{
let schema = #schema_expr;
gen.apply_metadata(schema, #self)
}
}
}
fn make_setters(self: &SchemaMetadata) -> Vec<TokenStream> {
let mut setters = Vec::<TokenStream>::new();
if let Some(title) = &self.title {
setters.push(quote! {
metadata.title = Some(#title.to_owned());
});
}
if let Some(description) = &self.description {
setters.push(quote! {
metadata.description = Some(#description.to_owned());
});
}
if self.read_only {
setters.push(quote! {
metadata.read_only = true;
});
}
if self.write_only {
setters.push(quote! {
metadata.write_only = true;
});
}
if let Some(default) = &self.default {
setters.push(quote! {
metadata.default = #default.and_then(|d| schemars::_serde_json::value::to_value(d).ok());
});
}
setters
}
}
|
use crate::data::{self, SharedDataBridge, SharedDataOps};
use drogue_cloud_service_api::endpoints::Endpoints;
use patternfly_yew::*;
use serde_json::json;
use yew::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExampleData {
pub app_id: String,
pub device_id: String,
pub password: String,
pub payload: String,
pub binary_mode: bool,
pub consumer_group: Option<String>,
pub drg_token: bool,
// whether to use a local certificate
pub enable_local_cert: bool,
pub cmd_empty_message: bool,
pub cmd_name: String,
pub cmd_payload: String,
}
impl Default for ExampleData {
fn default() -> Self {
Self {
app_id: "example-app".into(),
device_id: "device1".into(),
password: "hey-rodney".into(),
payload: json!({"temp": 42}).to_string(),
binary_mode: false,
consumer_group: None,
drg_token: true,
enable_local_cert: true,
cmd_empty_message: false,
cmd_name: "set-temp".into(),
cmd_payload: json!({"target-temp": 23}).to_string(),
}
}
}
impl ExampleData {
pub fn local_certs(&self, offer_local_certs: bool) -> bool {
offer_local_certs && self.enable_local_cert
}
}
#[derive(Clone, Debug, Properties, PartialEq, Eq)]
pub struct Props {
pub endpoints: Endpoints,
}
#[derive(Clone, Debug)]
pub enum Msg {
SetData(ExampleData),
SetApplicationId(String),
SetDeviceId(String),
SetPassword(String),
SetPayload(String),
SetLocalCerts(bool),
}
pub struct CoreExampleData {
props: Props,
link: ComponentLink<Self>,
data: Option<ExampleData>,
data_agent: SharedDataBridge<ExampleData>,
}
impl Component for CoreExampleData {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
let data_callback = link.batch_callback(|output| match output {
data::Response::State(data) => vec![Msg::SetData(data)],
});
let mut data_agent = SharedDataBridge::new(data_callback);
data_agent.request_state();
Self {
props,
link,
data: None,
data_agent,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::SetApplicationId(app) => self.data_agent.update(|mut data| data.app_id = app),
Msg::SetDeviceId(device) => self.data_agent.update(|mut data| data.device_id = device),
Msg::SetPassword(pwd) => self.data_agent.update(|mut data| data.password = pwd),
Msg::SetPayload(payload) => self.data_agent.update(|mut data| data.payload = payload),
Msg::SetLocalCerts(local_certs) => self
.data_agent
.update(move |mut data| data.enable_local_cert = local_certs),
Msg::SetData(data) => self.data = Some(data),
}
true
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props != props {
self.props = props;
true
} else {
false
}
}
fn view(&self) -> Html {
match &self.data {
Some(data) => self.render_view(data),
_ => html! {},
}
}
}
impl CoreExampleData {
fn render_view(&self, data: &ExampleData) -> Html {
let v = |value: &str| match value {
"" => InputState::Error,
_ => InputState::Default,
};
return html! {
<Stack gutter=true>
<StackItem>
<Title size=Size::XXLarge>{"Example Data"}</Title>
</StackItem>
<StackItem>
<Card title=html!{"App & Device"}>
<Form>
<FormGroup label="Application ID">
<TextInput
value=&data.app_id
required=true
onchange=self.link.callback(|app|Msg::SetApplicationId(app))
validator=Validator::from(v)
/>
</FormGroup>
<FormGroup label="Device ID">
<TextInput
value=&data.device_id
required=true
onchange=self.link.callback(|device|Msg::SetDeviceId(device))
validator=Validator::from(v)
/>
</FormGroup>
</Form>
</Card>
</StackItem>
<StackItem>
<Card title=html!{"Credentials"}>
<Form>
<FormGroup label="Password">
<TextInput
value=&data.password
required=true
onchange=self.link.callback(|password|Msg::SetPassword(password))
validator=Validator::from(v)
/>
</FormGroup>
</Form>
</Card>
</StackItem>
<StackItem>
<Card title=html!{"Payload"}>
<Form>
<TextArea
value=&data.payload
onchange=self.link.callback(|payload|Msg::SetPayload(payload))
validator=Validator::from(v)
/>
</Form>
</Card>
</StackItem>
{if self.props.endpoints.local_certs {html!{
<StackItem>
<Card title=html!{"Certificates"}>
<Switch
checked=data.enable_local_cert
label="Use local test certificates" label_off="Use system default certificates"
on_change=self.link.callback(|data| Msg::SetLocalCerts(data))
/>
</Card>
</StackItem>
}} else {html!{}}}
</Stack>
};
}
}
|
fn main() {
let add_one = |x| { 1i + x };
println!("The sum of 5 plus 1 is {}", add_one(5i));
let x = 5i;
let printer = || { println!("x is: {}", x); };
printer();
let p = proc() { x * x };
println!("{}", p());
let square = |x: int| { x * x };
assert_eq!(50i, twice(5i, square));
assert_eq!(50i, twice(5i, |x: int| { x * x }));
assert_eq!(50i, twice(5i, named_square));
}
fn twice(x: int, f: |int| -> int) -> int {
f(x) + f(x)
}
fn named_square(x: int) -> int {
x * x
} |
use std::fs::File;
fn main() {
let device_path = std::env::args().nth(1).unwrap();
let device = File::open(&device_path).unwrap();
println!("Reading {}", device_path);
let fs = fal_backend_btrfs::filesystem::Filesystem::mount(device);
println!("Superblock: {:?}", fs.superblock);
}
|
#[doc = "Register `OTG_GCCFG` reader"]
pub type R = crate::R<OTG_GCCFG_SPEC>;
#[doc = "Register `OTG_GCCFG` writer"]
pub type W = crate::W<OTG_GCCFG_SPEC>;
#[doc = "Field `PDET` reader - PDET"]
pub type PDET_R = crate::BitReader;
#[doc = "Field `SDET` reader - SDET"]
pub type SDET_R = crate::BitReader;
#[doc = "Field `PS2DET` reader - PS2DET"]
pub type PS2DET_R = crate::BitReader;
#[doc = "Field `PWRDWN` reader - PWRDWN"]
pub type PWRDWN_R = crate::BitReader;
#[doc = "Field `PWRDWN` writer - PWRDWN"]
pub type PWRDWN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `BCDEN` reader - BCDEN"]
pub type BCDEN_R = crate::BitReader;
#[doc = "Field `BCDEN` writer - BCDEN"]
pub type BCDEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PDEN` reader - PDEN"]
pub type PDEN_R = crate::BitReader;
#[doc = "Field `PDEN` writer - PDEN"]
pub type PDEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SDEN` reader - SDEN"]
pub type SDEN_R = crate::BitReader;
#[doc = "Field `SDEN` writer - SDEN"]
pub type SDEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `VBDEN` reader - VBDEN"]
pub type VBDEN_R = crate::BitReader;
#[doc = "Field `VBDEN` writer - VBDEN"]
pub type VBDEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IDEN` reader - IDEN"]
pub type IDEN_R = crate::BitReader;
#[doc = "Field `IDEN` writer - IDEN"]
pub type IDEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 1 - PDET"]
#[inline(always)]
pub fn pdet(&self) -> PDET_R {
PDET_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - SDET"]
#[inline(always)]
pub fn sdet(&self) -> SDET_R {
SDET_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - PS2DET"]
#[inline(always)]
pub fn ps2det(&self) -> PS2DET_R {
PS2DET_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 16 - PWRDWN"]
#[inline(always)]
pub fn pwrdwn(&self) -> PWRDWN_R {
PWRDWN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - BCDEN"]
#[inline(always)]
pub fn bcden(&self) -> BCDEN_R {
BCDEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 19 - PDEN"]
#[inline(always)]
pub fn pden(&self) -> PDEN_R {
PDEN_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - SDEN"]
#[inline(always)]
pub fn sden(&self) -> SDEN_R {
SDEN_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - VBDEN"]
#[inline(always)]
pub fn vbden(&self) -> VBDEN_R {
VBDEN_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - IDEN"]
#[inline(always)]
pub fn iden(&self) -> IDEN_R {
IDEN_R::new(((self.bits >> 22) & 1) != 0)
}
}
impl W {
#[doc = "Bit 16 - PWRDWN"]
#[inline(always)]
#[must_use]
pub fn pwrdwn(&mut self) -> PWRDWN_W<OTG_GCCFG_SPEC, 16> {
PWRDWN_W::new(self)
}
#[doc = "Bit 17 - BCDEN"]
#[inline(always)]
#[must_use]
pub fn bcden(&mut self) -> BCDEN_W<OTG_GCCFG_SPEC, 17> {
BCDEN_W::new(self)
}
#[doc = "Bit 19 - PDEN"]
#[inline(always)]
#[must_use]
pub fn pden(&mut self) -> PDEN_W<OTG_GCCFG_SPEC, 19> {
PDEN_W::new(self)
}
#[doc = "Bit 20 - SDEN"]
#[inline(always)]
#[must_use]
pub fn sden(&mut self) -> SDEN_W<OTG_GCCFG_SPEC, 20> {
SDEN_W::new(self)
}
#[doc = "Bit 21 - VBDEN"]
#[inline(always)]
#[must_use]
pub fn vbden(&mut self) -> VBDEN_W<OTG_GCCFG_SPEC, 21> {
VBDEN_W::new(self)
}
#[doc = "Bit 22 - IDEN"]
#[inline(always)]
#[must_use]
pub fn iden(&mut self) -> IDEN_W<OTG_GCCFG_SPEC, 22> {
IDEN_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 = "OTG general core configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`otg_gccfg::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 [`otg_gccfg::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct OTG_GCCFG_SPEC;
impl crate::RegisterSpec for OTG_GCCFG_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`otg_gccfg::R`](R) reader structure"]
impl crate::Readable for OTG_GCCFG_SPEC {}
#[doc = "`write(|w| ..)` method takes [`otg_gccfg::W`](W) writer structure"]
impl crate::Writable for OTG_GCCFG_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets OTG_GCCFG to value 0"]
impl crate::Resettable for OTG_GCCFG_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::context::Context;
use crate::data::convert_reflexive;
use crate::data::garbage::alloc_identity;
use crate::data::strings::String;
use crate::data::Alloc;
use crate::data::DynSendable;
use crate::data::DynSharable;
use macros::rewrite;
pub use bool;
pub use char;
pub use f32;
pub use f64;
pub use i128;
pub use i16;
pub use i32;
pub use i64;
pub use i8;
pub use u128;
pub use u16;
pub use u32;
pub use u64;
pub use u8;
#[allow(non_camel_case_types)]
pub type unit = ();
pub type Unit = ();
pub use std::ops::Range;
convert_reflexive!(i8);
convert_reflexive!(i16);
convert_reflexive!(i32);
convert_reflexive!(i64);
convert_reflexive!(i128);
convert_reflexive!(u8);
convert_reflexive!(u16);
convert_reflexive!(u32);
convert_reflexive!(u64);
convert_reflexive!(u128);
convert_reflexive!(f32);
convert_reflexive!(f64);
convert_reflexive!(bool);
// convert_reflexive!(char);
convert_reflexive!(unit);
alloc_identity!(i8);
alloc_identity!(i16);
alloc_identity!(i32);
alloc_identity!(i64);
alloc_identity!(i128);
alloc_identity!(u8);
alloc_identity!(u16);
alloc_identity!(u32);
alloc_identity!(u64);
alloc_identity!(f32);
alloc_identity!(f64);
alloc_identity!(bool);
alloc_identity!(char);
alloc_identity!(unit);
#[allow(non_upper_case_globals)]
pub const unit: unit = ();
#[allow(non_upper_case_globals)]
pub const Unit: unit = ();
#[rewrite]
pub fn assert(b: bool) {
assert!(b);
}
#[rewrite]
pub fn panic(s: String) {
panic!("{}", s.as_str())
}
#[rewrite]
pub fn print(s: String) {
println!("{}", s.as_str())
}
|
#[doc = "Reader of register SW_DSI_SEL"]
pub type R = crate::R<u32, super::SW_DSI_SEL>;
#[doc = "Writer for register SW_DSI_SEL"]
pub type W = crate::W<u32, super::SW_DSI_SEL>;
#[doc = "Register SW_DSI_SEL `reset()`'s with value 0"]
impl crate::ResetValue for super::SW_DSI_SEL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DSI_CSH_TANK`"]
pub type DSI_CSH_TANK_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DSI_CSH_TANK`"]
pub struct DSI_CSH_TANK_W<'a> {
w: &'a mut W,
}
impl<'a> DSI_CSH_TANK_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 `DSI_CMOD`"]
pub type DSI_CMOD_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DSI_CMOD`"]
pub struct DSI_CMOD_W<'a> {
w: &'a mut W,
}
impl<'a> DSI_CMOD_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 << 4)) | (((value as u32) & 0x0f) << 4);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - Select waveform for dsi_csh_tank output signal 0: static open 1: static closed 2: phi1 3: phi2 4: phi1 & HSCMP 5: phi2 & HSCMP 6: HSCMP // ignores phi1/2 7: !sense // = phi1 but ignores OVERLAP_PHI1 8: phi1_delay // phi1 delayed with shield delay 9: phi2_delay // phi2 delayed with shield delay 10: !phi1 11: !phi2 12: !(phi1 & HSCMP) 13: !(phi2 & HSCMP) 14: !HSCMP // ignores phi1/2 15: sense // = phi2 but ignores OVERLAP_PHI2"]
#[inline(always)]
pub fn dsi_csh_tank(&self) -> DSI_CSH_TANK_R {
DSI_CSH_TANK_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:7 - Select waveform for dsi_cmod output signal"]
#[inline(always)]
pub fn dsi_cmod(&self) -> DSI_CMOD_R {
DSI_CMOD_R::new(((self.bits >> 4) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - Select waveform for dsi_csh_tank output signal 0: static open 1: static closed 2: phi1 3: phi2 4: phi1 & HSCMP 5: phi2 & HSCMP 6: HSCMP // ignores phi1/2 7: !sense // = phi1 but ignores OVERLAP_PHI1 8: phi1_delay // phi1 delayed with shield delay 9: phi2_delay // phi2 delayed with shield delay 10: !phi1 11: !phi2 12: !(phi1 & HSCMP) 13: !(phi2 & HSCMP) 14: !HSCMP // ignores phi1/2 15: sense // = phi2 but ignores OVERLAP_PHI2"]
#[inline(always)]
pub fn dsi_csh_tank(&mut self) -> DSI_CSH_TANK_W {
DSI_CSH_TANK_W { w: self }
}
#[doc = "Bits 4:7 - Select waveform for dsi_cmod output signal"]
#[inline(always)]
pub fn dsi_cmod(&mut self) -> DSI_CMOD_W {
DSI_CMOD_W { w: self }
}
}
|
use crate::days::day12::{Movement, parse_input, default_input};
use direction::{Direction, Coord};
use std::ops::{Add, Mul};
pub fn run() {
println!("{}", ship_str(default_input()).unwrap())
}
pub fn ship_str(input : &str) -> Result<u32, ()> {
ship(parse_input(input))
}
pub fn ship(input: Vec<Movement>) -> Result<u32, ()> {
let mut dir = Direction::East;
let mut pos = Coord{x: 0, y: 0};
for movement in input {
match movement {
Movement::North(x) => {
pos = pos.add(Direction::North.coord().mul(x));
}
Movement::South(x) => {
pos = pos.add(Direction::South.coord().mul(x));
}
Movement::West(x) => {
pos = pos.add(Direction::West.coord().mul(x));
}
Movement::East(x) => {
pos = pos.add(Direction::East.coord().mul(x));
}
Movement::Left(r) => {
match r {
90 => dir = dir.left90(),
180 => dir = dir.opposite(),
270 => dir = dir.right90(),
_ => {}
}
}
Movement::Right(r) => {
match r {
90 => dir = dir.right90(),
180 => dir = dir.opposite(),
270 => dir = dir.left90(),
_ => {}
}
}
Movement::Forward(x) => {
pos = pos.add(dir.coord().mul(x));
}
}
}
Ok(pos.manhattan_magnitude())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn part1_answer() {
assert_eq!(1956, ship_str(default_input()).unwrap())
}
}
|
use config::{Config, File};
use dirs::home_dir;
use failure::{err_msg, Error};
#[derive(Debug, Deserialize, Clone)]
pub struct Configuration {
kindle_email: String,
gmail_username: String,
gmail_application_password: String,
mercury_token: String,
}
impl Configuration {
pub fn new() -> Result<Self, Error> {
let mut result = Config::new();
let mut config_file_path = home_dir().ok_or(err_msg("Couldn't find home dir"))?;
config_file_path.push(".tlrl.json");
result.merge(File::from(config_file_path))?;
let result: Configuration = result.try_into()?;
let logged_config = Configuration {
gmail_application_password: "[redacted]".into(),
mercury_token: "[redacted]".into(),
..result.clone()
};
info!("config: {:?}", logged_config);
Ok(result)
}
pub fn get_mercury_token(&self) -> String {
self.mercury_token.to_owned()
}
pub fn get_email_config(self) -> EmailConfig {
EmailConfig {
to: self.kindle_email,
username: self.gmail_username,
password: self.gmail_application_password,
}
}
}
#[derive(Debug, Deserialize)]
pub struct EmailConfig {
pub to: String,
pub username: String,
pub password: String,
}
|
extern crate td_revent;
extern crate psocket;
use psocket::{ToSocketAddrs};
use td_revent::*;
use self::psocket::TcpSocket;
fn client_read_callback(
_ev: &mut EventLoop,
buffer: &mut EventBuffer,
_data: Option<&mut CellAny>,
) -> RetValue {
println!("client_read_callback");
let len = buffer.read.len();
let data = buffer.read.drain_collect(len);
println!("data = {:?}", String::from_utf8_lossy(&data));
RetValue::OK
}
fn client_write_callback(
_ev: &mut EventLoop,
_buffer: &mut EventBuffer,
_data: Option<&mut CellAny>,
) -> RetValue {
println!("write callback");
RetValue::OK
}
fn client_end_callback(ev: &mut EventLoop, _buffer: &mut EventBuffer, _data: Option<CellAny>) {
println!("end callback!!!!!!!!!!!");
ev.shutdown();
}
//timer return no success(0) will no be repeat
fn time_callback(
ev: &mut EventLoop,
_timer: u32,
data: Option<&mut CellAny>,
) -> (RetValue, u64) {
println!("time call back");
let cell_any = data.unwrap();
{
let obj = any_to_mut!(cell_any, EventBuffer);
match obj.socket.check_ready() {
Err(_) => return (RetValue::OVER, 0),
Ok(false) => return (RetValue::CONTINUE, 10),
_ => ()
}
};
println!("Socket is ready");
let obj = any_unwrap!(cell_any, EventBuffer);
// let obj = any.downcast_mut::<EventBuffer>().unwrap();
let socket = obj.as_raw_socket();
let _ = ev.register_socket(
obj,
EventEntry::new_event(
socket,
EventFlags::FLAG_READ | EventFlags::FLAG_PERSIST,
Some(client_read_callback),
Some(client_write_callback),
Some(client_end_callback),
None,
),
);
let _ = ev.send_socket(&socket, b"GET /s?wd=1 HTTP/1.1\r\n\r\n");
(RetValue::OK, 0)
}
fn main() {
println!("Starting TEST_ECHO_SERVER");
let mut event_loop = EventLoop::new().unwrap();
let mut addrs_iter = "www.baidu.com:80".to_socket_addrs().unwrap();
let addr = addrs_iter.next().unwrap();
println!("addr = {:?}", addr);
let client = TcpSocket::connect_asyn(&addr).unwrap();
let _ = client.set_nonblocking(true);
let buffer = event_loop.new_buff(client);
event_loop.add_timer(EventEntry::new_timer(
100,
false,
Some(time_callback),
Some(Box::new(buffer)),
));
event_loop.run().unwrap();
// assert!(unsafe { S_COUNT } == 6);
println!("SUCCESS END TEST");
}
|
use crate::uses::*;
use core::sync::atomic::{AtomicUsize, Ordering};
use alloc::sync::Arc;
use crate::cap::{CapObject, CapObjectType, Capability, CapFlags};
static NEXT_KEY: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug)]
pub struct Key(usize);
impl Key {
pub fn new() -> Capability<Self> {
let id = NEXT_KEY.fetch_add(1, Ordering::Relaxed);
Capability::new(Arc::new(Key(id)), CapFlags::empty())
}
pub fn id(&self) -> usize {
self.0
}
}
impl CapObject for Key {
fn cap_object_type() -> CapObjectType {
CapObjectType::Key
}
fn inc_ref(&self) {}
fn dec_ref(&self) {}
}
|
mod socket_read;
mod socket_write;
mod socket_write_vectored;
mod tcp_listener_accept;
mod tcp_stream_connect;
mod udp_recv_from;
mod udp_send_to;
mod unix_listener_accept;
mod unix_recv_from;
mod unix_send_to;
mod unix_stream_connect;
pub use self::socket_read::SocketRead;
pub use self::socket_write::SocketWrite;
pub use self::socket_write_vectored::SocketWriteVectored;
pub use self::tcp_listener_accept::TcpListenerAccept;
pub use self::tcp_stream_connect::TcpStreamConnect;
pub use self::udp_recv_from::UdpRecvFrom;
pub use self::udp_send_to::UdpSendTo;
pub use self::unix_listener_accept::UnixListenerAccept;
pub use self::unix_recv_from::UnixRecvFrom;
pub use self::unix_send_to::UnixSendTo;
pub use self::unix_stream_connect::UnixStreamConnect;
|
//! Shader utilities of game engine.
/// Default shaders which are used in game engine.
pub mod default {
/// Default vertex shader utilities.
pub mod vertex {
vulkano_shaders::shader! {
ty: "vertex",
path: "src/graphics/shader/default.vert",
}
}
/// Default fragment shader utilities.
pub mod fragment {
vulkano_shaders::shader! {
ty: "fragment",
path: "src/graphics/shader/default.frag",
}
}
}
/// Shaders which are used in UI rendering.
pub mod ui {
/// UI vertex shader utilities.
pub mod vertex {
vulkano_shaders::shader! {
ty: "vertex",
path: "src/graphics/shader/ui.vert",
}
}
/// UI fragment shader utilities.
pub mod fragment {
vulkano_shaders::shader! {
ty: "fragment",
path: "src/graphics/shader/ui.frag",
}
}
}
|
use hydroflow::hydroflow_syntax;
pub fn main() {
let mut flow = hydroflow_syntax! {
source_iter(0..10) -> for_each(|n| println!("Hello {}", n));
};
flow.run_available();
}
|
struct Solution;
impl Solution {
pub fn kth_smallest(matrix: Vec<Vec<i32>>, k: i32) -> i32 {
let num_rows = matrix.len();
let (mut min, mut max) = (matrix[0][0], matrix[num_rows - 1][num_rows - 1]); // 左上角和右下角
while min < max {
let mid = (max - min) / 2 + min;
println!("min = {}, max = {}, mid = {}", min, max, mid);
if Self::count_lte_k(&matrix, mid, num_rows as i32) >= k {
// 说明答案比 mid 小
max = mid;
} else {
min = mid + 1;
}
}
min
}
// 小于等于 mid 的有多少个
fn count_lte_k(matrix: &Vec<Vec<i32>>, mid: i32, num_rows: i32) -> i32 {
let mut count = 0;
let (mut x, mut y) = (num_rows - 1, 0_i32); // 从左下角开始向右上角查找
while x >= 0 && y < num_rows {
if matrix[x as usize][y as usize] <= mid {
count += x + 1; // 这一列有多少个
y += 1;
} else {
x -= 1;
}
}
count
}
// by zhangyuchen.
// 想错了,选中一列后,并不能把矩阵分成两部分,因为左边可能会有数据大于右边,比如:
// [[1, 2], [4, 5]]
pub fn kth_smallest_failed(matrix: Vec<Vec<i32>>, k: i32) -> i32 {
// 二分查找
Self::binary_search(&matrix, 0, matrix.len(), k as usize)
}
fn binary_search(matrix: &Vec<Vec<i32>>, i: usize, j: usize, k: usize) -> i32 {
let mid = (i + j) / 2;
let num_row = matrix.len();
if i == j - 1 {
// 只剩一列,在这一列找就可以了,列也是升序,所以直接返回
return matrix[k - 1][i];
}
let left_count = (mid - i + 1) * num_row; // 包含 mid 那一列
println!(
"i={},j={},k={},mid={},left_count={}",
i, j, k, mid, left_count
);
if left_count == k {
// 左边最大的那个,就是最后一行那个
return matrix[num_row - 1][mid];
}
if left_count < k {
// 在右边找 k-left_count 小的元素
return Self::binary_search(matrix, mid + 1, j, k - left_count);
}
// 在左边找第 k 小的元素
// mid-1 的话就少了 num_row 个元素了,不能减
// 如果只剩最后一列了,这里就死循环了。
Self::binary_search(matrix, i, mid, k)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_kth_smallest1() {
let matrix = vec![vec![1, 5, 9], vec![10, 11, 13], vec![12, 13, 15]];
assert_eq!(Solution::kth_smallest(matrix, 8), 13);
}
#[test]
fn test_kth_smallest2() {
let matrix = vec![vec![-5]];
assert_eq!(Solution::kth_smallest(matrix, 1), -5);
}
#[test]
fn test_kth_smallest3() {
let matrix = vec![vec![1, 2], vec![1, 3]];
assert_eq!(Solution::kth_smallest(matrix, 4), 3);
}
#[test]
fn test_kth_smallest4() {
let matrix = vec![vec![1, 2], vec![3, 3]];
assert_eq!(Solution::kth_smallest(matrix, 2), 2);
}
#[test]
fn test_kth_smallest5() {
let matrix = vec![vec![1, 10], vec![2, 20]];
assert_eq!(Solution::kth_smallest(matrix, 3), 10);
}
}
|
use std::error::Error;
use std::fmt;
use rustc::mir;
use rustc::ty::{FnSig, Ty, layout};
use memory::MemoryPointer;
use rustc_const_math::ConstMathErr;
use syntax::codemap::Span;
#[derive(Clone, Debug)]
pub enum EvalError<'tcx> {
FunctionPointerTyMismatch(FnSig<'tcx>, FnSig<'tcx>),
NoMirFor(String),
UnterminatedCString(MemoryPointer),
DanglingPointerDeref,
InvalidMemoryAccess,
InvalidFunctionPointer,
InvalidBool,
InvalidDiscriminant,
PointerOutOfBounds {
ptr: MemoryPointer,
access: bool,
allocation_size: u64,
},
InvalidNullPointerUsage,
ReadPointerAsBytes,
ReadBytesAsPointer,
InvalidPointerMath,
ReadUndefBytes,
DeadLocal,
InvalidBoolOp(mir::BinOp),
Unimplemented(String),
DerefFunctionPointer,
ExecuteMemory,
ArrayIndexOutOfBounds(Span, u64, u64),
Math(Span, ConstMathErr),
Intrinsic(String),
OverflowingMath,
InvalidChar(u128),
OutOfMemory {
allocation_size: u64,
memory_size: u64,
memory_usage: u64,
},
ExecutionTimeLimitReached,
StackFrameLimitReached,
OutOfTls,
TlsOutOfBounds,
AbiViolation(String),
AlignmentCheckFailed {
required: u64,
has: u64,
},
CalledClosureAsFunction,
VtableForArgumentlessMethod,
ModifiedConstantMemory,
AssumptionNotHeld,
InlineAsm,
TypeNotPrimitive(Ty<'tcx>),
ReallocatedStaticMemory,
DeallocatedStaticMemory,
ReallocateNonBasePtr,
DeallocateNonBasePtr,
IncorrectAllocationInformation,
Layout(layout::LayoutError<'tcx>),
HeapAllocZeroBytes,
HeapAllocNonPowerOfTwoAlignment(u64),
Unreachable,
Panic,
NeedsRfc(String),
NotConst(String),
ReadFromReturnPointer,
PathNotFound(Vec<String>),
}
pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>;
impl<'tcx> Error for EvalError<'tcx> {
fn description(&self) -> &str {
use EvalError::*;
match *self {
FunctionPointerTyMismatch(..) =>
"tried to call a function through a function pointer of a different type",
InvalidMemoryAccess =>
"tried to access memory through an invalid pointer",
DanglingPointerDeref =>
"dangling pointer was dereferenced",
InvalidFunctionPointer =>
"tried to use an integer pointer or a dangling pointer as a function pointer",
InvalidBool =>
"invalid boolean value read",
InvalidDiscriminant =>
"invalid enum discriminant value read",
PointerOutOfBounds { .. } =>
"pointer offset outside bounds of allocation",
InvalidNullPointerUsage =>
"invalid use of NULL pointer",
ReadPointerAsBytes =>
"a raw memory access tried to access part of a pointer value as raw bytes",
ReadBytesAsPointer =>
"a memory access tried to interpret some bytes as a pointer",
InvalidPointerMath =>
"attempted to do invalid arithmetic on pointers that would leak base addresses, e.g. comparing pointers into different allocations",
ReadUndefBytes =>
"attempted to read undefined bytes",
DeadLocal =>
"tried to access a dead local variable",
InvalidBoolOp(_) =>
"invalid boolean operation",
Unimplemented(ref msg) => msg,
DerefFunctionPointer =>
"tried to dereference a function pointer",
ExecuteMemory =>
"tried to treat a memory pointer as a function pointer",
ArrayIndexOutOfBounds(..) =>
"array index out of bounds",
Math(..) =>
"mathematical operation failed",
Intrinsic(..) =>
"intrinsic failed",
OverflowingMath =>
"attempted to do overflowing math",
NoMirFor(..) =>
"mir not found",
InvalidChar(..) =>
"tried to interpret an invalid 32-bit value as a char",
OutOfMemory{..} =>
"could not allocate more memory",
ExecutionTimeLimitReached =>
"reached the configured maximum execution time",
StackFrameLimitReached =>
"reached the configured maximum number of stack frames",
OutOfTls =>
"reached the maximum number of representable TLS keys",
TlsOutOfBounds =>
"accessed an invalid (unallocated) TLS key",
AbiViolation(ref msg) => msg,
AlignmentCheckFailed{..} =>
"tried to execute a misaligned read or write",
CalledClosureAsFunction =>
"tried to call a closure through a function pointer",
VtableForArgumentlessMethod =>
"tried to call a vtable function without arguments",
ModifiedConstantMemory =>
"tried to modify constant memory",
AssumptionNotHeld =>
"`assume` argument was false",
InlineAsm =>
"miri does not support inline assembly",
TypeNotPrimitive(_) =>
"expected primitive type, got nonprimitive",
ReallocatedStaticMemory =>
"tried to reallocate static memory",
DeallocatedStaticMemory =>
"tried to deallocate static memory",
ReallocateNonBasePtr =>
"tried to reallocate with a pointer not to the beginning of an existing object",
DeallocateNonBasePtr =>
"tried to deallocate with a pointer not to the beginning of an existing object",
IncorrectAllocationInformation =>
"tried to deallocate or reallocate using incorrect alignment or size",
Layout(_) =>
"rustc layout computation failed",
UnterminatedCString(_) =>
"attempted to get length of a null terminated string, but no null found before end of allocation",
HeapAllocZeroBytes =>
"tried to re-, de- or allocate zero bytes on the heap",
HeapAllocNonPowerOfTwoAlignment(_) =>
"tried to re-, de-, or allocate heap memory with alignment that is not a power of two",
Unreachable =>
"entered unreachable code",
Panic =>
"the evaluated program panicked",
NeedsRfc(_) =>
"this feature needs an rfc before being allowed inside constants",
NotConst(_) =>
"this feature is not compatible with constant evaluation",
ReadFromReturnPointer =>
"tried to read from the return pointer",
EvalError::PathNotFound(_) =>
"a path could not be resolved, maybe the crate is not loaded",
}
}
fn cause(&self) -> Option<&Error> { None }
}
impl<'tcx> fmt::Display for EvalError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use EvalError::*;
match *self {
PointerOutOfBounds { ptr, access, allocation_size } => {
write!(f, "{} at offset {}, outside bounds of allocation {} which has size {}",
if access { "memory access" } else { "pointer computed" },
ptr.offset, ptr.alloc_id, allocation_size)
},
NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
FunctionPointerTyMismatch(sig, got) =>
write!(f, "tried to call a function with sig {} through a function pointer of type {}", sig, got),
ArrayIndexOutOfBounds(span, len, index) =>
write!(f, "index out of bounds: the len is {} but the index is {} at {:?}", len, index, span),
Math(span, ref err) =>
write!(f, "{:?} at {:?}", err, span),
Intrinsic(ref err) =>
write!(f, "{}", err),
InvalidChar(c) =>
write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
OutOfMemory { allocation_size, memory_size, memory_usage } =>
write!(f, "tried to allocate {} more bytes, but only {} bytes are free of the {} byte memory",
allocation_size, memory_size - memory_usage, memory_size),
AlignmentCheckFailed { required, has } =>
write!(f, "tried to access memory with alignment {}, but alignment {} is required",
has, required),
TypeNotPrimitive(ty) =>
write!(f, "expected primitive type, got {}", ty),
Layout(ref err) =>
write!(f, "rustc layout computation failed: {:?}", err),
NeedsRfc(ref msg) =>
write!(f, "\"{}\" needs an rfc before being allowed inside constants", msg),
NotConst(ref msg) =>
write!(f, "Cannot evaluate within constants: \"{}\"", msg),
EvalError::PathNotFound(ref path) =>
write!(f, "Cannot find path {:?}", path),
_ => write!(f, "{}", self.description()),
}
}
}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Simple numerics.
//!
//! This crate contains arbitrary-sized integer, rational, and complex types.
//!
//! ## Example
//!
//! This example uses the BigRational type and [Newton's method][newt] to
//! approximate a square root to arbitrary precision:
//!
//! ```
//! extern crate num;
//!
//! use num::FromPrimitive;
//! use num::bigint::BigInt;
//! use num::rational::{Ratio, BigRational};
//!
//! fn approx_sqrt(number: u64, iterations: usize) -> BigRational {
//! let start: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u64(number).unwrap());
//! let mut approx = start.clone();
//!
//! for _ in 0..iterations {
//! approx = (&approx + (&start / &approx)) /
//! Ratio::from_integer(FromPrimitive::from_u64(2).unwrap());
//! }
//!
//! approx
//! }
//!
//! fn main() {
//! println!("{}", approx_sqrt(10, 4)); // prints 4057691201/1283082416
//! }
//! ```
//!
//! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
//#![cfg_attr(test, deny(warnings))]
#![cfg_attr(test, feature(test))]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/num/",
html_playground_url = "http://play.rust-lang.org/")]
extern crate rustc_serialize;
extern crate rand;
pub use bigint::{BigInt, BigUint};
pub use rational::{Rational, BigRational};
pub use complex::Complex;
pub use integer::Integer;
pub use iter::{range, range_inclusive, range_step, range_step_inclusive};
pub use traits::{Num, Zero, One, Signed, Unsigned, Bounded,
Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv,
PrimInt, Float, ToPrimitive, FromPrimitive, NumCast};
#[cfg(test)] use std::hash;
use std::ops::{Mul};
pub mod bigint;
pub mod complex;
pub mod integer;
pub mod iter;
pub mod traits;
pub mod rational;
/// Returns the additive identity, `0`.
#[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
/// Returns the multiplicative identity, `1`.
#[inline(always)] pub fn one<T: One>() -> T { One::one() }
/// Computes the absolute value.
///
/// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`
///
/// For signed integers, `::MIN` will be returned if the number is `::MIN`.
#[inline(always)]
pub fn abs<T: Signed>(value: T) -> T {
value.abs()
}
/// The positive difference of two numbers.
///
/// Returns zero if `x` is less than or equal to `y`, otherwise the difference
/// between `x` and `y` is returned.
#[inline(always)]
pub fn abs_sub<T: Signed>(x: T, y: T) -> T {
x.abs_sub(&y)
}
/// Returns the sign of the number.
///
/// For `f32` and `f64`:
///
/// * `1.0` if the number is positive, `+0.0` or `INFINITY`
/// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
/// * `NaN` if the number is `NaN`
///
/// For signed integers:
///
/// * `0` if the number is zero
/// * `1` if the number is positive
/// * `-1` if the number is negative
#[inline(always)] pub fn signum<T: Signed>(value: T) -> T { value.signum() }
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num;
///
/// assert_eq!(num::pow(2i8, 4), 16);
/// assert_eq!(num::pow(6u8, 3), 216);
/// ```
#[inline]
pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T {
if exp == 1 { base }
else {
let mut acc = one::<T>();
while exp > 0 {
if (exp & 1) == 1 {
acc = acc * base.clone();
}
// avoid overflow if we won't need it
if exp > 1 {
base = base.clone() * base;
}
exp = exp >> 1;
}
acc
}
}
#[cfg(test)]
fn hash<T: hash::Hash>(x: &T) -> u64 {
use std::hash::Hasher;
let mut hasher = hash::SipHasher::new();
x.hash(&mut hasher);
hasher.finish()
}
|
//! Provides some operations on items of slices.
pub mod ops;
|
use super::util::sightglass_cli;
use assert_cmd::prelude::*;
#[test]
fn help() {
sightglass_cli().arg("help").assert().success();
}
|
use crate::extensions::NodeExt;
use gdnative::api::{AnimatedSprite, RigidBody2D};
use gdnative::prelude::*;
use rand::seq::SliceRandom;
#[derive(Copy, Clone, Debug)]
/// Mob types.
enum MobType {
Walk,
Swim,
Fly,
}
impl MobType {
/// Return the mob type name.
pub fn to_string(self) -> String {
format!("{:?}", self).to_lowercase()
}
}
/// List of mob types
const MOB_TYPES: [MobType; 3] = [MobType::Walk, MobType::Swim, MobType::Fly];
#[derive(NativeClass)]
#[inherit(RigidBody2D)]
#[user_data(user_data::MutexData<Mob>)]
/// Mob struct.
pub struct Mob {
#[property(default = 150.0)]
min_speed: f32,
#[property(default = 250.0)]
max_speed: f32,
}
#[methods]
impl Mob {
/// Create a Mob.
pub fn new(_owner: &RigidBody2D) -> Self {
Mob { min_speed: 150.0, max_speed: 250.0 }
}
/// Return the mob min speed.
pub fn min_speed(&self, _owner: &RigidBody2D) -> f32 {
self.min_speed
}
/// Return the mob max speed.
pub fn max_speed(&self, _owner: &RigidBody2D) -> f32 {
self.max_speed
}
#[export]
/// Prepare the mob.
pub fn _ready(&self, owner: &RigidBody2D) {
// Initialize rand generator
let mut rng = rand::thread_rng();
// Set mob animation
if let Some(anim) = MOB_TYPES.choose(&mut rng) {
unsafe { owner.get_typed_node::<AnimatedSprite, _>("AnimatedSprite") }
.set_animation(anim.to_string());
} else {
panic!("The chosen Mob type does not exist.");
}
}
#[export]
/// Free the Mob when it exits the screen.
pub fn _on_visibility_screen_exited(&self, owner: &RigidBody2D) {
unsafe { owner.assume_unique().queue_free(); }
}
#[export]
/// Free the remaining mobs of the last game when the game start.
pub fn on_start_game(&self, owner: &RigidBody2D) {
unsafe { owner.assume_unique().queue_free(); }
}
}
|
#[doc = "Register `FMC_BCHIER` reader"]
pub type R = crate::R<FMC_BCHIER_SPEC>;
#[doc = "Register `FMC_BCHIER` writer"]
pub type W = crate::W<FMC_BCHIER_SPEC>;
#[doc = "Field `DUEIE` reader - DUEIE"]
pub type DUEIE_R = crate::BitReader;
#[doc = "Field `DUEIE` writer - DUEIE"]
pub type DUEIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DERIE` reader - DERIE"]
pub type DERIE_R = crate::BitReader;
#[doc = "Field `DERIE` writer - DERIE"]
pub type DERIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DEFIE` reader - DEFIE"]
pub type DEFIE_R = crate::BitReader;
#[doc = "Field `DEFIE` writer - DEFIE"]
pub type DEFIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DSRIE` reader - DSRIE"]
pub type DSRIE_R = crate::BitReader;
#[doc = "Field `DSRIE` writer - DSRIE"]
pub type DSRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EPBRIE` reader - EPBRIE"]
pub type EPBRIE_R = crate::BitReader;
#[doc = "Field `EPBRIE` writer - EPBRIE"]
pub type EPBRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - DUEIE"]
#[inline(always)]
pub fn dueie(&self) -> DUEIE_R {
DUEIE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - DERIE"]
#[inline(always)]
pub fn derie(&self) -> DERIE_R {
DERIE_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - DEFIE"]
#[inline(always)]
pub fn defie(&self) -> DEFIE_R {
DEFIE_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - DSRIE"]
#[inline(always)]
pub fn dsrie(&self) -> DSRIE_R {
DSRIE_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - EPBRIE"]
#[inline(always)]
pub fn epbrie(&self) -> EPBRIE_R {
EPBRIE_R::new(((self.bits >> 4) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - DUEIE"]
#[inline(always)]
#[must_use]
pub fn dueie(&mut self) -> DUEIE_W<FMC_BCHIER_SPEC, 0> {
DUEIE_W::new(self)
}
#[doc = "Bit 1 - DERIE"]
#[inline(always)]
#[must_use]
pub fn derie(&mut self) -> DERIE_W<FMC_BCHIER_SPEC, 1> {
DERIE_W::new(self)
}
#[doc = "Bit 2 - DEFIE"]
#[inline(always)]
#[must_use]
pub fn defie(&mut self) -> DEFIE_W<FMC_BCHIER_SPEC, 2> {
DEFIE_W::new(self)
}
#[doc = "Bit 3 - DSRIE"]
#[inline(always)]
#[must_use]
pub fn dsrie(&mut self) -> DSRIE_W<FMC_BCHIER_SPEC, 3> {
DSRIE_W::new(self)
}
#[doc = "Bit 4 - EPBRIE"]
#[inline(always)]
#[must_use]
pub fn epbrie(&mut self) -> EPBRIE_W<FMC_BCHIER_SPEC, 4> {
EPBRIE_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 = "FMC BCH Interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fmc_bchier::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 [`fmc_bchier::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct FMC_BCHIER_SPEC;
impl crate::RegisterSpec for FMC_BCHIER_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`fmc_bchier::R`](R) reader structure"]
impl crate::Readable for FMC_BCHIER_SPEC {}
#[doc = "`write(|w| ..)` method takes [`fmc_bchier::W`](W) writer structure"]
impl crate::Writable for FMC_BCHIER_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets FMC_BCHIER to value 0"]
impl crate::Resettable for FMC_BCHIER_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::player::PLAYER_SIZE;
use crate::world::{
BounceMarker, CharType, Counter, DefaultSize, Location, MaterialResource, ObjectMarker,
Velocity,
};
use bevy::prelude::*;
const SIZE: f32 = 7.5f32;
const BULLET_VELOCITY: f32 = 275f32;
const TIME: f32 = 5f32;
#[derive(Bundle)]
pub struct BulletBundle {
marker: BounceMarker,
obj_marker: ObjectMarker,
type_marker: CharType,
#[bundle]
sprite: SpriteBundle,
size: DefaultSize,
location: Location,
velocity: Velocity,
counter: Counter,
}
pub fn new_bullet(target: Vec2, source: Vec2, material: Handle<ColorMaterial>) -> BulletBundle {
let dir = (target - source).normalize();
BulletBundle {
marker: BounceMarker,
obj_marker: ObjectMarker(2),
type_marker: CharType::Bullet,
sprite: SpriteBundle {
sprite: Sprite::new(Vec2::new(SIZE, SIZE)),
transform: Transform::from_translation(Vec3::new(source.x, source.y, 0f32)),
material,
..Default::default()
},
size: DefaultSize {
width: SIZE,
height: SIZE,
},
location: Location(Vec2::new(source.x, source.y) + PLAYER_SIZE * dir),
counter: Counter(TIME),
velocity: Velocity(dir * BULLET_VELOCITY),
}
}
|
use std::fmt;
use serde_bencode::{de, Error};
use serde_bytes::ByteBuf;
use std::ops::Deref;
use byteorder::{ByteOrder, BigEndian};
const BYTES_PER_PEER: usize = 6;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct Peer {
host: String,
port: u16,
}
impl Peer {
pub fn from(chunk: &[u8]) -> Result<Self, Error> {
if chunk.len() != BYTES_PER_PEER {
Err(Error::Custom(
String::from("Chunk length is not equal to BYTES_PER_PEER"),
))
} else {
Ok(Peer {
host: format!("{}.{}.{}.{}", chunk[0], chunk[1], chunk[2], chunk[3]),
port: BigEndian::read_u16(&chunk[4..BYTES_PER_PEER]),
})
}
}
}
impl fmt::Display for Peer {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fmt, "{}:{}", self.host, self.port)
}
}
#[derive(Debug)]
pub struct Response {
pub interval: i64,
pub complete: i64,
pub incomplete: i64,
pub peers: Vec<Peer>,
}
impl Response {
pub fn from(buffer: &[u8]) -> Result<Self, Error> {
let response = de::from_bytes::<ResponseCompact>(&buffer)?;
if let Some(failure) = response.failure_reason {
Err(Error::Custom(failure))
} else {
Ok(Response {
interval: response.interval.unwrap_or_default(),
complete: response.complete.unwrap_or_default(),
incomplete: response.incomplete.unwrap_or_default(),
peers: Self::peers(&response)?,
})
}
}
fn peers(response: &ResponseCompact) -> Result<Vec<Peer>, Error> {
let mut peers = Vec::new();
if let Some(ref records) = response.peers {
let mut it = records.deref().chunks(BYTES_PER_PEER);
while let Some(chunk) = it.next() {
let peer = Peer::from(chunk);
peers.push(peer?);
}
}
Ok(peers)
}
}
impl fmt::Display for Response {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
writeln!(fmt, "Interval:\t\t{}", self.interval)?;
writeln!(fmt, "Seeders:\t\t{}", self.complete)?;
writeln!(fmt, "Leechers:\t\t{}", self.incomplete)?;
for peer in &self.peers {
writeln!(fmt, "\tPeer:\t{}", peer)?;
}
write!(fmt, "")
}
}
#[derive(Debug, Deserialize)]
struct ResponseCompact {
#[serde(rename = "failure reason")]
pub failure_reason: Option<String>,
pub interval: Option<i64>,
pub complete: Option<i64>,
pub incomplete: Option<i64>,
pub peers: Option<ByteBuf>,
}
|
//! Implementations of various traits.
mod std_ttable;
mod std_ttable_entry;
mod dummy_hash_table;
mod simple_search;
mod std_search_node;
mod std_qsearch;
mod std_move_generator;
mod std_time_manager;
mod simple_evaluator;
mod deepening;
pub use self::std_ttable::*;
pub use self::std_ttable_entry::*;
pub use self::dummy_hash_table::*;
pub use self::simple_search::*;
pub use self::std_search_node::*;
pub use self::std_qsearch::*;
pub use self::std_move_generator::*;
pub use self::std_time_manager::*;
pub use self::simple_evaluator::*;
pub use self::deepening::*;
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use actix::prelude::*;
use anyhow::{format_err, Result};
use futures::executor::block_on;
use starcoin_config::{ChainNetwork, NodeConfig, StarcoinOpt};
use starcoin_consensus::{argon::ArgonConsensus, dev::DevConsensus};
use starcoin_logger::prelude::*;
use starcoin_traits::Consensus;
use std::sync::Arc;
use std::thread::JoinHandle;
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
mod actor;
pub mod message;
mod node;
pub use actor::{NodeActor, NodeRef};
pub struct NodeHandle {
runtime: Runtime,
thread_handle: JoinHandle<()>,
stop_sender: oneshot::Sender<()>,
}
#[cfg(unix)]
mod platform {
use futures::{future::FutureExt, pin_mut, select};
use tokio::signal::unix::{signal, SignalKind};
pub async fn wait_signal() {
println!("Waiting SIGINT or SIGTERM ...");
let mut sigint = signal(SignalKind::interrupt()).expect("register signal error");
let sigint_fut = sigint.recv().fuse();
let mut sigterm = signal(SignalKind::terminate()).expect("register signal error");
let sigterm_fut = sigterm.recv().fuse();
pin_mut!(sigint_fut, sigterm_fut);
select! {
_ = sigterm_fut => {
println!("received SIGTERM");
}
_ = sigint_fut => {
println!("received SIGINT");
}
}
}
}
#[cfg(not(unix))]
mod platform {
use std::error::Error;
pub async fn wait_signal() {
println!("Waiting Ctrl-C ...");
tokio::signal::ctrl_c().await.unwrap();
println!("Ctrl-C received, shutting down");
}
}
impl NodeHandle {
pub fn new(
thread_handle: std::thread::JoinHandle<()>,
stop_sender: oneshot::Sender<()>,
) -> Self {
Self {
runtime: Runtime::new().unwrap(),
thread_handle,
stop_sender,
}
}
pub fn join(mut self) -> Result<()> {
self.runtime.block_on(async {
platform::wait_signal().await;
});
self.stop()
}
pub fn stop(self) -> Result<()> {
self.stop_sender
.send(())
.map_err(|_| format_err!("Stop message send fail."))?;
self.thread_handle
.join()
.map_err(|e| format_err!("Waiting thread exist fail. {:?}", e))?;
println!("Starcoin node shutdown success.");
Ok(())
}
}
pub fn run_node_by_opt(opt: &StarcoinOpt) -> Result<(Option<NodeHandle>, Arc<NodeConfig>)> {
let config = Arc::new(starcoin_config::load_config_with_opt(opt)?);
let ipc_file = config.rpc.get_ipc_file();
let node_handle = if !ipc_file.exists() {
let node_handle = match config.net() {
ChainNetwork::Dev => run_dev_node(config.clone()),
_ => run_normal_node(config.clone()),
};
Some(node_handle)
} else {
//TODO check ipc file is available.
info!("Node has started at {:?}", ipc_file);
None
};
Ok((node_handle, config))
}
pub fn run_dev_node(config: Arc<NodeConfig>) -> NodeHandle {
run_node::<DevConsensus>(config)
}
pub fn run_normal_node(config: Arc<NodeConfig>) -> NodeHandle {
run_node::<ArgonConsensus>(config)
}
/// Run node in a new Thread, and return a NodeHandle.
pub fn run_node<C>(config: Arc<NodeConfig>) -> NodeHandle
where
C: Consensus + 'static,
{
let logger_handle = starcoin_logger::init();
info!("Final data-dir is : {:?}", config.data_dir());
if config.logger.enable_file() {
let file_log_path = config.logger.get_log_path();
info!("Write log to file: {:?}", file_log_path);
logger_handle.enable_file(
file_log_path,
config.logger.max_file_size,
config.logger.max_backup,
);
}
if config.logger.enable_stderr {
logger_handle.enable_stderr();
} else {
logger_handle.disable_stderr();
}
// start metric server
if config.metrics.enable_metrics {
starcoin_metrics::metric_server::start_server(
config.metrics.address.clone(),
config.metrics.metrics_server_port,
);
}
let (start_sender, start_receiver) = oneshot::channel();
let (stop_sender, stop_receiver) = oneshot::channel();
let thread_handle = std::thread::spawn(move || {
//TODO actix and tokio use same runtime, and config thread pool.
let rt = tokio::runtime::Runtime::new().unwrap();
let handle = rt.handle().clone();
let mut system = System::builder().stop_on_panic(true).name("main").build();
system.block_on(async {
//let node_actor = NodeActor::<C, H>::new(config, handle);
//let _node_ref = node_actor.start();
//TODO fix me, this just a work around method.
let _handle = match node::start::<C>(config, logger_handle, handle).await {
Err(e) => {
error!("Node start fail: {:?}, exist.", e);
System::current().stop();
return;
}
Ok(handle) => handle,
};
if start_sender.send(()).is_err() {
info!("Start send error.");
}
if stop_receiver.await.is_err() {
info!("Stop receiver await error.");
}
info!("Receive stop signal, try to stop system.");
System::current().stop();
});
});
let result = block_on(async { start_receiver.await });
if result.is_err() {
std::process::exit(1);
}
NodeHandle::new(thread_handle, stop_sender)
}
|
use crate::boards::*;
use actix_web::{get, post, delete, put, web, HttpResponse, Responder};
use sqlx::{Postgres, Pool, Error};
#[get("/boards/")]
async fn get_all_boards(db_pool: web::Data<Pool<Postgres>>) -> impl Responder {
let result = Board::find_all_visible_boards(db_pool.get_ref()).await;
match result {
Ok(boards) => HttpResponse::Ok().json(boards),
_ => HttpResponse::BadRequest().body("Bad request.")
}
}
pub fn init_routes(config: &mut web::ServiceConfig) {
config.service(get_all_boards);
} |
#[doc = "Register `PCR` reader"]
pub type R = crate::R<PCR_SPEC>;
#[doc = "Register `PCR` writer"]
pub type W = crate::W<PCR_SPEC>;
#[doc = "Field `PWAITEN` reader - PWAITEN"]
pub type PWAITEN_R = crate::BitReader<PWAITEN_A>;
#[doc = "PWAITEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PWAITEN_A {
#[doc = "0: Wait feature disabled"]
Disabled = 0,
#[doc = "1: Wait feature enabled"]
Enabled = 1,
}
impl From<PWAITEN_A> for bool {
#[inline(always)]
fn from(variant: PWAITEN_A) -> Self {
variant as u8 != 0
}
}
impl PWAITEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PWAITEN_A {
match self.bits {
false => PWAITEN_A::Disabled,
true => PWAITEN_A::Enabled,
}
}
#[doc = "Wait feature disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PWAITEN_A::Disabled
}
#[doc = "Wait feature enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PWAITEN_A::Enabled
}
}
#[doc = "Field `PWAITEN` writer - PWAITEN"]
pub type PWAITEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PWAITEN_A>;
impl<'a, REG, const O: u8> PWAITEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Wait feature disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(PWAITEN_A::Disabled)
}
#[doc = "Wait feature enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(PWAITEN_A::Enabled)
}
}
#[doc = "Field `PBKEN` reader - PBKEN"]
pub type PBKEN_R = crate::BitReader<PBKEN_A>;
#[doc = "PBKEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PBKEN_A {
#[doc = "0: Corresponding memory bank is disabled"]
Disabled = 0,
#[doc = "1: Corresponding memory bank is enabled"]
Enabled = 1,
}
impl From<PBKEN_A> for bool {
#[inline(always)]
fn from(variant: PBKEN_A) -> Self {
variant as u8 != 0
}
}
impl PBKEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PBKEN_A {
match self.bits {
false => PBKEN_A::Disabled,
true => PBKEN_A::Enabled,
}
}
#[doc = "Corresponding memory bank is disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == PBKEN_A::Disabled
}
#[doc = "Corresponding memory bank is enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == PBKEN_A::Enabled
}
}
#[doc = "Field `PBKEN` writer - PBKEN"]
pub type PBKEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PBKEN_A>;
impl<'a, REG, const O: u8> PBKEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Corresponding memory bank is disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(PBKEN_A::Disabled)
}
#[doc = "Corresponding memory bank is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(PBKEN_A::Enabled)
}
}
#[doc = "Field `PTYP` reader - PTYP"]
pub type PTYP_R = crate::BitReader<PTYP_A>;
#[doc = "PTYP\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PTYP_A {
#[doc = "1: NAND Flash"]
Nandflash = 1,
}
impl From<PTYP_A> for bool {
#[inline(always)]
fn from(variant: PTYP_A) -> Self {
variant as u8 != 0
}
}
impl PTYP_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<PTYP_A> {
match self.bits {
true => Some(PTYP_A::Nandflash),
_ => None,
}
}
#[doc = "NAND Flash"]
#[inline(always)]
pub fn is_nandflash(&self) -> bool {
*self == PTYP_A::Nandflash
}
}
#[doc = "Field `PTYP` writer - PTYP"]
pub type PTYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PTYP_A>;
impl<'a, REG, const O: u8> PTYP_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "NAND Flash"]
#[inline(always)]
pub fn nandflash(self) -> &'a mut crate::W<REG> {
self.variant(PTYP_A::Nandflash)
}
}
#[doc = "Field `PWID` reader - PWID"]
pub type PWID_R = crate::FieldReader<PWID_A>;
#[doc = "PWID\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum PWID_A {
#[doc = "0: External memory device width 8 bits"]
Bits8 = 0,
#[doc = "1: External memory device width 16 bits"]
Bits16 = 1,
}
impl From<PWID_A> for u8 {
#[inline(always)]
fn from(variant: PWID_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for PWID_A {
type Ux = u8;
}
impl PWID_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<PWID_A> {
match self.bits {
0 => Some(PWID_A::Bits8),
1 => Some(PWID_A::Bits16),
_ => None,
}
}
#[doc = "External memory device width 8 bits"]
#[inline(always)]
pub fn is_bits8(&self) -> bool {
*self == PWID_A::Bits8
}
#[doc = "External memory device width 16 bits"]
#[inline(always)]
pub fn is_bits16(&self) -> bool {
*self == PWID_A::Bits16
}
}
#[doc = "Field `PWID` writer - PWID"]
pub type PWID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, PWID_A>;
impl<'a, REG, const O: u8> PWID_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "External memory device width 8 bits"]
#[inline(always)]
pub fn bits8(self) -> &'a mut crate::W<REG> {
self.variant(PWID_A::Bits8)
}
#[doc = "External memory device width 16 bits"]
#[inline(always)]
pub fn bits16(self) -> &'a mut crate::W<REG> {
self.variant(PWID_A::Bits16)
}
}
#[doc = "Field `ECCEN` reader - ECCEN"]
pub type ECCEN_R = crate::BitReader<ECCEN_A>;
#[doc = "ECCEN\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ECCEN_A {
#[doc = "0: ECC logic is disabled and reset"]
Disabled = 0,
#[doc = "1: ECC logic is enabled"]
Enabled = 1,
}
impl From<ECCEN_A> for bool {
#[inline(always)]
fn from(variant: ECCEN_A) -> Self {
variant as u8 != 0
}
}
impl ECCEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ECCEN_A {
match self.bits {
false => ECCEN_A::Disabled,
true => ECCEN_A::Enabled,
}
}
#[doc = "ECC logic is disabled and reset"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ECCEN_A::Disabled
}
#[doc = "ECC logic is enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ECCEN_A::Enabled
}
}
#[doc = "Field `ECCEN` writer - ECCEN"]
pub type ECCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ECCEN_A>;
impl<'a, REG, const O: u8> ECCEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "ECC logic is disabled and reset"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(ECCEN_A::Disabled)
}
#[doc = "ECC logic is enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(ECCEN_A::Enabled)
}
}
#[doc = "Field `TCLR` reader - TCLR"]
pub type TCLR_R = crate::FieldReader;
#[doc = "Field `TCLR` writer - TCLR"]
pub type TCLR_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O>;
#[doc = "Field `TAR` reader - TAR"]
pub type TAR_R = crate::FieldReader;
#[doc = "Field `TAR` writer - TAR"]
pub type TAR_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O>;
#[doc = "Field `ECCPS` reader - ECCPS"]
pub type ECCPS_R = crate::FieldReader<ECCPS_A>;
#[doc = "ECCPS\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum ECCPS_A {
#[doc = "0: ECC page size 256 bytes"]
Bytes256 = 0,
#[doc = "1: ECC page size 512 bytes"]
Bytes512 = 1,
#[doc = "2: ECC page size 1024 bytes"]
Bytes1024 = 2,
#[doc = "3: ECC page size 2048 bytes"]
Bytes2048 = 3,
#[doc = "4: ECC page size 4096 bytes"]
Bytes4096 = 4,
#[doc = "5: ECC page size 8192 bytes"]
Bytes8192 = 5,
}
impl From<ECCPS_A> for u8 {
#[inline(always)]
fn from(variant: ECCPS_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for ECCPS_A {
type Ux = u8;
}
impl ECCPS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<ECCPS_A> {
match self.bits {
0 => Some(ECCPS_A::Bytes256),
1 => Some(ECCPS_A::Bytes512),
2 => Some(ECCPS_A::Bytes1024),
3 => Some(ECCPS_A::Bytes2048),
4 => Some(ECCPS_A::Bytes4096),
5 => Some(ECCPS_A::Bytes8192),
_ => None,
}
}
#[doc = "ECC page size 256 bytes"]
#[inline(always)]
pub fn is_bytes256(&self) -> bool {
*self == ECCPS_A::Bytes256
}
#[doc = "ECC page size 512 bytes"]
#[inline(always)]
pub fn is_bytes512(&self) -> bool {
*self == ECCPS_A::Bytes512
}
#[doc = "ECC page size 1024 bytes"]
#[inline(always)]
pub fn is_bytes1024(&self) -> bool {
*self == ECCPS_A::Bytes1024
}
#[doc = "ECC page size 2048 bytes"]
#[inline(always)]
pub fn is_bytes2048(&self) -> bool {
*self == ECCPS_A::Bytes2048
}
#[doc = "ECC page size 4096 bytes"]
#[inline(always)]
pub fn is_bytes4096(&self) -> bool {
*self == ECCPS_A::Bytes4096
}
#[doc = "ECC page size 8192 bytes"]
#[inline(always)]
pub fn is_bytes8192(&self) -> bool {
*self == ECCPS_A::Bytes8192
}
}
#[doc = "Field `ECCPS` writer - ECCPS"]
pub type ECCPS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O, ECCPS_A>;
impl<'a, REG, const O: u8> ECCPS_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "ECC page size 256 bytes"]
#[inline(always)]
pub fn bytes256(self) -> &'a mut crate::W<REG> {
self.variant(ECCPS_A::Bytes256)
}
#[doc = "ECC page size 512 bytes"]
#[inline(always)]
pub fn bytes512(self) -> &'a mut crate::W<REG> {
self.variant(ECCPS_A::Bytes512)
}
#[doc = "ECC page size 1024 bytes"]
#[inline(always)]
pub fn bytes1024(self) -> &'a mut crate::W<REG> {
self.variant(ECCPS_A::Bytes1024)
}
#[doc = "ECC page size 2048 bytes"]
#[inline(always)]
pub fn bytes2048(self) -> &'a mut crate::W<REG> {
self.variant(ECCPS_A::Bytes2048)
}
#[doc = "ECC page size 4096 bytes"]
#[inline(always)]
pub fn bytes4096(self) -> &'a mut crate::W<REG> {
self.variant(ECCPS_A::Bytes4096)
}
#[doc = "ECC page size 8192 bytes"]
#[inline(always)]
pub fn bytes8192(self) -> &'a mut crate::W<REG> {
self.variant(ECCPS_A::Bytes8192)
}
}
impl R {
#[doc = "Bit 1 - PWAITEN"]
#[inline(always)]
pub fn pwaiten(&self) -> PWAITEN_R {
PWAITEN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - PBKEN"]
#[inline(always)]
pub fn pbken(&self) -> PBKEN_R {
PBKEN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - PTYP"]
#[inline(always)]
pub fn ptyp(&self) -> PTYP_R {
PTYP_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bits 4:5 - PWID"]
#[inline(always)]
pub fn pwid(&self) -> PWID_R {
PWID_R::new(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bit 6 - ECCEN"]
#[inline(always)]
pub fn eccen(&self) -> ECCEN_R {
ECCEN_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bits 9:12 - TCLR"]
#[inline(always)]
pub fn tclr(&self) -> TCLR_R {
TCLR_R::new(((self.bits >> 9) & 0x0f) as u8)
}
#[doc = "Bits 13:16 - TAR"]
#[inline(always)]
pub fn tar(&self) -> TAR_R {
TAR_R::new(((self.bits >> 13) & 0x0f) as u8)
}
#[doc = "Bits 17:19 - ECCPS"]
#[inline(always)]
pub fn eccps(&self) -> ECCPS_R {
ECCPS_R::new(((self.bits >> 17) & 7) as u8)
}
}
impl W {
#[doc = "Bit 1 - PWAITEN"]
#[inline(always)]
#[must_use]
pub fn pwaiten(&mut self) -> PWAITEN_W<PCR_SPEC, 1> {
PWAITEN_W::new(self)
}
#[doc = "Bit 2 - PBKEN"]
#[inline(always)]
#[must_use]
pub fn pbken(&mut self) -> PBKEN_W<PCR_SPEC, 2> {
PBKEN_W::new(self)
}
#[doc = "Bit 3 - PTYP"]
#[inline(always)]
#[must_use]
pub fn ptyp(&mut self) -> PTYP_W<PCR_SPEC, 3> {
PTYP_W::new(self)
}
#[doc = "Bits 4:5 - PWID"]
#[inline(always)]
#[must_use]
pub fn pwid(&mut self) -> PWID_W<PCR_SPEC, 4> {
PWID_W::new(self)
}
#[doc = "Bit 6 - ECCEN"]
#[inline(always)]
#[must_use]
pub fn eccen(&mut self) -> ECCEN_W<PCR_SPEC, 6> {
ECCEN_W::new(self)
}
#[doc = "Bits 9:12 - TCLR"]
#[inline(always)]
#[must_use]
pub fn tclr(&mut self) -> TCLR_W<PCR_SPEC, 9> {
TCLR_W::new(self)
}
#[doc = "Bits 13:16 - TAR"]
#[inline(always)]
#[must_use]
pub fn tar(&mut self) -> TAR_W<PCR_SPEC, 13> {
TAR_W::new(self)
}
#[doc = "Bits 17:19 - ECCPS"]
#[inline(always)]
#[must_use]
pub fn eccps(&mut self) -> ECCPS_W<PCR_SPEC, 17> {
ECCPS_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 = "PC Card/NAND Flash control register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pcr::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 [`pcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PCR_SPEC;
impl crate::RegisterSpec for PCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pcr::R`](R) reader structure"]
impl crate::Readable for PCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`pcr::W`](W) writer structure"]
impl crate::Writable for PCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PCR to value 0x18"]
impl crate::Resettable for PCR_SPEC {
const RESET_VALUE: Self::Ux = 0x18;
}
|
#[doc = "Register `M5SEAR` reader"]
pub type R = crate::R<M5SEAR_SPEC>;
#[doc = "Field `ESEA` reader - ECC single error address When the ALE bit is set in the RAMCFG_MxCR register, this field is updated with the address corresponding to the ECC single error."]
pub type ESEA_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - ECC single error address When the ALE bit is set in the RAMCFG_MxCR register, this field is updated with the address corresponding to the ECC single error."]
#[inline(always)]
pub fn esea(&self) -> ESEA_R {
ESEA_R::new(self.bits)
}
}
#[doc = "RAMCFG memory 5 ECC single error address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m5sear::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct M5SEAR_SPEC;
impl crate::RegisterSpec for M5SEAR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`m5sear::R`](R) reader structure"]
impl crate::Readable for M5SEAR_SPEC {}
#[doc = "`reset()` method sets M5SEAR to value 0"]
impl crate::Resettable for M5SEAR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
mod domain;
mod domain_tx_pre_validator;
pub mod providers;
pub mod rpc;
pub use self::domain::{new_full, DomainOperator, DomainParams, FullPool, NewFull};
use futures::channel::oneshot;
use futures::{FutureExt, StreamExt};
use sc_client_api::{BlockBackend, BlockchainEvents, HeaderBackend, ProofProvider};
use sc_consensus::ImportQueue;
use sc_executor::NativeElseWasmExecutor;
use sc_network::config::Roles;
use sc_network::NetworkService;
use sc_network_sync::block_request_handler::BlockRequestHandler;
use sc_network_sync::engine::SyncingEngine;
use sc_network_sync::service::network::NetworkServiceProvider;
use sc_network_sync::state_request_handler::StateRequestHandler;
use sc_network_sync::SyncingService;
use sc_service::config::SyncMode;
use sc_service::{
build_system_rpc_future, BuildNetworkParams, Configuration as ServiceConfiguration,
NetworkStarter, TFullClient, TransactionPoolAdapter,
};
use sc_transaction_pool_api::MaintainedTransactionPool;
use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedSender};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderMetadata;
use sp_consensus::block_validation::{Chain, DefaultBlockAnnounceValidator};
use sp_runtime::traits::{Block as BlockT, BlockIdTo, Zero};
use std::sync::atomic::Ordering;
use std::sync::Arc;
/// Domain full client.
pub type FullClient<Block, RuntimeApi, ExecutorDispatch> =
TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;
pub type FullBackend<Block> = sc_service::TFullBackend<Block>;
/// Domain configuration.
pub struct DomainConfiguration<AccountId> {
pub service_config: ServiceConfiguration,
pub maybe_relayer_id: Option<AccountId>,
}
/// Build the network service, the network status sinks and an RPC sender.
///
/// Port from `sc_service::build_network` mostly the same with block sync disabled.
// TODO: Struct for returned value
#[allow(clippy::type_complexity)]
pub fn build_network<TBl, TExPool, TImpQu, TCl>(
params: BuildNetworkParams<TBl, TExPool, TImpQu, TCl>,
) -> Result<
(
Arc<NetworkService<TBl, <TBl as BlockT>::Hash>>,
TracingUnboundedSender<sc_rpc::system::Request<TBl>>,
sc_network_transactions::TransactionsHandlerController<<TBl as BlockT>::Hash>,
NetworkStarter,
Arc<SyncingService<TBl>>,
),
sc_service::Error,
>
where
TBl: BlockT,
TCl: ProvideRuntimeApi<TBl>
+ HeaderMetadata<TBl, Error = sp_blockchain::Error>
+ Chain<TBl>
+ BlockBackend<TBl>
+ BlockIdTo<TBl, Error = sp_blockchain::Error>
+ ProofProvider<TBl>
+ HeaderBackend<TBl>
+ BlockchainEvents<TBl>
+ 'static,
TExPool: MaintainedTransactionPool<Block = TBl, Hash = <TBl as BlockT>::Hash> + 'static,
TImpQu: ImportQueue<TBl> + 'static,
{
let BuildNetworkParams {
config,
mut net_config,
client,
transaction_pool,
spawn_handle,
import_queue,
block_announce_validator_builder: _,
warp_sync_params: _,
block_relay,
} = params;
if client.requires_full_sync() {
match config.network.sync_mode.load(Ordering::Acquire) {
SyncMode::LightState { .. } => {
return Err("Fast sync doesn't work for archive nodes".into())
}
SyncMode::Warp => return Err("Warp sync doesn't work for archive nodes".into()),
SyncMode::Full | SyncMode::Paused => {}
}
}
let protocol_id = config.protocol_id();
let (chain_sync_network_provider, chain_sync_network_handle) = NetworkServiceProvider::new();
let (mut block_server, block_downloader, block_request_protocol_config) = match block_relay {
Some(params) => (
params.server,
params.downloader,
params.request_response_config,
),
None => {
// Custom protocol was not specified, use the default block handler.
let params = BlockRequestHandler::new(
chain_sync_network_handle.clone(),
&protocol_id,
config.chain_spec.fork_id(),
client.clone(),
config.network.default_peers_set.in_peers as usize
+ config.network.default_peers_set.out_peers as usize,
);
(
params.server,
params.downloader,
params.request_response_config,
)
}
};
spawn_handle.spawn("block-request-handler", Some("networking"), async move {
block_server.run().await;
});
let state_request_protocol_config = {
// Allow both outgoing and incoming requests.
let (handler, protocol_config) = StateRequestHandler::new(
&protocol_id,
config.chain_spec.fork_id(),
client.clone(),
config.network.default_peers_set_num_full as usize,
);
spawn_handle.spawn("state-request-handler", Some("networking"), handler.run());
protocol_config
};
let (tx, rx) = sc_utils::mpsc::tracing_unbounded("mpsc_syncing_engine_protocol", 100_000);
let (engine, sync_service, block_announce_config) = SyncingEngine::new(
Roles::from(&config.role),
client.clone(),
config
.prometheus_config
.as_ref()
.map(|config| config.registry.clone())
.as_ref(),
&net_config,
protocol_id.clone(),
&config.chain_spec.fork_id().map(ToOwned::to_owned),
Box::new(DefaultBlockAnnounceValidator),
None,
chain_sync_network_handle,
import_queue.service(),
block_downloader,
state_request_protocol_config.name.clone(),
None,
rx,
config.network.force_synced,
)?;
let sync_service_import_queue = sync_service.clone();
let sync_service = Arc::new(sync_service);
let genesis_hash = client
.hash(Zero::zero())
.ok()
.flatten()
.expect("Genesis block exists; qed");
// crate transactions protocol and add it to the list of supported protocols of `network_params`
let transactions_handler_proto = sc_network_transactions::TransactionsHandlerPrototype::new(
protocol_id.clone(),
client
.block_hash(0u32.into())
.ok()
.flatten()
.expect("Genesis block exists; qed"),
config.chain_spec.fork_id(),
);
net_config.add_notification_protocol(transactions_handler_proto.set_config());
net_config.add_request_response_protocol(block_request_protocol_config);
net_config.add_request_response_protocol(state_request_protocol_config);
let network_params = sc_network::config::Params::<TBl> {
role: config.role.clone(),
executor: {
let spawn_handle = Clone::clone(&spawn_handle);
Box::new(move |fut| {
spawn_handle.spawn("libp2p-node", Some("networking"), fut);
})
},
network_config: net_config,
genesis_hash,
protocol_id,
fork_id: config.chain_spec.fork_id().map(ToOwned::to_owned),
metrics_registry: config
.prometheus_config
.as_ref()
.map(|config| config.registry.clone()),
block_announce_config,
tx,
};
let has_bootnodes = !network_params
.network_config
.network_config
.boot_nodes
.is_empty();
let network_mut = sc_network::NetworkWorker::new(network_params)?;
let network = network_mut.service().clone();
let (tx_handler, tx_handler_controller) = transactions_handler_proto.build(
network.clone(),
sync_service.clone(),
Arc::new(TransactionPoolAdapter::new(
transaction_pool,
client.clone(),
)),
config
.prometheus_config
.as_ref()
.map(|config| &config.registry),
)?;
spawn_handle.spawn(
"network-transactions-handler",
Some("networking"),
tx_handler.run(),
);
spawn_handle.spawn_blocking(
"chain-sync-network-service-provider",
Some("networking"),
chain_sync_network_provider.run(network.clone()),
);
spawn_handle.spawn(
"import-queue",
None,
import_queue.run(Box::new(sync_service_import_queue)),
);
spawn_handle.spawn_blocking("syncing", None, engine.run());
let (system_rpc_tx, system_rpc_rx) = tracing_unbounded("mpsc_system_rpc", 10_000);
spawn_handle.spawn(
"system-rpc-handler",
Some("networking"),
build_system_rpc_future(
config.role.clone(),
network_mut.service().clone(),
sync_service.clone(),
client.clone(),
system_rpc_rx,
has_bootnodes,
),
);
let future = build_network_future(network_mut, client, sync_service.clone());
// TODO: Normally, one is supposed to pass a list of notifications protocols supported by the
// node through the `NetworkConfiguration` struct. But because this function doesn't know in
// advance which components, such as GrandPa or Polkadot, will be plugged on top of the
// service, it is unfortunately not possible to do so without some deep refactoring. To bypass
// this problem, the `NetworkService` provides a `register_notifications_protocol` method that
// can be called even after the network has been initialized. However, we want to avoid the
// situation where `register_notifications_protocol` is called *after* the network actually
// connects to other peers. For this reason, we delay the process of the network future until
// the user calls `NetworkStarter::start_network`.
//
// This entire hack should eventually be removed in favour of passing the list of protocols
// through the configuration.
//
// See also https://github.com/paritytech/substrate/issues/6827
let (network_start_tx, network_start_rx) = oneshot::channel();
// The network worker is responsible for gathering all network messages and processing
// them. This is quite a heavy task, and at the time of the writing of this comment it
// frequently happens that this future takes several seconds or in some situations
// even more than a minute until it has processed its entire queue. This is clearly an
// issue, and ideally we would like to fix the network future to take as little time as
// possible, but we also take the extra harm-prevention measure to execute the networking
// future using `spawn_blocking`.
spawn_handle.spawn_blocking("network-worker", Some("networking"), async move {
if network_start_rx.await.is_err() {
log::warn!(
"The NetworkStart returned as part of `build_network` has been silently dropped"
);
// This `return` might seem unnecessary, but we don't want to make it look like
// everything is working as normal even though the user is clearly misusing the API.
return;
}
future.await
});
Ok((
network,
system_rpc_tx,
tx_handler_controller,
NetworkStarter::new(network_start_tx),
sync_service,
))
}
/// Builds a future that continuously polls the network.
async fn build_network_future<
B: BlockT,
C: BlockchainEvents<B>
+ HeaderBackend<B>
+ BlockBackend<B>
+ HeaderMetadata<B, Error = sp_blockchain::Error>
+ ProofProvider<B>
+ Send
+ Sync
+ 'static,
H: sc_network_common::ExHashT,
>(
network: sc_network::NetworkWorker<B, H>,
client: Arc<C>,
sync_service: Arc<SyncingService<B>>,
) {
// Stream of finalized blocks reported by the client.
let mut finality_notification_stream = client.finality_notification_stream().fuse();
let network_run = network.run().fuse();
futures::pin_mut!(network_run);
loop {
futures::select! {
// List of blocks that the client has finalized.
notification = finality_notification_stream.select_next_some() => {
sync_service.on_block_finalized(notification.hash, notification.header);
}
// Drive the network. Shut down the network future if `NetworkWorker` has terminated.
_ = network_run => {
tracing::debug!("`NetworkWorker` has terminated, shutting down the network future.");
return
}
}
}
}
|
//! Get info on your team's User Groups.
use rtm::Usergroup;
/// Create a User Group
///
/// Wraps https://api.slack.com/methods/usergroups.create
#[derive(Clone, Debug, Serialize, new)]
pub struct CreateRequest<'a> {
/// A name for the User Group. Must be unique among User Groups.
pub name: &'a str,
/// A mention handle. Must be unique among channels, users and User Groups.
#[new(default)]
pub handle: Option<&'a str>,
/// A short description of the User Group.
#[new(default)]
pub description: Option<&'a str>,
/// A comma separated string of encoded channel IDs for which the User Group uses as a default.
#[new(default)]
pub channels: Option<&'a str>,
/// Include the number of users in each User Group.
#[new(default)]
pub include_count: Option<bool>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CreateResponse {
ok: bool,
pub usergroup: Option<Usergroup>,
}
/// Disable an existing User Group
///
/// Wraps https://api.slack.com/methods/usergroups.disable
#[derive(Clone, Debug, Serialize, new)]
pub struct DisableRequest {
/// The encoded ID of the User Group to disable.
pub usergroup: ::UsergroupId,
/// Include the number of users in the User Group.
#[new(default)]
pub include_count: Option<bool>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DisableResponse {
ok: bool,
pub usergroup: Option<Usergroup>,
}
/// Enable a User Group
///
/// Wraps https://api.slack.com/methods/usergroups.enable
#[derive(Clone, Debug, Serialize, new)]
pub struct EnableRequest {
/// The encoded ID of the User Group to enable.
pub usergroup: ::UsergroupId,
/// Include the number of users in the User Group.
#[new(default)]
pub include_count: Option<bool>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EnableResponse {
ok: bool,
pub usergroup: Option<Usergroup>,
}
/// List all User Groups for a team
///
/// Wraps https://api.slack.com/methods/usergroups.list
#[derive(Clone, Debug, Serialize, new)]
pub struct ListRequest {
/// Include disabled User Groups.
#[new(default)]
pub include_disabled: Option<bool>,
/// Include the number of users in each User Group.
#[new(default)]
pub include_count: Option<bool>,
/// Include the list of users for each User Group.
#[new(default)]
pub include_users: Option<bool>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ListResponse {
ok: bool,
pub usergroups: Option<Vec<Usergroup>>,
}
/// Update an existing User Group
///
/// Wraps https://api.slack.com/methods/usergroups.update
#[derive(Clone, Debug, Serialize, new)]
pub struct UpdateRequest<'a> {
/// The encoded ID of the User Group to update.
pub usergroup: ::UsergroupId,
/// A name for the User Group. Must be unique among User Groups.
#[new(default)]
pub name: Option<&'a str>,
/// A mention handle. Must be unique among channels, users and User Groups.
#[new(default)]
pub handle: Option<&'a str>,
/// A short description of the User Group.
#[new(default)]
pub description: Option<&'a str>,
/// A comma separated string of encoded channel IDs for which the User Group uses as a default.
#[new(default)]
#[serde(serialize_with = "::serialize_comma_separated")]
pub channels: &'a [::UserId],
/// Include the number of users in the User Group.
#[new(default)]
pub include_count: Option<bool>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateResponse {
ok: bool,
pub usergroup: Option<Usergroup>,
}
|
use aoc_runner_derive::*;
struct Rule {
a1: u16,
b1: u16,
a2: u16,
b2: u16,
}
impl Rule {
fn new(ranges: &str) -> Rule {
let mut split_or = ranges.split(" or ");
let first_range = split_or.next().unwrap().trim();
let second_range = split_or.next().unwrap().trim();
let (a1, b1) = parse_range(first_range);
let (a2, b2) = parse_range(second_range);
Rule { a1, b1, a2, b2 }
}
fn applies(&self, val: u16) -> bool {
(self.a1 <= val && val <= self.b1) || (self.a2 <= val && val <= self.b2)
}
}
type Ticket = Vec<u16>;
type Input = (Vec<Rule>, Ticket, Vec<Ticket>);
#[derive(Clone)]
struct IndexSet {
size: usize,
inner: Vec<bool>,
len: usize,
}
impl IndexSet {
fn new(size: usize, initial: bool) -> IndexSet {
IndexSet {
size,
inner: vec![initial; size],
len: if initial { size } else { 0 },
}
}
fn contains(&self, val: usize) -> bool {
val < self.size && self.inner[val]
}
fn iter(&self) -> impl Iterator<Item = usize> + '_ {
self.inner
.iter()
.enumerate()
.filter(|(_, b)| **b)
.map(|(i, _)| i)
}
fn insert(&mut self, val: usize) {
if val < self.size && !self.inner[val] {
self.inner[val] = true;
self.len += 1;
}
}
fn remove(&mut self, val: usize) {
if val < self.size && self.inner[val] {
self.inner[val] = false;
self.len -= 1;
}
}
fn retain<T: FnMut(usize) -> bool>(&mut self, mut predicate: T) {
for i in 0..self.size {
if self.inner[i] && !predicate(i) {
self.inner[i] = false;
self.len -= 1;
}
}
}
fn len(&self) -> usize {
self.len
}
}
impl std::fmt::Debug for IndexSet {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
fmt.debug_list().entries(self.iter()).finish()
}
}
#[aoc_generator(day16)]
fn generate(input: &str) -> (Vec<Rule>, Ticket, Vec<Ticket>) {
let mut rules = vec![];
let mut lines = input.lines();
for line in lines.by_ref() {
if line.is_empty() {
break;
}
let mut split_colon = line.split(':');
let rule = Rule::new(split_colon.nth(1).unwrap());
rules.push(rule);
}
let my_ticket = parse_ticket(lines.nth(1).unwrap());
lines.nth(1).unwrap();
let mut tickets = vec![];
tickets.extend(lines.map(parse_ticket));
(rules, my_ticket, tickets)
}
fn parse_range(range: &str) -> (u16, u16) {
let mut split = range.split('-');
let first = split.next().unwrap().parse().unwrap();
let second = split.next().unwrap().parse().unwrap();
(first, second)
}
fn parse_ticket(ticket: &str) -> Ticket {
ticket
.split(',')
.map(str::parse)
.map(Result::unwrap)
.collect()
}
#[aoc(day16, part1)]
fn solve_part1(input: &Input) -> u16 {
let tickets = &input.2;
tickets
.iter()
.map(|x| invalid_ticket_values(x, &input.0))
.sum()
}
fn invalid_ticket_values(ticket: &[u16], rules: &[Rule]) -> u16 {
ticket.iter().filter(|x| !is_valid_value(**x, rules)).sum()
}
fn is_valid_value(val: u16, rules: &[Rule]) -> bool {
rules.iter().any(|rule| rule.applies(val))
}
#[aoc(day16, part2)]
fn solve_part2(input: &Input) -> u64 {
let valid_tickets: Vec<Ticket> = input
.2
.iter()
.cloned()
.filter(|ticket| is_valid_ticket(ticket, &input.0))
.collect();
let rules = &input.0;
let mut rule_positions: Vec<IndexSet> = vec![];
for rule in rules {
let mut flags = IndexSet::new(rules.len(), true);
for ticket in &valid_tickets {
flags.retain(|i| rule.applies(ticket[i]))
}
rule_positions.push(flags);
}
// at this point, rule_positions contains a list of possible positions
// for each rule.
let rule_positions = find_rules_permutation(rules, &rule_positions);
let my_ticket = &input.1;
rule_positions
.iter()
.take(6)
.map(|rule_pos| my_ticket[*rule_pos] as u64)
.product()
}
fn is_valid_ticket(ticket: &[u16], rules: &[Rule]) -> bool {
ticket.iter().all(|&val| is_valid_value(val, rules))
}
fn find_rules_permutation(rules: &[Rule], positions: &[IndexSet]) -> Vec<usize> {
let mut new_positions: Vec<_> = positions.iter().cloned().enumerate().collect();
new_positions.sort_unstable_by_key(|x| x.1.len());
let mut perm = vec![];
let mut encountered = IndexSet::new(rules.len(), false);
find_rules_permutation_inner(rules, &new_positions, &mut perm, &mut encountered);
assert_eq!(perm.len(), rules.len());
perm.sort_unstable_by_key(|x| x.0);
perm.iter().map(|x| x.1).collect()
}
fn find_rules_permutation_inner(
rules: &[Rule],
positions: &[(usize, IndexSet)],
perm: &mut Vec<(usize, usize)>,
enc: &mut IndexSet,
) -> bool {
let i = perm.len();
if i == rules.len() {
return true;
}
for pos in positions[i].1.iter() {
if enc.contains(pos) {
continue;
}
perm.push((positions[i].0, pos));
enc.insert(pos);
let ret = find_rules_permutation_inner(rules, positions, perm, enc);
if ret {
return true;
}
enc.remove(pos);
perm.pop();
}
false
}
|
//! This module contains the logic for the main `safety` binary.
use crate::safety::{SafetyGame, SafetyGameSolver};
use aiger::Aiger;
use bosy::specification::Semantics;
use clap::{App, Arg};
use cudd::{CuddManager, CuddReordering};
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
pub struct Config {
filename: String,
}
impl Config {
pub fn new(args: &[String]) -> Self {
let matches = App::new("Safety")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Symbolic safety game solver")
.arg(
Arg::with_name("INPUT")
.help("Sets the input file to use")
.long("--spec")
.required(true)
.takes_value(true),
)
.get_matches_from(args);
let filename = matches.value_of("INPUT").map(|s| s.to_string()).unwrap();
Config { filename }
}
pub fn run(&self) -> Result<(), Box<Error>> {
let mut file = File::open(&self.filename)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let aiger = Aiger::from_str(&contents)?;
let manager = CuddManager::new();
manager.set_auto_dyn(CuddReordering::GroupSift);
let safety_game = SafetyGame::from_aiger(&aiger, &manager);
let mut solver = SafetyGameSolver::new(safety_game, Semantics::Mealy);
if solver.solve().is_none() {
println!("unrealizable");
} else {
println!("realizable");
}
Ok(())
}
}
|
use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned as _;
use syn::{
Attribute, Data, DeriveInput, Field, Fields, Generics, Ident, PredicateType, TraitBound,
TraitBoundModifier, Type, TypeParamBound, WherePredicate,
};
use crate::error::Error;
use crate::options::Options;
use crate::utils::{AttributeExt, PathExt, TypeExt};
pub fn derive(input: &DeriveInput) -> crate::Result<TokenStream> {
let name = &input.ident;
let mut errors = vec![];
let mut functions: Vec<TokenStream> = vec![];
let options = Options::from_derive_input(input)?;
match &options.data {
Data::Struct(s) => {
let generator = Generator::from_options(&options);
match &s.fields {
Fields::Named(named) => {
let result = named
.named
.iter()
.map(|field| generator.generate(field))
.collect::<Vec<Result<_, _>>>();
if result.iter().any(Result::is_err) {
return Err(Error::multiple(result.into_iter().filter_map(Result::err)));
} else {
functions.extend(
result
.into_iter()
.filter_map(Result::ok)
.collect::<Vec<_>>(),
);
}
}
// A TupleStruct has no field names.
Fields::Unnamed(_) => {
errors
.push(Error::custom("tuple structs are not supported.").with_span(&input));
}
// A Unit has no fields.
Fields::Unit => {
errors.push(Error::custom("unit structs are not supported.").with_span(&input));
}
}
}
Data::Enum(_) => {
errors.push(Error::custom("enum are not supported.").with_span(&input));
}
Data::Union(_) => {
errors.push(Error::custom("union structs are not supported.").with_span(&input));
}
}
if !errors.is_empty() {
return Err(Error::multiple(errors));
}
let (impl_generics, ty_generics, where_clause) = options.generics.split_for_impl();
if (options.attributes.try_into || options.attributes.into)
&& quote!(#impl_generics #ty_generics #where_clause)
.to_string()
.contains("VALUE")
{
return Err(
Error::custom("a generic called `VALUE` is not supported, please rename it.")
.with_span(&options.generics),
);
}
Ok(quote! {
#[allow(dead_code)]
#[allow(clippy::all)]
impl #impl_generics #name #ty_generics #where_clause {
#(#functions)*
}
})
}
fn generate_assertion(
name: &TokenStream,
field_type: &Type,
generics: &Generics,
bound: &TokenStream,
) -> TokenStream {
let where_clause = {
if let Some(where_clause) = &generics.where_clause {
let mut result = (*where_clause).clone();
result
.predicates
.push_value(WherePredicate::Type(PredicateType {
lifetimes: None,
bounded_ty: field_type.clone(),
colon_token: syn::parse2(quote!(:)).unwrap(),
bounds: {
let mut bounds = Punctuated::new();
bounds.push_value(TypeParamBound::Trait(TraitBound {
paren_token: None,
modifier: TraitBoundModifier::None,
lifetimes: None,
path: syn::parse2(quote!(#bound)).unwrap(),
}));
bounds
},
}));
quote!(#result)
} else {
quote!( where #field_type: #bound )
}
};
let fields = {
let mut result = vec![];
let mut field_number: usize = 0;
for lifetime_def in generics.lifetimes() {
let lifetime = &lifetime_def.lifetime;
let name = format_ident!("__field_{}", field_number);
result.push(quote! {
#name: ::std::marker::PhantomData<& #lifetime ()>
});
field_number += 1;
}
for param in generics.type_params() {
let ident = ¶m.ident;
let name = format_ident!("__field_{}", field_number);
result.push(quote! {
#name: ::std::marker::PhantomData<#ident>
});
field_number += 1;
}
result
};
let (_, ty_generics, _) = generics.split_for_impl();
// this will expand to for example
// struct _AssertCopy where usize: Copy;
//
// it acts as a check for wether a type implements Copy or not.
quote_spanned! {
field_type.span() =>
struct #name #ty_generics #where_clause {
#(#fields),*
}
}
}
struct Generator<'a> {
options: &'a Options,
}
impl<'a> Generator<'a> {
pub const fn from_options(options: &'a Options) -> Self { Self { options } }
pub fn get(
options: &Options,
field_name: &Ident,
field_type: &Type,
) -> Result<TokenStream, Error> {
// apply the rename template, if there is none, use the default:
// -> field: usize
// -> with template `prefix_{}_suffix` -> prefix_field_suffix
// -> without template -> `field`
let function_name = {
if options.attributes.rename {
options.rename.format_get(field_name)?
} else {
field_name.clone()
}
};
let mut attributes: Vec<Attribute> = options.attrs.clone();
let arguments = vec![quote![&self]];
let visibility = &options.visibility;
let mut assertions = vec![];
// add attributes to the function
if options.attributes.inline {
attributes.push(Attribute::from_token_stream(quote!(#[inline(always)])).unwrap());
}
if options.attributes.must_use {
attributes.push(Attribute::from_token_stream(quote!(#[must_use])).unwrap());
}
// change body, depending on the type and config:
let (return_type, body) = {
if options.attributes.primitive_copy && field_type.is_primitive_copy()
|| options.attributes.copy
{
(quote![#field_type], quote![self.#field_name])
} else if options.attributes.option_as_ref && field_type.is_option() {
// The getter will have the following signature
// fn field(&self) -> Option<&String>;
// instead of:
// fn field(&self) -> &Option<String>;
(
field_type.to_as_ref().unwrap(),
quote![self.#field_name.as_ref()],
)
} else if options.attributes.clone {
assertions.push(generate_assertion(
"e!(_AssertClone),
field_type,
&options.generics,
"e!(::std::clone::Clone),
));
(quote![#field_type], quote! { self.#field_name.clone() })
} else {
(quote![&#field_type], quote![&self.#field_name])
}
};
// if the copy field has been enabled an assertion is needed, that ensures, that
// the type implements `Copy`.
if options.attributes.copy
|| (options.attributes.primitive_copy
&& field_type.is_primitive_copy()
// the assertion does not work with lifetimes :(
&& !field_type.is_reference())
{
assertions.push(generate_assertion(
"e!(_AssertCopy),
field_type,
&options.generics,
"e!(::std::marker::Copy),
));
}
let const_fn = {
if options.attributes.const_fn {
quote![const]
} else {
quote![]
}
};
Ok(quote! {
#(#attributes)*
#visibility #const_fn fn #function_name(#(#arguments),*) -> #return_type {
#(#assertions)*
#body
}
})
}
pub fn set(
options: &Options,
field_name: &Ident,
field_type: &Type,
) -> Result<TokenStream, Error> {
// apply the rename template, if there is none, use the default:
// -> field: usize
// -> with template `prefix_{}_suffix` -> prefix_field_suffix
// -> without template -> `set_field`
let function_name = {
if options.attributes.rename {
options.rename.format_set(field_name)?
} else {
format_ident!("set_{}", field_name)
}
};
let mut generics = vec![];
let mut arguments = vec![quote![&mut self]];
let return_type = quote![&mut Self];
let visibility = &options.visibility;
let mut argument = quote! { value: #field_type };
let mut assignment = quote! { self.#field_name = value; };
if options.attributes.into {
argument = quote! { value: VALUE };
let mut bound = quote! { VALUE: ::std::convert::Into<#field_type> };
// default assignment for into
assignment = quote! {
self.#field_name = value.into();
};
// For Option we might want to have
//
// fn set_field<T: Into<String>>(value: Option<T>);
//
// instead of
//
// fn set_field<T: Into<Option<String>>>(value: T);
//
if field_type.is_ident("Option") {
// tries to get the `T` from Option<T>
if let Some(arg) = field_type
.arguments()
.into_iter()
.find_map(|s| s.into_iter().last())
{
bound = quote! { VALUE: ::std::convert::Into<#arg> };
if options.attributes.strip_option {
assignment = quote! {
self.#field_name = Some(value.into());
};
} else {
argument = quote! { value: ::std::option::Option<VALUE> };
assignment = quote! {
self.#field_name = value.map(|v| v.into());
};
}
}
}
generics.push(bound);
} else if field_type.is_ident("Option") && options.attributes.strip_option {
if let Some(arg) = field_type
.arguments()
.into_iter()
.find_map(|s| s.into_iter().last())
{
argument = quote! { value: #arg };
assignment = quote! {
self.#field_name = Some(value);
};
}
}
arguments.push(argument);
// Attributes like `#[allow(clippy::use_self)]`
let mut attributes: Vec<Attribute> = options.attrs.clone();
if options.attributes.inline {
attributes.push(Attribute::from_token_stream(quote!(#[inline(always)])).unwrap());
}
// TODO: allow const for setters
// Blocked by: - rust-lang/rust#57349
// - rust-lang/rfcs#2632
let verify = &options.verify;
Ok(quote! {
#(#attributes)*
#visibility fn #function_name <#(#generics),*> ( #(#arguments),* ) -> #return_type {
#assignment
#verify
self
}
})
}
pub fn try_set(
options: &Options,
field_name: &Ident,
field_type: &Type,
) -> Result<TokenStream, Error> {
let function_name = {
if options.attributes.rename {
options.rename.format_try_set(field_name)?
} else {
format_ident!("try_{}", field_name)
}
};
let mut attributes: Vec<Attribute> = options.attrs.clone();
let mut argument = quote! { value: VALUE };
if options.attributes.inline {
attributes.push(Attribute::from_token_stream(quote!(#[inline(always)])).unwrap());
}
let visibility = &options.visibility;
let mut body = quote! {
self.#field_name = value.try_into()?;
};
let mut bound = quote! {
VALUE: ::std::convert::TryInto<#field_type>
};
if field_type.is_ident("Option") {
if let Some(arg) = field_type
.arguments()
.into_iter()
.find_map(|s| s.into_iter().last())
{
if options.attributes.strip_option {
body = quote! {
self.#field_name = Some(value.try_into()?);
};
} else {
argument = quote! { value: ::std::option::Option<VALUE> };
body = quote! {
self.#field_name = value.map(|v| v.try_into()).transpose()?;
};
}
bound = quote! {
VALUE: ::std::convert::TryInto<#arg>
};
}
}
let verify = &options.verify;
Ok(quote! {
#(#attributes)*
#visibility fn #function_name<VALUE>(
&mut self,
#argument
) -> Result<&mut Self, VALUE::Error>
where
#bound
{
#body
#verify
Ok(self)
}
})
}
pub fn get_mut(
options: &Options,
field_name: &Ident,
field_type: &Type,
) -> Result<TokenStream, Error> {
let function_name = {
if options.attributes.rename {
options.rename.format_get_mut(field_name)?
} else {
format_ident!("{}_mut", field_name)
}
};
let mut attributes: Vec<Attribute> = options.attrs.clone();
if options.attributes.inline {
attributes.push(Attribute::from_token_stream(quote!(#[inline(always)])).unwrap());
}
if options.attributes.must_use {
attributes.push(Attribute::from_token_stream(quote!(#[must_use])).unwrap());
}
let visibility = &options.visibility;
Ok(quote! {
#(#attributes)*
#visibility fn #function_name(&mut self) -> &mut #field_type {
&mut self.#field_name
}
})
}
pub fn collection_magic(
options: &Options,
field_name: &Ident,
field_type: &Type,
) -> Result<TokenStream, Error> {
let visibility = &options.visibility;
let mut attributes = options.attrs.clone();
let type_name = Ident::new(&field_type.path().unwrap().to_string(), field_type.span());
let mut function_name = None;
let mut body = quote![];
let mut arguments = vec![quote!(&mut self)];
for (index, value) in field_type.arguments().unwrap().iter().enumerate() {
let ident = format_ident!("value_{}", index);
arguments.push(quote!(#ident: #value));
}
if options.attributes.inline {
attributes.push(Attribute::from_token_stream(quote!(#[inline(always)])).unwrap());
}
if options.attributes.must_use {
attributes.push(Attribute::from_token_stream(quote!(#[must_use])).unwrap());
}
if field_type.is_ident("Vec") {
function_name = Some(format_ident!("push_{}", field_name));
body = quote_spanned! {
field_type.span() =>
struct __AssertVec(::std::vec::Vec<()>);
__AssertVec(#type_name::new());
self.#field_name.push(value_0);
self
};
} else if field_type.is_ident("BTreeMap")
|| field_type.is_ident("BTreeSet")
|| field_type.is_ident("HashMap")
|| field_type.is_ident("HashSet")
{
let insert_args = (0..arguments.len() - 1).map(|i| format_ident!("value_{}", i));
let assert_args = (0..arguments.len() - 1).map(|_| quote![()]);
function_name = Some(format_ident!("insert_{}", field_name));
body = quote_spanned! {
field_type.span() =>
struct __AssertCollection(::std::collections::#type_name<#(#assert_args),*>);
__AssertCollection(#type_name::new());
self.#field_name.insert(#(#insert_args),*);
self
};
}
if let Some(function_name) = function_name {
Ok(quote! {
#(#attributes)*
#visibility fn #function_name(#(#arguments),*) -> &mut Self {
#body
}
})
} else {
Ok(quote!())
}
}
/// This function generates the Functions for a [`Field`], based on the
/// [`Options`] and the [`Field`] itself.
pub fn generate(&self, field: &Field) -> Result<TokenStream, Error> {
let options = self.options.with_attrs(&field.attrs)?;
let field_name = {
if let Some(ident) = field.ident.as_ref() {
ident
} else {
// This shouldn't be reached, because expand::derive ensures, that all fields
// have a name.
unreachable!("unnamed field guard failed");
}
};
let mut result = quote![];
if (options.attributes.ignore_phantomdata && field.ty.is_ident("PhantomData"))
|| options.attributes.skip
|| (options.attributes.ignore_underscore && {
field
.ty
.path()
.map_or(false, |p| p.to_string().starts_with('_'))
})
|| {
// empty tuple
if let syn::Type::Tuple(s) = &field.ty {
s.elems.is_empty()
} else {
false
}
}
|| {
if let syn::Type::Never(_) = &field.ty {
true
} else {
false
}
}
{
return Ok(quote![]);
}
if options.attributes.get {
let function = Self::get(&options, field_name, &field.ty)?;
result = quote! {
#result
#function
};
}
if options.attributes.set {
let function = Self::set(&options, field_name, &field.ty)?;
result = quote! {
#result
#function
};
}
if options.attributes.try_into {
let function = Self::try_set(&options, field_name, &field.ty)?;
result = quote! {
#result
#function
};
}
if options.attributes.get_mut {
let function = Self::get_mut(&options, field_name, &field.ty)?;
result = quote! {
#result
#function
};
}
#[allow(clippy::collapsible_if)]
{
if options.attributes.collection_magic {
if field.ty.is_ident("Vec")
|| field.ty.is_ident("BTreeMap")
|| field.ty.is_ident("BTreeSet")
|| field.ty.is_ident("HashMap")
|| field.ty.is_ident("HashSet")
{
let function = Self::collection_magic(&options, field_name, &field.ty)?;
result = quote! {
#result
#function
};
}
}
}
Ok(result)
}
}
|
//
// 0 1 0 Mnemosyne: a functional systems programming language.
// 0 0 1 (c) 2015 Hawk Weisman
// 1 1 1 hi@hawkweisman.me
//
// Mnemosyne is released under the MIT License. Please refer to
// the LICENSE file at the top-level directory of this distribution
// or at https://github.com/hawkw/mnemosyne/.
//
use rustc::lib::llvm;
use rustc::lib::llvm::*;
use std::ffi::CString;
use std::mem::transmute;
use libc::{c_char, c_uint};
use ::errors::{ExpectICE, UnwrapICE};
// pub struct Context(llvm::ContextRef);
//
// pub struct Builder(llvm::BuilderRef);
/// because we are in the Raw Pointer Sadness Zone (read: unsafe),
/// it is necessary that we assert that everything exists.
macro_rules! not_null {
($target:expr) => ({
let e = $target;
if e.is_null() {
ice!( "assertion failed: {} returned null!"
, stringify!($target)
);
} else { e }
})
}
trait LLVMWrapper {
type Ref;
fn to_ref(&self) -> Self::Ref;
fn from_ref(r: Self::Ref) -> Self;
}
macro_rules! llvm_wrapper {
( $($name:ident wrapping $wrapped:path),*) => {$(
pub struct $name ($wrapped);
impl LLVMWrapper for $name {
type Ref = $wrapped;
fn to_ref(&self) -> Self::Ref {
not_null!(self.0)
}
fn from_ref(r: $wrapped) -> Self {
$name( not_null!(r) )
}
}
)*};
( $($name:ident wrapping $wrapped:path, dropped by $drop:path),*) => {$(
llvm_wrapper!{ $name wrapping $wrapped }
impl Drop for $name {
fn drop(&mut self) {
unsafe { $drop(self.0) }
}
}
)*}
}
llvm_wrapper! {
Context wrapping llvm::ContextRef,
dropped by llvm::LLVMContextDispose,
Builder wrapping llvm::BuilderRef,
dropped by llvm::LLVMDisposeBuilder,
OperandBundle wrapping llvm::OperandBundleDefRef,
dropped by llvm::LLVMRustFreeOperandBundleDef
}
llvm_wrapper! {
BasicBlock wrapping llvm::BasicBlockRef,
Value wrapping llvm::ValueRef
}
impl Context {
/// Construct a new `Builder` within this `Context`.
pub fn create_builder(&self) -> Builder {
unsafe {
Builder::from_ref(LLVMCreateBuilderInContext(self.to_ref()))
}
}
}
impl OperandBundle {
/// Construct a new `OperandBundle`
pub fn new(name: &str, vals: &mut [Value]) -> Self {
let cname = CString::new(name).unwrap_ice();
unsafe {
let vals_ref = transmute::<&mut [Value], &mut [ValueRef]>(vals);
let def = LLVMRustBuildOperandBundleDef( cname.as_ptr()
, vals_ref.as_ptr()
, vals_ref.len() as c_uint);
OperandBundle(def)
}
}
}
impl Builder {
//---- positioning --------------------------------------------------------
/// Wrapper for `LLVMPositionBuilder`.
pub fn position(&mut self, block: &mut BasicBlock, inst: &Value)
-> &mut Self {
unsafe {
LLVMPositionBuilder(self.to_ref(), block.to_ref(), inst.to_ref());
}
self
}
/// Wrapper for `LLVMPositionBuilderBefore`.
pub fn position_before(&mut self, inst: &Value) -> &mut Self {
unsafe { LLVMPositionBuilderBefore(self.to_ref(), inst.to_ref()) }
self
}
/// Wrapper for `LLVMPositionBuilderAtEnd`.
pub fn position_at_end(&mut self, block: &mut BasicBlock) -> &mut Self {
unsafe { LLVMPositionBuilderAtEnd(self.to_ref(), block.to_ref()) }
self
}
//---- insertion ----------------------------------------------------------
pub fn get_insert_block(&mut self) -> BasicBlock {
unsafe { BasicBlock::from_ref(LLVMGetInsertBlock(self.to_ref())) }
}
pub fn clear_insertion_position(&mut self) -> &mut Self {
unsafe { LLVMClearInsertionPosition(self.to_ref()) }
self
}
pub fn insert(&mut self, inst: &mut Value) -> &mut Self {
unsafe { LLVMInsertIntoBuilder(self.to_ref(), inst.to_ref()) }
self
}
pub fn insert_with_name(&mut self, inst: &mut Value, name: &str)
-> &mut Self {
let cname = CString::new(name).expect_ice(
format!("Couldn't create CString for {}", name).as_ref());
unsafe {
LLVMInsertIntoBuilderWithName( self.to_ref()
, inst.to_ref()
, cname.as_ptr() as *const c_char)
}
self
}
//---- building ----------------------------------------------------------
/// Create a `ret void` return instruction.
pub fn build_ret_void(&mut self) -> Value {
unsafe { Value::from_ref( LLVMBuildRetVoid(self.to_ref()) ) }
}
/// Create a `ret <value>` instruction.
///
/// # Arguments
///
/// + `v`: the `Value` to return
pub fn build_ret(&mut self, v: &Value) -> Value {
unsafe {
Value::from_ref( LLVMBuildRet(self.to_ref(), v.to_ref()) )
}
}
/// Create an unconditional branch `br label X` instruction.
///
/// # Arguments
///
/// + `dest` the `BasicBlock` to branch to.
///
/// # Return Value
/// An unconditional branch `br` instruction.
pub fn build_br(&mut self, dest: &BasicBlock) -> Value {
unsafe {
Value::from_ref( LLVMBuildBr(self.to_ref(), dest.to_ref()) )
}
}
/// Create a conditional branch instruction.
///
/// # Arguments
///
/// + `condition`: the condition to test
/// + `then_block`: the block to branch to if the condition is true
/// + `else_block`: the block to branch to if the condition is false
///
/// # Returns Value
///
/// A conditional branch instruction of the form
/// `br $condition, $then_block, $else_block`.
pub fn build_cond_br( &mut self
, condition: Value
, then_block: &BasicBlock
, else_block: &BasicBlock )
-> Value {
unsafe {
let val = LLVMBuildCondBr( self.to_ref()
, condition.to_ref()
, then_block.to_ref()
, else_block.to_ref() );
Value::from_ref(val)
}
}
/// Create a switch instruction.
///
/// # Arguments
///
/// + `on`: the `Value` to switch on
/// + `else_block`: a `BasicBlock` representing the default destination
/// + `num_cases`: a hint towards the number of cases in the switch
/// expression (for more efficient allocation)
///
/// # Return Value
///
/// A switch instruction with the specified value and default destination.
pub fn build_switch_br( &mut self
, on: Value
, else_block: &BasicBlock
, num_cases: u32 )
-> Value {
unsafe {
Value::from_ref(LLVMBuildSwitch( self.to_ref()
, on.to_ref()
, else_block.to_ref()
, num_cases))
}
}
/// Create a function invocation instruction.
///
/// # Arguments
///
/// + `function`: the function to invoke
/// + `args': the arguments to `function`
/// + `then_block`:
/// + `catch_block`:
/// + `name`: the name of the instruction.
/// + `bundle`:
///
/// # Return Value
///
/// A function invocation instruction.
pub fn build_invoke( &mut self
, function: Value
, args: &mut [Value]
, then_block: &BasicBlock
, catch_block: &BasicBlock
, bundle: &OperandBundle
, name: &str )
-> Value {
let cname = CString::new(name).unwrap_ice().as_ptr();
unsafe {
let args_ref = transmute::<&mut [Value], &mut [ValueRef]>(args)
.as_ptr();
let val = LLVMRustBuildInvoke( self.to_ref()
, function.to_ref()
, args_ref, args.len() as c_uint
, then_block.to_ref()
, catch_block.to_ref()
, bundle.to_ref()
, cname as *const c_char);
Value::from_ref(val)
}
}
/// Create landing pad
///
// TODO: do we even want to support this? We don't have checked exns
pub fn build_landing_pad( &mut self
, ty: TypeRef
, pers_fn: Value
, num_clauses: usize
, name: &str
, f: Value)
-> Value {
let cname = CString::new(name).unwrap_ice().as_ptr();
unsafe {
Value::from_ref(
LLVMRustBuildLandingPad( self.to_ref()
, ty
, pers_fn.to_ref()
, num_clauses as c_uint
, cname as *const c_char
, f.to_ref() )
)
}
}
pub fn build_cleanup_pad( &mut self
, parent_pad: Value
, args: &mut [Value]
, name: &str )
-> Value {
let cname = CString::new(name).unwrap_ice().as_ptr();
unsafe {
let args_ref = transmute::<&mut [Value], &mut [ValueRef]>(args);
Value::from_ref(
LLVMRustBuildCleanupPad( self.to_ref()
, parent_pad.to_ref()
, args_ref.len() as c_uint
, args_ref.as_ptr()
, cname as *const c_char ))
}
}
pub fn build_cleanup_ret( &mut self
, cleanup_pad: Value
, unwind_blk: BasicBlock )
-> Value {
unsafe {
Value::from_ref(LLVMRustBuildCleanupRet( self.to_ref()
, cleanup_pad.to_ref()
, unwind_blk.to_ref() ))
}
}
pub fn build_resume(&mut self, ex: Value) -> Value {
unsafe { Value::from_ref(LLVMBuildResume(self.to_ref(), ex.to_ref())) }
}
pub fn build_unreachable(&mut self) -> Value {
unsafe { Value::from_ref(LLVMBuildUnreachable(self.to_ref())) }
}
}
|
use anyhow::Result;
use edif::netlist;
use std::fs;
#[test]
fn parse() -> Result<()> {
let s = fs::read_to_string(format!("{}/tests/test.edf", env!("CARGO_MANIFEST_DIR")))?;
let n = netlist::from_str(&s)?;
n.verify_references()?;
Ok(())
}
|
#[doc = "Reader of register FM_MEM_DATA[%s]"]
pub type R = crate::R<u32, super::FM_MEM_DATA>;
#[doc = "Reader of field `DATA32`"]
pub type DATA32_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - Sense amplifier and cloumn multiplexer structure Bytes. The read data is dependent on FM_CTL.IF_SEL: - IF_SEL is '0': data as specified by the R interface address - IF_SEL is '1': data as specified by FM_MEM_ADDR and the offset of the accessed FM_MEM_DATA register."]
#[inline(always)]
pub fn data32(&self) -> DATA32_R {
DATA32_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
use clap::{Arg, App};
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
fn main() {
let matches = App::new("thing")
.version(VERSION.unwrap_or("unknown version"))
.arg(...)
...
.get_matches();
}
}
|
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2016 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT.
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum mxm_log_level_t
{
MXM_LOG_LEVEL_FATAL = 0,
MXM_LOG_LEVEL_ERROR = 1,
MXM_LOG_LEVEL_WARN = 2,
MXM_LOG_LEVEL_INFO = 3,
MXM_LOG_LEVEL_DEBUG = 4,
MXM_LOG_LEVEL_TRACE = 5,
MXM_LOG_LEVEL_TRACE_REQ = 6,
MXM_LOG_LEVEL_TRACE_DATA = 7,
MXM_LOG_LEVEL_TRACE_ASYNC = 8,
MXM_LOG_LEVEL_TRACE_FUNC = 9,
MXM_LOG_LEVEL_TRACE_POLL = 10,
MXM_LOG_LEVEL_LAST = 11,
}
|
use std::ops::{Index, IndexMut};
use crate::ast::Expression;
#[derive(Debug, Clone)]
pub struct Pipeline {
pub expressions: Vec<Expression>,
}
impl Default for Pipeline {
fn default() -> Self {
Self::new()
}
}
impl Pipeline {
pub fn new() -> Self {
Self {
expressions: vec![],
}
}
pub fn from_vec(expressions: Vec<Expression>) -> Pipeline {
Self { expressions }
}
pub fn len(&self) -> usize {
self.expressions.len()
}
pub fn is_empty(&self) -> bool {
self.expressions.is_empty()
}
}
impl Index<usize> for Pipeline {
type Output = Expression;
fn index(&self, index: usize) -> &Self::Output {
&self.expressions[index]
}
}
impl IndexMut<usize> for Pipeline {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.expressions[index]
}
}
|
pub mod automatic_queryable_encryption;
pub mod explicit_encryption;
pub mod explicit_encryption_auto_decryption;
pub mod explicit_queryable_encryption;
pub mod local_rules;
pub mod server_side_enforcement;
|
//! zser.rs: Implementation of the zcred serialization format
#![deny(missing_docs)]
#![cfg_attr(not(test), no_std)]
#![cfg_attr(feature = "bench", feature(test))]
extern crate byteorder;
#[cfg(all(feature = "bench", test))]
extern crate test;
// For competitive benchmarking
#[cfg(all(feature = "bench", test))]
extern crate leb128;
pub mod varint;
|
#[doc = "Reader of register TX_CTRL"]
pub type R = crate::R<u32, super::TX_CTRL>;
#[doc = "Writer for register TX_CTRL"]
pub type W = crate::W<u32, super::TX_CTRL>;
#[doc = "Register TX_CTRL `reset()`'s with value 0x21"]
impl crate::ResetValue for super::TX_CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x21
}
}
#[doc = "Reader of field `MSB_FIRST`"]
pub type MSB_FIRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MSB_FIRST`"]
pub struct MSB_FIRST_W<'a> {
w: &'a mut W,
}
impl<'a> MSB_FIRST_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 `FIFO_RECONFIG`"]
pub type FIFO_RECONFIG_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FIFO_RECONFIG`"]
pub struct FIFO_RECONFIG_W<'a> {
w: &'a mut W,
}
impl<'a> FIFO_RECONFIG_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 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `TX_ENTRIES`"]
pub type TX_ENTRIES_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TX_ENTRIES`"]
pub struct TX_ENTRIES_W<'a> {
w: &'a mut W,
}
impl<'a> TX_ENTRIES_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 & !(0x1f << 2)) | (((value as u32) & 0x1f) << 2);
self.w
}
}
impl R {
#[doc = "Bit 0 - Least significant bit first ('0') or most significant bit first ('1'). This field also affects the Address field When MSB_FIRST = 1, then \\[15:0\\] is data and \\[(ADDR_WIDTH+15):16\\] is used for address When MSB_FIRST = 0, then \\[15:0\\] is for data. No address field"]
#[inline(always)]
pub fn msb_first(&self) -> MSB_FIRST_R {
MSB_FIRST_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Setting this bit, clears the FIFO and resets the pointer"]
#[inline(always)]
pub fn fifo_reconfig(&self) -> FIFO_RECONFIG_R {
FIFO_RECONFIG_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bits 2:6 - This field determines the depth of the TX_FIFO. Allowed legal values are 8 and 16 only"]
#[inline(always)]
pub fn tx_entries(&self) -> TX_ENTRIES_R {
TX_ENTRIES_R::new(((self.bits >> 2) & 0x1f) as u8)
}
}
impl W {
#[doc = "Bit 0 - Least significant bit first ('0') or most significant bit first ('1'). This field also affects the Address field When MSB_FIRST = 1, then \\[15:0\\] is data and \\[(ADDR_WIDTH+15):16\\] is used for address When MSB_FIRST = 0, then \\[15:0\\] is for data. No address field"]
#[inline(always)]
pub fn msb_first(&mut self) -> MSB_FIRST_W {
MSB_FIRST_W { w: self }
}
#[doc = "Bit 1 - Setting this bit, clears the FIFO and resets the pointer"]
#[inline(always)]
pub fn fifo_reconfig(&mut self) -> FIFO_RECONFIG_W {
FIFO_RECONFIG_W { w: self }
}
#[doc = "Bits 2:6 - This field determines the depth of the TX_FIFO. Allowed legal values are 8 and 16 only"]
#[inline(always)]
pub fn tx_entries(&mut self) -> TX_ENTRIES_W {
TX_ENTRIES_W { w: self }
}
}
|
#[doc = "Reader of register SATURATE_INTR_MASKED"]
pub type R = crate::R<u32, super::SATURATE_INTR_MASKED>;
#[doc = "Reader of field `SATURATE_MASKED`"]
pub type SATURATE_MASKED_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Logical and of corresponding request and mask bits."]
#[inline(always)]
pub fn saturate_masked(&self) -> SATURATE_MASKED_R {
SATURATE_MASKED_R::new((self.bits & 0xffff) as u16)
}
}
|
use crate::geometry::{Point, Rect, Size};
/// Texture coordinates (in [0, 1] range).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[repr(C)]
pub struct TexCoord {
pub u: f32,
pub v: f32,
}
impl TexCoord {
pub const TOP_LEFT: TexCoord = TexCoord::new(0.0, 0.0);
pub const TOP_RIGHT: TexCoord = TexCoord::new(1.0, 0.0);
pub const BOTTOM_LEFT: TexCoord = TexCoord::new(0.0, 1.0);
pub const BOTTOM_RIGHT: TexCoord = TexCoord::new(1.0, 1.0);
#[inline]
pub const fn new(u: f32, v: f32) -> Self {
TexCoord { u, v }
}
#[inline]
pub fn normalize(self) -> Self {
TexCoord {
u: self.u % 1.0,
v: self.v % 1.0,
}
}
implement_map!(f32, u, v);
}
impl From<[f32; 2]> for TexCoord {
#[inline]
fn from([u, v]: [f32; 2]) -> Self {
TexCoord { u, v }
}
}
impl From<(f32, f32)> for TexCoord {
#[inline]
fn from((u, v): (f32, f32)) -> Self {
TexCoord { u, v }
}
}
impl From<Point<f32>> for TexCoord {
#[inline]
fn from(Point { x: u, y: v }: Point<f32>) -> Self {
TexCoord { u, v }
}
}
impl From<TexCoord> for [f32; 2] {
#[inline]
fn from(t: TexCoord) -> Self {
[t.u, t.v]
}
}
impl From<TexCoord> for (f32, f32) {
#[inline]
fn from(t: TexCoord) -> Self {
(t.u, t.v)
}
}
implement_ops!(TexCoord, f32);
impl_from_unit_default!(TexCoord);
/// Texture coordinates of a rectangle.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TexRect {
pub top_left: TexCoord,
pub bot_right: TexCoord,
}
impl TexRect {
#[inline]
pub const fn new(top_left: TexCoord, bot_right: TexCoord) -> Self {
Self { top_left, bot_right }
}
pub fn from_rect(rect: impl Into<Rect>, scale: impl Into<Size>) -> Self {
let rect = rect.into();
let this = Self {
top_left: rect.pos.cast().into(),
bot_right: (rect.pos + rect.size.as_point()).cast().into(),
};
this / TexCoord::from(scale.into().as_point())
}
#[inline]
pub fn top_left(&self) -> TexCoord {
self.top_left
}
#[inline]
pub fn bot_right(&self) -> TexCoord {
self.bot_right
}
#[inline]
pub fn top_right(&self) -> TexCoord {
TexCoord {
u: self.bot_right.u,
v: self.top_left.v,
}
}
#[inline]
pub fn bot_left(&self) -> TexCoord {
TexCoord {
u: self.top_left.u,
v: self.bot_right.v,
}
}
implement_map!(TexCoord, top_left, bot_right);
}
impl From<[TexCoord; 2]> for TexRect {
#[inline]
fn from([top_left, bot_right]: [TexCoord; 2]) -> Self {
Self { top_left, bot_right }
}
}
impl From<(TexCoord, TexCoord)> for TexRect {
#[inline]
fn from((top_left, bot_right): (TexCoord, TexCoord)) -> Self {
Self { top_left, bot_right }
}
}
impl From<TexRect> for [TexCoord; 2] {
#[inline]
fn from(tr: TexRect) -> Self {
[tr.top_left, tr.bot_right]
}
}
impl From<TexRect> for (TexCoord, TexCoord) {
#[inline]
fn from(tr: TexRect) -> Self {
(tr.top_left, tr.bot_right)
}
}
impl From<TexRect> for [f32; 4] {
#[inline]
fn from(TexRect { top_left, bot_right }: TexRect) -> Self {
[top_left.u, top_left.v, bot_right.u, bot_right.v]
}
}
impl Default for TexRect {
#[inline]
fn default() -> Self {
TexRect::new(TexCoord::TOP_LEFT, TexCoord::BOTTOM_RIGHT)
}
}
impl_from_unit_default!(TexRect);
impl std::ops::Add<TexCoord> for TexRect {
type Output = Self;
#[inline]
fn add(self, rhs: TexCoord) -> Self::Output {
self.map(|a| a + rhs)
}
}
impl std::ops::Sub<TexCoord> for TexRect {
type Output = Self;
#[inline]
fn sub(self, rhs: TexCoord) -> Self::Output {
self.map(|a| a - rhs)
}
}
impl std::ops::Mul<TexCoord> for TexRect {
type Output = Self;
#[inline]
fn mul(self, rhs: TexCoord) -> Self::Output {
self.map(|a| a * rhs)
}
}
impl std::ops::Div<TexCoord> for TexRect {
type Output = Self;
#[inline]
fn div(self, rhs: TexCoord) -> Self::Output {
self.map(|a| a / rhs)
}
}
impl std::ops::Mul<f32> for TexRect {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.map(|a| a * rhs)
}
}
impl std::ops::Div<f32> for TexRect {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.map(|a| a / rhs)
}
}
|
// Copyright © 2019 Bart Massey
// [This program is licensed under the "MIT License"]
// Please see the file LICENSE in the source
// distribution of this software for license terms.
//! Synthesizer MIDI input.
use std::error::Error;
use std::io;
use std::sync::mpsc;
use midir::MidiInput;
use wmidi::*;
use wmidi::MidiMessage::*;
/// Read and process key events from a MIDI keyboard with the
/// given name.
pub fn read_keys(port_name: &str) -> Result<(), Box<Error>> {
// Keymap indicating which keys are currently down (true).
let mut keymap = [false; 128];
// Channel for communicating events from midir callback.
let (sender, receiver) = mpsc::channel();
// Set up for reading key events.
let input = MidiInput::new("samplr")?;
let inport = (0..input.port_count())
.find(|p| {
let name = input.port_name(*p).unwrap();
let port_index = name.rfind(' ').unwrap();
&name[..port_index] == port_name
})
.ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?;
// Read and process key events.
let _handler = input.connect(
inport,
"samplr-input",
move |_, message: &[u8], _| {
let message = MidiMessage::from_bytes(message).unwrap();
match message {
NoteOn(c, note, velocity) => {
// If velocity is zero, treat as a note off message.
if velocity == 0 {
println!("note off: {}", note);
keymap[note as usize] = false;
sender.send(NoteOff(c, note, velocity)).unwrap();
} else {
println!("note on: {} {}", note, velocity);
keymap[note as usize] = true;
sender.send(NoteOn(c, note, velocity)).unwrap();
}
},
NoteOff(c, note, velocity) => {
println!("note off: {} {}", note, velocity);
keymap[note as usize] = false;
sender.send(NoteOff(c, note, velocity)).unwrap();
},
ActiveSensing => {
// Active sensing ignored for now.
},
// Other messages ignored for now.
m => println!("unrecognized message {:?}", m),
}
},
(),
);
// Wait for stop message to leave.
loop {
let _ = receiver.recv()?;
}
#[allow(unused)]
Ok(())
}
|
///Describ the size of a register
#[repr(u8)]
#[derive(Copy,Clone,Debug,PartialEq,Eq,PartialOrd,Ord)]
pub enum RegSize {
Bit8,
Bit16,
Bit32,
Bit64,
Bit80,
BitMMX,
Bit128,
Bit256,
Bit512
}
impl RegSize {
#[inline(always)]
pub fn byte_size(&self) -> usize {
match self {
&RegSize::Bit8 => 1,
&RegSize::Bit16 => 2,
&RegSize::Bit32 => 4,
&RegSize::Bit64 => 8,
&RegSize::Bit80 => 10,
&RegSize::BitMMX => 8,
&RegSize::Bit128 => 16,
&RegSize::Bit256 => 32,
&RegSize::Bit512 => 64
}
}
}
|
//! [Generic Types], Traits, and Lifetimes
//!
//! # Examples
//!
//! ```
//! use the_book::ch10::sec00::largest;
//!
//! let list = vec![1, 2, 3, 4, 5];
//! assert_eq!(5, largest(&list));
//!
//! let list = vec![5, 4, 3, 2, 1];
//! assert_eq!(5, largest(&list));
//!
//! let list = vec![-1, -2, -3, -4, -5];
//! assert_eq!(-1, largest(&list));
//!
//! let list = vec![-5, -4, -3, -2, -1];
//! assert_eq!(-1, largest(&list));
//! ```
//! [generic types]: https://doc.rust-lang.org/book/ch10-00-generics.html
pub fn largest(list: &[i32]) -> i32 {
let mut largest = -1;
list.iter().for_each(|&item| {
if largest < item {
largest = item;
}
});
largest
}
|
use libmdbx::*;
use std::borrow::Cow;
use tempfile::tempdir;
type Database = libmdbx::Database<NoWriteMap>;
#[test]
fn test_get() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let txn = db.begin_rw_txn().unwrap();
let table = txn.open_table(None).unwrap();
assert_eq!(None, txn.cursor(&table).unwrap().first::<(), ()>().unwrap());
for (k, v) in [(b"key1", b"val1"), (b"key2", b"val2"), (b"key3", b"val3")] {
txn.put(&table, k, v, WriteFlags::empty()).unwrap();
}
let mut cursor = txn.cursor(&table).unwrap();
assert_eq!(cursor.first().unwrap(), Some((*b"key1", *b"val1")));
assert_eq!(cursor.get_current().unwrap(), Some((*b"key1", *b"val1")));
assert_eq!(cursor.next().unwrap(), Some((*b"key2", *b"val2")));
assert_eq!(cursor.prev().unwrap(), Some((*b"key1", *b"val1")));
assert_eq!(cursor.last().unwrap(), Some((*b"key3", *b"val3")));
assert_eq!(cursor.set(b"key1").unwrap(), Some(*b"val1"));
assert_eq!(cursor.set_key(b"key3").unwrap(), Some((*b"key3", *b"val3")));
assert_eq!(
cursor.set_range(b"key2\0").unwrap(),
Some((*b"key3", *b"val3"))
);
}
#[test]
fn test_get_dup() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let txn = db.begin_rw_txn().unwrap();
let table = txn.create_table(None, TableFlags::DUP_SORT).unwrap();
for (k, v) in [
(b"key1", b"val1"),
(b"key1", b"val2"),
(b"key1", b"val3"),
(b"key2", b"val1"),
(b"key2", b"val2"),
(b"key2", b"val3"),
] {
txn.put(&table, k, v, WriteFlags::empty()).unwrap();
}
let mut cursor = txn.cursor(&table).unwrap();
assert_eq!(cursor.first().unwrap(), Some((*b"key1", *b"val1")));
assert_eq!(cursor.first_dup().unwrap(), Some(*b"val1"));
assert_eq!(cursor.get_current().unwrap(), Some((*b"key1", *b"val1")));
assert_eq!(cursor.next_nodup().unwrap(), Some((*b"key2", *b"val1")));
assert_eq!(cursor.next().unwrap(), Some((*b"key2", *b"val2")));
assert_eq!(cursor.prev().unwrap(), Some((*b"key2", *b"val1")));
assert_eq!(cursor.next_dup().unwrap(), Some((*b"key2", *b"val2")));
assert_eq!(cursor.next_dup().unwrap(), Some((*b"key2", *b"val3")));
assert_eq!(cursor.next_dup::<(), ()>().unwrap(), None);
assert_eq!(cursor.prev_dup().unwrap(), Some((*b"key2", *b"val2")));
assert_eq!(cursor.last_dup().unwrap(), Some(*b"val3"));
assert_eq!(cursor.prev_nodup().unwrap(), Some((*b"key1", *b"val3")));
assert_eq!(cursor.next_dup::<(), ()>().unwrap(), None);
assert_eq!(cursor.set(b"key1").unwrap(), Some(*b"val1"));
assert_eq!(cursor.set(b"key2").unwrap(), Some(*b"val1"));
assert_eq!(
cursor.set_range(b"key1\0").unwrap(),
Some((*b"key2", *b"val1"))
);
assert_eq!(cursor.get_both(b"key1", b"val3").unwrap(), Some(*b"val3"));
assert_eq!(cursor.get_both_range::<()>(b"key1", b"val4").unwrap(), None);
assert_eq!(
cursor.get_both_range(b"key2", b"val").unwrap(),
Some(*b"val1")
);
for kv in [
(*b"key2", *b"val3"),
(*b"key2", *b"val2"),
(*b"key2", *b"val1"),
(*b"key1", *b"val3"),
] {
assert_eq!(cursor.last().unwrap(), Some(kv));
cursor.del(WriteFlags::empty()).unwrap();
}
}
#[test]
fn test_get_dupfixed() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let txn = db.begin_rw_txn().unwrap();
let table = txn
.create_table(None, TableFlags::DUP_SORT | TableFlags::DUP_FIXED)
.unwrap();
for (k, v) in [
(b"key1", b"val1"),
(b"key1", b"val2"),
(b"key1", b"val3"),
(b"key2", b"val1"),
(b"key2", b"val2"),
(b"key2", b"val3"),
] {
txn.put(&table, k, v, WriteFlags::empty()).unwrap();
}
let mut cursor = txn.cursor(&table).unwrap();
assert_eq!(cursor.first().unwrap(), Some((*b"key1", *b"val1")));
assert_eq!(cursor.get_multiple().unwrap(), Some(*b"val1val2val3"));
assert_eq!(cursor.next_multiple::<(), ()>().unwrap(), None);
}
#[test]
fn test_iter() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let items = vec![
(*b"key1", *b"val1"),
(*b"key2", *b"val2"),
(*b"key3", *b"val3"),
(*b"key5", *b"val5"),
];
{
let txn = db.begin_rw_txn().unwrap();
let table = txn.open_table(None).unwrap();
for (key, data) in &items {
txn.put(&table, key, data, WriteFlags::empty()).unwrap();
}
assert!(!txn.commit().unwrap());
}
let txn = db.begin_ro_txn().unwrap();
let table = txn.open_table(None).unwrap();
let mut cursor = txn.cursor(&table).unwrap();
// Because Result implements FromIterator, we can collect the iterator
// of items of type Result<_, E> into a Result<Vec<_, E>> by specifying
// the collection type via the turbofish syntax.
assert_eq!(items, cursor.iter().collect::<Result<Vec<_>>>().unwrap());
// Alternately, we can collect it into an appropriately typed variable.
let retr: Result<Vec<_>> = cursor.iter_start().collect();
assert_eq!(items, retr.unwrap());
cursor.set::<()>(b"key2").unwrap();
assert_eq!(
items.clone().into_iter().skip(2).collect::<Vec<_>>(),
cursor.iter().collect::<Result<Vec<_>>>().unwrap()
);
assert_eq!(
items,
cursor.iter_start().collect::<Result<Vec<_>>>().unwrap()
);
assert_eq!(
items.clone().into_iter().skip(1).collect::<Vec<_>>(),
cursor
.iter_from(b"key2")
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
items.into_iter().skip(3).collect::<Vec<_>>(),
cursor
.iter_from(b"key4")
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
Vec::<((), ())>::new(),
cursor
.iter_from(b"key6")
.collect::<Result<Vec<_>>>()
.unwrap()
);
}
#[test]
fn test_iter_empty_database() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let txn = db.begin_ro_txn().unwrap();
let table = txn.open_table(None).unwrap();
let mut cursor = txn.cursor(&table).unwrap();
assert!(cursor.iter::<(), ()>().next().is_none());
assert!(cursor.iter_start::<(), ()>().next().is_none());
assert!(cursor.iter_from::<(), ()>(b"foo").next().is_none());
}
#[test]
fn test_iter_empty_dup_database() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let txn = db.begin_rw_txn().unwrap();
txn.create_table(None, TableFlags::DUP_SORT).unwrap();
txn.commit().unwrap();
let txn = db.begin_ro_txn().unwrap();
let table = txn.open_table(None).unwrap();
let mut cursor = txn.cursor(&table).unwrap();
assert!(cursor.iter::<(), ()>().next().is_none());
assert!(cursor.iter_start::<(), ()>().next().is_none());
assert!(cursor.iter_from::<(), ()>(b"foo").next().is_none());
assert!(cursor.iter_from::<(), ()>(b"foo").next().is_none());
assert!(cursor.iter_dup::<(), ()>().flatten().next().is_none());
assert!(cursor.iter_dup_start::<(), ()>().flatten().next().is_none());
assert!(cursor
.iter_dup_from::<(), ()>(b"foo")
.flatten()
.next()
.is_none());
assert!(cursor.iter_dup_of::<(), ()>(b"foo").next().is_none());
}
#[test]
fn test_iter_dup() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let txn = db.begin_rw_txn().unwrap();
txn.create_table(None, TableFlags::DUP_SORT).unwrap();
txn.commit().unwrap();
let items = [
(b"a", b"1"),
(b"a", b"2"),
(b"a", b"3"),
(b"b", b"1"),
(b"b", b"2"),
(b"b", b"3"),
(b"c", b"1"),
(b"c", b"2"),
(b"c", b"3"),
(b"e", b"1"),
(b"e", b"2"),
(b"e", b"3"),
]
.iter()
.map(|&(&k, &v)| (k, v))
.collect::<Vec<_>>();
{
let txn = db.begin_rw_txn().unwrap();
for (key, data) in items.clone() {
let table = txn.open_table(None).unwrap();
txn.put(&table, key, data, WriteFlags::empty()).unwrap();
}
txn.commit().unwrap();
}
let txn = db.begin_ro_txn().unwrap();
let table = txn.open_table(None).unwrap();
let mut cursor = txn.cursor(&table).unwrap();
assert_eq!(
items,
cursor
.iter_dup()
.flatten()
.collect::<Result<Vec<_>>>()
.unwrap()
);
cursor.set::<()>(b"b").unwrap();
assert_eq!(
items.iter().copied().skip(4).collect::<Vec<_>>(),
cursor
.iter_dup()
.flatten()
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
items,
cursor
.iter_dup_start()
.flatten()
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
items.iter().copied().skip(3).collect::<Vec<_>>(),
cursor
.iter_dup_from(b"b")
.flatten()
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
items.iter().copied().skip(3).collect::<Vec<_>>(),
cursor
.iter_dup_from(b"ab")
.flatten()
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
items.iter().copied().skip(9).collect::<Vec<_>>(),
cursor
.iter_dup_from(b"d")
.flatten()
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
Vec::<([u8; 1], [u8; 1])>::new(),
cursor
.iter_dup_from(b"f")
.flatten()
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
items.iter().copied().skip(3).take(3).collect::<Vec<_>>(),
cursor
.iter_dup_of(b"b")
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(0, cursor.iter_dup_of::<(), ()>(b"foo").count());
}
#[test]
fn test_iter_del_get() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let items = vec![(*b"a", *b"1"), (*b"b", *b"2")];
{
let txn = db.begin_rw_txn().unwrap();
let table = txn.create_table(None, TableFlags::DUP_SORT).unwrap();
assert_eq!(
txn.cursor(&table)
.unwrap()
.iter_dup_of::<(), ()>(b"a")
.collect::<Result<Vec<_>>>()
.unwrap()
.len(),
0
);
txn.commit().unwrap();
}
{
let txn = db.begin_rw_txn().unwrap();
let table = txn.open_table(None).unwrap();
for (key, data) in &items {
txn.put(&table, key, data, WriteFlags::empty()).unwrap();
}
txn.commit().unwrap();
}
let txn = db.begin_rw_txn().unwrap();
let table = txn.open_table(None).unwrap();
let mut cursor = txn.cursor(&table).unwrap();
assert_eq!(
items,
cursor
.iter_dup()
.flatten()
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(
items.iter().copied().take(1).collect::<Vec<(_, _)>>(),
cursor
.iter_dup_of(b"a")
.collect::<Result<Vec<_>>>()
.unwrap()
);
assert_eq!(cursor.set(b"a").unwrap(), Some(*b"1"));
cursor.del(WriteFlags::empty()).unwrap();
assert_eq!(
cursor
.iter_dup_of::<(), ()>(b"a")
.collect::<Result<Vec<_>>>()
.unwrap()
.len(),
0
);
}
#[test]
fn test_put_del() {
let dir = tempdir().unwrap();
let db = Database::new().open(dir.path()).unwrap();
let txn = db.begin_rw_txn().unwrap();
let table = txn.open_table(None).unwrap();
let mut cursor = txn.cursor(&table).unwrap();
for (k, v) in [(b"key1", b"val1"), (b"key2", b"val2"), (b"key3", b"val3")] {
cursor.put(k, v, WriteFlags::empty()).unwrap();
}
assert_eq!(
cursor.get_current().unwrap().unwrap(),
(
Cow::Borrowed(b"key3" as &[u8]),
Cow::Borrowed(b"val3" as &[u8])
)
);
cursor.del(WriteFlags::empty()).unwrap();
assert_eq!(cursor.get_current::<Vec<u8>, Vec<u8>>().unwrap(), None);
assert_eq!(
cursor.last().unwrap().unwrap(),
(
Cow::Borrowed(b"key2" as &[u8]),
Cow::Borrowed(b"val2" as &[u8])
)
);
}
|
use mongodb::bson::{document::Document, oid::ObjectId};
use serde::Serialize;
#[derive(Serialize, Clone)]
pub struct Source {
#[serde(skip)]
id: Option<ObjectId>,
name: Option<String>,
url: Option<String>,
}
impl From<&Document> for Source {
fn from(doc: &Document) -> Self {
Self {
id: doc.get_object_id("_id").map(|id| id.clone()).ok(),
name: doc.get_str("name").map(String::from).ok(),
url: doc.get_str("url").map(String::from).ok(),
}
}
}
|
use super::Expression;
use super::BinaryOp;
impl Expression
{
pub fn width(&self) -> Option<usize>
{
match self
{
&Expression::BinaryOp(_, _, BinaryOp::Concat, ref lhs, ref rhs) =>
{
let lhs_width = lhs.width();
let rhs_width = rhs.width();
if lhs_width.is_none() || rhs_width.is_none()
{ return None; }
Some(lhs_width.unwrap() + rhs_width.unwrap())
}
&Expression::BitSlice(_, _, left, right, _) => Some(left + 1 - right),
&Expression::Block(_, ref exprs) =>
{
match exprs.last()
{
None => None,
Some(expr) => expr.width()
}
}
_ => None
}
}
pub fn slice(&self) -> Option<(usize, usize)>
{
match self
{
&Expression::BinaryOp(_, _, BinaryOp::Concat, _, _) => self.width().map(|w| (w - 1, 0)),
&Expression::BitSlice(_, _, left, right, _) => Some((left, right)),
&Expression::Block(_, ref exprs) =>
{
match exprs.last()
{
None => None,
Some(expr) => expr.slice()
}
}
_ => None
}
}
} |
use pretty_assertions::assert_eq;
use super::*;
use crate::ast::tests::Locator;
#[test]
fn function_call_with_unbalanced_braces() {
let mut p = Parser::new(r#"from() |> range() |> map(fn: (r) => { return r._value )"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 56),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 56),
..BaseNode::default()
},
expression: Expression::PipeExpr(Box::new(PipeExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 56),
..BaseNode::default()
},
argument: Expression::PipeExpr(Box::new(PipeExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 18),
..BaseNode::default()
},
argument: Expression::Call(Box::new(CallExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 7),
..BaseNode::default()
},
callee: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
name: "from".to_string()
}),
lparen: vec![],
arguments: vec![],
rparen: vec![],
})),
call: CallExpr {
base: BaseNode {
location: loc.get(1, 11, 1, 18),
..BaseNode::default()
},
callee: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 11, 1, 16),
..BaseNode::default()
},
name: "range".to_string()
}),
lparen: vec![],
arguments: vec![],
rparen: vec![],
}
})),
call: CallExpr {
base: BaseNode {
location: loc.get(1, 22, 1, 56),
..BaseNode::default()
},
callee: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 22, 1, 25),
..BaseNode::default()
},
name: "map".to_string()
}),
lparen: vec![],
arguments: vec![Expression::Object(Box::new(ObjectExpr {
base: BaseNode {
location: loc.get(1, 26, 1, 56),
..BaseNode::default()
},
lbrace: vec![],
with: None,
properties: vec![Property {
base: BaseNode {
location: loc.get(1, 26, 1, 56),
..BaseNode::default()
},
key: PropertyKey::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 26, 1, 28),
..BaseNode::default()
},
name: "fn".to_string()
}),
separator: vec![],
value: Some(Expression::Function(Box::new(FunctionExpr {
base: BaseNode {
location: loc.get(1, 30, 1, 56),
..BaseNode::default()
},
lparen: vec![],
params: vec![Property {
base: BaseNode {
location: loc.get(1, 31, 1, 32),
..BaseNode::default()
},
key: PropertyKey::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 31, 1, 32),
..BaseNode::default()
},
name: "r".to_string()
}),
separator: vec![],
value: None,
comma: vec![],
}],
rparen: vec![],
arrow: vec![],
body: FunctionBody::Block(Block {
base: BaseNode {
location: loc.get(1, 37, 1, 56),
errors: vec!["expected RBRACE, got RPAREN".to_string()],
..BaseNode::default()
},
lbrace: vec![],
body: vec![Statement::Return(Box::new(ReturnStmt {
base: BaseNode {
location: loc.get(1, 39, 1, 54),
..BaseNode::default()
},
argument: Expression::Member(Box::new(MemberExpr {
base: BaseNode {
location: loc.get(1, 46, 1, 54),
..BaseNode::default()
},
object: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 46, 1, 47),
..BaseNode::default()
},
name: "r".to_string()
}),
lbrack: vec![],
property: PropertyKey::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 48, 1, 54),
..BaseNode::default()
},
name: "_value".to_string()
}),
rbrack: vec![],
}))
}))],
rbrace: vec![],
}),
}))),
comma: vec![],
}],
rbrace: vec![],
}))],
rparen: vec![],
}
}))
}))],
eof: vec![],
},
)
}
// TODO(affo): that error is injected by ast.Check().
#[test]
fn illegal_statement_token() {
let mut p = Parser::new(r#"@ ident"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 8),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![
Statement::Bad(Box::new(BadStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 2),
// errors: vec!["invalid statement @1:1-1:2: @".to_string()]
..BaseNode::default()
},
text: "@".to_string()
})),
Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 3, 1, 8),
..BaseNode::default()
},
expression: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 3, 1, 8),
..BaseNode::default()
},
name: "ident".to_string()
})
}))
],
eof: vec![],
},
)
}
// TODO(affo): that error is injected by ast.Check().
#[test]
fn multiple_idents_in_parens() {
let mut p = Parser::new(r#"(a b)"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
expression: Expression::Paren(Box::new(ParenExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
lparen: vec![],
expression: Expression::Binary(Box::new(BinaryExpr {
// TODO(affo): ast.Check would add the error "expected an operator between two expressions".
base: BaseNode {
location: loc.get(1, 2, 1, 5),
..BaseNode::default()
},
operator: Operator::InvalidOperator,
left: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 2, 1, 3),
..BaseNode::default()
},
name: "a".to_string()
}),
right: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 4, 1, 5),
..BaseNode::default()
},
name: "b".to_string()
})
})),
rparen: vec![],
}))
}))],
eof: vec![],
},
)
}
// TODO(affo): that error is injected by ast.Check().
// TODO(jsternberg): Parens aren't recorded correctly in the source and are mostly ignored.
#[test]
fn missing_left_hand_side() {
let mut p = Parser::new(r#"(*b)"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
expression: Expression::Paren(Box::new(ParenExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
lparen: vec![],
expression: Expression::Binary(Box::new(BinaryExpr {
// TODO(affo): this should be like this:
// base: BaseNode {location: ..., errors: vec!["missing left hand side of expression".to_string()] },
base: BaseNode {
location: loc.get(1, 2, 1, 4),
..BaseNode::default()
},
operator: Operator::MultiplicationOperator,
left: Expression::Bad(Box::new(BadExpr {
base: BaseNode {
location: loc.get(1, 2, 1, 3),
..BaseNode::default()
},
text: "invalid token for primary expression: MUL".to_string(),
expression: None
})),
right: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 3, 1, 4),
..BaseNode::default()
},
name: "b".to_string()
})
})),
rparen: vec![],
}))
}))],
eof: vec![],
},
)
}
// TODO(affo): that error is injected by ast.Check().
// TODO(jsternberg): Parens aren't recorded correctly in the source and are mostly ignored.
#[test]
fn missing_right_hand_side() {
let mut p = Parser::new(r#"(a*)"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
expression: Expression::Paren(Box::new(ParenExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
lparen: vec![],
expression: Expression::Binary(Box::new(BinaryExpr {
// TODO(affo): this should be like this:
// base: BaseNode {location: ..., errors: vec!["missing right hand side of expression".to_string()] },
base: BaseNode {
location: loc.get(1, 2, 1, 5),
..BaseNode::default()
},
operator: Operator::MultiplicationOperator,
left: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 2, 1, 3),
..BaseNode::default()
},
name: "a".to_string()
}),
right: Expression::Bad(Box::new(BadExpr {
base: BaseNode {
location: loc.get(1, 4, 1, 5),
..BaseNode::default()
},
text: "invalid token for primary expression: RPAREN".to_string(),
expression: None
})),
})),
rparen: vec![],
}))
}))],
eof: vec![],
},
)
}
#[test]
fn illegal_expression() {
let mut p = Parser::new(r#"(@)"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 4),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 4),
..BaseNode::default()
},
expression: Expression::Paren(Box::new(ParenExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 4),
errors: vec!["invalid expression @1:2-1:3: @".to_string()],
..BaseNode::default()
},
lparen: vec![],
expression: Expression::Bad(Box::new(BadExpr {
base: BaseNode {
location: loc.get(1, 2, 1, 3),
..BaseNode::default()
},
text: "@".to_string(),
expression: None
})),
rparen: vec![],
}))
}))],
eof: vec![],
},
)
}
// NOTE(affo): this is slightly different from Go. We have a BadExpr in the body.
#[test]
fn missing_arrow_in_function_expression() {
let mut p = Parser::new(r#"(a, b) a + b"#);
let parsed = p.parse_file("".to_string());
expect_test::expect![[r#"
File {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 1,
},
end: Position {
line: 1,
column: 13,
},
source: Some(
"(a, b) a + b",
),
},
comments: [],
errors: [],
},
name: "",
metadata: "parser-type=rust",
package: None,
imports: [],
body: [
Expr(
ExprStmt {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 1,
},
end: Position {
line: 1,
column: 13,
},
source: Some(
"(a, b) a + b",
),
},
comments: [],
errors: [],
},
expression: Function(
FunctionExpr {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 1,
},
end: Position {
line: 1,
column: 13,
},
source: Some(
"(a, b) a + b",
),
},
comments: [],
errors: [],
},
lparen: [],
params: [
Property {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 2,
},
end: Position {
line: 1,
column: 3,
},
source: Some(
"a",
),
},
comments: [],
errors: [],
},
key: Identifier(
Identifier {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 2,
},
end: Position {
line: 1,
column: 3,
},
source: Some(
"a",
),
},
comments: [],
errors: [],
},
name: "a",
},
),
separator: [],
value: None,
comma: [],
},
Property {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 5,
},
end: Position {
line: 1,
column: 6,
},
source: Some(
"b",
),
},
comments: [],
errors: [],
},
key: Identifier(
Identifier {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 5,
},
end: Position {
line: 1,
column: 6,
},
source: Some(
"b",
),
},
comments: [],
errors: [],
},
name: "b",
},
),
separator: [],
value: None,
comma: [],
},
],
rparen: [],
arrow: [],
body: Expr(
Binary(
BinaryExpr {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 8,
},
end: Position {
line: 1,
column: 13,
},
source: Some(
"a + b",
),
},
comments: [],
errors: [],
},
operator: AdditionOperator,
left: Identifier(
Identifier {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 8,
},
end: Position {
line: 1,
column: 9,
},
source: Some(
"a",
),
},
comments: [],
errors: [
"expected ARROW, got IDENT (a) at 1:8",
],
},
name: "a",
},
),
right: Identifier(
Identifier {
base: BaseNode {
location: SourceLocation {
file: None,
start: Position {
line: 1,
column: 12,
},
end: Position {
line: 1,
column: 13,
},
source: Some(
"b",
),
},
comments: [],
errors: [],
},
name: "b",
},
),
},
),
),
},
),
},
),
],
eof: [],
}
"#]]
.assert_debug_eq(&parsed);
}
#[test]
fn index_with_unclosed_bracket() {
let mut p = Parser::new(r#"a[b()"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
expression: Expression::Index(Box::new(IndexExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
errors: vec!["expected RBRACK, got EOF".to_string()],
..BaseNode::default()
},
array: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 1, 1, 2),
..BaseNode::default()
},
name: "a".to_string()
}),
lbrack: vec![],
index: Expression::Call(Box::new(CallExpr {
base: BaseNode {
location: loc.get(1, 3, 1, 6),
..BaseNode::default()
},
callee: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 3, 1, 4),
..BaseNode::default()
},
name: "b".to_string()
}),
lparen: vec![],
arguments: vec![],
rparen: vec![],
})),
rbrack: vec![],
}))
}))],
eof: vec![],
},
)
}
#[test]
fn index_with_unbalanced_parenthesis() {
let mut p = Parser::new(r#"a[b(]"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
expression: Expression::Index(Box::new(IndexExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
array: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 1, 1, 2),
..BaseNode::default()
},
name: "a".to_string()
}),
lbrack: vec![],
index: Expression::Call(Box::new(CallExpr {
base: BaseNode {
location: loc.get(1, 3, 1, 6),
errors: vec!["expected RPAREN, got RBRACK".to_string()],
..BaseNode::default()
},
callee: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 3, 1, 4),
..BaseNode::default()
},
name: "b".to_string()
}),
lparen: vec![],
arguments: vec![],
rparen: vec![],
})),
rbrack: vec![],
}))
}))],
eof: vec![],
},
)
}
#[test]
fn index_with_unexpected_rparen() {
let mut p = Parser::new(r#"a[b)]"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
..BaseNode::default()
},
expression: Expression::Index(Box::new(IndexExpr {
base: BaseNode {
location: loc.get(1, 1, 1, 6),
errors: vec!["invalid expression @1:4-1:5: )".to_string()],
..BaseNode::default()
},
array: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 1, 1, 2),
..BaseNode::default()
},
name: "a".to_string()
}),
lbrack: vec![],
index: Expression::Identifier(Identifier {
base: BaseNode {
location: loc.get(1, 3, 1, 4),
..BaseNode::default()
},
name: "b".to_string()
}),
rbrack: vec![],
}))
}))],
eof: vec![],
},
)
}
#[test]
fn int_literal_zero_prefix() {
let mut p = Parser::new(r#"0123"#);
let parsed = p.parse_file("".to_string());
let loc = Locator::new(&p.source[..]);
assert_eq!(
parsed,
File {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
name: "".to_string(),
metadata: "parser-type=rust".to_string(),
package: None,
imports: vec![],
body: vec![Statement::Expr(Box::new(ExprStmt {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
..BaseNode::default()
},
expression: Expression::Integer(IntegerLit {
base: BaseNode {
location: loc.get(1, 1, 1, 5),
errors: vec![
"invalid integer literal \"0123\": nonzero value cannot start with 0"
.to_string()
],
..BaseNode::default()
},
value: 0,
})
}))],
eof: vec![],
},
)
}
#[test]
fn issue_4231() {
let mut p = Parser::new(
r#"
map(fn: (r) => ({ r with _value: if true and false then 1}) )
"#,
);
let parsed = p.parse_file("".to_string());
expect_test::expect![[r#"error @2:34-2:59: expected ELSE, got RBRACE (}) at 2:58"#]].assert_eq(
&ast::check::check(ast::walk::Node::File(&parsed))
.unwrap_err()
.to_string(),
);
}
|
fn main() {
os_check();
#[cfg(feature = "name")]
my_name();
println!("this line out of `cfg` scope.");
}
// 这个函数仅当目标系统是 Linux 的时候才会编译
#[cfg(target_os = "linux")]
fn are_you_on_linux() {
println!("You are running linux!");
}
// 而这个函数仅当目标系统 **不是** Linux 时才会编译
#[cfg(not(target_os = "linux"))]
fn are_you_on_linux() {
println!("You are *not* running linux!");
}
fn os_check() {
are_you_on_linux();
println!("Are you sure?");
if cfg!(target_os = "linux") {
println!("Yes. It's definitely linux!");
} else {
println!("Yes. It's definitely *not* linux!");
}
}
#[cfg(feature = "name")]
// cfg影响下面的一行或一个程序块
// 需要在编译选项上支持:
// ```
// $ cargo build --features name
// ```
fn my_name() {
println!("feature `name` active! I'm John");
}
|
use std::io::stdin;
fn main() {
let mut input = String::new();
stdin().read_line(&mut input).unwrap();
// read_line leaves a trailing newline, which trim removes
let command = input.trim();
Command::new(command).spawn().unwrap();
}
|
extern crate hyper;
extern crate rustc_serialize;
pub mod sg_client;
pub mod mail;
|
pub mod solutions;
mod intcode;
|
use crate::{
keypair::PublicKey,
result::{anyhow, Result},
};
use helium_proto::*;
pub trait TxnPayer {
fn payer(&self) -> Result<Option<PublicKey>>;
}
impl TxnPayer for BlockchainTxn {
fn payer(&self) -> Result<Option<PublicKey>> {
let maybe_payer = |v: &[u8]| {
if v.is_empty() {
None
} else {
Some(PublicKey::from_bytes(v).ok()?)
}
};
match &self.txn {
Some(Txn::AddGateway(t)) => Ok(maybe_payer(&t.payer)),
Some(Txn::AssertLocation(t)) => Ok(maybe_payer(&t.payer)),
Some(Txn::CreateHtlc(t)) => Ok(maybe_payer(&t.payer)),
Some(Txn::Payment(t)) => Ok(maybe_payer(&t.payer)),
Some(Txn::PaymentV2(t)) => Ok(maybe_payer(&t.payer)),
Some(Txn::Oui(t)) => Ok(maybe_payer(&t.payer)),
Some(Txn::TokenBurn(t)) => Ok(maybe_payer(&t.payer)),
Some(Txn::TransferHotspot(t)) => Ok(maybe_payer(&t.buyer)),
_ => Err(anyhow!("Unsupported transaction")),
}
}
}
|
#[doc = "Reader of register OSCLK_DR1"]
pub type R = crate::R<u32, super::OSCLK_DR1>;
#[doc = "Reader of field `ADDER_MSB`"]
pub type ADDER_MSB_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:6 - These bits return the upper 7 bits of the oscillator locking circuits adder output."]
#[inline(always)]
pub fn adder_msb(&self) -> ADDER_MSB_R {
ADDER_MSB_R::new((self.bits & 0x7f) as u8)
}
}
|
#[doc = "Register `CIFR` reader"]
pub type R = crate::R<CIFR_SPEC>;
#[doc = "Field `LSIRDYF` reader - LSI ready interrupt flag"]
pub type LSIRDYF_R = crate::BitReader;
#[doc = "Field `LSERDYF` reader - LSE ready interrupt flag"]
pub type LSERDYF_R = crate::BitReader;
#[doc = "Field `HSIRDYF` reader - HSI ready interrupt flag"]
pub type HSIRDYF_R = crate::BitReader;
#[doc = "Field `HSERDYF` reader - HSE ready interrupt flag"]
pub type HSERDYF_R = crate::BitReader;
#[doc = "Field `PLLRDYF` reader - PLL ready interrupt flag"]
pub type PLLRDYF_R = crate::BitReader;
#[doc = "Field `CSSF` reader - Clock security system interrupt flag"]
pub type CSSF_R = crate::BitReader;
#[doc = "Field `LSECSSF` reader - LSE Clock security system interrupt flag"]
pub type LSECSSF_R = crate::BitReader;
#[doc = "Field `HSI48RDYF` reader - HSI48 ready interrupt flag"]
pub type HSI48RDYF_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - LSI ready interrupt flag"]
#[inline(always)]
pub fn lsirdyf(&self) -> LSIRDYF_R {
LSIRDYF_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - LSE ready interrupt flag"]
#[inline(always)]
pub fn lserdyf(&self) -> LSERDYF_R {
LSERDYF_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 3 - HSI ready interrupt flag"]
#[inline(always)]
pub fn hsirdyf(&self) -> HSIRDYF_R {
HSIRDYF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - HSE ready interrupt flag"]
#[inline(always)]
pub fn hserdyf(&self) -> HSERDYF_R {
HSERDYF_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - PLL ready interrupt flag"]
#[inline(always)]
pub fn pllrdyf(&self) -> PLLRDYF_R {
PLLRDYF_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 8 - Clock security system interrupt flag"]
#[inline(always)]
pub fn cssf(&self) -> CSSF_R {
CSSF_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - LSE Clock security system interrupt flag"]
#[inline(always)]
pub fn lsecssf(&self) -> LSECSSF_R {
LSECSSF_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - HSI48 ready interrupt flag"]
#[inline(always)]
pub fn hsi48rdyf(&self) -> HSI48RDYF_R {
HSI48RDYF_R::new(((self.bits >> 10) & 1) != 0)
}
}
#[doc = "Clock interrupt flag register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cifr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CIFR_SPEC;
impl crate::RegisterSpec for CIFR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cifr::R`](R) reader structure"]
impl crate::Readable for CIFR_SPEC {}
#[doc = "`reset()` method sets CIFR to value 0"]
impl crate::Resettable for CIFR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
pub mod health;
pub mod position;
use crate::{component::Component, component::Health, component::Size, entity::Entity};
#[allow(dead_code)]
pub fn get_health(entity: &mut Entity) -> &Health {
let entity_health = match entity
.get_component(|c| {
if let Component::Health(_) = c {
true
} else {
false
}
})
.unwrap()
{
Component::Health(value) => value,
_ => panic!("No position component found."),
};
entity_health
}
#[allow(dead_code)]
pub fn get_size(entity: &mut Entity) -> &Size {
let entity_size = match entity
.get_component(|c| {
if let Component::Size(_) = c {
true
} else {
false
}
})
.unwrap()
{
Component::Size(value) => value,
_ => panic!("No Size component found."),
};
entity_size
}
pub fn print(c: &Component) {
println!("{:#?}", c);
}
|
/*pub enum Result<T, E> {
Ok(T),
Err(E),
}*/
use std::env::args;
use std::fs::File;
use std::io;
use std::io::Read;
#[derive(Debug)]
pub enum MyErr {
IOErr(std::io::Error),
}
// if there were many Error types in being joined into this one type then each From means you can
// just use into and all the errors work together
// You can also use match on teh error type to decide on your next action
impl From<io::Error> for MyErr {
fn from(e: io::Error) -> Self {
MyErr::IOErr(e)
}
}
fn main() {
for a in args().skip(1) {
let w = count_ws(&a);
let w2 = count_ws2(&a);
println!("{}, has {:?} 'w's", a, w);
if let (Ok(a), Ok(b)) = (&w, &w2) {
assert_eq!(a, b);
println!("All OK");
}
//let g = w2.expect("Shold we have an error here");
//println!("g = {}", g);
//you dont have to use match to make small changes map_err also helps to change the error
//type
let big = w.map(|n| n > 10);
println!("big = {:?}", big);
}
println!("Hello, world!");
}
pub fn count_ws(filename: &str) -> Result<i32, MyErr> {
let mut f = match File::open(filename) {
Ok(v) => v,
Err(e) => return Err(e.into()),
};
let mut s = String::new();
if let Err(e) = f.read_to_string(&mut s) {
return Err(MyErr::IOErr(e));
}
let mut res = 0;
for c in s.chars() {
//chars reades unicode points one at a time
if c == 'w' {
res += 1;
}
}
Ok(res)
}
pub fn count_ws2(filename: &str) -> Result<i32, MyErr> {
let mut s = String::new();
File::open(filename)?.read_to_string(&mut s)?;
Ok(s.chars().fold(0, |n, c| if c == 'w' { n + 1 } else { n }))
}
|
use core::ops::{Add, Sub};
/// Trait defined over generic 2D points P which themselves are generic over F
/// Many libraries already provide Point-types and the mathematical operations
/// that we need for working with curves, so that implementing methods requires mostly wrapping.
/// Keeping the trait as minimal as possible to make integration with other libraries easy
pub trait Point: Add + Sub + Copy + PartialEq + Default
{
type Scalar;
fn x(&self) -> Self::Scalar;
fn y(&self) -> Self::Scalar; // return 0.0 if dim < 2 ?
// TODO / TBD
// - maybe add a z() function for most common use cases, returning 0.0 if dim < 3 ?
// - define an iterator for the dimensions, would make generic derivatives easier
// OR define a dim() method to depend on that ?
fn distance(&self, other: Self) -> Self::Scalar;
fn abs(&self) -> Self::Scalar;
} |
use std::collections::HashMap;
use lazy_static::lazy_static;
use rand::{seq::SliceRandom, thread_rng, Rng};
use regex::Regex;
use reqwest::{Client, Url};
use serde::Deserialize;
use serde_json::Value as JsonValue;
use strum_macros::{EnumString, ToString};
lazy_static! {
static ref CLIENT: Client = Client::builder().gzip(true).brotli(true).build().unwrap();
static ref IMAGE_EXT_RE: Regex = Regex::new(r"^.*(png|gif|jpeg|jpg)$").unwrap();
}
#[derive(Clone, Deserialize)]
pub struct ValorantStatus {
pub name: String,
pub regions: Vec<Region>,
}
#[derive(Clone, Deserialize)]
pub struct Region {
pub name: String,
pub maintenances: Vec<Incident>,
pub incidents: Vec<Incident>,
}
#[derive(Clone, Deserialize)]
pub struct Incident {
pub description: String,
pub created_at: String,
pub platforms: Vec<String>,
pub maintenance_status: Option<String>,
pub incident_severity: Option<String>,
pub updates: Vec<Update>,
pub updated_at: Option<String>,
}
#[derive(Clone, Deserialize)]
pub struct Update {
pub description: String,
pub created_at: String,
pub updated_at: String,
}
pub async fn get_valorant_status() -> anyhow::Result<ValorantStatus> {
Ok(CLIENT
.get(Url::parse("https://riotstatus.vercel.app/valorant")?)
.send()
.await?
.json::<Vec<ValorantStatus>>()
.await?[0]
.clone())
}
// Structs used to deserialize the output of the urban dictionary api call.
#[derive(Deserialize, Clone)]
pub struct UrbanDict {
pub definition: String,
pub permalink: String,
pub thumbs_up: u32,
pub thumbs_down: u32,
pub author: String,
pub written_on: String,
pub example: String,
pub word: String,
}
#[derive(Deserialize)]
pub struct UrbanList {
pub list: Vec<UrbanDict>,
}
pub async fn urban_dict<S: Into<String>>(term: S) -> anyhow::Result<UrbanList> {
Ok(CLIENT
.get(Url::parse_with_params(
"http://api.urbandictionary.com/v0/define",
&[("term", term.into())],
)?)
.send()
.await?
.json::<UrbanList>()
.await?)
}
// Structs used to deserialize the output of the dictionary api call.
#[derive(Debug, Deserialize)]
pub struct DictionaryElement {
pub word: String,
pub phonetic: Option<String>,
pub origin: Option<String>,
pub meanings: Vec<Meaning>,
}
#[derive(Debug, Deserialize)]
pub struct Meaning {
#[serde(rename = "partOfSpeech")]
pub part_of_speech: Option<String>,
pub definitions: Vec<Definition>,
}
#[derive(Debug, Deserialize)]
pub struct Definition {
pub definition: String,
pub synonyms: Option<Vec<String>>,
pub example: Option<String>,
}
pub async fn define_term<S: Into<String>>(
word: S,
lang: S,
) -> anyhow::Result<Vec<DictionaryElement>> {
Ok(CLIENT
.get(
Url::parse("https://api.dictionaryapi.dev/api/v2/entries/")?
.join(&(lang.into() + "/"))?
.join(&word.into())?,
)
.send()
.await?
.json::<Vec<DictionaryElement>>()
.await?)
}
// Structs used to deserialize the output of the chuck norris joke api call.
#[derive(Debug, Deserialize)]
pub struct ChuckResponse {
pub categories: Option<Vec<String>>,
pub value: Option<String>,
}
pub async fn get_chuck() -> anyhow::Result<ChuckResponse> {
Ok(CLIENT
.get(Url::parse("https://api.chucknorris.io/jokes/random")?)
.send()
.await?
.json::<ChuckResponse>()
.await?)
}
pub async fn neko_api<S: Into<String>>(
endpoint: S,
img: bool,
) -> anyhow::Result<HashMap<String, String>> {
let mut url = Url::parse("https://nekos.life/api/v2/")?;
if img {
url = url.join("img/")?;
}
url = url.join(&endpoint.into())?;
Ok(CLIENT
.get(url)
.send()
.await?
.json::<HashMap<String, String>>()
.await?)
}
pub async fn get_translate<S: Into<String>>(target: S, text: S) -> anyhow::Result<String> {
Ok(CLIENT
.get(Url::parse_with_params(
"https://translate.googleapis.com/translate_a/single",
&[
("client", "gtx"),
("ie", "UTF-8"),
("oe", "UTF-8"),
("dt", "t"),
("sl", "auto"),
("tl", &target.into()),
("q", &text.into()),
],
)?)
.send()
.await?
.json::<JsonValue>()
.await?
.as_array()
.unwrap()[0]
.as_array()
.unwrap()[0]
.as_array()
.unwrap()[0]
.as_str()
.unwrap()
.to_string())
}
#[derive(Clone, Deserialize, Debug)]
pub struct TriviaResponse {
pub response_code: u8,
pub results: Vec<TriviaResult>,
}
#[derive(Clone, Deserialize, Debug)]
pub struct TriviaResult {
pub category: String,
#[serde(rename = "type")]
pub question_type: String,
pub difficulty: String,
pub question: String,
pub correct_answer: String,
pub incorrect_answers: Vec<String>,
}
#[derive(Copy, Clone, Deserialize, Debug, EnumString)]
pub enum TriviaCategory {
Any,
GeneralKnowledge,
EntertainmentBooks,
EntertainmentFilm,
EntertainmentMusic,
EntertainmentMusicalsAndTheatres,
EntertainmentTelevision,
EntertainmentVideoGames,
EntertainmentBoardGames,
ScienceNature,
ScienceComputers,
ScienceMathematics,
Mythology,
Sports,
Geography,
History,
Politics,
Art,
Celebrities,
Animals,
Vehicles,
EntertainmentComics,
ScienceGadgets,
EntertainmentJapaneseAnimeAndManga,
EntertainmentCartoonAndAnimations,
}
#[derive(Copy, Clone, Deserialize, Debug, EnumString, ToString)]
pub enum TriviaDifficulty {
Any,
Easy,
Medium,
Hard,
}
pub async fn get_trivia(
amount: usize,
category: TriviaCategory,
difficulty: TriviaDifficulty,
) -> anyhow::Result<TriviaResponse> {
let mut difficulty_str: String = difficulty.to_string().to_lowercase();
if difficulty_str.contains("any") {
difficulty_str = "0".to_string();
}
Ok(CLIENT
.get("https://opentdb.com/api.php")
.query(&[
("amount", amount.to_string()),
("category", (category as u8).to_string()),
("difficulty", difficulty_str),
])
.send()
.await?
.json::<TriviaResponse>()
.await?)
}
// Structs used to deserialize the output of the reddit api.
#[derive(Deserialize, Clone)]
pub struct RedditPost {
pub title: String,
pub subreddit_name_prefixed: String,
pub selftext: String,
pub downs: i64,
pub ups: i64,
pub created: f64,
pub url: String,
pub over_18: bool,
pub permalink: String,
}
#[derive(Deserialize)]
struct RedditDataChild {
data: RedditPost,
}
#[derive(Deserialize)]
struct RedditData {
dist: i64,
children: Vec<RedditDataChild>,
}
#[derive(Deserialize)]
struct RedditResponse {
data: RedditData,
}
// Gets a random post from a vector of subreddit.
pub async fn reddit_random_post(subreddits: &[&str], image: bool) -> anyhow::Result<RedditPost> {
let subreddit = subreddits.choose(&mut thread_rng()).unwrap();
let url = Url::parse(&format!(
r"https://www.reddit.com/r/{}/hot/.json?sort=top&t=week&limit=25",
subreddit
))?;
let data = CLIENT
.get(url)
.header("User-Agent", "bowot")
.send()
.await?
.json::<RedditResponse>()
.await?;
let posts = data.data.children;
let mut rng = thread_rng();
let mut idx: i64 = rng.gen_range(0..data.data.dist);
let mut post: RedditPost;
for _ in 0..10 {
post = posts[idx as usize].data.clone();
if !post.over_18 {
if image {
if IMAGE_EXT_RE.is_match(&post.url) {
return Ok(post);
}
} else {
if post.selftext != "" && post.selftext.len() < 2048 {
return Ok(post);
}
}
}
idx = rng.gen_range(0..data.data.dist);
}
Err(anyhow::anyhow!("No result found"))
}
pub async fn generate_triggered_avatar<S: Into<String>>(avatar: S) -> anyhow::Result<Vec<u8>> {
Ok(CLIENT
.get("https://some-random-api.ml/canvas/triggered")
.query(&[("avatar", avatar.into())])
.send()
.await?
.bytes()
.await?
.to_vec())
}
|
use super::*;
pub fn do_chown(path: &str, uid: u32, gid: u32) -> Result<()> {
println!("chown: path: {:?}, uid: {}, gid: {}", path, uid, gid);
let inode = {
let current = current!();
let fs = current.fs().lock().unwrap();
fs.lookup_inode(path)?
};
let mut info = inode.metadata()?;
info.uid = uid as usize;
info.gid = gid as usize;
inode.set_metadata(&info)?;
Ok(())
}
pub fn do_fchown(fd: FileDesc, uid: u32, gid: u32) -> Result<()> {
println!("fchown: fd: {}, uid: {}, gid: {}", fd, uid, gid);
let file_ref = current!().file(fd)?;
let mut info = file_ref.metadata()?;
info.uid = uid as usize;
info.gid = gid as usize;
file_ref.set_metadata(&info)?;
Ok(())
}
pub fn do_lchown(path: &str, uid: u32, gid: u32) -> Result<()> {
println!("lchown: path: {:?}, uid: {}, gid: {}", path, uid, gid);
let inode = {
let current = current!();
let fs = current.fs().lock().unwrap();
fs.lookup_inode_no_follow(path)?
};
let mut info = inode.metadata()?;
info.uid = uid as usize;
info.gid = gid as usize;
inode.set_metadata(&info)?;
Ok(())
}
|
use std::mem;
#[derive(Debug)]
#[derive(PartialEq)]
pub struct List {
head: Link,
}
#[derive(Debug)]
#[derive(PartialEq)]
enum Link {
Empty,
More(Box<Node>),
}
#[derive(Debug)]
#[derive(PartialEq)]
struct Node {
elem: i32,
next: Link,
}
impl List {
pub fn new() -> Self {
List { head: Link::Empty }
}
pub fn push(&mut self, elem: i32) {
let new_node = Box::new(Node {
elem: elem,
next: mem::replace(&mut self.head, Link::Empty),
});
println!("{:?}", self.head);
println!("{:?}", new_node);
self.head = Link::More(new_node);
println!("{:?}", self.head);
}
pub fn pop(&mut self) -> Option<i32> {
match mem::replace(&mut self.head, Link::Empty) {
Link::Empty => None,
Link::More(node) => {
self.head = node.next;
Some(node.elem)
}
}
}
pub fn push_end(&mut self, elem: i32) {
let new_node = Box::new(Node{
elem: elem,
next: Link::Empty,
});
let mut last = &mut self.head;
println!("{:?}", *last );
while *last != Link::Empty {
match last{
Link::More(node)=>{
last = &mut (node.next);
println!(" value of last : {:?}", last );
},
Link::Empty =>println!("none")
}
}
mem::replace(last, Link::More(new_node));
println!(" value of last : {:?}", last );
}
}
pub fn run(){
let mut list = List::new();
list.push(1);
list.push(2);
println!("{:?}", list );
list.pop();
println!("{:?}", list );
list.push_end(5);
println!("{:?}", list );
list.push_end(34);
println!("{:?}", list );
} |
#![feature(asm)]
#![no_main]
#![no_std]
extern crate panic_halt;
use cortex_m_rt::{entry, exception};
use spin::Mutex; // spin = "0.5.0"
static TO: Mutex<&'static (dyn Foo + Sync)> = Mutex::new(&Bar);
#[entry]
#[inline(never)]
fn main() -> ! {
// trait object dispatch
(*TO.lock()).foo();
Quux.foo();
loop {}
}
trait Foo {
// default implementation of this method
fn foo(&self) -> bool {
// spill variables onto the stack
unsafe { asm!("" : : "r"(0) "r"(1) "r"(2) "r"(3) "r"(4) "r"(5)) }
false
}
}
struct Bar;
// uses the default method implementation
impl Foo for Bar {}
struct Baz;
impl Foo for Baz {
// overrides the default method
fn foo(&self) -> bool {
unsafe { asm!("" : : "r"(0) "r"(1) "r"(2) "r"(3) "r"(4) "r"(5) "r"(6) "r"(7)) }
true
}
}
struct Quux;
impl Quux {
// not a trait method!
#[inline(never)]
fn foo(&self) -> bool {
// NOTE(asm!) side effect to preserve function calls to this method
unsafe { asm!("NOP" : : : : "volatile") }
false
}
}
// this handler can change the trait object at any time
#[exception]
fn SysTick() {
*TO.lock() = &Baz;
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ComputeDiagnosticsList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ComputeDiagnosticBase>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ComputeDiagnosticBase {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DiagnosticProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticProperties {
#[serde(rename = "supportedResourceTypes", default, skip_serializing_if = "Vec::is_empty")]
pub supported_resource_types: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunDiskInspectionInput {
#[serde(rename = "resourceId")]
pub resource_id: String,
pub manifest: String,
#[serde(rename = "uploadSasUri")]
pub upload_sas_uri: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunDiskInspectionAsyncOperationResult {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<String>,
#[serde(rename = "resultStatus", default, skip_serializing_if = "Option::is_none")]
pub result_status: Option<run_disk_inspection_async_operation_result::ResultStatus>,
#[serde(rename = "errorDetail", default, skip_serializing_if = "Option::is_none")]
pub error_detail: Option<ErrorDetail>,
#[serde(rename = "createdUTC", default, skip_serializing_if = "Option::is_none")]
pub created_utc: Option<String>,
}
pub mod run_disk_inspection_async_operation_result {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ResultStatus {
Success,
Failed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDetail>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetail {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorDetail>,
#[serde(rename = "innerError", default, skip_serializing_if = "Option::is_none")]
pub inner_error: Option<InnerError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InnerError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exceptiontype: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub errordetail: Option<String>,
}
|
// 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
extern crate luther;
#[macro_use]
extern crate luther_derive;
#[derive(Lexer, Debug)]
enum Token {
#[luther(regex = "ab")] Ab,
#[luther(regex = "acc*")] Acc,
#[luther(regex = "a(bc|de)")] Abcde(String),
}
fn main() {
println!("Hello World!");
}
|
use clap::{crate_description, crate_name, crate_version, App, AppSettings, Arg, SubCommand};
use moebius::{
instruction::{initialize, update_data},
state::Moebius,
};
use rand::RngCore;
use solana_clap_utils::{
fee_payer::fee_payer_arg,
input_parsers::{pubkey_of, pubkey_of_signer, signer_of},
input_validators::{is_url, is_valid_pubkey, is_valid_signer},
keypair::{signer_from_path, DefaultSigner},
nonce::*,
offline::*,
};
use solana_cli_output::{return_signers, OutputFormat};
use solana_client::{
blockhash_query::BlockhashQuery, rpc_client::RpcClient, rpc_config::RpcSendTransactionConfig,
};
use solana_sdk::{
commitment_config::CommitmentConfig, instruction::Instruction, message::Message,
native_token::*, program_pack::Pack, pubkey::Pubkey, signature::Signer, system_instruction,
transaction::Transaction,
};
use std::process::exit;
type Error = Box<dyn std::error::Error>;
type CommandResult = Result<Option<(u64, Vec<Vec<Instruction>>)>, Error>;
#[allow(dead_code)]
struct Config {
rpc_client: RpcClient,
verbose: bool,
owner: Pubkey,
fee_payer: Pubkey,
commitment_config: CommitmentConfig,
default_signer: DefaultSigner,
nonce_account: Option<Pubkey>,
nonce_authority: Option<Pubkey>,
blockhash_query: BlockhashQuery,
sign_only: bool,
}
fn check_fee_payer_balance(config: &Config, required_balance: u64) -> Result<(), Error> {
let balance = config.rpc_client.get_balance(&config.fee_payer)?;
if balance < required_balance {
Err(format!(
"Fee payer, {}, has insufficient balance: {} required, {} available",
config.fee_payer,
lamports_to_sol(required_balance),
lamports_to_sol(balance)
)
.into())
} else {
Ok(())
}
}
fn rand_bytes(n: usize) -> Vec<u8> {
let mut output = vec![0u8; n];
rand::thread_rng().fill_bytes(output.as_mut_slice());
output
}
fn command_initialize(config: &Config, account: &Pubkey) -> CommandResult {
let minimum_balance_for_rent_exemption = if !config.sign_only {
config
.rpc_client
.get_minimum_balance_for_rent_exemption(Moebius::LEN)?
} else {
0
};
let instructions = vec![
system_instruction::create_account(
&config.fee_payer,
&account,
minimum_balance_for_rent_exemption,
Moebius::LEN as u64,
&moebius::id(),
),
initialize(&moebius::id(), account, &config.owner)?,
];
Ok(Some((
minimum_balance_for_rent_exemption,
vec![instructions],
)))
}
fn command_update_data(
_config: &Config,
moebius_account: &Pubkey,
authority: &Pubkey,
target_program: &Pubkey,
target_account: &Pubkey,
data: Vec<u8>,
) -> CommandResult {
let (caller_account, _) = Pubkey::find_program_address(
&[&target_program.to_bytes(), &target_account.to_bytes()],
&moebius::id(),
);
let instructions = vec![update_data(
&moebius::id(),
moebius_account,
authority,
&caller_account,
target_program,
target_account,
data,
)?];
Ok(Some((0u64, vec![instructions])))
}
fn main() {
let app_matches = App::new(crate_name!())
.about(crate_description!())
.version(crate_version!())
.setting(AppSettings::SubcommandRequiredElseHelp)
.arg({
let arg = Arg::with_name("config_file")
.short("C")
.long("config")
.value_name("PATH")
.takes_value(true)
.global(true)
.help("Configuration file to use");
if let Some(ref config_file) = *solana_cli_config::CONFIG_FILE {
arg.default_value(&config_file)
} else {
arg
}
})
.arg(
Arg::with_name("verbose")
.long("verbose")
.short("v")
.takes_value(false)
.global(true)
.help("Show additional information"),
)
.arg(
Arg::with_name("json_rpc_url")
.long("url")
.value_name("URL")
.takes_value(true)
.global(true)
.validator(is_url)
.help("JSON RPC URL for the cluster. Default from the configuration file."),
)
.arg(
Arg::with_name("owner")
.long("owner")
.value_name("KEYPAIR")
.validator(is_valid_signer)
.takes_value(true)
.global(true)
.help(
"Specify the token owner account. \
This may be a keypair file, the ASK keyword. \
Defaults to the client keypair.",
),
)
.arg(fee_payer_arg().global(true))
.subcommand(
SubCommand::with_name("initialize")
.about("Initialize Moebius")
.arg(
Arg::with_name("account-keypair")
.long("account-keypair")
.value_name("ACCOUNT_KEYPAIR")
.validator(is_valid_signer)
.takes_value(true)
.required(true)
.help(
"Specify the moebius account. \
This may be a keypair file, the ASK keyword. \
Defaults to the client keypair.",
),
)
.nonce_args(true)
.offline_args(),
)
.subcommand(
SubCommand::with_name("update-data")
.about("Update data in an account via a moebius-compatible program")
.arg(
Arg::with_name("moebius-account")
.long("moebius-account")
.value_name("MOEBIUS_ID")
.validator(is_valid_pubkey)
.takes_value(true)
.required(true)
.help("Specify the moebius account"),
)
.arg(
Arg::with_name("authority-keypair")
.long("authority-keypair")
.value_name("AUTHORITY_KEYPAIR")
.validator(is_valid_signer)
.takes_value(true)
.required(true)
.help(
"Specify the moebius authority key. \
This may be a keypair file, the ASK keyword. \
Defaults to the client keypair.",
),
)
.arg(
Arg::with_name("target-program")
.long("target-program")
.value_name("TARGET_PROGRAM_ID")
.validator(is_valid_pubkey)
.takes_value(true)
.required(true)
.help("Specify the target program ID"),
)
.arg(
Arg::with_name("target-account")
.long("target-account")
.value_name("TARGET_ACCOUNT_ID")
.validator(is_valid_pubkey)
.takes_value(true)
.required(true)
.help("Specify the target account ID"),
)
.nonce_args(true)
.offline_args(),
)
.get_matches();
let mut wallet_manager = None;
let mut bulk_signers: Vec<Option<Box<dyn Signer>>> = Vec::new();
let (sub_command, sub_matches) = app_matches.subcommand();
let matches = sub_matches.unwrap();
let config = {
let cli_config = if let Some(config_file) = matches.value_of("config_file") {
solana_cli_config::Config::load(config_file).unwrap_or_default()
} else {
solana_cli_config::Config::default()
};
let json_rpc_url = matches
.value_of("json_rpc_url")
.unwrap_or(&cli_config.json_rpc_url)
.to_string();
let default_signer_arg_name = "owner".to_string();
let default_signer_path = matches
.value_of(&default_signer_arg_name)
.map(|s| s.to_string())
.unwrap_or_else(|| cli_config.keypair_path.clone());
let default_signer = DefaultSigner {
path: default_signer_path,
arg_name: default_signer_arg_name,
};
bulk_signers.push(None);
let owner = default_signer
.signer_from_path(&matches, &mut wallet_manager)
.unwrap_or_else(|e| {
eprintln!("error: {}", e);
exit(1);
})
.pubkey();
let (signer, fee_payer) = signer_from_path(
&matches,
matches
.value_of("fee_payer")
.unwrap_or(&cli_config.keypair_path),
"fee_payer",
&mut wallet_manager,
)
.map(|s| {
let p = s.pubkey();
(Some(s), p)
})
.unwrap_or_else(|e| {
eprintln!("error: {}", e);
exit(1);
});
bulk_signers.push(signer);
let verbose = matches.is_present("verbose");
let nonce_account = pubkey_of_signer(&matches, NONCE_ARG.name, &mut wallet_manager)
.unwrap_or_else(|e| {
eprintln!("error: {}", e);
exit(1);
});
let (signer, nonce_authority) =
signer_of(&matches, NONCE_AUTHORITY_ARG.name, &mut wallet_manager).unwrap_or_else(
|e| {
eprintln!("error: {}", e);
exit(1);
},
);
if signer.is_some() {
bulk_signers.push(signer);
}
let blockhash_query = BlockhashQuery::new_from_matches(matches);
let sign_only = matches.is_present(SIGN_ONLY_ARG.name);
Config {
rpc_client: RpcClient::new(json_rpc_url),
verbose,
owner,
fee_payer,
commitment_config: CommitmentConfig::single_gossip(),
default_signer,
nonce_account,
nonce_authority,
blockhash_query,
sign_only,
}
};
solana_logger::setup_with_default("solana=info");
let _ = match (sub_command, sub_matches) {
("initialize", Some(arg_matches)) => {
let (signer, account) = signer_of(&arg_matches, "account-keypair", &mut wallet_manager)
.unwrap_or_else(|e| {
eprintln!("error: {}", e);
exit(1);
});
bulk_signers.push(signer);
command_initialize(&config, &account.unwrap())
}
("update-data", Some(arg_matches)) => {
let moebius_account = pubkey_of(arg_matches, "moebius-account").unwrap();
let target_program = pubkey_of(arg_matches, "target-program").unwrap();
let target_account = pubkey_of(arg_matches, "target-account").unwrap();
let (signer, authority) =
signer_of(&arg_matches, "authority-keypair", &mut wallet_manager).unwrap_or_else(
|e| {
eprintln!("error: {}", e);
exit(1);
},
);
bulk_signers.push(signer);
let mut data: Vec<u8> = vec![];
let rand_val_bytes32 = rand_bytes(32usize);
let rand_val_address = rand_bytes(20usize);
let rand_val_uint256 = rand_bytes(32usize);
data.extend_from_slice(rand_val_bytes32.as_slice());
data.extend_from_slice(&[0u8; 12]);
data.extend_from_slice(rand_val_address.as_slice());
data.extend_from_slice(rand_val_uint256.as_slice());
command_update_data(
&config,
&moebius_account,
&authority.unwrap(),
&target_program,
&target_account,
data,
)
}
_ => unreachable!(),
}
.and_then(|transaction_info| {
if let Some((minimum_balance_for_rent_exemption, instruction_batches)) = transaction_info {
let fee_payer = Some(&config.fee_payer);
let signer_info = config
.default_signer
.generate_unique_signers(bulk_signers, &matches, &mut wallet_manager)
.unwrap_or_else(|e| {
eprintln!("error: {}", e);
exit(1);
});
for instructions in instruction_batches {
let message = if let Some(nonce_account) = config.nonce_account.as_ref() {
Message::new_with_nonce(
instructions,
fee_payer,
nonce_account,
config.nonce_authority.as_ref().unwrap(),
)
} else {
Message::new(&instructions, fee_payer)
};
let (recent_blockhash, fee_calculator) = config
.blockhash_query
.get_blockhash_and_fee_calculator(&config.rpc_client, config.commitment_config)
.unwrap_or_else(|e| {
eprintln!("error: {}", e);
exit(1);
});
if !config.sign_only {
check_fee_payer_balance(
&config,
minimum_balance_for_rent_exemption + fee_calculator.calculate_fee(&message),
)?;
}
let mut transaction = Transaction::new_unsigned(message);
if config.sign_only {
transaction.try_partial_sign(&signer_info.signers, recent_blockhash)?;
println!("{}", return_signers(&transaction, &OutputFormat::Display)?);
} else {
transaction.try_sign(&signer_info.signers, recent_blockhash)?;
let signature = config
.rpc_client
.send_and_confirm_transaction_with_spinner_and_config(
&transaction,
config.commitment_config,
RpcSendTransactionConfig {
preflight_commitment: Some(config.commitment_config.commitment),
..RpcSendTransactionConfig::default()
},
)?;
println!("Signature: {}", signature);
}
}
}
Ok(())
})
.map_err(|err| {
eprintln!("{}", err);
exit(1);
});
}
|
//! A Rust client for the `open.189.cn` API.
#![feature(proc_macro)]
#![recursion_limit = "1024"]
#![deny(missing_docs)]
#![deny(warnings)]
extern crate chrono;
extern crate crypto;
#[macro_use]
extern crate error_chain;
extern crate hyper;
#[macro_use]
extern crate lazy_static;
extern crate rand;
extern crate rustc_serialize;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate url;
mod app;
pub mod errors;
pub mod msg;
mod net;
mod resp;
mod sig;
mod util;
pub use app::*;
|
use crate::{InputValueError, InputValueResult, ScalarType, Value};
use async_graphql_derive::Scalar;
use chrono::{DateTime, FixedOffset, Utc};
/// Implement the DateTime<FixedOffset> scalar
///
/// The input/output is a string in RFC3339 format.
#[Scalar(internal, name = "DateTimeFixedOffset")]
impl ScalarType for DateTime<FixedOffset> {
fn parse(value: Value) -> InputValueResult<Self> {
match &value {
Value::String(s) => Ok(DateTime::parse_from_rfc3339(s)?),
_ => Err(InputValueError::ExpectedType(value)),
}
}
fn to_value(&self) -> Value {
Value::String(self.to_rfc3339())
}
}
/// Implement the DateTime<Utc> scalar
///
/// The input/output is a string in RFC3339 format.
#[Scalar(internal, name = "DateTimeUtc")]
impl ScalarType for DateTime<Utc> {
fn parse(value: Value) -> InputValueResult<Self> {
match &value {
Value::String(s) => Ok(s.parse::<DateTime<Utc>>()?),
_ => Err(InputValueError::ExpectedType(value)),
}
}
fn to_value(&self) -> Value {
Value::String(self.to_rfc3339())
}
}
|
use std::{io, process};
#[derive(thiserror::Error, Debug)]
pub enum InstallError {
#[error("Payload error")]
Payload(#[from] crate::repo::PayloadError),
#[error("Wrong payload type")]
WrongPayloadType,
#[error("Package not found in cache (not downloaded?)")]
PackageNotInCache,
#[error("Installation process failed")]
InstallerFailure(#[from] ProcessError),
}
#[derive(thiserror::Error, Debug)]
pub enum ProcessError {
#[error("IO error")]
Io(#[from] io::Error),
#[error("Not found")]
NotFound,
#[error("Unknown error")]
Unknown(process::Output),
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.